diff --git a/internal/gateway/routing.go b/internal/gateway/routing.go index 9e0da9f82..0007d0632 100644 --- a/internal/gateway/routing.go +++ b/internal/gateway/routing.go @@ -260,6 +260,10 @@ func init() { provider.OnRenewed(renewed) } // staleAllowance is provider.StaleAllowance, swapped in tests. var staleAllowance = provider.StaleAllowance +// RestOf is why what rests by key — a provider's id, or its id#key — is +// passed over now, while it is. +func RestOf(key string) (Rest, bool) { return restOf(key) } + // Unrest lifts the rest of what rests by key — an account just verified // with its vendor, say — so the next request asks it again. False when it // wasn't resting. diff --git a/internal/gui/assets/app.css b/internal/gui/assets/app.css index 3f6a86989..5456d14f5 100644 --- a/internal/gui/assets/app.css +++ b/internal/gui/assets/app.css @@ -1781,6 +1781,9 @@ body.window .ag-sk-icon { width: 22px; height: 22px; border-radius: 6px; } .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; } } +.acc.adding .bulk-keys { width: 100%; box-sizing: border-box; resize: vertical; min-height: 84px; font-family: var(--code); font-size: 11.5px; line-height: 1.5; padding: 6px 8px; border: 1px solid var(--line); border-radius: 6px; background: var(--card); color: var(--fg); } +.acc.adding .bulk-count { margin-left: 6px; white-space: nowrap; } +.acc .key-rest { flex: none; font-size: 11px; padding: 1px 6px; border-radius: 5px; color: var(--amber); background: var(--amber-soft); white-space: nowrap; } .acc .proto { flex: none; display: inline-flex; align-items: center; gap: 3px; height: 20px; padding: 0 5px 0 7px; font: inherit; font-size: 11px; color: var(--muted); border: 0; border-radius: 5px; background: var(--pill); white-space: nowrap; cursor: default; transition: opacity .15s, background .12s, color .12s; } .acc .proto svg { opacity: .7; transition: transform .15s var(--ease); } .acc .proto.open svg { transform: rotate(180deg); } diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index 52ec41054..6db122fd6 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -10040,6 +10040,12 @@ function renderKeyAccounts(p) { }; row.append(dot, name); if (k.name) row.append(el("span", "plan mono", k.masked)); + // one the gateway passes over after a failure: why, and until when + if (k.rest && new Date(k.rest.until) > Date.now()) { + const r = el("span", "key-rest", t("Resting · {why} · back at {time}", { why: (k.rest.status ? k.rest.status + " " : "") + t(KEY_FAIL[k.rest.why] || "failed"), time: new Date(k.rest.until).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" }) })); + r.title = t("The gateway passes this key over until then, and tries the next one"); + row.append(r); + } const proto = protoPicker(p, k.protocol, (v) => accountAction("keys/protocol", { id: p.id, ref: k.id, protocol: v })); if (proto) row.append(proto); // its own models (#474), when there is another key to send the rest to @@ -10060,13 +10066,70 @@ function renderKeyAccounts(p) { if (amBox) row.append(amBox), row.classList.add("with-am"); list.append(row); } - if (addingKey?.id === p.id) { + if (addingKey?.id === p.id && addingKey.bulk) { + // many keys at once (361 on Discord): pasted one a line, or separated + // by commas or spaces; those the provider has are passed over + const box = el("div", "acc adding bulk"); + const keys = el("textarea", "bulk-keys"); + keys.value = addingKey.key || ""; + keys.rows = 5; + keys.spellcheck = false; + keys.placeholder = t("Paste the keys, one a line or separated by commas"); + const count = el("span", "hint bulk-count"); + const add = el("button", "text primary", t("Add")); + const counted = () => { + const n = splitKeys(keys.value).length; + count.textContent = n ? t(n === 1 ? "1 key" : "{n} keys", { n }) : ""; + add.disabled = !n; + }; + keys.oninput = () => { addingKey.key = keys.value; counted(); }; + counted(); + const go = async () => { + if (!splitKeys(keys.value).length) return; + add.classList.add("busy"); + try { + providers = await api("keys/import", { id: p.id, key: keys.value, protocol: addingKey.protocol || "" }); + } catch (e) { + add.classList.remove("busy"); + if (!editorError(e.message, "err")) status(e.message, "err"); + return; + } + const { added = 0, had = 0 } = providers; + addingKey = null; + renderProviders(); + state = await api("state").catch(() => state); + renderAgents(); + saidMoved(had ? t("{n} keys added, {m} already there", { n: added, m: had }) : t("{n} keys added — each takes over when the ones before it run out", { n: added })); + }; + add.onclick = go; + keys.onkeydown = (e) => { e.stopPropagation(); if (e.key === "Enter" && (e.metaKey || e.ctrlKey)) go(); else if (e.key === "Escape") { addingKey = null; renderProviders(); } }; + const one = el("button", "link", t("Add one key")); + one.onclick = () => { addingKey = { id: p.id, name: "", key: "", protocol: addingKey.protocol }; renderProviders(); }; + const x = el("button", "text", t("Cancel")); + x.onclick = () => { addingKey = null; renderProviders(); }; + const proto = protoPicker(p, addingKey.protocol || "", (v) => { addingKey.protocol = v; }); + const bar = el("div", "kb"); + bar.append(one); + if (proto) bar.append(proto); + bar.append(count, el("span", "grow"), x, add); + box.append(keys, bar); + list.append(box); + queueMicrotask(() => keys.focus({ preventScroll: true })); + } else if (addingKey?.id === p.id) { const box = el("div", "acc adding"); // the key is what's needed; a name is only for telling keys apart const name = input(addingKey.name, t("Name (optional), 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; }; + // several keys pasted into the one field: the box takes them all + key.onpaste = (e) => { + const text = e.clipboardData?.getData("text") || ""; + if (splitKeys(text).length < 2) return; + e.preventDefault(); + addingKey = { id: p.id, name: "", key: text, protocol: addingKey.protocol, bulk: true }; + renderProviders(); + }; const add = el("button", "text primary", t("Add")); const go = async () => { add.classList.add("busy"); @@ -10084,6 +10147,10 @@ function renderKeyAccounts(p) { const proto = protoPicker(p, addingKey.protocol || "", (v) => { addingKey.protocol = v; }); 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); } + const many = el("button", "link", t("Paste several")); + many.title = t("Add many keys at once, one a line or separated by commas"); + many.onclick = () => { addingKey = { id: p.id, name: "", key: "", protocol: addingKey.protocol, bulk: true }; renderProviders(); }; + bar.append(many); if (proto) bar.append(proto); bar.append(el("span", "grow"), x, add); box.append(fields, bar); @@ -10101,6 +10168,19 @@ function renderKeyAccounts(p) { return list; } +// splitKeys is the keys in text pasted at once, as provider.SplitKeys +// reads them: one a line, or separated by commas, semicolons or spaces. +function splitKeys(text) { + const out = []; + for (let f of String(text).split(/[,;,;\s\u3000]+/)) { + f = f.replace(/^["'`]+|["'`]+$/g, ""); + if (f && !out.includes(f)) out.push(f); + } + return out; +} +// a key's rest, worded as the Routing page words a failure +const KEY_FAIL = { rate: "rate limited", credit: "out of credit", quota: "quota used up", other: "failed", auth: "sign-in required", verify: "needs verification", refused: "refused (safety filter)", proxy: "proxy not reachable", slow: "slow to start" }; + // protoPicker: which protocol a key works with. Some relays hand out one // key for Anthropic and another for OpenAI; a key set to one is used on // that endpoint only, and the gateway sends each request to the key that diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index 620e9392c..2c5b8df19 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -829,6 +829,15 @@ const I18N = { "{n} keys": "{n} 个密钥", "Make first": "设为首选", "{name} tries {key} first": "{name} 会先用 {key}", + "Resting · {why} · back at {time}": "暂停使用 · {why} · {time} 恢复", + "The gateway passes this key over until then, and tries the next one": "在此之前网关会跳过这个密钥,改用下一个", + "Paste the keys, one a line or separated by commas": "粘贴密钥,每行一个,或用逗号分隔", + "1 key": "1 个密钥", + "{n} keys added, {m} already there": "已添加 {n} 个密钥,{m} 个已存在", + "{n} keys added — each takes over when the ones before it run out": "已添加 {n} 个密钥 — 前面的用完时依次接替", + "Add one key": "添加单个密钥", + "Paste several": "批量粘贴", + "Add many keys at once, one a line or separated by commas": "一次添加多个密钥,每行一个或用逗号分隔", "Add another key": "添加另一个密钥", "Name (optional), e.g. Team": "名称(可选),例如 团队", "Name, e.g. Personal or Team": "名称,例如 个人 或 团队", @@ -3870,6 +3879,15 @@ const I18N = { "{n} keys": "{n} 個のキー", "Make first": "最初にする", "{name} tries {key} first": "{name} は最初に {key} を試します", + "Resting · {why} · back at {time}": "休止中 · {why} · {time} に復帰", + "The gateway passes this key over until then, and tries the next one": "それまでゲートウェイはこのキーを飛ばし、次のキーを使います", + "Paste the keys, one a line or separated by commas": "キーを貼り付け(1 行に 1 つ、またはカンマ区切り)", + "1 key": "1 個のキー", + "{n} keys added, {m} already there": "{n} 個のキーを追加しました({m} 個は登録済み)", + "{n} keys added — each takes over when the ones before it run out": "{n} 個のキーを追加しました — 前のキーが尽きると順に引き継ぎます", + "Add one key": "キーを 1 つ追加", + "Paste several": "まとめて貼り付け", + "Add many keys at once, one a line or separated by commas": "複数のキーを一度に追加(1 行に 1 つ、またはカンマ区切り)", "Add another key": "別のキーを追加", "Name (optional), e.g. Team": "名前(任意)、例:チーム", "Name, e.g. Personal or Team": "名前、例:個人 または チーム", @@ -6903,6 +6921,15 @@ const I18N = { "{n} keys": "{n} Schlüssel", "Make first": "An erste Stelle setzen", "{name} tries {key} first": "{name} versucht zuerst {key}", + "Resting · {why} · back at {time}": "Pausiert · {why} · zurück um {time}", + "The gateway passes this key over until then, and tries the next one": "Bis dahin überspringt das Gateway diesen Schlüssel und nimmt den nächsten", + "Paste the keys, one a line or separated by commas": "Schlüssel einfügen, einer pro Zeile oder durch Kommas getrennt", + "1 key": "1 Schlüssel", + "{n} keys added, {m} already there": "{n} Schlüssel hinzugefügt, {m} waren schon da", + "{n} keys added — each takes over when the ones before it run out": "{n} Schlüssel hinzugefügt — jeder übernimmt, wenn die davor erschöpft sind", + "Add one key": "Einen Schlüssel hinzufügen", + "Paste several": "Mehrere einfügen", + "Add many keys at once, one a line or separated by commas": "Viele Schlüssel auf einmal hinzufügen, einer pro Zeile oder durch Kommas getrennt", "Add another key": "Weiteren Schlüssel hinzufügen", "Name (optional), e.g. Team": "Name (optional), z. B. Team", "Name, e.g. Personal or Team": "Name, z. B. Privat oder Team", diff --git a/internal/gui/keys_import_test.go b/internal/gui/keys_import_test.go new file mode 100644 index 000000000..f04e2685c --- /dev/null +++ b/internal/gui/keys_import_test.go @@ -0,0 +1,79 @@ +package gui + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/yetone/magpie/internal/gateway" + "github.com/yetone/magpie/internal/provider" +) + +// keys/import adds the keys pasted at once (361 on Discord), says how many +// were new, and a key the gateway rests says so in its row. +func TestKeysImportAndRest(t *testing.T) { + h := t.TempDir() + t.Setenv("HOME", h) + t.Setenv("USERPROFILE", h) + t.Setenv("XDG_CONFIG_HOME", filepath.Join(h, ".config")) + t.Setenv("XDG_CACHE_HOME", filepath.Join(h, ".cache")) + p := provider.Provider{ID: "import-test", Name: "Import", Chat: "https://example.invalid/v1", Key: "first"} + if err := provider.Save(p); err != nil { + t.Fatal(err) + } + until := time.Now().Add(10 * time.Minute) + was := keyRestOf + keyRestOf = func(key string) (gateway.Rest, bool) { + if key == p.ID+"#"+provider.KeyID("two") { + return gateway.Rest{Why: "rate", Status: 429, Until: until}, true + } + return gateway.Rest{}, false + } + defer func() { keyRestOf = was }() + mux := http.NewServeMux() + providerRoutes(mux, nil) + w := httptest.NewRecorder() + mux.ServeHTTP(w, httptest.NewRequest("POST", "/api/keys/import", strings.NewReader(`{"id":"import-test","key":"first\ntwo, three\n\n'four'"}`))) + if w.Code != 200 { + t.Fatalf("%d %s", w.Code, w.Body) + } + var st providersJSON + if err := json.Unmarshal(w.Body.Bytes(), &st); err != nil { + t.Fatal(err) + } + if st.Added != 3 || st.Had != 1 { + t.Fatalf("added %d had %d", st.Added, st.Had) + } + var info *providerJSON + for i := range st.Providers { + if st.Providers[i].ID == p.ID { + info = &st.Providers[i] + } + } + if info == nil || len(info.KeyList) != 4 { + t.Fatalf("keys: %+v", info) + } + for i, k := range info.KeyList { + if (k.Rest != nil) != (i == 1) { + t.Fatalf("key %d rest %+v", i, k.Rest) + } + } + if r := info.KeyList[1].Rest; r.Status != 429 || r.Why != "rate" || !r.Until.Equal(until) { + t.Fatalf("rest %+v", r) + } + for _, k := range []string{`"first"`, `"two"`, `"three"`, `"four"`} { + if strings.Contains(w.Body.String(), `"key":`+k) { + t.Fatal("leaked a key") + } + } + // pasting only keys it has is refused, saying so + w = httptest.NewRecorder() + mux.ServeHTTP(w, httptest.NewRequest("POST", "/api/keys/import", strings.NewReader(`{"id":"import-test","key":"two three"}`))) + if w.Code == 200 || !strings.Contains(w.Body.String(), "already has") { + t.Fatalf("%d %s", w.Code, w.Body) + } +} diff --git a/internal/gui/providers.go b/internal/gui/providers.go index eddf8fdf6..d12920649 100644 --- a/internal/gui/providers.go +++ b/internal/gui/providers.go @@ -319,6 +319,10 @@ type providersJSON struct { // Moved is the agents the change moved off models it stopped serving // (agent.Reseat), for the page to say so. Moved []agent.Move `json:"moved,omitempty"` + // Added and Had: of the keys pasted at once (keys/import), how many + // were new and how many the provider had already. + Added int `json:"added,omitempty"` + Had int `json:"had,omitempty"` // FileError is why providers.json can't be read (provider.FileError): // the page says so over what is listed, which is then the signed-in // accounts alone, never "add your first provider". @@ -407,6 +411,15 @@ func providerInfo(p provider.Provider, agents []agentUse) providerJSON { if out.KeyList == nil { out.KeyList = []provider.KeyInfo{} } + // a key the gateway passes over after a failure says so on its row + for i, k := range out.KeyList { + if !k.On { + continue + } + if r, ok := keyRestOf(p.RestKey(k)); ok { + out.KeyList[i].Rest = &provider.KeyRest{Why: r.Why, Status: r.Status, Until: r.Until, Key: p.RestKey(k)} + } + } if !out.Key.Set && p.Ready() { out.Key.Optional = true } @@ -525,6 +538,9 @@ func providerInfo(p provider.Provider, agents []agentUse) providerJSON { return out } +// keyRestOf is gateway.RestOf, swapped in tests. +var keyRestOf = gateway.RestOf + func providersState() providersJSON { // an account signed in since start-up is listed with its vendor's // models, not magpie's own list of them (#204): asked behind the page, @@ -1343,6 +1359,7 @@ func providerRoutes(mux *http.ServeMux, w Windows) { ID, Key, Name, Ref string Protocol provider.Protocol } + var added, had int if err := json.NewDecoder(r.Body).Decode(&in); err != nil { fail(rw, err) return @@ -1352,6 +1369,9 @@ func providerRoutes(mux *http.ServeMux, w Windows) { switch r.PathValue("action") { case "add": err = provider.AddKey(in.ID, in.Name, in.Key, in.Protocol) + case "import": + // many keys pasted at once, one a line or comma separated + added, had, err = provider.AddKeys(in.ID, provider.SplitKeys(in.Key), in.Protocol) case "protocol": err = provider.SetKeyProtocol(in.ID, in.Ref, in.Protocol) case "use": @@ -1375,7 +1395,7 @@ func providerRoutes(mux *http.ServeMux, w Windows) { // models a key sees is known only from its own list, and an off // key's isn't asked (#76), so until then a relay that hands out a // key per group would send the key nothing, or everything - if a := r.PathValue("action"); a == "add" || a == "on" { + if a := r.PathValue("action"); a == "add" || a == "import" || a == "on" { if p, err := provider.Find(in.ID); err == nil && p.Ready() && len(p.KeysOn()) > 1 { ctx, cancel := context.WithTimeout(r.Context(), 8*time.Second) p.Fetch(ctx) @@ -1383,7 +1403,7 @@ func providerRoutes(mux *http.ServeMux, w Windows) { } } st := providersState() - st.Moved = moved + st.Moved, st.Added, st.Had = moved, added, had writeJSON(rw, st) }) // Adding a subscription: magpie opens the vendor's sign-in in the diff --git a/internal/gui/tests/key-import.test.cjs b/internal/gui/tests/key-import.test.cjs new file mode 100644 index 000000000..0bec65e88 --- /dev/null +++ b/internal/gui/tests/key-import.test.cjs @@ -0,0 +1,137 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// Many keys at once (361 on Discord: 密钥比较多的话,需要批量导入的话就不方便了): +// a key provider's Add another key has Paste several, a box that takes keys +// one a line or separated by commas, counts them, and posts keys/import; +// pasting several into the one key's field opens it with them. The note +// says how many were added and how many it had. A key the gateway rests +// says why and until when on its row. The page doesn't scroll. In English +// and Chinese. +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 until = new Date(Date.now() + 10 * 60e3).toISOString(); +const relay = () => ({ + id: "relay", name: "Relay", icon: "generic", chat: "https://relay.example.com/v1", responses: "", anthropic: "", catalog: "", + models: [{ id: "big", name: "", on: true }], agents: [], fallback: [], headers: {}, + key: { set: true, masked: "sk-…one" }, balanceToken: { takes: false, set: false }, proxy: "", + keyList: [ + { id: "aaaaaaaaaa", name: "", masked: "sk-…one", on: true, active: true }, + { id: "bbbbbbbbbb", name: "", masked: "sk-…two", on: true, rest: { why: "rate", status: 429, until, key: "relay#bbbbbbbbbb" } }, + ], +}); + +function serve(lang, posts) { + const p = relay(); + const providers = { providers: [p], presets: [], excluded: [], gateway: { running: true, window: true } }; + 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/providers") return json(providers); + if (url.pathname === "/api/groups") return json({ groups: [] }); + if (url.pathname === "/api/plugins") return json({ plugins: [] }); + if (url.pathname === "/api/keys/import" && route.request().method() === "POST") { + const body = route.request().postDataJSON(); + posts.push(body); + p.keyList = [...p.keyList, { id: "cccccccccc", name: "", masked: "sk-…new", on: true }, { id: "dddddddddd", name: "", masked: "sk-…nw2", on: true }]; + return json({ ...providers, added: 2, had: 1 }); + } + 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)]; + await route.fulfill({ body: await fs.readFile(file), contentType }); + }; +} + +const words = { + en: { another: "Add another key", several: "Paste several", add: "Add", three: "3 keys", note: "2 keys added, 1 already there", rest: /Resting · 429 rate limited · back at/ }, + zh: { another: "添加另一个密钥", several: "批量粘贴", add: "添加", three: "3 个密钥", note: "已添加 2 个密钥,1 个已存在", rest: /暂停使用 · 429 限流 · .* 恢复/ }, +}; + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + for (const lang of ["en", "zh"]) { + const w = words[lang]; + const open = async (t, name) => { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + t.after(async () => { + 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}-${name}-key-import.png`) }); + } + await browser.close(); + }); + const page = await (await browser.newContext({ viewport: { width: 900, height: 760 }, reducedMotion: "reduce" })).newPage(); + page.setDefaultTimeout(5000); + const errors = []; + page.on("pageerror", (e) => errors.push(e.message)); + const posts = []; + await page.route("**/*", serve(lang, posts)); + await page.goto("http://magpie.test/?view=providers"); + await page.locator(".row.provider", { hasText: "Relay" }).first().click(); + await page.locator(".editor .accts .acc.add").waitFor(); + return { page, errors, posts }; + }; + const scrolled = (page) => page.evaluate(() => [window.scrollY, ...[...document.querySelectorAll("*")].filter((e) => e.scrollTop > 0).map((e) => `${e.className}:${e.scrollTop}`)].join(" ")); + const posted = async (posts) => { + for (let i = 0; i < 60 && !posts.length; i++) await new Promise((r) => setTimeout(r, 50)); + return posts.at(-1); + }; + + test(`${engine} ${lang}: Paste several takes many keys at once`, async (t) => { + const { page, errors, posts } = await open(t, "box"); + // a resting key says why and until when + assert.match(await page.locator('.acc[data-account-id="bbbbbbbbbb"] .key-rest').textContent(), w.rest); + assert.equal(await page.locator('.acc[data-account-id="aaaaaaaaaa"] .key-rest').count(), 0); + await page.getByRole("button", { name: w.another }).click(); + const sc = await scrolled(page); + await page.locator(".acc.adding").getByRole("button", { name: w.several }).click(); + const box = page.locator(".acc.adding.bulk textarea"); + await box.waitFor(); + assert.equal(await scrolled(page), sc, "a click scrolled"); + await box.fill("sk-one\nsk-two, sk-three\n\nsk-two"); + assert.equal((await page.locator(".bulk-count").textContent()).trim(), w.three); + await page.locator(".acc.adding.bulk").getByRole("button", { name: w.add, exact: true }).click(); + const body = await posted(posts); + assert.equal(body.id, "relay"); + assert.equal(body.key, "sk-one\nsk-two, sk-three\n\nsk-two"); + await page.locator('.acc[data-account-id="dddddddddd"]').waitFor(); + assert.equal(await page.locator(".acc.adding").count(), 0, "the box stays open"); + assert.equal((await page.locator("#status").textContent()).trim(), w.note); + assert.deepEqual(errors, []); + }); + + test(`${engine} ${lang}: several keys pasted into the key field open the box with them`, async (t) => { + const { page, errors } = await open(t, "paste"); + await page.getByRole("button", { name: w.another }).click(); + const field = page.locator(".acc.adding input[type=password]"); + await field.waitFor(); + await field.evaluate((i) => { + const dt = new DataTransfer(); + dt.setData("text/plain", "sk-a\nsk-b\nsk-c"); + i.dispatchEvent(new ClipboardEvent("paste", { clipboardData: dt, bubbles: true, cancelable: true })); + }); + const box = page.locator(".acc.adding.bulk textarea"); + await box.waitFor(); + assert.equal(await box.inputValue(), "sk-a\nsk-b\nsk-c"); + assert.equal((await page.locator(".bulk-count").textContent()).trim(), w.three); + // one key pasted stays in the field + await page.locator(".acc.adding.bulk").getByRole("button", { name: lang === "en" ? "Add one key" : "添加单个密钥" }).click(); + const one = page.locator(".acc.adding input[type=password]"); + await one.waitFor(); + await one.evaluate((i) => { + const dt = new DataTransfer(); + dt.setData("text/plain", "sk-only"); + i.dispatchEvent(new ClipboardEvent("paste", { clipboardData: dt, bubbles: true, cancelable: true })); + }); + assert.equal(await page.locator(".acc.adding.bulk").count(), 0); + assert.deepEqual(errors, []); + }); + } +} diff --git a/internal/provider/keys.go b/internal/provider/keys.go index 5d3c8d0ac..576b2e038 100644 --- a/internal/provider/keys.go +++ b/internal/provider/keys.go @@ -13,6 +13,7 @@ import ( "errors" "fmt" "strings" + "time" ) // KeyAccount is a saved key after the first. Off keeps it without using it. @@ -34,6 +35,28 @@ type KeyInfo struct { On bool `json:"on"` // in use: the first, or next in line Protocol Protocol `json:"protocol,omitempty"` // the only one it works with + + // Rest is why the gateway passes it over now, after a failure, and + // until when; nil while it takes requests. + Rest *KeyRest `json:"rest,omitempty"` +} + +// KeyRest is a key's rest as the gateway keeps it: failQuota, failRate…, +// the status it answered, until when, and the key to lift it by. +type KeyRest struct { + Why string `json:"why"` + Status int `json:"status"` + Until time.Time `json:"until"` + Key string `json:"key"` +} + +// RestKey is what the gateway rests the key k of a provider by: the +// provider's id while it has one key on, else the id and the key's. +func (p Provider) RestKey(k KeyInfo) string { + if len(p.KeysOn()) > 1 { + return p.ID + "#" + k.ID + } + return p.ID } func keyID(key string) string { @@ -101,6 +124,67 @@ func AddKey(id, name, key string, proto Protocol) error { return Save(*p) } +// SplitKeys is the keys in text pasted at once: one a line, or separated +// by commas, semicolons or spaces, trimmed of quotes, each once. +func SplitKeys(text string) []string { + var out []string + seen := map[string]bool{} + for _, f := range strings.FieldsFunc(text, func(r rune) bool { + return r == ',' || r == ';' || r == ',' || r == ';' || r == ' ' || r == '\t' || r == '\n' || r == '\r' || r == '\u3000' + }) { + f = strings.Trim(f, "\"'`") + if f != "" && !seen[f] { + seen[f] = true + out = append(out, f) + } + } + return out +} + +// AddKeys saves several keys at once, on, after the ones the provider has, +// with the protocol given: those it has already are passed over. added is +// how many were new, had how many it had. +func AddKeys(id string, keys []string, proto Protocol) (added, had int, err error) { + if err := keyProtocolOK(proto); err != nil { + return 0, 0, err + } + p, err := Find(id) + if err != nil { + return 0, 0, err + } + if p.Account != nil { + return 0, 0, errors.New("a signed-in account has no keys") + } + seen := map[string]bool{} + for _, k := range p.KeyList() { + seen[k.ID] = true + } + for _, key := range keys { + key = strings.TrimSpace(key) + if key == "" { + continue + } + if seen[keyID(key)] { + had++ + continue + } + seen[keyID(key)] = true + added++ + if p.Key == "" { + p.Key, p.KeyName, p.KeyProtocol = key, "", proto + } else { + p.Keys = append(p.Keys, KeyAccount{Key: key, Protocol: proto}) + } + } + if added == 0 { + if had > 0 { + return 0, had, fmt.Errorf("%s already has these keys", p.Name) + } + return 0, 0, errors.New("paste the keys to add") + } + return added, had, Save(*p) +} + // first is the first key as a KeyAccount, and setFirst makes k the first. func (p *Provider) first() KeyAccount { return KeyAccount{Name: p.KeyName, Key: p.Key, Protocol: p.KeyProtocol} diff --git a/internal/provider/keys_bulk_test.go b/internal/provider/keys_bulk_test.go new file mode 100644 index 000000000..8b4eb7b78 --- /dev/null +++ b/internal/provider/keys_bulk_test.go @@ -0,0 +1,64 @@ +package provider + +import ( + "path/filepath" + "reflect" + "testing" +) + +// Many keys pasted at once (361 on Discord: a provider with many keys was +// tedious to fill one by one): split one a line, or by commas or spaces, +// trimmed of quotes, each once. +func TestSplitKeys(t *testing.T) { + got := SplitKeys("sk-a\nsk-b, sk-c;\t\"sk-d\"\r\n\nsk-a sk-e,sk-f 'sk-g'") + want := []string{"sk-a", "sk-b", "sk-c", "sk-d", "sk-e", "sk-f", "sk-g"} + if !reflect.DeepEqual(got, want) { + t.Fatalf("got %q", got) + } + if len(SplitKeys(" \n , ")) != 0 { + t.Fatal("blank text has keys") + } +} + +// AddKeys saves the new ones after the provider's own, on, with the +// protocol given, in one save, and passes over the keys it has. +func TestAddKeys(t *testing.T) { + h := t.TempDir() + t.Setenv("HOME", h) + t.Setenv("USERPROFILE", h) + t.Setenv("XDG_CONFIG_HOME", filepath.Join(h, ".config")) + t.Setenv("XDG_CACHE_HOME", filepath.Join(h, ".cache")) + if err := Save(Provider{ID: "bulk", Name: "Bulk", Chat: "https://example.invalid/v1", Key: "k1"}); err != nil { + t.Fatal(err) + } + // the key it has is passed over, the others go after it + added, had, err := AddKeys("bulk", []string{"k1", "k2", "k2", "k3"}, "") + if err != nil || added != 2 || had != 2 { + t.Fatalf("added %d had %d: %v", added, had, err) + } + p, _ := Find("bulk") + if p.Key != "k1" || len(p.Keys) != 2 || p.Keys[0].Key != "k2" || p.Keys[1].Key != "k3" || p.Keys[0].Off { + t.Fatalf("saved %q %+v", p.Key, p.Keys) + } + added, had, err = AddKeys("bulk", []string{"k3", "k4"}, Anthropic) + if err != nil || added != 1 || had != 1 { + t.Fatalf("added %d had %d: %v", added, had, err) + } + p, _ = Find("bulk") + if l := p.Keys[len(p.Keys)-1]; l.Key != "k4" || l.Protocol != Anthropic { + t.Fatalf("last %+v", l) + } + if _, _, err := AddKeys("bulk", []string{"k1", "k4"}, ""); err == nil { + t.Fatal("only keys it had: no error") + } + if _, _, err := AddKeys("bulk", nil, ""); err == nil { + t.Fatal("no keys: no error") + } + // the rest key the gateway gives each: the id alone with one key on + if k := (Provider{ID: "x", Key: "a"}).KeyList()[0]; (Provider{ID: "x", Key: "a"}).RestKey(k) != "x" { + t.Fatal("one key rests as the provider") + } + if k := p.KeyList()[1]; p.RestKey(k) != "bulk#"+KeyID("k2") { + t.Fatalf("rest key %q", p.RestKey(k)) + } +}