providers: mark a provider and a routing group on a plan or pay as you go (EV_John_Liu on X)

EV_John_Liu on X asked for pay-as-you-go and token plans to be marked on
providers and routing groups. A provider row now carries a quiet grey
badge, Plan, Pay as you go, or Plan + pay as you go when its keys are
on both (Volcengine's Coding Plan beside a pay-as-you-go key). It is
read from what magpie knows: a signed-in subscription is a plan; a
plan preset (Kimi Code, Qwen/Bailian token plans, OpenCode Go,
ClinePass) is a plan; a preset region's own name (Coding Plan, Token
Plan, Pay as you go) decides; other vendor and relay presets are pay as
you go. Presets whose billing magpie can't tell (MiniMax, Ollama Cloud,
ModelScope and others) and custom endpoints show nothing until the
user says: the provider editor's Advanced has Billing (Auto / Plan /
Pay as you go), and `magpie providers set <id> billing=plan|payg|auto`.
The user's word always wins. A routing group gets the same tag when
every on member is known; its title lists each member.

Run on mote with these changes on origin/main ccc96b4a7; pushed rebased
on 901e641f2, no conflict, where the core scripts weigh 1,531,382 of
their 1,533,802 (at ccc96b4a7 they were 1,934 over; main has since
moved code out, so no raise):
- go test -run 'Billing|CountFree|KeyPlan|GroupModelsCarry|ProviderSet'
  ./internal/provider ./internal/gui ./internal/cli: ok.
- gofmt -l clean; go vet darwin, linux -tags nogui, windows.
- provider-billing.test.cjs: 5 languages, 900 and 440px, chromium and
  webkit, green (54 of 54 together with the ticks file); i18n-keys and
  i18n-en-no-cjk green.

Broken by hand: BillingKind returning "" turns TestBillingKind,
TestBillingKindMixedKeys, TestBillingEveryRegion and
TestProviderBilling red; dropping the badge turns
provider-billing.test.cjs red in every run.

Not tried: real accounts of each vendor (the marker reads saved
settings only, nothing goes upstream); the real app window. The whole
GUI suite was started after this record.
This commit is contained in:
yetone
2026-11-10 18:58:03 +08:00
parent 79f5c15e91
commit 07af9f86a6
13 changed files with 625 additions and 6 deletions
@@ -0,0 +1,49 @@
package cli
import (
"strings"
"testing"
"github.com/yetone/magpie/internal/provider"
)
// magpie provider set billing=plan marks a provider on a plan (EV_John_Liu
// on X), show says so, billing=auto hands it back to magpie's reading, and
// any other value is refused and leaves the saved one alone.
func TestProviderSetBilling(t *testing.T) {
groupsHome(t)
if _, err := printed(t, func() error { return providerCmd([]string{"provider", "set", "a", "billing=plan"}) }); err != nil {
t.Fatal(err)
}
if p := mustFind(t, "a"); p.Billing != provider.BillingPlan || p.BillingKind() != provider.BillingPlan {
t.Fatalf("billing=plan: %q", p.Billing)
}
out, err := printed(t, func() error { return providerCmd([]string{"provider", "a"}) })
if err != nil {
t.Fatal(err)
}
if !strings.Contains(out, "billing") || !strings.Contains(out, "by your word") {
t.Fatalf("show doesn't say how it bills:\n%s", out)
}
for _, v := range []string{"maybe", "mixed", "--help"} {
err := providerCmd([]string{"provider", "set", "a", "billing=" + v})
if err == nil || !strings.Contains(err.Error(), "billing=plan|payg|auto") {
t.Errorf("billing=%q: %v", v, err)
}
if mustFind(t, "a").Billing != provider.BillingPlan {
t.Errorf("a refused billing=%q changed it", v)
}
}
if _, err := printed(t, func() error { return providerCmd([]string{"provider", "set", "a", "billing=payg"}) }); err != nil {
t.Fatal(err)
}
if mustFind(t, "a").Billing != provider.BillingPAYG {
t.Fatal("billing=payg not saved")
}
if _, err := printed(t, func() error { return providerCmd([]string{"provider", "set", "a", "billing=auto"}) }); err != nil {
t.Fatal(err)
}
if mustFind(t, "a").Billing != "" {
t.Fatal("billing=auto left the user's word")
}
}
+37
View File
@@ -179,6 +179,9 @@ const providerUsage = `usage:
magpie provider set modelscope free=yes
(every model of it counts as free, so a Free first routing spends it before
paid ones, as a free daily quota; prices and Usage's costs stay as listed)
magpie provider set my-relay billing=plan
(marks it on a plan, or billing=payg pay as you go, on Providers and Routing;
billing=auto goes back to magpie's reading of its endpoints)
magpie provider add "My Relay" url=https://relay.example.com/v1 key=sk-… balance=https://relay.example.com/api/usage/token balance.path='$data.total_available / 500000'
magpie provider set my-relay balance.path='(1 - credits.monthlyCredits / 70) %'
magpie provider set my-relay balance.method=POST
@@ -902,6 +905,13 @@ func showProviderAsking(p provider.Provider, ask bool) error {
}
kv("unmasked", "yes"+muted.Render(why))
}
switch b := p.BillingKind(); {
case b == "":
case p.Billing != "":
kv("billing", billingWord(b)+muted.Render(" by your word"))
default:
kv("billing", billingWord(b))
}
if p.CountFree {
kv("free", "yes"+muted.Render(" counted free by Free first and Cheapest routing; prices and Usage's costs stay as listed"))
}
@@ -1329,6 +1339,20 @@ func applyPairs(p *provider.Provider, pairs []string) error {
default:
return fmt.Errorf("free=yes|no, not %q", v)
}
case "billing":
// plan or payg: how the provider bills, by the user's word,
// marked on Providers and Routing (EV_John_Liu on X); auto:
// magpie's reading of it (provider.BillingKind)
switch strings.ToLower(v) {
case "plan":
p.Billing = provider.BillingPlan
case "payg", "pay-as-you-go":
p.Billing = provider.BillingPAYG
case "auto", "":
p.Billing = ""
default:
return fmt.Errorf("billing=plan|payg|auto, not %q", v)
}
case "context":
if err := setContext(p, "*", v); err != nil {
return err
@@ -2408,3 +2432,16 @@ func patienceArg(v string) (int, error) {
}
return int((d + time.Second - 1) / time.Second), nil
}
// billingWord is how a provider bills, in words (provider.BillingKind).
func billingWord(b string) string {
switch b {
case provider.BillingPlan:
return "plan"
case provider.BillingPAYG:
return "pay as you go"
case provider.BillingMixed:
return "plan and pay as you go"
}
return b
}
+2
View File
@@ -2771,6 +2771,8 @@ body.window .ag-sk-icon { width: 22px; height: 22px; border-radius: 6px; }
.badge.path.direct { background: var(--pill); color: var(--muted); box-shadow: inset 0 0 0 1px var(--line); }
.badge.ctx { background: var(--pill); color: var(--muted); box-shadow: inset 0 0 0 1px var(--line); letter-spacing: .02em; }
.badge.wsl { background: var(--pill); color: var(--muted); box-shadow: inset 0 0 0 1px var(--line); letter-spacing: .02em; text-transform: none; }
/* how a provider bills, plan or pay as you go (EV_John_Liu on X): grey, a fact */
.badge.bill { background: var(--pill); color: var(--muted); letter-spacing: .02em; text-transform: none; }
/* a model's credit rate (0.5×): grey, a fact to pick by; a discount's price before it struck through */
.badge.rate { background: var(--pill); color: var(--muted); letter-spacing: .02em; text-transform: none; font-variant-numeric: tabular-nums; display: inline-flex; gap: 3px; }
.badge.rate s { font-weight: 500; opacity: .75; }
+21 -5
View File
@@ -6131,6 +6131,9 @@ function renderProviders(quiet) {
const rate = "×" + (p.rateNow < 0.01 ? "<0.01" : +p.rateNow.toFixed(2));
name.append(Object.assign(el("span", "badge rate-now", rate), { title: t("Bills at {rate} now: the price rate times this hour's window", { rate }) }));
}
// on a plan or pay as you go, quietly (EV_John_Liu on X)
const bill = billingWord(p.billingKind);
if (bill) name.append(el("span", "badge bill", bill));
// a provider that only draws images (Settings → Image generation) says so
const models = n ? t(n === 1 ? "{n} model" : "{n} models", { n })
: p.draws ? t(p.draws === 1 ? "{n} image model" : "{n} image models", { n: p.draws }) : t(p.noModels ? "usage only" : "no models exposed");
@@ -7777,6 +7780,18 @@ function countFreeField() {
c.onchange = () => { draft.countFree = c.checked; };
return field(t("Free for me"), l, t("For a free quota, like a daily allowance: Free first uses its models before paid ones, and Cheapest first counts them as costing nothing. Prices and the costs Usage counts stay as listed."));
}
// billingWord: how a provider bills, as its badge says it
// (provider.BillingKind); "" when magpie can't tell
function billingWord(kind) {
return { plan: t("Plan"), payg: t("Pay as you go"), mixed: t("Plan + pay as you go") }[kind] || "";
}
// billingField: provider.Billing, the user's word over magpie's reading
// of its endpoints (EV_John_Liu on X)
function billingField() {
const seg = segs([["", t("Auto")], ["plan", t("Plan")], ["payg", t("Pay as you go")]], draft.billing || "", (v) => { draft.billing = v; });
seg.classList.add("billing");
return field(t("Billing"), seg);
}
// a provider's hours at its own rate (#2463), drawn by ratewindows.js
function rateWindowsField() {
const box = el("div", "stack rate-windows"), d = draft;
@@ -7921,7 +7936,7 @@ function advancedSet(d, p) {
!!d.proxyMode || Object.values(d.accountProxies || {}).some((x) => x?.mode) ||
[d.concurrency, d.maxAccounts, d.queueLimit, d.queueWait, d.maxRPM, d.priceRate, d.contexts, d.outputs, d.compacts].some((v) => String(v ?? "").trim()) ||
!!d.rateWindows?.length ||
!!(d.searches || d.authHeader || d.passUserAgent === false || d.unredacted || d.countFree || d.pinUpstream || d.nativeCompaction || d.balanceToken || d.limitRestOff || d.http1 || d.socket || d.imageFilesOff || d.passErrors || d.clientCert || d.serverCA) ||
!!(d.searches || d.authHeader || d.passUserAgent === false || d.unredacted || d.countFree || d.billing || d.pinUpstream || d.nativeCompaction || d.balanceToken || d.limitRestOff || d.http1 || d.socket || d.imageFilesOff || d.passErrors || d.clientCert || d.serverCA) ||
!!d.fallback?.length || !!p?.balanceToken?.set;
}
function priceRateError(ed) {
@@ -9213,7 +9228,7 @@ function baseAPIOf(p) {
// draftOf is a saved provider as its editor's form holds it.
function draftOf(p) {
return { id: p.id, name: p.name, preset: p.preset, chat: p.chat, responses: p.responses, anthropic: p.anthropic, gemini: p.gemini || "", catalog: p.catalog, decide: p.decide || "", key: "", api: baseAPIOf(p), chosen: pickedOf(p), none: !!p.noModels, best: !!p.bestInFamily, extra: [], headers: headerRows(p.headers), extraBody: extraBodyText(p.extraBody), replyHeaders: (p.replyHeaders || []).join(", "), passHeaders: (p.passHeaders || []).join(", "), icon: p.icon || "", iconFrom: p.iconFrom || "", fallback: [...(p.fallback || [])], unlisted: !!p.unlisted, hiddenDrawers: [...(p.hiddenDrawers || [])], hiddenVideomakers: [...(p.hiddenVideomakers || [])], searches: !!p.searches, unredacted: !!p.unredacted, countFree: !!p.countFree, insecureTLS: !!p.insecureTLS, http1: !!p.http1, clientCert: p.clientCert || "", clientKey: p.clientKey || "", serverCA: p.serverCA || "", socket: p.socket || "", limitRestOff: !!p.limitRestOff, passErrors: !!p.passErrors, imageFilesOff: !!p.imageFilesOff, nativeCompaction: !!p.nativeCompaction, passUserAgent: p.passUserAgent !== false, pinUpstream: !!p.pinUpstream, authHeader: p.authHeader || "", balanceURL: p.balanceURL || "", balancePath: p.balancePath || "", balanceMethod: p.balanceMethod || "", modelsURL: p.modelsURL || "", listOff: !!p.listOff, contexts: contextsText(p.contexts), outputs: contextsText(p.outputs), compacts: contextsText(p.compacts), keysUrl: p.keysUrl || "", ...proxyDraft(p), ...concurrencyDraft(p), rateWindows: (p.rateWindows || []).map((w) => ({ ...w })) };
return { id: p.id, name: p.name, preset: p.preset, chat: p.chat, responses: p.responses, anthropic: p.anthropic, gemini: p.gemini || "", catalog: p.catalog, decide: p.decide || "", key: "", api: baseAPIOf(p), chosen: pickedOf(p), none: !!p.noModels, best: !!p.bestInFamily, extra: [], headers: headerRows(p.headers), extraBody: extraBodyText(p.extraBody), replyHeaders: (p.replyHeaders || []).join(", "), passHeaders: (p.passHeaders || []).join(", "), icon: p.icon || "", iconFrom: p.iconFrom || "", fallback: [...(p.fallback || [])], unlisted: !!p.unlisted, hiddenDrawers: [...(p.hiddenDrawers || [])], hiddenVideomakers: [...(p.hiddenVideomakers || [])], searches: !!p.searches, unredacted: !!p.unredacted, countFree: !!p.countFree, billing: p.billing || "", insecureTLS: !!p.insecureTLS, http1: !!p.http1, clientCert: p.clientCert || "", clientKey: p.clientKey || "", serverCA: p.serverCA || "", socket: p.socket || "", limitRestOff: !!p.limitRestOff, passErrors: !!p.passErrors, imageFilesOff: !!p.imageFilesOff, nativeCompaction: !!p.nativeCompaction, passUserAgent: p.passUserAgent !== false, pinUpstream: !!p.pinUpstream, authHeader: p.authHeader || "", balanceURL: p.balanceURL || "", balancePath: p.balancePath || "", balanceMethod: p.balanceMethod || "", modelsURL: p.modelsURL || "", listOff: !!p.listOff, contexts: contextsText(p.contexts), outputs: contextsText(p.outputs), compacts: contextsText(p.compacts), keysUrl: p.keysUrl || "", ...proxyDraft(p), ...concurrencyDraft(p), rateWindows: (p.rateWindows || []).map((w) => ({ ...w })) };
}
// duplicateProvider opens the Add form on a copy of p, its key p's unless another is pasted (#268).
@@ -9519,7 +9534,7 @@ function drawEditor(p, presetID) {
if (perAccount) proxies.append(perAccount);
advIn.append(...field(t("Proxy"), proxies));
advIn.append(...concurrencyField(p));
advIn.append(...priceRateField(), ...countFreeField(), ...rateWindowsField());
advIn.append(...priceRateField(), ...countFreeField(), ...billingField(), ...rateWindowsField());
if (p.cline) advIn.append(...upstreamField());
advIn.append(...unmaskRow(""));
ed.append(...pluginOptionsField(subOf(a.agent)));
@@ -9566,7 +9581,7 @@ function drawEditor(p, presetID) {
if (priceTypedError(ed)) return;
const picked = accountModelsDraft(p);
if (picked === false) return pickError();
const body = { id: p.id, models: chosenIds(), noModels: noneChosen(), bestInFamily: bestChosen(), unlisted: draft.unlisted, hiddenDrawers: draft.hiddenDrawers, hiddenVideomakers: draft.hiddenVideomakers, fallback: draft.fallback, contexts: cx.map, outputs: ox.map, compacts: cpx.map, proxy, accountProxies: own.map, maxConcurrency, maxAccounts, ...queue, priceRate, rateWindows, modelPrefs: modelPrefsOfDraft(), pinUpstream: !!draft.pinUpstream, unredacted: !!draft.unredacted, countFree: !!draft.countFree, ...(p.carriesCompaction ? { nativeCompaction: !!draft.nativeCompaction } : {}), ...routingOfDraft(p) };
const body = { id: p.id, models: chosenIds(), noModels: noneChosen(), bestInFamily: bestChosen(), unlisted: draft.unlisted, hiddenDrawers: draft.hiddenDrawers, hiddenVideomakers: draft.hiddenVideomakers, fallback: draft.fallback, contexts: cx.map, outputs: ox.map, compacts: cpx.map, proxy, accountProxies: own.map, maxConcurrency, maxAccounts, ...queue, priceRate, rateWindows, modelPrefs: modelPrefsOfDraft(), pinUpstream: !!draft.pinUpstream, unredacted: !!draft.unredacted, countFree: !!draft.countFree, billing: draft.billing || "", ...(p.carriesCompaction ? { nativeCompaction: !!draft.nativeCompaction } : {}), ...routingOfDraft(p) };
saving(saveBtn, t("Saving…"));
saveAccountModelsDraft(picked).then(() => savePluginOptions(subOf(a.agent))).then(() => providerAction("save", body, t("{name} saved", { name: p.name })), (e) => { doneSaving(saveBtn); editorError(e.message || String(e)); }); };
bar.append(cancel, saveBtn);
@@ -9753,7 +9768,7 @@ function drawEditor(p, presetID) {
if (perKey) proxies.append(perKey);
advIn.append(...field(t("Proxy"), proxies));
advIn.append(...concurrencyField(p));
advIn.append(...priceRateField(), ...countFreeField(), ...rateWindowsField());
advIn.append(...priceRateField(), ...countFreeField(), ...billingField(), ...rateWindowsField());
if (p?.cline || (isNew && pr?.id === "clinepass")) advIn.append(...upstreamField());
@@ -10218,6 +10233,7 @@ function drawEditor(p, presetID) {
if (twoKeyHeaders()) body.authHeader = draft.authHeader || "";
body.unredacted = !!draft.unredacted;
body.countFree = !!draft.countFree;
body.billing = draft.billing || "";
if (tlsTakes()) { body.insecureTLS = !!draft.insecureTLS && onHTTPS(); body.http1 = !!draft.http1 && onHTTPS(); }
if (certTakes()) for (const k of CERT_FIELDS) body[k] = onHTTPS() ? (draft[k] || "").trim() : "";
if (socketable()) body.socket = draft.socket || "";
+8
View File
@@ -3217,6 +3217,8 @@ const I18N = {
"China Mainland": "中国大陆",
"Plan": "套餐",
"Pay as you go": "按量付费",
"Billing": "计费方式",
"Plan + pay as you go": "套餐 + 按量付费",
"Token Plan Personal": "Token Plan 个人版",
"Token Plan Enterprise": "Token Plan 企业版",
"Token Plan · pay as you go": "Token Plan · 按量付费",
@@ -8131,6 +8133,8 @@ const I18N = {
"China Mainland": "中國大陸",
"Plan": "套餐",
"Pay as you go": "按量付費",
"Billing": "計費方式",
"Plan + pay as you go": "套餐 + 按量付費",
"Token Plan Personal": "Token Plan 個人版",
"Token Plan Enterprise": "Token Plan 企業版",
"Token Plan · pay as you go": "Token Plan · 按量付費",
@@ -13042,6 +13046,8 @@ const I18N = {
"China Mainland": "中国本土",
"Plan": "プラン",
"Pay as you go": "従量課金",
"Billing": "課金方式",
"Plan + pay as you go": "プラン + 従量課金",
"Token Plan Personal": "Token Plan Personal",
"Token Plan Enterprise": "Token Plan Enterprise",
"Token Plan · pay as you go": "Token Plan · 従量課金",
@@ -17964,6 +17970,8 @@ const I18N = {
"China Mainland": "Festlandchina",
"Plan": "Tarif",
"Pay as you go": "Nutzungsbasiert",
"Billing": "Abrechnung",
"Plan + pay as you go": "Tarif + nutzungsbasiert",
"Token Plan Personal": "Token Plan Personal",
"Token Plan Enterprise": "Token Plan Enterprise",
"Token Plan · pay as you go": "Token Plan · nutzungsbasiert",
@@ -6879,6 +6879,22 @@ function routingPage(part) {
status(e.message, "err");
}
}
// billTag: the group's members' billing summed up, quiet, each member's
// on hover; null while one of them is unknown or a group
function billTag(g) {
const kinds = new Set(), lines = [];
for (const id of shownMembers(g)) {
if (g.off?.includes(id)) continue;
const kind = g.memberInfo?.find((x) => x.id === id)?.billing;
if (!kind) return null;
for (const k of kind === "mixed" ? ["plan", "payg"] : [kind]) kinds.add(k);
lines.push(`${memberLabel(g, id)}: ${billingWord(kind)}`);
}
if (!kinds.size) return null;
const k = el("span", "tag bill", billingWord(kinds.size > 1 ? "mixed" : [...kinds][0]));
k.title = lines.join("\n");
return k;
}
function groupRow(g) {
const row = el("div", "rt-group" + (g.ready ? "" : " off") + (g.disabled ? " disabled" : ""));
row.dataset.id = row.dataset.gslot = g.id;
@@ -6930,6 +6946,10 @@ function routingPage(part) {
k.title = t(LIST_HINT.unlists);
tags.append(k);
}
// on a plan, pay as you go or both, as its members' providers bill
// (EV_John_Liu on X); said only when magpie knows of every one
const bill = billTag(g);
if (bill) tags.append(bill);
if (g.firstToken > 0 && !manual) tags.append(el("span", "tag", t("Next after {n} without a first token", { n: took(g.firstToken * 1000) })));
if (g.rules?.length) {
const r = el("span", "tag" + (manual ? " idle" : ""), t(g.rules.length === 1 ? "1 rule" : "{n} rules", { n: g.rules.length }));
+72
View File
@@ -0,0 +1,72 @@
package gui
import (
"net/http"
"net/http/httptest"
"os"
"strings"
"testing"
"github.com/yetone/magpie/internal/provider"
)
// EV_John_Liu on X: whether a provider is on a plan or pay as you go is
// marked on Providers and on a routing group's members. /api/providers
// gives magpie's reading (billingKind) and the user's word (billing),
// the editor's save keeps the word on a preset and on a typed-in
// provider, refuses a value that is neither, and a group's member says
// its provider's billing.
func TestProviderBilling(t *testing.T) {
t.Setenv("HOME", t.TempDir())
t.Setenv("USERPROFILE", os.Getenv("HOME"))
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
t.Setenv("XDG_CACHE_HOME", t.TempDir())
mux := http.NewServeMux()
providerRoutes(mux, nil)
do := func(method, path, body string, code int) string {
t.Helper()
w := httptest.NewRecorder()
mux.ServeHTTP(w, httptest.NewRequest(method, path, strings.NewReader(body)))
if w.Code != code {
t.Fatalf("%s: %d %s", path, w.Code, w.Body)
}
return w.Body.String()
}
do("POST", "/api/provider/save", `{"id":"openrouter","name":"OpenRouter","preset":"openrouter","key":"k","new":true}`, 200)
if !strings.Contains(do("GET", "/api/providers", "", 200), `"billingKind":"payg"`) {
t.Fatal("/api/providers doesn't say OpenRouter is pay as you go")
}
do("POST", "/api/provider/save", `{"id":"openrouter","from":"openrouter","name":"OpenRouter","preset":"openrouter","key":"","billing":"plan"}`, 200)
if p, err := provider.Find("openrouter"); err != nil || p.Billing != provider.BillingPlan || p.BillingKind() != provider.BillingPlan {
t.Fatalf("the preset's word wasn't kept: %+v %v", p.Billing, err)
}
if out := do("GET", "/api/providers", "", 200); !strings.Contains(out, `"billing":"plan"`) || !strings.Contains(out, `"billingKind":"plan"`) {
t.Fatal("/api/providers doesn't give the word back")
}
do("POST", "/api/provider/save", `{"id":"openrouter","from":"openrouter","name":"OpenRouter","preset":"openrouter","key":"","billing":"mixed"}`, 400)
if p, _ := provider.Find("openrouter"); p.Billing != provider.BillingPlan {
t.Fatalf("a refused value changed it: %q", p.Billing)
}
do("POST", "/api/provider/save", `{"id":"openrouter","from":"openrouter","name":"OpenRouter","preset":"openrouter","key":"","billing":""}`, 200)
if p, _ := provider.Find("openrouter"); p.Billing != "" {
t.Fatalf("Auto left the word: %q", p.Billing)
}
do("POST", "/api/provider/save", `{"id":"box","name":"Box","chat":"http://127.0.0.1:9/v1","key":"k","models":["m"],"billing":"payg","new":true}`, 200)
if p, err := provider.Find("box"); err != nil || p.Billing != provider.BillingPAYG {
t.Fatalf("a typed-in provider's word wasn't kept: %+v %v", p.Billing, err)
}
if err := provider.SaveGroup(provider.Group{ID: "g", Name: "G", Members: []string{"box/m"}}); err != nil {
t.Fatal(err)
}
for _, g := range groupsState().Groups {
if g.ID != "g" {
continue
}
if len(g.Info) != 1 || g.Info[0].Billing != provider.BillingPAYG {
t.Fatalf("the member doesn't say its provider's billing: %+v", g.Info)
}
return
}
t.Fatal("group g not listed")
}
+4
View File
@@ -161,6 +161,9 @@ type memberJSON struct {
// "<provider>/<id>" as Accounts has them ("provider/model#<id>",
// EastonXvii on X); "" for every one the group allows
Account string `json:"account,omitempty"`
// Billing is how its provider bills: plan, payg or mixed, "" when
// unknown (provider.BillingKind; EV_John_Liu on X)
Billing string `json:"billing,omitempty"`
// Fast: the group sends it in its vendor's fast mode; CanFast: its
// model has one (provider.CanFast)
Fast bool `json:"fast,omitempty"`
@@ -468,6 +471,7 @@ func groupsState() groupsJSON {
m.OwnFast = m.CanFast && provider.OwnFast(p, model)
m.Fast = m.CanFast && g.IsFast(id)
m.Free = p.FreeModel(model)
m.Billing = p.BillingKind()
for _, e := range served {
if e.Group == "" && e.Provider.ID == p.ID && e.Model == model {
m.Context, m.Images, m.ImagesUnknown = e.Context, seesImages(e), imagesUnknown(e)
+11 -1
View File
@@ -131,6 +131,11 @@ type providerJSON struct {
// every model of it counted free by the user's word, for Free first
// and Cheapest (provider.CountFree)
CountFree bool `json:"countFree,omitempty"`
// how it bills, by the user's word ("" for magpie's reading), and as
// it is taken: plan, payg, mixed or "" when unknown
// (provider.BillingKind; EV_John_Liu on X)
Billing string `json:"billing,omitempty"`
BillingKind string `json:"billingKind,omitempty"`
// a provider the user added whose own HTTPS host's certificate is
// taken as it is (provider.InsecureTLS, #2383); TakesInsecureTLS: it
// may be, being the user's own and not a preset's or a sign-in's
@@ -817,7 +822,7 @@ func providerInfoWith(p provider.Provider, ls provider.Listing, agents []agentUs
ID: p.ID, Name: p.Name, Icon: p.Icon, IconFrom: p.IconFrom, Preset: p.Preset, Host: p.Host(),
Chat: p.Chat, Responses: p.Responses, Anthropic: p.Anthropic, Gemini: p.Gemini, Decide: p.Decide, BaseAPI: p.BaseAPI, ModelTest: p.ModelTest(), TestsAs: p.TestClients(), DecideTest: p.AsksDecideModels(), MarksKinds: p.MarksKinds(),
Catalog: p.Catalog, Website: p.Website, KeysURL: p.KeysURL,
Proxy: p.Proxy, AccountProxies: p.AccountProxies, AccountModels: p.AccountModels, AccountCaps: p.AccountCaps, AccountWindowCaps: p.AccountWindowCaps, AccountWindowAmounts: p.AccountWindowAmounts, AccountNames: p.AccountNames, Headers: p.Headers, ExtraBody: p.ExtraBody, ReplyHeaders: p.ReplyHeaders, PassHeaders: p.PassHeaders, Searches: p.Searches, Cline: p.ClinePinnable(), PinUpstream: p.PinUpstream, Unredacted: p.Unredacted, CountFree: p.CountFree, InsecureTLS: p.InsecureTLS, TakesInsecureTLS: p.TakesInsecureTLS(), HTTP1: p.HTTP1, ClientCert: tilde(p.ClientCert), ClientKey: tilde(p.ClientKey), ServerCA: tilde(p.ServerCA), TakesClientCert: p.TakesClientCert(), Socket: p.Socket, TakesSocket: p.TakesSocket(), LimitRestOff: p.LimitRestOff, ImageFilesOff: p.ImageFilesOff, TakesImageFiles: p.TakesImageFiles(), NativeCompaction: p.NativeCompaction, CarriesCompaction: p.CarriesCompaction(), PassUserAgent: !p.MagpieUserAgent, OwnClient: p.OwnClient(), PassErrors: p.PassErrors, TakesPassErrors: p.TakesPassErrors(), AuthHeader: p.AuthHeader, BothAuth: p.BothAuth(), BalanceURL: p.BalanceURL, BalancePath: p.BalancePath, BalanceMethod: p.BalanceMethod, ModelsURL: p.ModelsURL, ListOff: p.ListsOff(), TakesListOff: p.Account == nil && !p.IsPlugin() && !p.DecideOnly(), TakesModelHeaders: p.Account == nil, DecideAPIKind: p.DecideAPIKind(),
Proxy: p.Proxy, AccountProxies: p.AccountProxies, AccountModels: p.AccountModels, AccountCaps: p.AccountCaps, AccountWindowCaps: p.AccountWindowCaps, AccountWindowAmounts: p.AccountWindowAmounts, AccountNames: p.AccountNames, Headers: p.Headers, ExtraBody: p.ExtraBody, ReplyHeaders: p.ReplyHeaders, PassHeaders: p.PassHeaders, Searches: p.Searches, Cline: p.ClinePinnable(), PinUpstream: p.PinUpstream, Unredacted: p.Unredacted, CountFree: p.CountFree, Billing: p.Billing, BillingKind: p.BillingKind(), InsecureTLS: p.InsecureTLS, TakesInsecureTLS: p.TakesInsecureTLS(), HTTP1: p.HTTP1, ClientCert: tilde(p.ClientCert), ClientKey: tilde(p.ClientKey), ServerCA: tilde(p.ServerCA), TakesClientCert: p.TakesClientCert(), Socket: p.Socket, TakesSocket: p.TakesSocket(), LimitRestOff: p.LimitRestOff, ImageFilesOff: p.ImageFilesOff, TakesImageFiles: p.TakesImageFiles(), NativeCompaction: p.NativeCompaction, CarriesCompaction: p.CarriesCompaction(), PassUserAgent: !p.MagpieUserAgent, OwnClient: p.OwnClient(), PassErrors: p.PassErrors, TakesPassErrors: p.TakesPassErrors(), AuthHeader: p.AuthHeader, BothAuth: p.BothAuth(), BalanceURL: p.BalanceURL, BalancePath: p.BalancePath, BalanceMethod: p.BalanceMethod, ModelsURL: p.ModelsURL, ListOff: p.ListsOff(), TakesListOff: p.Account == nil && !p.IsPlugin() && !p.DecideOnly(), TakesModelHeaders: p.Account == nil, DecideAPIKind: p.DecideAPIKind(),
Ready: p.Ready(), Chosen: p.PicksOf(avail), Agents: make([]providerAgent, 0, len(agents)),
Fallback: p.Fallback, Routing: p.Routing, Sink: p.Sink, UseFirst: p.UseFirst, Affinity: p.Affinity, KeepLogin: p.KeepLogin, KeepLoginAs: p.KeepLoginAs, SwitchOnly: p.SwitchOnly, RestartApp: p.RestartApp, Self: p.SelfAnswered(), KeepSelf: p.KeepSelf, CapStop: p.CapStop, CapCareful: p.CapCareful, Unlisted: p.Unlisted, NoModels: p.ServesNone(), BestInFamily: p.BestInFamily && len(p.Models) == 0 && !p.NoModels, Off: p.Off, Contexts: p.Contexts,
MaxConcurrency: p.MaxConcurrency, PluginConcurrency: p.PluginConcurrency(), MaxAccounts: p.MaxAccounts, PluginAccounts: p.PluginAtOnce(), PriceRate: p.PriceRate,
@@ -1798,6 +1803,10 @@ func providerRoutes(mux *http.ServeMux, w Windows) {
return
}
in := req.Provider
if !provider.BillingOK(in.Billing) {
fail(rw, fmt.Errorf("billing is plan, payg or empty, not %q", in.Billing))
return
}
if req.NoModels != nil {
in.NoModels = *req.NoModels
}
@@ -1912,6 +1921,7 @@ func providerRoutes(mux *http.ServeMux, w Windows) {
pr.PinUpstream = in.PinUpstream
pr.Unredacted = in.Unredacted
pr.CountFree = in.CountFree
pr.Billing = in.Billing
pr.NativeCompaction = in.NativeCompaction
pr.MagpieUserAgent = in.MagpieUserAgent
pr.AuthHeader = in.AuthHeader
@@ -0,0 +1,172 @@
// Run with Node's test runner and Playwright on the module path; see README.md.
// A provider on a plan and one paid as used are told apart (EV_John_Liu
// on X): a quiet grey badge on its Providers row (Plan, Pay as you go, or
// both for keys on each), none where magpie can't tell; the editor's
// Billing under Advanced sets it by the user's word, Auto handing it back;
// and a routing group's card sums up its members' billing, each member's
// on hover. In every language, in both engines, wide and narrow.
const assert = require("node:assert/strict");
const fs = require("node:fs/promises");
const path = require("node:path");
const { test } = require("node:test");
const { chromium, webkit } = require("playwright");
const assets = path.resolve(__dirname, "../assets");
const base = {
icon: "generic", chat: "", responses: "", anthropic: "", catalog: "",
models: [{ id: "m", name: "M", on: true }], agents: [], fallback: [], headers: {},
key: { set: true, masked: "sk-…1234" }, keyList: [], balanceToken: { takes: false, set: false }, proxy: "", searches: false, unredacted: false,
};
const glm = { ...base, id: "zhipu", name: "Zhipu GLM", preset: "zhipu", chat: "https://open.bigmodel.cn/api/coding/paas/v4", billingKind: "plan" };
const relay = { ...base, id: "relay", name: "Some Relay", chat: "https://relay.example.com/v1", billingKind: "payg", billing: "payg" };
const volc = { ...base, id: "volc", name: "Volcengine", preset: "volcengine", chat: "https://ark.cn-beijing.volces.com/api/coding/v3", billingKind: "mixed" };
const own = { ...base, id: "own", name: "Own Server", chat: "http://192.168.1.5:8000/v1" };
const models = [
{ id: "zhipu/glm-5", name: "glm-5", providerName: "Zhipu GLM", icon: "generic" },
{ id: "relay/glm-5", name: "glm-5", providerName: "Some Relay", icon: "generic" },
{ id: "own/glm-5", name: "glm-5", providerName: "Own Server", icon: "generic" },
];
const member = (id, name, billing) => ({ id, ready: true, provider: id.split("/")[0], name, model: "glm-5", on: 1, ...(billing ? { billing } : {}) });
const groups = [
{ id: "both", name: "Both", members: ["zhipu/glm-5", "relay/glm-5"], ready: true, memberInfo: [member("zhipu/glm-5", "Zhipu GLM", "plan"), member("relay/glm-5", "Some Relay", "payg")] },
{ id: "plans", name: "Plans", members: ["zhipu/glm-5"], ready: true, memberInfo: [member("zhipu/glm-5", "Zhipu GLM", "plan")] },
{ id: "unsure", name: "Unsure", members: ["zhipu/glm-5", "own/glm-5"], ready: true, memberInfo: [member("zhipu/glm-5", "Zhipu GLM", "plan"), member("own/glm-5", "Own Server", "")] },
];
function serve(lang, posts) {
const providers = { providers: [glm, relay, volc, own], presets: [], excluded: [], gateway: { running: true, window: true, url: "http://127.0.0.1:3999" } };
const state = { agents: [], profiles: [], settings: { lang, theme: "light" } };
return async (route) => {
const url = new URL(route.request().url());
const json = (data) => route.fulfill({ json: data });
if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:true};` });
if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" });
if (url.pathname === "/api/state") return json(state);
if (url.pathname === "/api/plugins") return json({ plugins: [] });
if (url.pathname === "/api/providers") return json(providers);
if (url.pathname === "/api/gateway/trace") {
if (url.searchParams.get("wait")) return new Promise(() => {});
return json({ mine: true, now: new Date().toISOString(), seq: 1, totals: { requests: 0, rerouted: 0, errors: 0 }, routes: [] });
}
if (url.pathname === "/api/gateway/history") return json({ cut: false, days: [], routes: [] });
if (url.pathname === "/api/groups") return json({ models, pools: [], deciders: [], found: true, groups });
if (url.pathname.startsWith("/api/provider/") && route.request().method() === "POST") {
posts.push({ action: url.pathname.slice("/api/provider/".length), body: route.request().postDataJSON() });
return json(providers);
}
if (url.pathname.startsWith("/api/")) return json({});
const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname);
const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)];
const body = await fs.readFile(file).catch(() => null);
if (!body) return route.fulfill({ status: 404, body: "" });
await route.fulfill({ body, contentType });
};
}
const STRINGS = ["Billing", "Plan", "Pay as you go", "Plan + pay as you go", "Auto"];
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
for (const lang of ["en", "zh", "zh-TW", "ja", "de"]) {
for (const width of [900, 440]) {
const open = async (t, view, name) => {
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
let page;
t.after(async () => {
if (process.env.ARTIFACT_DIR && page) {
await fs.mkdir(process.env.ARTIFACT_DIR, { recursive: true });
await page.screenshot({ path: path.join(process.env.ARTIFACT_DIR, `${engine}-${lang}-${width}-${name}-billing.png`), fullPage: true });
}
await browser.close();
});
page = await (await browser.newContext({ viewport: { width, height: 760 }, reducedMotion: "reduce" })).newPage();
page.setDefaultTimeout(5000);
page.setDefaultNavigationTimeout(60000);
const errors = [], posts = [];
page.on("pageerror", (e) => errors.push(e.message));
await page.route("**/*", serve(lang, posts));
await page.goto(`http://magpie.test/?view=${view}`);
const w = await page.evaluate((ks) => Object.fromEntries(ks.map((k) => [k, t(k)])), STRINGS);
return { page, errors, posts, w };
};
const badge = (page, name) => page.locator(".row.provider", { hasText: name }).locator(".name .badge.bill");
const adv = (page) => page.locator(".editor details.advanced");
const seg = (page) => page.locator(".editor .segs.billing");
const save = async (page, posts) => {
const n = posts.length;
const label = await page.evaluate(() => t("Save"));
await page.locator(".editor .bar").getByRole("button", { name: label, exact: true }).click();
for (let i = 0; i < 50 && posts.length === n; i++) await page.waitForTimeout(50);
return posts.at(-1);
};
test(`${engine} ${lang} ${width}: each provider says how it bills, quietly`, async (t) => {
const { page, errors, posts, w } = await open(t, "providers", "rows");
await page.locator(".row.provider", { hasText: "Zhipu GLM" }).waitFor();
assert.equal(await badge(page, "Zhipu GLM").textContent(), w["Plan"]);
assert.equal(await badge(page, "Some Relay").textContent(), w["Pay as you go"]);
assert.equal(await badge(page, "Volcengine").textContent(), w["Plan + pay as you go"]);
assert.equal(await badge(page, "Own Server").count(), 0, "no badge where magpie can't tell");
// grey, not an accent: the muted colour on the pill
const look = await badge(page, "Zhipu GLM").evaluate((b) => {
const s = getComputedStyle(b), probe = document.createElement("span");
probe.style.color = "var(--muted)";
document.body.append(probe);
const muted = getComputedStyle(probe).color;
probe.remove();
return { color: s.color, muted, image: s.backgroundImage };
});
assert.equal(look.color, look.muted);
assert.equal(look.image, "none");
assert.equal(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth), true, "no sideways scroll");
if (lang !== "en") {
const missing = await page.evaluate(([l, ks]) => ks.filter((k) => !I18N[l][k]), [lang, STRINGS]);
assert.deepEqual(missing, [], `every string has its ${lang}`);
}
assert.deepEqual(posts, []);
assert.deepEqual(errors, []);
});
test(`${engine} ${lang} ${width}: Billing is set in the editor, and Auto hands it back`, async (t) => {
const { page, errors, posts, w } = await open(t, "providers", "editor");
await page.locator(".row.provider", { hasText: "Own Server" }).click();
await page.locator(".editor .bar").waitFor();
assert.equal(await adv(page).evaluate((d) => d.open), false, "nothing set opens Advanced");
await adv(page).locator(":scope > summary").click();
await seg(page).scrollIntoViewIfNeeded();
assert.equal(await seg(page).locator(".opt.on").textContent(), w["Auto"]);
await seg(page).getByRole("button", { name: w["Plan"], exact: true }).click();
let saved = await save(page, posts);
assert.equal(saved.action, "save");
assert.equal(saved.body.id, "own");
assert.equal(saved.body.billing, "plan");
await page.locator(".row.provider", { hasText: "Some Relay" }).click();
await page.locator(".editor .bar").waitFor();
await page.waitForFunction(() => document.querySelector(".editor details.advanced")?.open);
await seg(page).scrollIntoViewIfNeeded();
assert.equal(await seg(page).locator(".opt.on").textContent(), w["Pay as you go"], "opens as saved");
const r = await seg(page).boundingBox();
assert.ok(r && r.x >= 0 && r.x + r.width <= width, `fits: ${JSON.stringify(r)}`);
await seg(page).getByRole("button", { name: w["Auto"], exact: true }).click();
saved = await save(page, posts);
assert.equal(saved.body.id, "relay");
assert.equal(saved.body.billing, "");
assert.deepEqual(errors, []);
});
if (width === 900) test(`${engine} ${lang}: a routing group sums up its members' billing`, async (t) => {
const { page, errors, w } = await open(t, "groups", "routing");
const card = (name) => page.locator(".rt-groups .rt-group", { hasText: name });
await card("Both").waitFor();
const tag = (name) => card(name).locator(".tag.bill");
assert.equal(await tag("Both").textContent(), w["Plan + pay as you go"]);
const title = await tag("Both").getAttribute("title");
assert.ok(title.includes(w["Plan"]) && title.includes(w["Pay as you go"]), title);
assert.equal(await tag("Plans").textContent(), w["Plan"]);
assert.equal(await tag("Unsure").count(), 0, "one member unknown: said nowhere");
assert.deepEqual(errors, []);
});
}
}
}
+111
View File
@@ -0,0 +1,111 @@
package provider
import "strings"
// How a provider bills (EV_John_Liu on X: mark pay as you go apart from a
// token plan on Providers and Routing): on a plan, a subscription or
// token package paid ahead, or pay as you go, each call billed as used.
// The Providers list and a routing group's card say it. The user's word
// (Provider.Billing) stands; else it is read from what magpie knows of
// the provider: a signed-in account is a plan, a preset's plan or pay as
// you go endpoints (its Regions) say theirs, a key of a vendor or relay
// is pay as you go. A provider added by its address, a local server or
// another magpie says nothing until the user sets it.
const (
BillingPlan = "plan"
BillingPAYG = "payg"
BillingMixed = "mixed" // its keys are on a plan and on pay as you go
)
// BillingOK reports whether s is a billing the user may set: plan, pay
// as you go, or "" for magpie to read it.
func BillingOK(s string) bool { return s == "" || s == BillingPlan || s == BillingPAYG }
// planPresets are presets whose keys are a plan's alone, with no pay as
// you go endpoints of their own to tell them apart by.
var planPresets = map[string]bool{
"kimi-code": true, "kimi-code-cn": true,
"qwen-token-plan": true, "bailian-token-plan": true, "qwencloud-token-plan": true,
"opencode-go": true, "clinepass": true,
}
// unsaidPresets are vendors and relays whose one endpoint takes a plan's
// keys and pay as you go's alike, or that are free, so magpie can't say
// which a key is (MiniMax's Coding Plan keys, ModelScope's daily quota),
// and decision models, which bill as their own provider does.
var unsaidPresets = map[string]bool{
"minimax": true, "minimax-cn": true, "ollama-cloud": true, "modelscope": true,
"nvidia": true, "longcat": true, "commandcode": true,
"typesafe": true, "vercel-jev": true, "cloudflare-jev": true,
"bailian-decision": true, "qwen-decision": true, "volcengine-decision": true,
}
// regionBilling is what a preset's region's name says of its billing:
// "Pay as you go …" or "… Plan …"; "" for one named by place.
func regionBilling(r *Region) string {
if r == nil {
return ""
}
n := strings.ToLower(r.Name)
switch {
case strings.HasPrefix(n, "pay as you go"):
return BillingPAYG
case strings.Contains(n, "plan"):
return BillingPlan
}
return ""
}
// BillingKind is how p bills: the user's word, else what magpie reads of
// it (BillingPlan, BillingPAYG, BillingMixed), "" when it can't say.
func (p Provider) BillingKind() string {
if p.Billing != "" {
return p.Billing
}
if p.Account != nil {
return BillingPlan
}
pr := Preset(p.Preset)
if pr == nil || unsaidPresets[pr.ID] || strings.HasSuffix(pr.ID, "-decision") || (pr.Kind != KindVendor && pr.Kind != KindRelay) {
return ""
}
if planPresets[pr.ID] {
return BillingPlan
}
// the region the provider sits at: a plan or pay as you go by its
// name, the vendor's API (billed as used) when named by place; one
// asked at none of its regions' endpoints can't be told
own := BillingPAYG
if len(pr.Regions) > 0 {
r := p.regionOf(pr)
if r == nil {
return ""
}
if b := regionBilling(r); b != "" {
own = b
}
}
// keys on another plan than the provider's (KeyAccount.Plan)
if p.plansMixed() {
for _, plan := range append([]string{p.KeyPlan}, keyPlans(p)...) {
if _, r, _ := p.keyRegion(plan); r != nil {
if b := regionBilling(r); b != "" && b != own {
return BillingMixed
}
}
}
}
return own
}
// keyPlans are the plans p's other keys in use say they are for.
func keyPlans(p Provider) []string {
var out []string
for _, k := range p.Keys {
if k.Off || k.Key == "" || k.Key == p.Key || k.Plan == "" {
continue
}
out = append(out, k.Plan)
}
return out
}
+109
View File
@@ -0,0 +1,109 @@
package provider
import (
"strings"
"testing"
)
// billAt is a provider of preset id sitting at its region rid's endpoints.
func billAt(t *testing.T, id, rid string) Provider {
t.Helper()
pr := Preset(id)
if pr == nil {
t.Fatalf("no preset %s", id)
}
p := Provider{ID: id, Name: pr.Name, Preset: id, Chat: pr.Chat, Responses: pr.Responses, Anthropic: pr.Anthropic, Key: "k"}
for _, r := range pr.Regions {
if r.ID == rid {
p.Chat, p.Responses, p.Anthropic = r.Chat, r.Responses, r.Anthropic
return p
}
}
if rid != "" {
t.Fatalf("%s has no region %s", id, rid)
}
return p
}
// A provider says whether it is on a plan or pay as you go (EV_John_Liu
// on X): by the endpoints it sits at, a signed-in account, a plan's own
// preset, or the user's word, which stands.
func TestBillingKind(t *testing.T) {
cases := []struct {
name string
p Provider
want string
}{
{"GLM Coding Plan", billAt(t, "zhipu", "coding"), BillingPlan},
{"GLM pay as you go", billAt(t, "zhipu", "api"), BillingPAYG},
{"Step Plan", billAt(t, "stepfun", "plan"), BillingPlan},
{"Kimi Code", billAt(t, "kimi-code", ""), BillingPlan},
{"OpenRouter", billAt(t, "openrouter", ""), BillingPAYG},
{"DeepSeek", billAt(t, "deepseek", ""), BillingPAYG},
{"MiniMax: one endpoint for both", billAt(t, "minimax", ""), ""},
{"Ollama on this computer", billAt(t, "ollama", ""), ""},
{"added by its address", Provider{ID: "x", Name: "X", Chat: "https://x.example/v1", Key: "k"}, ""},
{"signed-in account", Provider{ID: "codex", Name: "Codex", Account: &Account{}}, BillingPlan},
{"user says pay as you go", func() Provider { p := billAt(t, "zhipu", "coding"); p.Billing = BillingPAYG; return p }(), BillingPAYG},
{"user says plan of a relay", func() Provider { p := billAt(t, "openrouter", ""); p.Billing = BillingPlan; return p }(), BillingPlan},
{"user's word on an unknown one", Provider{ID: "x", Name: "X", Chat: "https://x.example/v1", Billing: BillingPlan}, BillingPlan},
}
for _, c := range cases {
if got := c.p.BillingKind(); got != c.want {
t.Errorf("%s: BillingKind = %q, want %q", c.name, got, c.want)
}
}
}
// Volcengine at its Coding Plan with a pay-as-you-go key beside (yckonnnn
// on X) is both; with only another plan's key, a plan still.
func TestBillingKindMixedKeys(t *testing.T) {
if got := volcMixed().BillingKind(); got != BillingMixed {
t.Fatalf("coding plan + pay-as-you-go key: %q, want mixed", got)
}
p := volcMixed()
p.Keys = []KeyAccount{{Key: "k-agent", Plan: "agent"}}
if got := p.BillingKind(); got != BillingPlan {
t.Fatalf("coding + agent plan keys: %q, want plan", got)
}
p.Keys = []KeyAccount{{Key: "k-api", Plan: "api", Off: true}}
if got := p.BillingKind(); got != BillingPlan {
t.Fatalf("pay-as-you-go key switched off: %q, want plan", got)
}
}
// Every preset region named as a plan or as pay as you go reads so at its
// own endpoints, and the lists name presets that exist.
func TestBillingEveryRegion(t *testing.T) {
for id := range planPresets {
if Preset(id) == nil {
t.Errorf("planPresets names no preset %s", id)
}
}
for id := range unsaidPresets {
if Preset(id) == nil {
t.Errorf("unsaidPresets names no preset %s", id)
}
}
for _, pr := range Presets() {
if unsaidPresets[pr.ID] || strings.HasSuffix(pr.ID, "-decision") || (pr.Kind != KindVendor && pr.Kind != KindRelay) {
continue
}
for _, r := range pr.Regions {
p := billAt(t, pr.ID, r.ID)
if p.regionOf(&pr) == nil || p.regionOf(&pr).ID != r.ID {
continue // two regions at one endpoint: told apart elsewhere
}
want := regionBilling(&r)
if want == "" {
want = BillingPAYG
}
if planPresets[pr.ID] {
want = BillingPlan
}
if got := p.BillingKind(); got != want {
t.Errorf("%s at %s (%q): %q, want %q", pr.ID, r.ID, r.Name, got, want)
}
}
}
}
+9
View File
@@ -272,6 +272,10 @@ type Provider struct {
// weighs it at nothing). Prices and the costs Usage counts stay as
// listed: it says what to spend first, not what a call cost.
CountFree bool `json:"countFree,omitempty"`
// Billing is the user's word on how the provider bills: BillingPlan
// or BillingPAYG (EV_John_Liu on X); "" has magpie read it
// (BillingKind). It only marks the provider on Providers and Routing.
Billing string `json:"billing,omitempty"`
// RateWindows are the time-of-day windows it bills at its own rate
// (#2463): a peak at 2× or 3×, a discount off peak. The first window
// that holds a call's time multiplies the price again, on top of
@@ -1077,6 +1081,8 @@ func accountSettings(a, pk Provider) Provider {
a.PriceRate = pk.PriceRate
// counted free by the user's word, every account alike
a.CountFree = pk.CountFree
// and how it bills, by the user's word (BillingKind)
a.Billing = pk.Billing
// the hours the provider bills at its own rate (#2463), as the editor
// keeps them for the account like the rest of these
a.RateWindows = pk.RateWindows
@@ -1507,6 +1513,9 @@ func AddCopy(p Provider, from string) (string, error) {
p.Searches = p.Searches || src.Searches
p.Unredacted = p.Unredacted || src.Unredacted
p.CountFree = p.CountFree || src.CountFree
if p.Billing == "" {
p.Billing = src.Billing
}
p.NativeCompaction = p.NativeCompaction || src.NativeCompaction
if p.Socket == "" {
p.Socket = src.Socket