diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index 07c9fe115..2d97e5908 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -14403,9 +14403,8 @@ async function accountAction(path, body, okMsg, confirmed = false, say = (m) => // it saved them (#2862). let acctModels = null; function accountModelsOf(p, ref) { return p.accountModels?.[String(ref).toLowerCase()] || []; } -// accountModelsDraft: what the open picker of p's has picked and not saved, -// as provider/accountmodels takes it; null when nothing, false when it has -// every model unpicked, which no Save keeps. +// accountModelsDraft: the open picker's unsaved picks as accountmodels takes +// them; null when none, false when every model is unpicked. function accountModelsDraft(p) { const a = acctModels; if (!p || a?.id !== p.id) return null; @@ -14430,9 +14429,8 @@ function accountModels(p, ref, isKey, name) { if (!open) return [pill, null]; const box = el("div", "acct-models"); const chips = el("div", "mchips"); - // the models the provider serves agents, and any the account has that it no longer lists + // served models, and any the account keeps const ids = p.models.filter((m) => m.on).map((m) => m.id); - for (const id of acctModels.chosen) if (!ids.includes(id)) ids.push(id); const foot = el("div", "acm-foot"); const save = el("button", "text primary", t("Save")); const post = async (allow, msg) => { @@ -14441,6 +14439,7 @@ function accountModels(p, ref, isKey, name) { if (!await accountAction("provider/accountmodels", { id: p.id, account: ref, allow }, msg)) { acctModels = was; renderProviders(); } }; const draw = () => { + for (const id of acctModels.chosen) if (!ids.includes(id)) ids.push(id); chips.replaceChildren(); const tells = modelTells(ids.map((id) => p.models.find((x) => x.id === id) || { id })); for (const id of ids) { @@ -14459,12 +14458,20 @@ function accountModels(p, ref, isKey, name) { }; draw(); save.onclick = () => { save.classList.add("busy"); post(acctModels.chosen, t("{who} serves only {models}", { who: name, models: acctModels.chosen.join(", ") })); }; + const av = el("button", "text action", t("Select all available")); + av.title = t(isKey ? "Ticks every model this key's own list has, un-ticked ones too" : "Ticks every model shown"); + av.onclick = async () => { + const was = acctModels, r = isKey && await api("provider/keylisted", { id: p.id, account: ref }).catch((e) => (status(e.message, "warn"), null)); + if (acctModels !== was || r === null) return; + for (const id of r?.known ? r.models.filter((x) => ids.includes(x)) : ids) if (!was.chosen.includes(id)) was.chosen.push(id); + chips.isConnected ? draw() : renderProviders(); + }; const all = el("button", "text action", t("All models")); all.title = t("Every model of the provider, as an account without a list of its own"); all.onclick = () => own.length ? post([], t("{who} serves every model again", { who: name })) : (acctModels = null, renderProviders()); const x = el("button", "text", t("Cancel")); x.onclick = () => { acctModels = null; renderProviders(); }; - foot.append(el("span", "hint", t(isKey ? "Only the models picked go to this key; the others go to the provider's other keys." : "Only the models picked go to this account; the others go to the provider's other accounts.")), el("span", "grow"), all, x, save); + foot.append(el("span", "hint", t(isKey ? "Only the models picked go to this key; the others go to the provider's other keys." : "Only the models picked go to this account; the others go to the provider's other accounts.")), el("span", "grow"), av, all, x, save); box.append(chips, foot); return [pill, box]; } diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index edbd44682..118d75665 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -3911,6 +3911,9 @@ const I18N = { "{who} serves only {models}": "{who} 只用于 {models}", "{who} serves every model again": "{who} 重新用于全部模型", "Every model of the provider, as an account without a list of its own": "供应商的全部模型,和没有单独设置模型的账号一样", + "Select all available": "全选可用模型", + "Ticks every model this key's own list has, un-ticked ones too": "勾选这个密钥自己的列表里的每个模型,取消过的也勾上;点「保存」生效", + "Ticks every model shown": "勾选列出的每个模型;点「保存」生效", "Only the models picked go to this account; the others go to the provider's other accounts.": "只有选中的模型会用这个账号,其他模型交给该供应商的其他账号。", "Only the models picked go to this key; the others go to the provider's other keys.": "只有选中的模型会用这个 Key,其他模型交给该供应商的其他 Key。", "routing group": "路由组", @@ -8478,6 +8481,9 @@ const I18N = { "{who} serves only {models}": "{who} 只用於 {models}", "{who} serves every model again": "{who} 重新用於全部模型", "Every model of the provider, as an account without a list of its own": "供應商的全部模型,和沒有單獨設定模型的帳號一樣", + "Select all available": "全選可用模型", + "Ticks every model this key's own list has, un-ticked ones too": "勾選這個金鑰自己的列表裡的每個模型,取消過的也勾上;按「儲存」生效", + "Ticks every model shown": "勾選列出的每個模型;按「儲存」生效", "Only the models picked go to this account; the others go to the provider's other accounts.": "只有選中的模型會用這個帳號,其他模型交給該供應商的其他帳號。", "Only the models picked go to this key; the others go to the provider's other keys.": "只有選中的模型會用這個 Key,其他模型交給該供應商的其他 Key。", "routing group": "路由組", @@ -13059,6 +13065,9 @@ const I18N = { "{who} serves only {models}": "{who} は {models} のみに使用", "{who} serves every model again": "{who} は再びすべてのモデルに使用", "Every model of the provider, as an account without a list of its own": "プロバイダのすべてのモデル(独自のリストがないアカウントと同じ)", + "Select all available": "利用可能なモデルをすべて選択", + "Ticks every model this key's own list has, un-ticked ones too": "このキー自身のリストにあるすべてのモデルにチェックを入れます(外したものも含む)。「保存」で反映されます", + "Ticks every model shown": "表示中のすべてのモデルにチェックを入れます。「保存」で反映されます", "Only the models picked go to this account; the others go to the provider's other accounts.": "選んだモデルだけがこのアカウントを使い、他のモデルはプロバイダの他のアカウントに回ります。", "Only the models picked go to this key; the others go to the provider's other keys.": "選んだモデルだけがこのキーを使い、他のモデルはプロバイダの他のキーに回ります。", "routing group": "ルーティンググループ", @@ -17655,6 +17664,9 @@ const I18N = { "{who} serves only {models}": "{who} gilt nur für {models}", "{who} serves every model again": "{who} gilt wieder für alle Modelle", "Every model of the provider, as an account without a list of its own": "Alle Modelle des Anbieters, wie bei einem Konto ohne eigene Liste", + "Select all available": "Alle verfügbaren auswählen", + "Ticks every model this key's own list has, un-ticked ones too": "Jedes Modell aus der eigenen Liste dieses Schlüssels ankreuzen, auch abgewählte; Speichern übernimmt sie", + "Ticks every model shown": "Jedes angezeigte Modell ankreuzen; Speichern übernimmt sie", "Only the models picked go to this account; the others go to the provider's other accounts.": "Nur die gewählten Modelle gehen an dieses Konto, die übrigen an die anderen Konten des Anbieters.", "Only the models picked go to this key; the others go to the provider's other keys.": "Nur die gewählten Modelle gehen an diesen Schlüssel, die übrigen an die anderen Schlüssel des Anbieters.", "routing group": "Weiterleitungsgruppe", diff --git a/internal/gui/providers.go b/internal/gui/providers.go index 7ac08a04f..eac146a04 100644 --- a/internal/gui/providers.go +++ b/internal/gui/providers.go @@ -2153,6 +2153,12 @@ func providerRoutes(mux *http.ServeMux, w Windows) { fail(rw, err) return } + case "keylisted": + // the models the key Account's own fetched list has, for the + // key picker's Select all available; nothing saved + ms := provider.KeyListed(in.ID, req.Account) + writeJSON(rw, map[string]any{"models": ms, "known": ms != nil}) + return case "accountcap": if err := provider.SetAccountCap(in.ID, req.Account, req.Cap); err != nil { fail(rw, err) diff --git a/internal/gui/tests/account-models-available.test.cjs b/internal/gui/tests/account-models-available.test.cjs new file mode 100644 index 000000000..1e2b29c70 --- /dev/null +++ b/internal/gui/tests/account-models-available.test.cjs @@ -0,0 +1,174 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// young02036 on Discord: Fetch models ticks, for each key, the models its own +// list gained, and leaves the ones the user un-ticked alone. A key's model +// picker now has Select all available, which ticks every model the key's own +// fetched list has (provider/keylisted), the un-ticked ones too, since the +// user asks it; models the list lacks stay as they are, and nothing is saved +// until Save. A key no list marks, and a subscription's account, tick every +// model shown. In both engines, every language, at a narrow window. +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 fresh = () => ({ + codex: { + id: "codex", name: "Codex", icon: "codex-color", chat: "", responses: "", anthropic: "", catalog: "", + models: [{ id: "gpt-6", name: "", on: true }, { id: "gpt-6-mini", name: "", on: true }, { id: "gpt-5", name: "", on: false }], + agents: [], fallback: [], headers: {}, keyList: [], proxy: "", + account: { + agent: "codex", agentName: "Codex", user: "me@example.com", plan: "PLUS", + logins: [ + { user: "me@example.com", plan: "PLUS", active: true, on: true }, + { user: "spare@example.com", plan: "PLUS", on: true }, + ], + }, + accountModels: { "spare@example.com": ["gpt-6-mini"] }, + }, + relay: { + id: "relay", name: "Relay", icon: "generic", chat: "https://relay.example.com/v1", responses: "", anthropic: "", catalog: "", + models: [{ id: "big", name: "", on: true }, { id: "cheap", name: "", on: true }, { id: "mid", name: "", on: true }, { id: "off", name: "", on: false }], + agents: [], fallback: [], headers: {}, + key: { set: true, masked: "sk-…one" }, balanceToken: { takes: false, set: false }, proxy: "", + keyList: [{ id: "aaaaaaaaaa", name: "Team", masked: "sk-…one", on: true, active: true }, { id: "bbbbbbbbbb", name: "", masked: "sk-…two", on: true }], + // the user un-ticked cheap for the second key, which its group lists + accountModels: { "bbbbbbbbbb": ["big"] }, + }, +}); +// each key's own fetched list: the second key's group has big, cheap and a +// model the provider doesn't serve agents; the first key's is unknown +const listed = { bbbbbbbbbb: { models: ["big", "cheap", "off"], known: true }, aaaaaaaaaa: { models: null, known: false } }; + +function serve(lang, posts) { + const ps = fresh(); + const providers = { providers: [ps.codex, ps.relay], 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/provider/keylisted" && route.request().method() === "POST") { + const body = route.request().postDataJSON(); + posts.push({ asked: body.account, id: body.id }); + return json(listed[body.account] || { models: null, known: false }); + } + if (url.pathname === "/api/provider/accountmodels" && route.request().method() === "POST") { + const body = route.request().postDataJSON(); + posts.push(body); + const p = providers.providers.find((x) => x.id === body.id); + const am = { ...(p.accountModels || {}) }; + if (body.allow.length) am[body.account.toLowerCase()] = body.allow; + else delete am[body.account.toLowerCase()]; + p.accountModels = am; + 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)]; + await route.fulfill({ body: await fs.readFile(file), contentType }); + }; +} + +const label = { en: "Select all available", zh: "全选可用模型", "zh-TW": "全選可用模型", ja: "利用可能なモデルをすべて選択", de: "Alle verfügbaren auswählen" }; +const langs = process.env.GUI_LANG ? [process.env.GUI_LANG] : Object.keys(label); + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + for (const lang of langs) { + for (const width of [900, 420]) { + const open = async (t, name, wait) => { + 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}-${width}-${name}-available.png`) }); + } + await browser.close(); + }); + const page = await (await browser.newContext({ viewport: { width, height: 760 }, reducedMotion: "reduce" })).newPage(); + page.setDefaultTimeout(5000); + page.setDefaultNavigationTimeout(60000); + 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: name }).first().click(); + await page.locator(wait).first().waitFor(); + return { page, errors, posts }; + }; + const row = (page, id) => page.locator(`.editor .accts .acc[data-account-id="${id}"]`); + const pill = (page, id) => row(page, id).locator(".amodels"); + const panel = (page, id) => row(page, id).locator(".acct-models"); + const chips = (page, id) => panel(page, id).locator(".mchip").evaluateAll((cs) => cs.map((c) => `${c.textContent}${c.classList.contains("on") ? "*" : ""}`)); + const avail = (page, id) => panel(page, id).getByRole("button", { name: label[lang], exact: true }); + const reveal = async (page, id) => { + // a key's badge shows on hover (#841), an account's under its ⋯ + if (await pill(page, id).isVisible()) return; + await row(page, id).hover(); + if (await pill(page, id).isVisible()) return; + await row(page, id).locator(".acc-more").click(); + }; + const until = async (f) => { + for (let i = 0; i < 60; i++) { if (await f()) return true; await new Promise((r) => setTimeout(r, 50)); } + return false; + }; + // the button's words fit on its line, and nothing runs off the page + const fits = async (page, id) => { + const b = await avail(page, id).evaluate((e) => ({ over: e.scrollWidth > e.clientWidth + 1, right: e.getBoundingClientRect().right, vw: document.documentElement.clientWidth })); + assert(!b.over, "the button's words are cut"); + assert(b.right <= b.vw + 1, `the button runs off the page (${b.right} > ${b.vw})`); + }; + const saveOf = (page, id) => panel(page, id).locator(".acm-foot button.primary"); + + test(`${engine} ${lang} ${width}px: a key's Select all available ticks its own list, un-ticked ones too`, async (t) => { + const { page, errors, posts } = await open(t, "Relay", ".editor .accts .acc"); + await pill(page, "bbbbbbbbbb").click(); + assert.deepEqual(await chips(page, "bbbbbbbbbb"), ["big*", "cheap", "mid"]); + await fits(page, "bbbbbbbbbb"); + const title = await avail(page, "bbbbbbbbbb").getAttribute("title"); + assert(title, "the button says what it does"); + await avail(page, "bbbbbbbbbb").click(); + assert(await until(async () => (await chips(page, "bbbbbbbbbb")).join() === "big*,cheap*,mid"), `chips after: ${await chips(page, "bbbbbbbbbb")}`); + assert.deepEqual(posts.filter((x) => x.asked), [{ asked: "bbbbbbbbbb", id: "relay" }]); + // nothing saved till Save, which keeps the picks + assert.equal(posts.filter((x) => x.allow).length, 0, "Select all available saved by itself"); + await saveOf(page, "bbbbbbbbbb").click(); + assert(await until(() => posts.some((x) => x.allow))); + assert.deepEqual(posts.find((x) => x.allow), { id: "relay", account: "bbbbbbbbbb", allow: ["big", "cheap"] }); + assert.deepEqual(errors, []); + }); + + test(`${engine} ${lang} ${width}px: a key no list marks, and an account, tick every model shown`, async (t) => { + const { page, errors } = await open(t, "Relay", ".editor .accts .acc"); + await reveal(page, "aaaaaaaaaa"); + await pill(page, "aaaaaaaaaa").click(); + assert.deepEqual(await chips(page, "aaaaaaaaaa"), ["big", "cheap", "mid"]); + await avail(page, "aaaaaaaaaa").click(); + assert(await until(async () => (await chips(page, "aaaaaaaaaa")).join() === "big*,cheap*,mid*"), `chips after: ${await chips(page, "aaaaaaaaaa")}`); + assert(await saveOf(page, "aaaaaaaaaa").isEnabled()); + assert.deepEqual(errors, []); + }); + + test(`${engine} ${lang} ${width}px: a Codex account's Select all available ticks every model shown`, async (t) => { + const { page, errors, posts } = await open(t, "Codex", ".editor .accts .acc .amodels.set"); + await pill(page, "spare@example.com").click(); + assert.deepEqual(await chips(page, "spare@example.com"), ["gpt-6", "gpt-6-mini*"]); + await fits(page, "spare@example.com"); + await avail(page, "spare@example.com").click(); + assert(await until(async () => (await chips(page, "spare@example.com")).join() === "gpt-6*,gpt-6-mini*")); + assert.equal(posts.filter((x) => x.asked).length, 0, "an account asked a key's list"); + const missing = await page.evaluate(() => ["Select all available", "Ticks every model this key's own list has, un-ticked ones too", "Ticks every model shown"] + .flatMap((k) => ["zh", "zh-TW", "ja", "de"].filter((l) => !I18N[l]?.[k]).map((l) => `${l}: ${k}`))); + assert.deepEqual(missing, [], "every string has its translations"); + assert.deepEqual(errors, []); + }); + } + } +} diff --git a/internal/gui/tests/account-models.test.cjs b/internal/gui/tests/account-models.test.cjs index a49591820..bab46af27 100644 --- a/internal/gui/tests/account-models.test.cjs +++ b/internal/gui/tests/account-models.test.cjs @@ -167,7 +167,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", await still(page, "Spare@Example.com", pill(page, "Spare@Example.com")); assert.deepEqual(await chips(page, "Spare@Example.com"), ["gpt-6", "gpt-6-mini*"]); n = posts.length; - await panel(page, "Spare@Example.com").locator("button.action").click(); + await panel(page, "Spare@Example.com").getByRole("button", { name: w.all, exact: true }).click(); assert.deepEqual(await posted(posts, n), { id: "codex", account: "Spare@Example.com", allow: [] }); await page.locator(".editor .acct-models").waitFor({ state: "detached" }); assert.equal(await pill(page, "Spare@Example.com").textContent(), w.all); diff --git a/internal/provider/key_models_refresh.go b/internal/provider/key_models_refresh.go index b33d5ce62..714aacb7a 100644 --- a/internal/provider/key_models_refresh.go +++ b/internal/provider/key_models_refresh.go @@ -22,6 +22,7 @@ package provider import ( "slices" + "strings" "github.com/yetone/magpie/internal/catalog" ) @@ -126,3 +127,25 @@ func refreshKeyModels(id string, before, now map[string]map[string]bool) int { } return n } + +// KeyListed is the models the provider id's last fetched list marks its +// key ref (KeyID) as seeing, by the ids the provider lists them by, for +// the editor's Select all available (young02036 on Discord); nil when no +// list marks that key (one key on, a fetch not asked per key), which is +// unknown, not none. +func KeyListed(id, ref string) []string { + p, err := Find(id) + if err != nil { + return nil + } + seen := keyMarks(id)[strings.ToLower(strings.TrimSpace(ref))] + if len(seen) == 0 { + return nil + } + out := make([]string, 0, len(seen)) + for m := range seen { + out = append(out, p.ListedModelID(m)) + } + slices.Sort(out) + return out +} diff --git a/internal/provider/key_models_refresh_test.go b/internal/provider/key_models_refresh_test.go index 6cb64778c..7b4c4482b 100644 --- a/internal/provider/key_models_refresh_test.go +++ b/internal/provider/key_models_refresh_test.go @@ -142,3 +142,42 @@ func TestFetchRefreshesEachKeysModels(t *testing.T) { t.Errorf("the provider's picks were set: %v", p.Models) } } + +// young02036 on Discord: the editor's Select all available ticks every +// model a key's own list has, un-ticked ones too. KeyListed is that list, +// by the ids the provider lists them by; a key no list marks is unknown. +func TestKeyListedIsTheKeysOwnList(t *testing.T) { + prefillHome(t) + l := &relayLists{by: map[string][]string{ + "sk-a": {"gpt-5.5", "glm-5"}, + "sk-b": {"kimi-k3", "glm-5"}, + }} + srv := l.serve(t) + if err := Save(Provider{ID: "relay", Name: "Relay", Chat: srv.URL + "/v1", Key: "sk-a", + Keys: []KeyAccount{{Key: "sk-b"}}}); err != nil { + t.Fatal(err) + } + if got := KeyListed("relay", keyID("sk-b")); got != nil { + t.Fatalf("before any fetch: %v, want nil", got) + } + p, _ := Find("relay") + if _, err := p.Fetch(context.Background()); err != nil { + t.Fatal(err) + } + // the user un-ticks glm-5 for sk-b: its list still has it + if err := SetAccountModels("relay", keyID("sk-b"), []string{"kimi-k3"}); err != nil { + t.Fatal(err) + } + if got := KeyListed("relay", strings.ToUpper(keyID("sk-b"))); !slices.Equal(got, []string{"glm-5", "kimi-k3"}) { + t.Errorf("sk-b's list: %v, want [glm-5 kimi-k3]", got) + } + if got := KeyListed("relay", keyID("sk-a")); !slices.Equal(got, []string{"glm-5", "gpt-5.5"}) { + t.Errorf("sk-a's list: %v, want [glm-5 gpt-5.5]", got) + } + if got := KeyListed("relay", keyID("sk-none")); got != nil { + t.Errorf("a key no list marks: %v, want nil", got) + } + if got := KeyListed("nope", keyID("sk-a")); got != nil { + t.Errorf("no such provider: %v", got) + } +}