provider: every provider can hold several accounts — keep more than one API key, name them, and switch which one is in use from the editor

This commit is contained in:
yetone
2026-09-24 14:32:54 +08:00
parent b19f3dbabe
commit abc5962600
7 changed files with 351 additions and 14 deletions
+12
View File
@@ -533,6 +533,18 @@ body.window .foot { padding-left: 18px; }
.acc.add:hover { background: var(--card-2); color: var(--fg); }
.acc.add:hover .dot { box-shadow: inset 0 0 0 1.5px var(--fg); color: var(--fg); }
.acc .rename { font: inherit; font-weight: 500; color: inherit; background: none; border: 0; padding: 0; cursor: text; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.acc .rename:hover { text-decoration: underline dotted var(--faint); text-underline-offset: 3px; }
.acc .rename.mono { font-family: var(--code); font-size: 11.5px; font-weight: 450; }
.acc .rename-in { height: 24px; padding: 0 7px; font-size: 12.5px; max-width: 220px; }
.acc .plan.mono { font-family: var(--code); font-size: 10.5px; }
.acc.adding { display: grid; gap: 8px; padding: 10px 10px 8px 11px; background: var(--card-2); }
.acc.adding .kf { display: grid; grid-template-columns: minmax(0, 2fr) minmax(0, 3fr); gap: 6px; }
.acc.adding .kb { display: flex; align-items: center; gap: 4px; }
.acc.adding .kb .grow { flex: 1; }
.acc + .acc.adding { border-top: 1px solid var(--line-2); }
@media (max-width: 520px) { .acc.adding .kf { grid-template-columns: 1fr; } }
/* a sign-in under way, waiting on the browser */
.signing { display: flex; align-items: flex-start; gap: 11px; padding: 11px 10px 11px 12px; font-size: 12.5px; background: var(--card-2); animation: fade-in .2s; }
.sheet .signing { margin-top: 8px; border: 1px solid var(--line); border-radius: 10px; }
+103 -4
View File
@@ -600,7 +600,7 @@ function renderProviders() {
key = el("span", "key acct", accountPlan(p.account));
key.title = t("{agent} is signed in; its models are here for every other agent", { agent: p.account.agentName });
} else {
key = el("span", "key " + (p.key.set ? "on" : p.ready ? "free" : "none"), p.key.set ? p.key.masked : p.ready ? t("no key") : t("needs a key"));
key = el("span", "key " + (p.key.set ? "on" : p.ready ? "free" : "none"), p.key.set ? (p.keyList?.find((k) => k.active)?.name || p.key.masked) : p.ready ? t("no key") : t("needs a key"));
key.title = p.key.set ? t("API key {masked}", { masked: p.key.masked }) : p.ready ? t("Local servers need no key") : t("Open the row and paste an API key");
}
const chev = el("span", "chev");
@@ -1480,7 +1480,8 @@ function renderEditor(p, presetID) {
if (keysUrl) { const b = el("button", "link", t("Get a key ↗")); b.onclick = () => api("open", { url: keysUrl }); side.append(b); }
const keyWrap = el("div", "pair");
keyWrap.append(key, side);
ed.append(...field(t("API key"), keyWrap, isNew ? t("Kept in ~/.config/magpie/providers.json, readable by you alone. Nothing is read from your shell.") : ""));
if (p?.keyList?.length) ed.append(...field(t("Accounts"), renderKeyAccounts(p), t("Requests go out with the key in use. Keep several — personal and team, paid and free — and switch any time.")));
else ed.append(...field(t("API key"), keyWrap, isNew ? t("Kept in ~/.config/magpie/providers.json, readable by you alone. Nothing is read from your shell.") : ""));
// A user-defined provider can have its own picture; presets keep theirs.
if (custom) ed.append(...field(t("Icon"), iconPicker(ed), ""));
@@ -1911,10 +1912,10 @@ function renderAccounts(a) {
} else {
const forget = el("button", "text quiet", t("Remove"));
forget.title = t("magpie forgets this account's sign-in; the account itself is untouched");
forget.onclick = () => providerAction("forget", { agent: a.agent, user: l.user }, t("{user} removed", { user: l.user }), "login/");
forget.onclick = () => accountAction("login/forget", { agent: a.agent, user: l.user }, t("{user} removed", { user: l.user }));
const use = el("button", "text", t("Use"));
use.title = t("Sign {agent} in to this account", { agent: a.agentName });
use.onclick = () => { use.classList.add("busy"); providerAction("switch", { agent: a.agent, user: l.user }, t("{agent} is now signed in as {user}", { agent: a.agentName, user: l.user }), "login/"); };
use.onclick = () => { use.classList.add("busy"); accountAction("login/switch", { agent: a.agent, user: l.user }, t("{agent} is now signed in as {user}", { agent: a.agentName, user: l.user })); };
row.append(forget, use);
}
list.append(row);
@@ -1931,6 +1932,104 @@ function renderAccounts(a) {
return list;
}
// accountAction changes which account a provider uses, or which it has,
// and leaves its editor open on the result.
async function accountAction(path, body, okMsg) {
try {
providers = await api(path, body);
renderProviders();
state = await api("state");
renderAgents();
if (okMsg) status(okMsg, "ok");
return true;
} catch (e) {
if (!editorError(e.message, "err")) status(e.message, "err");
document.querySelector(".editor .busy")?.classList.remove("busy");
return false;
}
}
// renderKeyAccounts: a key provider's accounts, one per key, the same list
// a subscription has. addingKey holds the half-typed new one.
let addingKey = null;
function renderKeyAccounts(p) {
const list = el("div", "accts");
for (const k of p.keyList) {
const row = el("div", "acc" + (k.active ? " in-use" : "") + (k.id === justAdded ? " new" : ""));
const dot = el("span", "dot");
if (k.active) dot.append(svg(CHECK, 10, 2.2));
const name = el("button", "n rename" + (k.name ? "" : " mono"), k.name || k.masked);
name.title = t("Rename");
name.onclick = () => {
const i = input(k.name, t("Name, e.g. Personal or Team"));
i.className = "rename-in";
const done = (save) => {
if (save && i.value.trim() !== (k.name || "")) accountAction("keys/rename", { id: p.id, ref: k.id, name: i.value });
else renderProviders();
};
i.onkeydown = (e) => { e.stopPropagation(); if (e.key === "Enter") done(true); else if (e.key === "Escape") done(false); };
i.onblur = () => done(true);
name.replaceWith(i);
i.focus();
};
row.append(dot, name);
if (k.name) row.append(el("span", "plan mono", k.masked));
row.append(el("span", "grow"));
if (k.active) row.append(el("span", "using", t("In use")));
else {
const rm = el("button", "text quiet", t("Remove"));
rm.onclick = () => accountAction("keys/remove", { id: p.id, ref: k.id }, t("Key removed"));
const use = el("button", "text", t("Use"));
use.onclick = () => { use.classList.add("busy"); accountAction("keys/use", { id: p.id, ref: k.id }, t("{name} now uses {key}", { name: p.name, key: k.name || k.masked })); };
row.append(rm, use);
}
list.append(row);
}
if (addingKey?.id === p.id) {
const box = el("div", "acc adding");
const name = input(addingKey.name, t("Name, e.g. Team"));
name.oninput = () => { addingKey.name = name.value; };
const key = input(addingKey.key, t("paste an API key"), "password");
key.oninput = () => { addingKey.key = key.value; };
const add = el("button", "text primary", t("Add"));
const go = async () => {
add.classList.add("busy");
const id = await keyFingerprint(key.value.trim());
if (await accountAction("keys/add", { id: p.id, name: name.value, key: key.value }, t("Key added — switch to it any time"))) {
addingKey = null; justAdded = id; renderProviders(); setTimeout(() => { justAdded = ""; }, 2000);
}
};
add.onclick = go;
for (const i of [name, key]) i.onkeydown = (e) => { e.stopPropagation(); if (e.key === "Enter") go(); else if (e.key === "Escape") { addingKey = null; renderProviders(); } };
const x = el("button", "text", t("Cancel"));
x.onclick = () => { addingKey = null; renderProviders(); };
const fields = el("div", "kf");
fields.append(name, key);
const bar = el("div", "kb");
if (p.keysUrl) { const g = el("button", "link", t("Get a key ↗")); g.onclick = () => api("open", { url: p.keysUrl }); bar.append(g); }
bar.append(el("span", "grow"), x, add);
box.append(fields, bar);
list.append(box);
queueMicrotask(() => (addingKey.name ? key : name).focus());
} else {
const add = el("button", "acc add");
const ic = el("span", "dot");
ic.append(svg(PLUS, 10, 1.8));
add.append(ic, el("span", "n", t("Add another key")));
add.onclick = () => { addingKey = { id: p.id, name: "", key: "" }; renderProviders(); };
list.append(add);
}
return list;
}
// keyFingerprint is the id the backend gives a key, to greet a new one.
async function keyFingerprint(key) {
try {
const h = new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(key)));
return [...h.slice(0, 5)].map((b) => b.toString(16).padStart(2, "0")).join("");
} catch { return ""; }
}
async function providerAction(action, body, okMsg, base = "provider/") {
try {
providers = await api(base + action, body);
+9 -1
View File
@@ -130,9 +130,17 @@ const I18N = {
"When {name} is out of quota, rate limited or down, a request goes to these instead, top first. It only happens before any of the reply is sent, and {name} then sits out a minute.": "当 {name} 额度用完、被限流或不可用时,请求会按从上到下的顺序改发给这些模型。只在回复开始发送之前切换,之后 {name} 会暂停一分钟再用。",
"{agent} and the gateway use the one in use. Sessions already running keep theirs until restarted.": "{agent} 和网关使用标记为「使用中」的账号。已在运行的会话保持原账号,重启后切换。",
"In use": "使用中",
"Requests go out with the key in use. Keep several — personal and team, paid and free — and switch any time.": "请求使用标记为「使用中」的密钥。可以保存多个——个人的、团队的、付费的、免费的——随时切换。",
"Add another key": "添加另一个密钥",
"Name, e.g. Team": "名称,例如 团队",
"Name, e.g. Personal or Team": "名称,例如 个人 或 团队",
"Rename": "重命名",
"Key removed": "已移除密钥",
"Key added — switch to it any time": "已添加密钥,随时可以切换",
"{name} now uses {key}": "{name} 已切换为 {key}",
"Use": "使用",
"Add another {name} account": "添加另一个 {name} 账号",
"Subscriptions · sign in, no key": "订阅 · 登录即可,无需 Key",
"Subscriptions · sign in, no key": "订阅 · 登录即可,无需密钥",
"{name} subscription": "{name} 订阅",
"1 account · add another": "1 个账号 · 再添加一个",
"{n} accounts · add another": "{n} 个账号 · 再添加一个",
+48 -9
View File
@@ -43,15 +43,16 @@ type providerJSON struct {
Masked string `json:"masked"`
Optional bool `json:"optional"`
} `json:"key"`
Ready bool `json:"ready"`
Chosen []string `json:"chosen"` // the user's explicit picks, if any
Fallback []string `json:"fallback"` // where requests go when this one can't take them
Models []modelJSON `json:"models"` // everything the vendor lists, exposed ones flagged
Exposed int `json:"exposed"` // how many reach the agents
Fetched string `json:"fetched"` // "3h ago" when the list came from the vendor
Agents []providerAgent `json:"agents"` // detected agents, current ones flagged
Sponsored bool `json:"sponsored"`
Account *accountJSON `json:"account,omitempty"` // a signed-in agent, see provider.Account
Ready bool `json:"ready"`
Chosen []string `json:"chosen"` // the user's explicit picks, if any
Fallback []string `json:"fallback"` // where requests go when this one can't take them
Models []modelJSON `json:"models"` // everything the vendor lists, exposed ones flagged
Exposed int `json:"exposed"` // how many reach the agents
Fetched string `json:"fetched"` // "3h ago" when the list came from the vendor
Agents []providerAgent `json:"agents"` // detected agents, current ones flagged
Sponsored bool `json:"sponsored"`
KeyList []provider.KeyInfo `json:"keyList"` // its keys, the one in use first
Account *accountJSON `json:"account,omitempty"` // a signed-in agent, see provider.Account
}
type accountJSON struct {
@@ -132,6 +133,10 @@ func providerInfo(p provider.Provider, agents []*agent.Agent) providerJSON {
}
out.Key.Set = p.Key != ""
out.Key.Masked = provider.Mask(p.Key)
out.KeyList = p.KeyList()
if out.KeyList == nil {
out.KeyList = []provider.KeyInfo{}
}
if !out.Key.Set && p.Ready() {
out.Key.Optional = true
}
@@ -264,6 +269,13 @@ func providerRoutes(mux *http.ServeMux, w Windows, gw *gateway.Server) {
if in.Key == "" && old != nil {
in.Key = old.Key
}
if old != nil {
// the other keys are kept apart, in the Accounts list
in.Keys = old.Keys
if in.Key == old.Key {
in.KeyName = old.KeyName
}
}
if in.Icon == "" && old != nil && in.Preset == "" {
in.Icon = old.Icon
}
@@ -353,6 +365,33 @@ func providerRoutes(mux *http.ServeMux, w Windows, gw *gateway.Server) {
}
writeJSON(rw, providersState(gw))
})
// A provider's several keys: add one, put one in use, name or remove it.
mux.HandleFunc("POST /api/keys/{action}", func(rw http.ResponseWriter, r *http.Request) {
var in struct{ ID, Key, Name, Ref string }
if err := json.NewDecoder(r.Body).Decode(&in); err != nil {
fail(rw, err)
return
}
var err error
switch r.PathValue("action") {
case "add":
err = provider.AddKey(in.ID, in.Name, in.Key)
case "use":
err = provider.UseKey(in.ID, in.Ref)
case "remove":
err = provider.RemoveKey(in.ID, in.Ref)
case "rename":
err = provider.RenameKey(in.ID, in.Ref, in.Name)
default:
http.NotFound(rw, r)
return
}
if err != nil {
fail(rw, err)
return
}
writeJSON(rw, providersState(gw))
})
// Adding a subscription: magpie opens the vendor's sign-in in the
// browser and the window follows it until the account is in.
mux.HandleFunc("POST /api/signin", func(rw http.ResponseWriter, r *http.Request) {
+133
View File
@@ -0,0 +1,133 @@
package provider
// A provider can hold several accounts, as a subscription can: several API
// keys — a personal one and the team's, a paid plan and a free one — with
// one in use and the rest one click away. Key stays the one in use, so
// everything that talks to the vendor reads it as before.
import (
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"strings"
)
// KeyAccount is a saved key that isn't in use.
type KeyAccount struct {
Name string `json:"name,omitempty"`
Key string `json:"key"`
}
// KeyInfo describes one of a provider's keys without giving it away.
type KeyInfo struct {
ID string `json:"id"` // a fingerprint, to name it in a switch
Name string `json:"name,omitempty"`
Masked string `json:"masked"`
Active bool `json:"active"`
}
func keyID(key string) string {
sum := sha256.Sum256([]byte(key))
return hex.EncodeToString(sum[:5])
}
// KeyList is a provider's keys, the one in use first.
func (p Provider) KeyList() []KeyInfo {
var out []KeyInfo
if p.Key != "" {
out = append(out, KeyInfo{ID: keyID(p.Key), Name: p.KeyName, Masked: Mask(p.Key), Active: true})
}
for _, k := range p.Keys {
out = append(out, KeyInfo{ID: keyID(k.Key), Name: k.Name, Masked: Mask(k.Key)})
}
return out
}
// AddKey saves one more key for a provider. It is put in use when the
// provider has none yet.
func AddKey(id, name, key string) error {
name, key = strings.TrimSpace(name), strings.TrimSpace(key)
if key == "" {
return errors.New("paste the key to add")
}
p, err := Find(id)
if err != nil {
return err
}
if p.Account != nil {
return errors.New("a signed-in account has no keys")
}
for _, k := range p.KeyList() {
if k.ID == keyID(key) {
return fmt.Errorf("%s already has this key", p.Name)
}
}
if p.Key == "" {
p.Key, p.KeyName = key, name
} else {
p.Keys = append(p.Keys, KeyAccount{Name: name, Key: key})
}
return Save(*p)
}
// UseKey puts one of a provider's saved keys in use; the one it replaces
// is kept with the others.
func UseKey(id, keyRef string) error {
p, err := Find(id)
if err != nil {
return err
}
for i, k := range p.Keys {
if keyID(k.Key) == keyRef {
p.Keys[i] = KeyAccount{Name: p.KeyName, Key: p.Key}
p.Key, p.KeyName = k.Key, k.Name
if p.Key == "" || p.Keys[i].Key == "" {
p.Keys = append(p.Keys[:i], p.Keys[i+1:]...)
}
return Save(*p)
}
}
if p.Key != "" && keyID(p.Key) == keyRef {
return nil
}
return fmt.Errorf("%s has no such key", p.Name)
}
// RemoveKey forgets a saved key. The one in use stays: switch first.
func RemoveKey(id, keyRef string) error {
p, err := Find(id)
if err != nil {
return err
}
for i, k := range p.Keys {
if keyID(k.Key) == keyRef {
p.Keys = append(p.Keys[:i], p.Keys[i+1:]...)
return Save(*p)
}
}
if p.Key != "" && keyID(p.Key) == keyRef {
return errors.New("that key is in use; switch to another before removing it")
}
return fmt.Errorf("%s has no such key", p.Name)
}
// RenameKey names one of a provider's keys, "Personal", "Team".
func RenameKey(id, keyRef, name string) error {
p, err := Find(id)
if err != nil {
return err
}
name = strings.TrimSpace(name)
if p.Key != "" && keyID(p.Key) == keyRef {
p.KeyName = name
return Save(*p)
}
for i, k := range p.Keys {
if keyID(k.Key) == keyRef {
p.Keys[i].Name = name
return Save(*p)
}
}
return fmt.Errorf("%s has no such key", p.Name)
}
+41
View File
@@ -0,0 +1,41 @@
package provider
import "testing"
func TestSeveralKeys(t *testing.T) {
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
t.Setenv("XDG_CACHE_HOME", t.TempDir())
if err := Save(Provider{ID: "relay", Name: "Relay", Chat: "https://relay.test/v1", Key: "sk-personal-1111"}); err != nil {
t.Fatal(err)
}
if err := AddKey("relay", "Team", "sk-team-2222"); err != nil {
t.Fatal(err)
}
if err := AddKey("relay", "", "sk-team-2222"); err == nil {
t.Fatal("the same key was added twice")
}
p, _ := Find("relay")
ks := p.KeyList()
if p.Key != "sk-personal-1111" || len(ks) != 2 || !ks[0].Active || ks[1].Name != "Team" {
t.Fatalf("keys %+v", ks)
}
if err := RemoveKey("relay", ks[0].ID); err == nil {
t.Fatal("removed the key in use")
}
if err := RenameKey("relay", ks[0].ID, "Personal"); err != nil {
t.Fatal(err)
}
if err := UseKey("relay", ks[1].ID); err != nil {
t.Fatal(err)
}
p, _ = Find("relay")
if p.Key != "sk-team-2222" || p.KeyName != "Team" || len(p.Keys) != 1 || p.Keys[0] != (KeyAccount{"Personal", "sk-personal-1111"}) {
t.Fatalf("after use: %+v %q %+v", p.Key, p.KeyName, p.Keys)
}
if err := RemoveKey("relay", keyID("sk-personal-1111")); err != nil {
t.Fatal(err)
}
if p, _ = Find("relay"); len(p.Keys) != 0 || p.Key != "sk-team-2222" {
t.Fatalf("after remove: %+v", p)
}
}
+5
View File
@@ -37,6 +37,11 @@ type Provider struct {
Preset string `json:"preset,omitempty"` // preset this was created from, if any
Key string `json:"key"` // API key, as typed by the user
// KeyName names the key in use, and Keys are the provider's other
// accounts: keys saved to switch to (see keys.go).
KeyName string `json:"keyName,omitempty"`
Keys []KeyAccount `json:"keys,omitempty"`
// Base URLs, one per protocol the vendor serves natively. magpie appends
// the usual paths: chat/responses bases end in /v1 (OpenAI style),
// the Anthropic base is the root (what ANTHROPIC_BASE_URL takes).