Skip to content

Every agent's model. One place. Codex on DeepSeek, Claude Code on Kimi, from the menu bar.

routing, usage: an account renamed in magpie reads by its new name (magpie-community/plugins#310, molvqingtai)

yetone4f6498f8221f
diff --git a/docs/subsystems/providers-accounts.md b/docs/subsystems/providers-accounts.md
index 7b307776f..b611e95b7 100644
--- a/docs/subsystems/providers-accounts.md
+++ b/docs/subsystems/providers-accounts.md
@@ -48,7 +48,7 @@ keys and accounts per request is in [Gateway routing and fallback](gateway-routi
| A membership's $0 catalog | models.dev lists every model of Kimi Code's plans (`kimi-code-plan-global`, `kimi-code-plan-cn`) and of Xiaomi MiMo's Token Plans (`xiaomi-token-plan-cn`, `-sgp`, `-ams`) at $0: what the membership charges per token, not what the model costs. `membershipCatalogs` are never read for a price (`priceCatalogs`, `makerPriceCatalogs`), so a Xiaomi MiMo model is priced at `xiaomi`'s list price at every region, and each region of the preset names its own catalog, pay as you go `xiaomi` alone (#1873). A Kimi Code provider's model is priced at the Kimi API model it is (`kimiCodeAPI`, from Kimi Code's docs: k3 and k3-256k are kimi-k3, kimi-for-coding-highspeed is kimi-k2.7-code-highspeed), and kimi-for-coding (K2.8 Preview, not on the API) is unpriced rather than free (#1370). The alias is Kimi Code's alone (`kimiCodePlans`): a relay's own `k3` keeps its own price. A catalog other than these that lists a model at $0 still prices it at $0: models.dev has truly free models (nvidia, modelscope). The Requests list names the API model it was priced as (`PricedNameFor`). | [`models.go`](../../internal/provider/models.go) |
| A plugin's own price | A model no catalog prices (models.dev has no vendor's own model: Devin's SWE-2 and SWE-1.7 Lightning, Cursor's auto, Qoder's efficient) is priced at what its plugin lists it at (`ListPrice` → `pluginListPrice`, `plugin.Model.Cost`, read by `pluginPrice`: an input or output above 0, OpenCode's 0 being none), else at $0 when the plugin says the plan serves it free (`pluginFree`, `plugin.Model.Free`: Devin's Free cost tier, Qoder's and WorkBuddy's x0). Both come after every catalog, so a price a catalog gives is kept over the plugin's. Devin's plugin (0.1.18) lists each paid model at the price Devin's GetCliModelConfigs gives it (input, cached input and output per 1M tokens); a moved Devin user's calls on Devin's own models had no cost on Usage before (太陽と向日葵 on Discord, `TestPluginFreeModelCostsNothing`). A plugin that gives no price and doesn't say free leaves the model unpriced. | [`models.go`](../../internal/provider/models.go), [`plugins.go`](../../internal/provider/plugins.go), [`providers.go`](../../internal/plugin/providers.go) |
| A key's own windows | A sub2api key given a spending limit per 5 hours, day or 7 days answers its `/v1/usage` with `rate_limits` and no `remaining` (`readSub2APIKeyLimits`). With the Balance URL set to it, the key's card shows them as the windows *5 hours*, *1 day*, *7 days*, in USD, beside a balance field the user wrote; *Check balance* and `magpie provider show` give what its fullest window has left (`Balance`). A Balance URL at an account query left without its token (a sub2api panel's `/api/v1/user/profile`, new-api's `/api/user/self`, after the token was removed) asks the same panel's query for the key instead, the saved URL untouched (`keyQueryOf`, `BalanceQuery`), unless the user's Headers carry an Authorization or Cookie of their own. A Balance URL of the user's own is asked with GET, or with POST and no body when the provider's `BalanceMethod` says so (#2368: an endpoint that answers only a POST; the editor's GET/POST beside the URL, `balance.method=` on the command line); any other method is refused before anything is sent (`balanceMethodOf`). `KeyAllowance` gives routing the same windows: never waited for, read in the background at most once a minute, a failed read keeping the last, and seeded from the card's last reading (`quotas.json`) after a restart. A key bought as a plan (Kimi Code, GLM Coding Plan and Z.ai, MiniMax Coding Plan, OpenCode Go, Command Code, Ollama Cloud: `planQuotaSourceOf`) gives routing its card's windows the same way (`planKeyWindows`, Zhipu's team quota behind a key with none of its own); the Usage page's read of its card is taken at once (`noteKeyAllowance`), and a key there that turns out pay-as-you-go, with no windows, is asked again only every 30 minutes (`keyNoWindowsAge`). A Command Code plan's key has its month of credits as a *Credits* window beside the 5-hour and weekly ones, as the signed-in subscription's card has (`cmdKeyWindows`, #2451): billing/credits leaves the plan out, so it is the key's billing/subscriptions plan, asked at most every ten minutes and the last one kept while it can't be read; a key whose plan was never read has its two windows alone. Ollama Cloud's `ollama.com/api/balance` (#1888, `readOllamaPlan`) tells the plan's included allowance as one window in USD, *Month* when its period is a month long, renewing at `period.until`, and Aside while credits bought on top are left; those credits are the key's balance card (`readOllamaCredits`), and a reply that names none has no balance card rather than $0. StepFun's Step Plan is read through a platform sign-in, not the key, and isn't one of them: the sign-in is the provider's own, kept by provider id in `stepfun-auth.json` (two StepFun providers on one site can be two accounts, #2384), one card per signed-in provider; a file from before that, kept by site, is given on read to the StepFun providers on that site (`stepfunBySite`), and copies of one sign-in are renewed together. Nor are Volcengine Ark's Coding Plan and Agent Plan (#1427): their 5-hour, weekly and monthly windows are told only to the account's access key (`AccessKeyID`, `SecretAccessKey`), asked of `open.volcengineapi.com` (`GetCodingPlanUsage`, `GetAFPUsage`) and signed as Volcengine's own SDK signs (`volcSign`), so they are cards on the Usage page (`volcPlanQuotas` in `PlanQuotas`), never routing's windows. Nor is Tencent Cloud's Token Plan 企业版 (#1574): what a team plan has used of its cycle's credits (专业套餐) or tokens (轻享套餐) is told only to the account's SecretId and SecretKey (kept as `AccessKeyID`, `SecretAccessKey`), asked of `tokenhub.tencentcloudapi.com` (`DescribeTokenPlanList`, `DescribeTokenPlan`, version 2026-03-22) and signed TC3-HMAC-SHA256 (`tc3Sign`), one card per team plan (`tencentPlanQuotas`). | [`sub2api_usage.go`](../../internal/provider/sub2api_usage.go), [`key_allowance.go`](../../internal/provider/key_allowance.go), [`volcengine_usage.go`](../../internal/provider/volcengine_usage.go), [`tencent_usage.go`](../../internal/provider/tencent_usage.go) |
-| Account names and seats | `AccountNames` (by the account, in lower case, like `AccountCaps`) are names the user gives accounts, set by `SetAccountName` (GUI `provider/accountname`, `magpie accounts alias`); they live in providers.json only, never in a vendor's or plugin's sign-in. A GLM Coding Plan read with a key (`glmPlan`) and a ZCode account (built-in or `zcode-plugin`) whose windows' resets agree are one seat (`seatMatch`, #90/#953), shown once, on the account's card (`seatCards`, used by `quotas`, `Allotted` and `CachedCards`). A match is remembered in `seats.json` beside `quotas.json`: a failed read or a window with no reset yet is unknown and keeps the key's card off while the account is signed in; windows that disagree forget it (#1515). Cards carry `Seat` (the key provider's name, and the key's when it has several) and `Alias` (the user's name, else `Seat`), as `/v1/magpie/quotas`, `magpie quota` and `magpie accounts` do. | [`account_names.go`](../../internal/provider/account_names.go), [`account_seats.go`](../../internal/provider/account_seats.go) |
+| Account names and seats | `AccountNames` (by the account, in lower case, like `AccountCaps`) are names the user gives accounts, set by `SetAccountName` (GUI `provider/accountname`, `magpie accounts alias`); they live in providers.json only, never in a vendor's or plugin's sign-in. A GLM Coding Plan read with a key (`glmPlan`) and a ZCode account (built-in or `zcode-plugin`) whose windows' resets agree are one seat (`seatMatch`, #90/#953), shown once, on the account's card (`seatCards`, used by `quotas`, `Allotted` and `CachedCards`). A match is remembered in `seats.json` beside `quotas.json`: a failed read or a window with no reset yet is unknown and keeps the key's card off while the account is signed in; windows that disagree forget it (#1515). Cards carry `Seat` (the key provider's name, and the key's when it has several) and `Alias` (the user's name, else `Seat`), as `/v1/magpie/quotas`, `magpie quota` and `magpie accounts` do. Records (a trace's `who`, usage's `ProviderAccount`) keep the vendor's name, the key the user's name is kept by, and every list of them looks the name up as it is shown (`AccountShown`, `AccountShownOf`, `AccountRef.Shown`), so a request from before a rename reads by the new name too: the Routing page's accounts and requests (`userShown` in `plugins/routing/client.js`, from `/api/providers`' `accountNames`), its Several accounts pools (`onOf`), the Usage page's Accounts and the request log's Account filter (`usageapi`), `magpie usage`, and a gateway key's accounts (`AccountNames`, `/api/caller-keys`). Before plugins#310 (a renamed Kiro account read by its old name on every request after) those showed the vendor's name. | [`account_names.go`](../../internal/provider/account_names.go), [`account_seats.go`](../../internal/provider/account_seats.go) |
| Last served | `served.json` records when each account, plan or key last answered, shown as `lastServedAt` (#570) on `/v1/magpie/quotas` and on the Usage page's own cards (`Quotas` → `cardsServed`, this computer's cards only, the caches left alone). The Usage page and the tray panel show the last-answered account in full, and a menu bar card that follows the account in use (`codex|*`) takes the one that answered within the last hour, else `InUseLogin`'s guess, else the one that answered last at all (a plugin's accounts, #1516) (`trayInUseCard`; okingkee on X: A spent, B answering, the menu bar stayed on A). `NoteServed` calls `OnServedMoved` when a provider's answers move to another account or key, and `SwitchLogin` after a switch, so the menu bar reads its cards again at once. | [`served.go`](../../internal/provider/served.go), [`trayusage.go`](../../internal/gui/trayusage.go) |
| Partners | Services that pay to be listed first in the add sheet, under a heading of their own ("Partners · magpie's sponsors"). The list is `site/partners.js`, served at `usemagpie.ai/api/partners`: a change reaches users with a deploy, not a release. `Partners` never waits: it returns what was fetched last and fetches again behind the call every 6 hours (10 minutes after a failure), keeping the list in `partners.json` in the cache folder. Each entry is checked again on every read (`validPartners`): its own id, never a built-in preset's, a name, an endpoint, https only, at most 12; what only magpie's presets may set (a decision API, no key, a user endpoint) is cleared. Its logo is fetched through `FetchIcon` and kept as an uploaded icon. A partner is a preset to the rest of magpie (`Preset`, `FromPreset`, the editor), and one no longer listed still is to the providers added from it (`Seen`), without the sponsored mark. The window lists a partner in the languages it names (`langs`) only and shows its tagline in the page's language (`notes`, else `en`). `MAGPIE_PARTNERS` points it elsewhere, `off` lists none; tests list none unless they name a list. How often each listed partner was shown, opened (its row, its key page) and added is counted per UTC day (`CountPartner`, capped at 20 of each and 5 adds, kept in `partner-counts.json` in the cache folder) and sent with the next day's stats event as `magpie partner` events (`internal/stats`); nothing is counted with the stats or their usage part off. A listed partner the add sheet (or the TUI's, or `magpie providers presets`) hasn't shown yet is new (`NoticePartners` keeps those shown, as `noticed` in `partners.json`, whatever the stats); the window's add button carries a small dot for it, with its name in the title, until the sheet shows it. | [`partners.go`](../../internal/provider/partners.go), [`partner_events.go`](../../internal/provider/partner_events.go), [`site/partners.js`](../../site/partners.js) |
| Local servers | A preset of `KindLocal` (Ollama, LM Studio, oMLX, MLX-Serve) is at its server's default port on this machine. Another address — a port, or another computer — is given in the window's editor, under Server address, or in the TUI (asked on adding, `w` after); on the command line the URLs themselves (`url=`, `anthropic=`, `responses=`). `AtAddress` replaces only each URL's scheme, host and port, each API keeping its path; `AddressOf` is the address an editor starts from. The window sends the URLs moved only when the address was changed, so a Save doesn't move URLs set apart (another app's import). A provider of the user's own (no preset) has `w` in the TUI too: each base URL it has is asked in turn, typed in as it is, Enter alone keeping one (`customURLsAsk`). | [`local_address.go`](../../internal/provider/local_address.go) |
diff --git a/internal/cli/usage_cli.go b/internal/cli/usage_cli.go
index e0448f6ab..19fbe6718 100644
--- a/internal/cli/usage_cli.go
+++ b/internal/cli/usage_cli.go
@@ -13,6 +13,7 @@ import (
"github.com/yetone/magpie/internal/agent"
"github.com/yetone/magpie/internal/fx"
+ pr "github.com/yetone/magpie/internal/provider"
"github.com/yetone/magpie/internal/settings"
stats "github.com/yetone/magpie/internal/usage"
)
@@ -254,7 +255,8 @@ func printUsage(out io.Writer, s stats.Summary, title string, names map[string]s
}
if len(s.Accounts) > 0 {
table("accounts", s.Accounts, func(g stats.Group) string {
- who := g.Account
+ // by the name the user gave it now (plugins#310)
+ who := pr.AccountShownOf(g.Provider, g.Account)
if who == "" {
who = "account not recorded"
}
diff --git a/internal/gui/assets/plugins/routing/client.js b/internal/gui/assets/plugins/routing/client.js
index b14f6b376..e1b5ac3be 100644
--- a/internal/gui/assets/plugins/routing/client.js
+++ b/internal/gui/assets/plugins/routing/client.js
@@ -477,11 +477,22 @@ function routingPage(part) {
// sillytavern; a comma would part it in two (ParseRule)
const uaName = (s) => String(s || "").trim().split(/[\/\s,]/)[0].toLowerCase();
const agentName = (id) => agentOf(id)?.name || (id && id !== "other" ? id : t("your agent"));
+ // userShown is an account of provider as the user named it in magpie
+ // (provider.AccountNames, #1515), else as its vendor names it. The name
+ // is looked up as the page is drawn, by the account a request kept (its
+ // vendor's name, which the user's name is kept by), so every request
+ // reads by the name the account has now, one from before a rename too
+ // (plugins#310: a renamed Kiro account kept its old name on requests
+ // made after). Requests are still told apart by that vendor's name.
+ const userShown = (provider, user) => user && accountNameOf(providers?.providers?.find((p) => p.id === provider), user) || user;
+ // whoShown is the account or key a weighed one is: an account by its
+ // name of the user's own; a key's name is already the user's
+ const whoShown = (w) => w.kind === "account" ? userShown(w.provider, w.who) : w.who;
// who names an account or key in a sentence
- const who = (w) => w.kind === "provider" ? w.name : w.who;
+ const who = (w) => w.kind === "provider" ? w.name : whoShown(w);
// where names one as a place a request went: the provider, and the
// account or key when it has one
- const where = (w) => w.kind === "provider" || !w.who ? w.name || w.provider : `${w.name || w.provider} · ${w.who}`;
+ const where = (w) => w.kind === "provider" || !w.who ? w.name || w.provider : `${w.name || w.provider} · ${whoShown(w)}`;
// why one is left out: an account's plan lacks the model; a key's list
// from its vendor does — relays list each key its own group's models
// or the user set the account or key to serve other models only (#474)
@@ -987,7 +998,7 @@ function routingPage(part) {
// a Codex reset spent by itself: with Codex's own sign-in the one try
// it was spent for is the one that then answered
const spent = tr.reset && tr.status < 400
- ? t("Its week was used up, so one of {account}'s Codex resets was used by itself first.", { account: tr.reset.who }) + " "
+ ? t("Its week was used up, so one of {account}'s Codex resets was used by itself first.", { account: userShown(w?.provider, tr.reset.who) }) + " "
: "";
if (tr.status < 400 && tr.fail)
return tr.rest
@@ -1002,7 +1013,7 @@ function routingPage(part) {
}
if (tr.reset)
return t("{who} answered {status}: its week is used up and nobody else could take the request, so one of {account}'s Codex resets was used by itself and the request is asked again, before any of the reply reaches {agent}.",
- { who: name, status: tr.status, account: tr.reset.who, agent });
+ { who: name, status: tr.status, account: userShown(w?.provider, tr.reset.who), agent });
if (tr.fail === "canceled")
return t("{agent} canceled the request while {who} was answering: nobody failed, so nobody rests and nobody else is asked.", { who: name, agent });
if (tr.fail === "auth")
@@ -5926,7 +5937,7 @@ function routingPage(part) {
function pSeat(r, tr) {
const w = tr && tried(r, tr);
if (!w) return { key: r.provider || "?", name: r.provider || "?", sub: "" };
- const sub = w.kind === "provider" ? "" : w.who || "";
+ const sub = w.kind === "provider" ? "" : whoShown(w) || "";
return { key: w.provider || r.provider || "?", name: w.name || w.provider, sub };
}
// pPlace keeps those on the stage that are still wanted where they are,
diff --git a/internal/gui/assets/plugins/usage/page.js b/internal/gui/assets/plugins/usage/page.js
index 6e538ddd2..be1d54423 100644
--- a/internal/gui/assets/plugins/usage/page.js
+++ b/internal/gui/assets/plugins/usage/page.js
@@ -1546,7 +1546,7 @@ function renderLedger() {
sessPick($("#ledComputer"), "All computers", ledComputer, computers, "Computer", (v) => { ledComputer = v; ledOwn("computer"); ledOffset = 0; loadLedger().catch((e) => status(e.message, "err")); });
sessPick($("#ledAgent"), "All agents", ledAgent, l.agents.map((a) => ({ v: a.id, name: a.name, note: "" })), "Agent", (v) => { ledAgent = v; ledOwn("agent"); ledOffset = 0; loadLedger().catch((e) => status(e.message, "err")); });
sessPick($("#ledProvider"), "All providers", ledProvider, providers.map((p) => ({ v: p.id, name: t(p.name), note: "" })), "Provider", (v) => { ledProvider = v; ledOwn("provider"); ledOffset = 0; loadLedger().catch((e) => status(e.message, "err")); });
- sessPick($("#ledAccount"), "All accounts", ledAccount, accounts.map((a) => ({ v: a.id, name: a.id, note: (a.providers || []).map((p) => t(p)).join(" · ") })), "Account", (v) => { ledAccount = v; ledOffset = 0; loadLedger().catch((e) => status(e.message, "err")); });
+ sessPick($("#ledAccount"), "All accounts", ledAccount, accounts.map((a) => ({ v: a.id, name: a.name || a.id, note: [a.name && a.id, ...(a.providers || []).map((p) => t(p))].filter(Boolean).join(" · ") })), "Account", (v) => { ledAccount = v; ledOffset = 0; loadLedger().catch((e) => status(e.message, "err")); });
sessPick($("#ledKey"), "All gateway keys", ledCallerKey, callers.map((k) => ({
v: k.id, name: k.name, note: "",
})).concat(noKey ? [{ v: "none", name: t("No gateway key"), note: "" }] : []), "Gateway keys", (v) => { ledCallerKey = v; ledOwn("callerKey"); ledOffset = 0; loadLedger().catch((e) => status(e.message, "err")); });
diff --git a/internal/gui/caller_keys.go b/internal/gui/caller_keys.go
index 5e6ecfc49..fff30644e 100644
--- a/internal/gui/caller_keys.go
+++ b/internal/gui/caller_keys.go
@@ -79,10 +79,11 @@ func callerKeyRoutes(mux *http.ServeMux) {
continue
}
name := cmp.Or(p.Name, p.ID)
- // an account by its stable id, kept through renames, shown by who
- // is signed in; a key by its fingerprint
+ // an account by its stable id, kept through renames, shown by the
+ // name the user gave it, else who is signed in; a key by its
+ // fingerprint
for _, a := range p.AccountIDs() {
- accounts = append(accounts, keyModelJSON{ID: p.ID + "/" + a.ID, Name: a.User, Provider: p.ID, ProviderName: name, Account: !a.Key, Key: a.Key, Plan: a.Plan})
+ accounts = append(accounts, keyModelJSON{ID: p.ID + "/" + a.ID, Name: a.Shown(p), Provider: p.ID, ProviderName: name, Account: !a.Key, Key: a.Key, Plan: a.Plan})
}
}
writeJSON(w, map[string]any{"models": out, "accounts": accounts})
diff --git a/internal/gui/groups.go b/internal/gui/groups.go
index f98c1d0f7..37e0a7f31 100644
--- a/internal/gui/groups.go
+++ b/internal/gui/groups.go
@@ -176,12 +176,13 @@ func seesImages(e provider.Entry) bool { return e.Images && (e.ImageInput == nil
// list saying it takes none, and the page says unknown rather than text-only.
func imagesUnknown(e provider.Entry) bool { return e.ImageInput == nil && !e.Images }
-// onOf is who a provider's requests spread over: its accounts, or keys.
+// onOf is who a provider's requests spread over: its accounts, by the
+// name the user gave each (provider.AccountShown), or keys.
func onOf(p provider.Provider) (kind string, who []string) {
if p.Account != nil {
- who = append(who, p.Account.User)
+ who = append(who, p.AccountShown(p.Account.User))
for _, q := range p.AlsoOn() {
- who = append(who, q.Account.User)
+ who = append(who, p.AccountShown(q.Account.User))
}
return "account", who
}
diff --git a/internal/gui/tests/routing-account-name.test.cjs b/internal/gui/tests/routing-account-name.test.cjs
new file mode 100644
index 000000000..c378ee30c
--- /dev/null
+++ b/internal/gui/tests/routing-account-name.test.cjs
@@ -0,0 +1,94 @@
+// An account's name of the user's own (#1515) is what the Routing page
+// calls it (magpie-community/plugins#310, molvqingtai): a Kiro account
+// signed in as "[email protected] (foo)" and renamed in magpie to
+// "[email protected] (bar)" still read "(foo)" on every request made
+// after. The trace keeps the vendor's name (who), the key the user's name
+// is kept by; the page looks the name up as it draws, so a request from
+// before the rename reads by the new name too, and the two stay one
+// account. A key's name and an unnamed account read as they were.
+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 VENDOR = "[email protected] (foo)", NAMED = "[email protected] (bar)", OTHER = "[email protected]";
+
+function routes(now) {
+ const reset = new Date(now.getTime() + 4 * 3600e3).toISOString();
+ const kiro = { provider: "kiro", name: "Kiro", kind: "account", icon: "kiro", agent: "kiro", plan: "Pro", model: "claude-sonnet-4.5", known: true, used: 10, renews: [reset] };
+ const named = { ...kiro, id: "kiro", who: VENDOR };
+ const other = { ...kiro, id: "kiro@" + OTHER, who: OTHER, used: 20 };
+ const key = { provider: "relay", name: "Relay", kind: "key", icon: "generic", id: "relay#k1", who: "team key", model: "claude-sonnet-4.5", routing: "" };
+ return Array.from({ length: 4 }, (_, i) => {
+ const time = new Date(now.getTime() - (4 - i) * 1000).toISOString();
+ const id = i === 3 ? other.id : "kiro";
+ return { id: i + 1, seq: i + 1, time, agent: "claude", model: "kiro/claude-sonnet-4.5", provider: "kiro", order: [named, other, key], done: true,
+ status: 200, ms: 20, tries: [{ id, model: "claude-sonnet-4.5", start: time, done: true, status: 200, ms: 20 }] };
+ }).reverse();
+}
+
+function serve(lang, now, names) {
+ const assets = path.resolve(__dirname, "../assets");
+ 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({ agents: [], profiles: [], settings: { lang, theme: "light" } });
+ if (url.pathname === "/api/gateway/trace") {
+ if (url.searchParams.has("wait")) return;
+ return json({ mine: true, now: now.toISOString(), seq: 4, totals: { requests: 4, rerouted: 0, errors: 0 }, routes: routes(now) });
+ }
+ if (url.pathname === "/api/gateway/history") return json({ cut: false, days: [], routes: [] });
+ if (url.pathname === "/api/groups") return json({ groups: [] });
+ if (url.pathname === "/api/providers") return json({ providers: [{
+ id: "kiro", name: "Kiro", icon: "kiro", models: [{ id: "claude-sonnet-4.5", on: true }], keyList: [],
+ account: { agent: "plugin", user: VENDOR, logins: [{ user: VENDOR, active: true, on: true }, { user: OTHER, on: true }] },
+ accountNames: names(),
+ }], presets: [], excluded: [], gateway: { running: true, window: true } });
+ 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" }[path.extname(file)];
+ await route.fulfill({ body: await fs.readFile(file).catch(() => ""), contentType });
+ };
+}
+
+for (const engine of process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"]) {
+ for (const lang of ["en", "zh"]) {
+ test(`${engine} ${lang}: Routing names an account by the name the user gave it`, async (t) => {
+ const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
+ t.after(() => browser.close());
+ const page = await browser.newPage({ viewport: { width: 1100, height: 1000 } });
+ page.setDefaultTimeout(5000);
+ const errors = [];
+ page.on("pageerror", (e) => errors.push(e.message));
+ const now = new Date();
+ let names = {};
+ await page.route("**/*", serve(lang, now, () => names));
+ await page.goto("http://magpie.test/?view=routing");
+ await page.locator(".rt-act").first().waitFor();
+ const acts = page.locator(".rt-acts");
+ assert.ok((await acts.innerText()).includes(VENDOR), "unnamed, the account reads as its vendor names it");
+
+ names = { [VENDOR.toLowerCase()]: NAMED };
+ await page.reload();
+ await page.locator(".rt-act").first().waitFor();
+ const text = await acts.innerText();
+ assert.ok(text.includes(NAMED), "renamed, the account reads by its new name: " + text);
+ assert.ok(!text.includes(VENDOR), "and no longer by the old one: " + text);
+ assert.equal(await page.locator(".rt-act").count(), 3, "the requests from before and after are one account's, beside the other and the key");
+ assert.equal(await page.locator(".rt-act", { hasText: OTHER }).count(), 1, "an account with no name of its own reads as before");
+ assert.equal(await page.locator(".rt-act", { hasText: "team key" }).count(), 1, "a key reads by its own name");
+ // the list of requests says who answered by the same name
+ const list = await page.locator(".said").allInnerTexts();
+ assert.ok(list.some((s) => s.includes(NAMED)), "the requests list names who answered by the new name: " + list.join(" | "));
+ assert.ok(!list.some((s) => s.includes(VENDOR)), "and never by the old: " + list.join(" | "));
+ if (process.env.ARTIFACT_DIR) {
+ await fs.mkdir(process.env.ARTIFACT_DIR, { recursive: true });
+ await page.screenshot({ path: path.join(process.env.ARTIFACT_DIR, `${engine}-${lang}-routing-account-name.png`) });
+ }
+ assert.deepEqual(errors, []);
+ });
+ }
+}
diff --git a/internal/provider/account_models.go b/internal/provider/account_models.go
index 6e7ad6588..0cdfbd1d0 100644
--- a/internal/provider/account_models.go
+++ b/internal/provider/account_models.go
@@ -113,18 +113,28 @@ func (p Provider) AccountID() string {
}
// AccountNames maps every account and key a gateway key may name (#905),
-// "<provider>/<id>", to how it is shown, "<provider>/<user>"; what no
-// provider has now maps to itself.
+// "<provider>/<id>", to how it is shown, "<provider>/<user>", an account
+// by the name the user gave it (AccountShown); what no provider has now
+// maps to itself.
func AccountNames() map[string]string {
out := map[string]string{}
for _, p := range All() {
for _, a := range p.AccountIDs() {
- out[p.ID+"/"+a.ID] = p.ID + "/" + a.User
+ out[p.ID+"/"+a.ID] = p.ID + "/" + a.Shown(p)
}
}
return out
}
+// Shown is how the account or key a is shown on p: an account by the
+// name the user gave it, a key by its own name.
+func (a AccountRef) Shown(p Provider) string {
+ if a.Key {
+ return a.User
+ }
+ return p.AccountShown(a.User)
+}
+
// accountRef is the account or key of p that ref names: a signed-in
// account by its name, a key by its KeyID or its name, in any case.
func (p Provider) accountRef(ref string) (string, bool) {
diff --git a/internal/provider/account_names.go b/internal/provider/account_names.go
index abddb4777..f28bf6bc7 100644
--- a/internal/provider/account_names.go
+++ b/internal/provider/account_names.go
@@ -7,7 +7,9 @@ package provider
// the account's name in lower case; the vendor's or plugin's sign-in is
// never written to. It is shown wherever the account is: the Usage page,
// the menu bar, magpie accounts, magpie quota and /v1/magpie/quotas
-// (SubscriptionQuota.Alias, Quota.Alias).
+// (SubscriptionQuota.Alias, Quota.Alias), the Usage page's Accounts and
+// the request log's Account filter, a gateway key's accounts, and the
+// Routing page (which reads accountNames from /api/providers).
import (
"cmp"
@@ -74,6 +76,17 @@ func AccountNameOf(id, user string) string {
return ""
}
+// AccountShown is how the account user of p is shown: by the name the
+// user gave it, else as its vendor names it. Records and lists keep the
+// vendor's name, the key the user's name is kept by, and look this up as
+// they are shown, so a rename reaches what came before it too
+// (magpie-community/plugins#310: a renamed Kiro account read by its old
+// name on the requests after).
+func (p Provider) AccountShown(user string) string { return cmp.Or(p.AccountName(user), user) }
+
+// AccountShownOf is AccountShown for the account user of the provider id.
+func AccountShownOf(id, user string) string { return cmp.Or(AccountNameOf(id, user), user) }
+
// SetAccountName names the account ref of the subscription id; "" takes
// the name off.
func SetAccountName(id, ref, name string) error {
diff --git a/internal/provider/account_names_test.go b/internal/provider/account_names_test.go
index 16a13b10d..5e9ee3e00 100644
--- a/internal/provider/account_names_test.go
+++ b/internal/provider/account_names_test.go
@@ -56,6 +56,24 @@ func TestAccountNameOfAPluginAccount(t *testing.T) {
if qs[0].Alias != "某某·GLM 高级版" {
t.Fatalf("card alias %q", qs[0].Alias)
}
+ // and on what the vendor's name is kept by: the Usage page's Accounts,
+ // a gateway key's accounts, Routing's pools (magpie-community/plugins#310:
+ // a renamed Kiro account read by its old name on every request after)
+ if got := AccountShownOf(id, "31****[email protected]"); got != "某某·GLM 高级版" {
+ t.Fatalf("shown as %q", got)
+ }
+ if got := AccountShownOf(id, "[email protected]"); got != "[email protected]" {
+ t.Fatalf("an unnamed account shown as %q", got)
+ }
+ var shown []string
+ for _, v := range AccountNames() {
+ if strings.HasPrefix(v, id+"/") {
+ shown = append(shown, v)
+ }
+ }
+ if len(shown) != 1 || shown[0] != id+"/某某·GLM 高级版" {
+ t.Fatalf("a gateway key's accounts read %q", shown)
+ }
for _, bad := range []struct{ ref, name string }{
{"31****[email protected]", strings.Repeat("名", MaxAccountName+1)},
diff --git a/internal/usageapi/usageapi.go b/internal/usageapi/usageapi.go
index 25f29c6d4..1a60de68d 100644
--- a/internal/usageapi/usageapi.go
+++ b/internal/usageapi/usageapi.go
@@ -5,6 +5,7 @@
package usageapi
import (
+ "cmp"
"net/url"
"os"
"slices"
@@ -94,11 +95,13 @@ func stateOf(s usage.Summary) Usage {
out.Models = append(out.Models, ug)
}
// each subscription account's share, by the account that answered
- // (#557); Name "" is the calls whose record names none, the page
+ // (#557), named as the user named it now (provider.AccountShownOf,
+ // plugins#310): the record keeps the vendor's name, which the user's
+ // is kept by; Name "" is the calls whose record names none, the page
// saying "account not recorded"
for _, g := range s.Accounts {
p := which(g.Provider)
- ug := Group{Group: g, Name: g.Account, Sub: p.Name, Icon: p.Icon}
+ ug := Group{Group: g, Name: provider.AccountShownOf(g.Provider, g.Account), Sub: p.Name, Icon: p.Icon}
out.Accounts = append(out.Accounts, ug)
}
out.CallerKeys = callerGroups(s)
@@ -236,9 +239,12 @@ type Share struct {
}
// Account is a subscription account the Account filter offers: its
-// name, and the providers it answered for, by name.
+// name, as the record keeps it and the filter asks by, the name the user
+// gave it in magpie when there is one (plugins#310), and the providers it
+// answered for, by name.
type Account struct {
ID string `json:"id"`
+ Name string `json:"name,omitempty"`
Providers []string `json:"providers"`
}
@@ -321,14 +327,17 @@ func LedgerPage(p usage.Period, f usage.Filter, offset, limit int) Ledger {
at := map[string]int{}
for _, g := range l.Accounts {
name := which(g.Provider).Name
+ own := provider.AccountNameOf(g.Provider, g.Account)
if i, ok := at[g.Account]; ok {
- if a := &out.Accounts[i]; !slices.Contains(a.Providers, name) {
+ a := &out.Accounts[i]
+ if !slices.Contains(a.Providers, name) {
a.Providers = append(a.Providers, name)
}
+ a.Name = cmp.Or(a.Name, own)
continue
}
at[g.Account] = len(out.Accounts)
- out.Accounts = append(out.Accounts, Account{ID: g.Account, Providers: []string{name}})
+ out.Accounts = append(out.Accounts, Account{ID: g.Account, Name: own, Providers: []string{name}})
}
// what each is of: the rows of the filter, or, for the dimension the
// filter has picked, of the rows without that pick