diff --git a/internal/gui/assets/app.css b/internal/gui/assets/app.css index bf5bae40e..d1a81522f 100644 --- a/internal/gui/assets/app.css +++ b/internal/gui/assets/app.css @@ -2861,6 +2861,7 @@ body.window .ag-sk-icon { width: 22px; height: 22px; border-radius: 6px; } .badge.path.via { background: var(--accent-soft); color: var(--accent); } .badge.path.direct { background: var(--pill); color: var(--muted); box-shadow: inset 0 0 0 1px var(--line); } .badge.ctx { background: var(--pill); color: var(--muted); box-shadow: inset 0 0 0 1px var(--line); letter-spacing: .02em; } +.badge.mkey { background: var(--pill); color: var(--muted); box-shadow: inset 0 0 0 1px var(--line); font-weight: 500; letter-spacing: 0; text-transform: none; max-width: 14em; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .badge.wsl { background: var(--pill); color: var(--muted); box-shadow: inset 0 0 0 1px var(--line); letter-spacing: .02em; text-transform: none; } /* how a provider bills, plan or pay as you go (EV_John_Liu on X): grey, a fact */ .badge.bill { background: var(--pill); color: var(--muted); letter-spacing: .02em; text-transform: none; } diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index 8838f48a4..e4513c168 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -5306,6 +5306,19 @@ function tellTag(tell) { return tell ? el("span", "mtell", tell) : null; } +// keysTag: which of a provider's keys list a model, when not all of them +// do (cliddO11 on X): the key's name, two named, or how many; none when +// every key lists it +function keysTag(p, m) { + const ids = m.keys || []; + if (!ids.length) return null; + const n = m.keyCount || ids.length; + const names = ids.map((id) => { const k = p.keyList?.find((x) => x.id === id); return k ? k.name || k.masked : id; }); + const tag = el("span", "badge mkey", n <= 2 ? names.join(" · ") : t("{n} keys", { n })); + tag.title = t("Listed by {keys} only", { keys: names.join(", ") + (n > names.length ? " …" : "") }); + return tag; +} + // contextTag: the small grey 1M by a model that holds a million tokens or // more (Cursor's names said it, and no longer do); the usual 128K–400K // aren't marked, as nearly every model has one of those; nor is a name @@ -11477,6 +11490,8 @@ function renderModels(p) { c.append(el("span", "", m.name && m.name !== m.id ? m.name : m.id)); const tell = tellTag(tells.get(m.id)); if (tell) c.append(tell); + const kt = keysTag(p, m); + if (kt) c.append(kt); // one the plan serves at no cost to it (WorkBuddy's x0.00 credits) // or one its vendor names free (#185), or lists at $0 const free = m.free || m.zero || namedFree(m.id, m.name); diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index a3dfe4fbe..f06348fa4 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -2280,6 +2280,7 @@ const I18N = { "Pause: the gateway uses the other accounts, {agent} stays signed in to this one": "暂停:网关改用其他账号,{agent} 仍登录在这个账号上", "Resume: the gateway uses this account first again": "恢复:网关重新优先使用这个账号", "{n} keys": "{n} 个密钥", + "Listed by {keys} only": "只有 {keys} 列出这个模型", "Filled in from the curl command: {what}.": "已从 curl 命令填入:{what}。", "Filled in from the pasted text: {what}.": "已从粘贴的文本填入:{what}。", "The pasted text gives no web address: type the base URL.": "粘贴的文本里没有网址:请填写 API 地址。", @@ -7528,6 +7529,7 @@ const I18N = { "Pause: the gateway uses the other accounts, {agent} stays signed in to this one": "暫停:閘道改用其他帳號,{agent} 仍登入在這個帳號上", "Resume: the gateway uses this account first again": "恢復:閘道重新優先使用這個帳號", "{n} keys": "{n} 個金鑰", + "Listed by {keys} only": "只有 {keys} 列出這個模型", "Filled in from the curl command: {what}.": "已從 curl 指令填入:{what}。", "Filled in from the pasted text: {what}.": "已從貼上的文字填入:{what}。", "The pasted text gives no web address: type the base URL.": "貼上的文字裡沒有網址:請填寫 API 位址。", @@ -12751,6 +12753,7 @@ const I18N = { "Pause: the gateway uses the other accounts, {agent} stays signed in to this one": "一時停止:ゲートウェイは他のアカウントを使い、{agent} はこのアカウントにサインインしたままです", "Resume: the gateway uses this account first again": "再開:ゲートウェイは再びこのアカウントを最初に使います", "{n} keys": "{n} 個のキー", + "Listed by {keys} only": "このモデルを一覧に持つのは {keys} だけです", "Filled in from the curl command: {what}.": "curl コマンドから入力しました:{what}。", "Filled in from the pasted text: {what}.": "貼り付けたテキストから入力しました:{what}。", "The pasted text gives no web address: type the base URL.": "貼り付けたテキストに URL がありません。ベース URL を入力してください。", @@ -18005,6 +18008,7 @@ const I18N = { "Pause: the gateway uses the other accounts, {agent} stays signed in to this one": "Pausieren: Der Zugangspunkt verwendet die anderen Konten, {agent} bleibt bei diesem angemeldet", "Resume: the gateway uses this account first again": "Fortsetzen: Der Zugangspunkt verwendet dieses Konto wieder zuerst", "{n} keys": "{n} Schlüssel", + "Listed by {keys} only": "Nur {keys} führt dieses Modell", "Filled in from the curl command: {what}.": "Aus dem curl-Befehl übernommen: {what}.", "Filled in from the pasted text: {what}.": "Aus dem eingefügten Text übernommen: {what}.", "The pasted text gives no web address: type the base URL.": "Der eingefügte Text enthält keine Webadresse: Gib die Basis-URL ein.", diff --git a/internal/gui/model_keys_test.go b/internal/gui/model_keys_test.go new file mode 100644 index 000000000..d6ca07e64 --- /dev/null +++ b/internal/gui/model_keys_test.go @@ -0,0 +1,79 @@ +package gui + +import ( + "fmt" + "os" + "slices" + "testing" + + "github.com/yetone/magpie/internal/catalog" + "github.com/yetone/magpie/internal/provider" +) + +// A provider whose keys each list their own models (cliddO11 on X) says +// in its editor which keys list a model, when not all of them in use do: +// a model every key lists, one only an off key lists, and one of a list +// not asked per key carry none. +func TestModelSaysItsKeysWhenTheyDiffer(t *testing.T) { + t.Setenv("HOME", t.TempDir()) + t.Setenv("USERPROFILE", os.Getenv("HOME")) + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + t.Setenv("XDG_CACHE_HOME", t.TempDir()) + a, b, c, d := provider.KeyID("sk-aaaa1111"), provider.KeyID("sk-bbbb2222"), provider.KeyID("sk-cccc3333"), provider.KeyID("sk-dddd4444") + p := provider.Provider{ID: "relay", Name: "Relay", Chat: "https://relay.example/v1", Key: "sk-aaaa1111", Keys: []provider.KeyAccount{ + {Key: "sk-bbbb2222", Name: "Team"}, {Key: "sk-cccc3333", Off: true}, {Key: "sk-dddd4444"}, + }} + if err := catalog.SaveLive("relay", "https://relay.example/v1", []catalog.Model{ + {ID: "every", Keys: []string{d, c, b, a}}, + {ID: "two", Keys: []string{d, a}}, + {ID: "one", Keys: []string{b}}, + {ID: "off-only", Keys: []string{c}}, + {ID: "unasked"}, + }); err != nil { + t.Fatal(err) + } + got := map[string]modelJSON{} + for _, m := range providerInfo(p, nil).Models { + got[m.ID] = m + } + want := map[string][]string{"every": nil, "two": {a, d}, "one": {b}, "off-only": nil, "unasked": nil} + for id, keys := range want { + m, ok := got[id] + if !ok { + t.Fatalf("%s not listed: %v", id, got) + } + if !slices.Equal(m.Keys, keys) || m.KeyCount != 0 { + t.Errorf("%s: keys %v (count %d), want %v", id, m.Keys, m.KeyCount, keys) + } + } + + // one key in use: nothing to tell apart + p.Keys = nil + for _, m := range providerInfo(p, nil).Models { + if m.Keys != nil { + t.Errorf("single key: %s says keys %v", m.ID, m.Keys) + } + } +} + +// Past keysShown a model names no more keys and says how many: a provider +// of a thousand keys sends no thousand ids with each model. +func TestModelKeysCapped(t *testing.T) { + var on []string + at := map[string]int{} + for i := range 1000 { + id := fmt.Sprintf("k%04d", i) + at[id] = len(on) + on = append(on, id) + } + ids, n := keysApart(slices.Concat(on[:999], []string{"gone"}), on, at) + if n != 999 || !slices.Equal(ids, on[:keysShown]) { + t.Fatalf("999 of 1000: %v, %d", ids, n) + } + if ids, n := keysApart(on, on, at); ids != nil || n != 0 { + t.Fatalf("every key: %v, %d", ids, n) + } + if ids, n := keysApart([]string{"k0002", "k0001", "k0002"}, on, at); n != 2 || !slices.Equal(ids, []string{"k0001", "k0002"}) { + t.Fatalf("in the keys' order, once each: %v, %d", ids, n) + } +} diff --git a/internal/gui/providers.go b/internal/gui/providers.go index 3cca51477..b14b32331 100644 --- a/internal/gui/providers.go +++ b/internal/gui/providers.go @@ -105,6 +105,44 @@ type modelJSON struct { // vendor's list's, else models.dev's, within Listed; Model settings' // Max output shows it when none is set (sayagoodbyeplz on Discord) ListedOutput int `json:"listedOutput,omitempty"` // absent when Output + // Keys are the ids of the provider's keys in use whose own list has + // the model, in the keys' order, when some of them don't (cliddO11 on + // X): absent when every key lists it. At most keysShown, with KeyCount + // how many there are when more. + Keys []string `json:"keys,omitempty"` + KeyCount int `json:"keyCount,omitempty"` +} + +// keysShown is the most key ids a model of the editor names: past that the +// editor says how many, and a provider of a thousand keys sends no list of +// them with each model. +const keysShown = 6 + +// keysApart is which of on (the provider's keys in use, in order; at is +// each one's place in it) listed a model, by listed (catalog.Model.Keys), +// and how many: none when every one of them did or none did, or when on is +// a single key. +func keysApart(listed, on []string, at map[string]int) ([]string, int) { + if len(on) < 2 || len(listed) == 0 { + return nil, 0 + } + idx := make([]int, 0, len(listed)) + for _, id := range listed { + if i, ok := at[id]; ok { + idx = append(idx, i) + } + } + slices.Sort(idx) + idx = slices.Compact(idx) + if len(idx) == 0 || len(idx) == len(on) { + return nil, 0 + } + n := len(idx) + ids := make([]string, 0, min(n, keysShown)) + for _, i := range idx[:min(n, keysShown)] { + ids = append(ids, on[i]) + } + return ids, n } type providerJSON struct { @@ -1116,6 +1154,17 @@ func providerInfoWith(p provider.Provider, ls provider.Listing, agents []agentUs // each model's provider/model ref, made once: the settings' maps and // every agent's hidden list are looked up by it var refs []string + // the keys in use, whose lists say which model each has (fetchPerKey) + var onKeys []string + for _, k := range out.KeyList { + if k.On { + onKeys = append(onKeys, k.ID) + } + } + keyAt := make(map[string]int, len(onKeys)) + for i, id := range onKeys { + keyAt[id] = i + } named := func(m catalog.Model, on bool) modelJSON { ref := p.ID + "/" + m.ID refs = append(refs, ref) @@ -1132,6 +1181,9 @@ func providerInfoWith(p provider.Provider, ls provider.Listing, agents []agentUs j := modelJSON{ID: m.ID, Name: m.Name, Efforts: provider.EffortsOf(m), On: on, Context: window, Output: provider.OutputWithin(window, p.ReplyLimitIn(m, set)), Listed: provider.ListedWindow(m), ListedOutput: provider.OutputWithin(provider.ListedWindow(m), p.ReplyLimitIn(m, settings.Settings{})), Max: m.MaxContext, Free: m.Free, Rate: m.Rate, RateWas: m.RateWas, Images: images, ImageSet: imageSet, Own: own, Best: newest[m.ID], Inputs: mediaInputs(m.InputModalities)} list, listed, free := pricer.Prices(set, m.ID) j.Zero = !m.Free && free + if j.Keys, j.KeyCount = keysApart(m.Keys, onKeys, keyAt); j.KeyCount == len(j.Keys) { + j.KeyCount = 0 + } // a plugin reports a model's load by its own id, not one the user // lists it by (axelburks on Discord) ownID := p.OwnModelID(m.ID) diff --git a/internal/gui/tests/model-key-tag.test.cjs b/internal/gui/tests/model-key-tag.test.cjs new file mode 100644 index 000000000..4d1a6ab24 --- /dev/null +++ b/internal/gui/tests/model-key-tag.test.cjs @@ -0,0 +1,142 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// A provider whose keys each fetch their own models (cliddO11 on X: "when +// several keys each fetch models, could a colour or a small tag mark which +// key each model belongs to?") says on a model's chip, quietly after its +// name, which keys list it when not all of them do: one key's name (its +// masked value when it has none), two keys' names, or how many past two, +// the whole list in the tooltip. A model every key lists, and every model +// of a provider whose list isn't asked per key, carries no tag. The tag is +// grey (the 1M tag's look), never the accent, and stays inside its chip at +// a phone's width. Chromium and WebKit, wide and narrow, in every language. +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(process.env.ASSET_DIR || path.resolve(__dirname, "../assets")); +const fetched = new Date(Date.now() - 3600e3).toISOString(); +const key = (id, name, active) => ({ id, name, masked: "sk-…" + id.slice(0, 4), on: true, ...(active ? { active: true } : {}) }); +const relay = { + id: "relay", name: "Relay", icon: "generic", chat: "https://relay.example.com/v1", responses: "", anthropic: "", catalog: "", + models: [ + { id: "gpt-5.5", name: "", on: true }, + { id: "claude-opus-5", name: "", on: true, keys: ["aaaaaaaaaa"] }, + { id: "glm-5.2", name: "", on: true, keys: ["bbbbbbbbbb"] }, + { id: "kimi-k3", name: "", on: true, keys: ["aaaaaaaaaa", "bbbbbbbbbb"] }, + { id: "deepseek-v4.1", name: "", on: true, keys: ["aaaaaaaaaa", "bbbbbbbbbb", "cccccccccc"], keyCount: 3 }, + ], + chosen: [], fetched, agents: [], fallback: [], headers: {}, routing: "", + key: { set: true, masked: "sk-…aaaa" }, balanceToken: { takes: false, set: false }, proxy: "", + keyList: [key("aaaaaaaaaa", "Team", true), key("bbbbbbbbbb", ""), key("cccccccccc", "Spare"), key("dddddddddd", "Night")], +}; +// one key: its models are never tagged +const single = { ...relay, id: "single", name: "Single", chat: "https://single.example.com/v1", keyList: [], models: [{ id: "gpt-5.5", name: "", on: true }] }; + +function serve(lang) { + const providers = { providers: [relay, single], presets: [], excluded: [], gateway: { running: true, window: true } }; + const state = { agents: [], profiles: [], settings: { lang, theme: "light" } }; + return async (route) => { + const req = route.request(), url = new URL(req.url()); + const json = (data) => route.fulfill({ json: data }); + if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:true};` }); + if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" }); + if (url.pathname === "/api/state") return json(state); + if (url.pathname === "/api/plugins") return json({ plugins: [] }); + if (url.pathname === "/api/providers") return json(providers); + if (url.pathname === "/api/gateway/trace") { + if (url.searchParams.get("wait")) return new Promise(() => {}); // nothing more comes + return json({ mine: true, now: new Date().toISOString(), seq: 1, totals: { requests: 0, rerouted: 0, errors: 0 }, routes: [] }); + } + if (url.pathname === "/api/gateway/history") return json({ cut: false, days: [], routes: [] }); + if (url.pathname.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 LANGS = ["en", "zh", "zh-TW", "ja", "de"]; +const cases = [...LANGS.map((lang) => [lang, 1100]), ["en", 420], ["zh", 420]]; +const keysWord = { en: "3 keys", zh: "3 个密钥", "zh-TW": "3 個金鑰", ja: "3 個のキー", de: "3 Schlüssel" }; + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + for (const [lang, width] of cases) { + test(`${engine} ${lang} ${width}px: a model says which keys list it when not all do`, async (t) => { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + const page = await (await browser.newContext({ viewport: { width, height: 800 }, reducedMotion: "reduce" })).newPage(); + 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}-model-key-tag.png`) }); + } + await browser.close(); + }); + page.setDefaultTimeout(5000); + page.setDefaultNavigationTimeout(60000); + const errors = []; + page.on("pageerror", (e) => errors.push(e.message)); + await page.route("**/*", serve(lang)); + await page.goto("http://magpie.test/?view=providers"); + + const editor = page.locator("#modal:not([hidden]) .editor"); + await page.locator(".row.provider", { hasText: "Relay" }).click(); + const chips = editor.locator(".mchips .mchip"); + await chips.first().waitFor(); + const drawn = await chips.evaluateAll((cs) => cs.map((c) => { + const tag = c.querySelector(".mkey"); + return [c.querySelector("span").textContent, tag?.textContent ?? null, tag?.title ?? null]; + })); + const only = (keys) => ({ en: `Listed by ${keys} only`, zh: `只有 ${keys} 列出这个模型`, "zh-TW": `只有 ${keys} 列出這個模型`, ja: `このモデルを一覧に持つのは ${keys} だけです`, de: `Nur ${keys} führt dieses Modell` })[lang]; + assert.deepEqual(drawn, [ + ["gpt-5.5", null, null], + ["claude-opus-5", "Team", only("Team")], + // a key with no name goes by its masked value, as its row does + ["glm-5.2", "sk-…bbbb", only("sk-…bbbb")], + ["kimi-k3", "Team · sk-…bbbb", only("Team, sk-…bbbb")], + ["deepseek-v4.1", keysWord[lang], only("Team, sk-…bbbb, Spare")], + ]); + + // quiet: grey, as the 1M tag, never the accent; the key's name as written + const look = await editor.locator(".mkey").first().evaluate((e) => { + const s = getComputedStyle(e), probe = document.createElement("span"); + probe.className = "badge ctx"; + e.parentElement.append(probe); + const ctx = getComputedStyle(probe); + const out = { color: s.color, bg: s.backgroundColor, ctxColor: ctx.color, ctxBg: ctx.backgroundColor, transform: s.textTransform, border: s.borderLeftWidth }; + probe.remove(); + return out; + }); + assert.equal(look.color, look.ctxColor); + assert.equal(look.bg, look.ctxBg); + assert.equal(look.transform, "none"); + assert.equal(look.border, "0px"); + + // each tag inside its chip, each chip inside the editor, narrow too + const ed = await editor.boundingBox(); + const n = await chips.count(); + for (let i = 0; i < n; i++) { + const c = await chips.nth(i).boundingBox(); + assert.ok(c.x >= ed.x - 0.5 && c.x + c.width <= ed.x + ed.width + 0.5, `chip ${i} ${JSON.stringify(c)} inside editor ${JSON.stringify(ed)}`); + const tag = chips.nth(i).locator(".mkey"); + if (!await tag.count()) continue; + const b = await tag.boundingBox(); + assert.ok(b.x >= c.x && b.x + b.width <= c.x + c.width + 0.5 && b.y >= c.y - 0.5 && b.y + b.height <= c.y + c.height + 0.5, `tag ${JSON.stringify(b)} inside chip ${JSON.stringify(c)}`); + } + + if (process.env.ARTIFACT_DIR) { + await fs.mkdir(process.env.ARTIFACT_DIR, { recursive: true }); + await editor.locator(".mchips").first().screenshot({ path: path.join(process.env.ARTIFACT_DIR, `${engine}-${lang}-${width}-model-key-tag-chips.png`) }); + } + + // a provider of one key: no tags + await page.keyboard.press("Escape"); + await editor.waitFor({ state: "detached" }).catch(() => {}); + await page.goto("http://magpie.test/?view=providers"); + await page.locator(".row.provider", { hasText: "Single" }).click(); + await chips.first().waitFor(); + assert.equal(await editor.locator(".mkey").count(), 0); + assert.deepEqual(errors, []); + }); + } +}