diff --git a/docs/subsystems/providers-accounts.md b/docs/subsystems/providers-accounts.md index f5c7cfada..da19aba4f 100644 --- a/docs/subsystems/providers-accounts.md +++ b/docs/subsystems/providers-accounts.md @@ -257,6 +257,14 @@ of an id (`untagged`: `deepseek-v4.1-flash (WB)`, `[WB] …`, full-width it may be a variant's (`deepseek-v4.1-flash[fast]`), and a tagged id is never priced. `TestUserSameGivesTheSpecs`, `TestTaggedIDHasTheModelsSpecs`, `TestSameAsGivesAnUnlistedModelItsSpecs`. +The Same as box has a picker beside it (timfang4162 on X): the app's menu +over `GET /api/catalog/models` (`catalogModels` in +[`catalog_models.go`](../../internal/gui/catalog_models.go)), the synced +models.dev catalog with one entry a model by `catalog.SameModel`, read from +the cache with no fetch, filtered by id, name and maker +(`modelSamePick` in [`modellimits.js`](../../internal/gui/assets/modellimits.js)). +A pick only fills the box, so it is staged and saved as a typed id is. +`TestCatalogModelsListsTheSyncedCatalogOnce`, `model-same-pick.test.cjs`. A model can also be listed by an id the user gives it at its provider (zeewell on X: a relay's `deepseek-v4.1-flash-1017` as diff --git a/internal/gui/assets/app.css b/internal/gui/assets/app.css index 1de2e40d1..dc82ed909 100644 --- a/internal/gui/assets/app.css +++ b/internal/gui/assets/app.css @@ -3772,6 +3772,10 @@ body.window .ag-sk-icon { width: 22px; height: 22px; border-radius: 6px; } .mname .mapi { flex: none; min-height: 24px; font-size: 11px; } .mname .msame { display: flex; align-items: center; gap: 6px; flex: 0 1 230px; min-width: 0; font-size: 11.5px; color: var(--muted); } .mname .msame span { flex: none; } +.mname .msame-wrap { display: flex; align-items: center; gap: 2px; flex: 0 1 260px; min-width: 0; } +.mname .msame-wrap .msame { flex: 1 1 auto; } +.mname .mpick { flex: none; display: inline-flex; align-items: center; justify-content: center; width: 25px; height: 25px; padding: 0; color: var(--muted); } +.mpick-menu { max-width: min(420px, calc(100vw - 16px)); } .mname .msame input { flex: 1; min-width: 0; height: 25px; font-size: 11.5px; } .mname .mlimits { display: contents; } .mname .mlimit { flex: 0 1 170px; } diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index 9bce818bf..b4e401f40 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -11536,8 +11536,6 @@ function renderModels(p) { if (!ids.length) { names.append(el("span", "hint", t("Pick a model first."))); return; } const prefs = draft.modelPrefs = draft.modelPrefs || {}; draft.onModelPrefs = drawNames; - // how the agents' lists will call them (#868), and that the setting is - // every provider's, on Settings (joe on Discord) const sfx = el("div", "msuffix suffix-said"); const sfxSaid = el("span", "hint"); const first = p.models.find((x) => x.id === ids[0]) || { id: ids[0], name: ids[0] }; @@ -11562,12 +11560,10 @@ function renderModels(p) { sfx.append(sfxSaid, el("span", "where", t("“Provider in model names” is one setting for every provider")), where); sfx.append(noNamesLine("span", "said")); names.append(sfx); - // the APIs a model can be asked on (modelAPIs) const apis = modelAPIs(p); for (const id of ids) { const m = p.models.find((x) => x.id === id) || { id, name: id }; const own = m.default || m.name || m.id; - // what is staged for it, and what it is saved as const pref = () => prefs[id] = prefs[id] || {}; const savedName = m.default ? m.name : ""; const levels = m.efforts || []; @@ -11604,6 +11600,8 @@ function renderModels(p) { same.onkeydown = (e) => { e.stopPropagation(); if (e.key === "Enter") same.blur(); else if (e.key === "Escape") { same.value = sameNow(); same.blur(); } }; sameBox.append(el("span", "", t("Same as")), same); row.append(sameBox); + // its models.dev picker, in modellimits.js + window.modelSamePick ? modelSamePick(sameBox, same) : import("./modellimits.js").then(() => modelSamePick(sameBox, same), () => {}); // the id it is listed by here, asked for by its own (zeewell on X) const savedID = m.vendor ? m.id : ""; const idNow = () => prefs[id]?.id ?? savedID; @@ -11639,7 +11637,6 @@ function renderModels(p) { const shown = (n) => String(Math.round(n * 1e6) / 1e6); const listTier = m.list?.tiers?.[0]; const priceBox = el("div", "mprice"); - // a Remote magpie's model is listed at what that magpie counts it at priceBox.title = m.remoteList ? t("What {id} costs, in US dollars per million tokens, as the Usage page counts it; empty: what the other magpie counts it at, shown greyed. A price set here isn't multiplied by the provider's price rate", { id: m.id }) : t("What {id} costs, in US dollars per million tokens, as the Usage page counts it; empty: its list price, shown greyed. A price set here isn't multiplied by the provider's price rate", { id: m.id }); diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index f3791d3bc..6ee9dc2dc 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -727,6 +727,8 @@ const I18N = { "Allowances refreshed": "额度已刷新", "Quit": "退出", "Filter…": "筛选…", + "Pick from models.dev": "从 models.dev 选择", + "models.dev's list could not be read": "无法读取 models.dev 的列表", // agents "No agents found": "没有找到 Agent", @@ -5745,6 +5747,8 @@ const I18N = { "Allowances refreshed": "額度已重新整理", "Quit": "退出", "Filter…": "篩選…", + "Pick from models.dev": "從 models.dev 選擇", + "models.dev's list could not be read": "無法讀取 models.dev 的清單", "No agents found": "沒有找到 Agent", "Install Claude Code, Codex, Gemini CLI, OpenCode… and magpie will list them here.": "安裝 Claude Code、Codex、Gemini CLI、OpenCode 等之後,會列在這裡。", "Show {n} more": "顯示其餘 {n} 個", @@ -10725,6 +10729,8 @@ const I18N = { "Allowances refreshed": "利用枠を更新しました", "Quit": "終了", "Filter…": "絞り込み…", + "Pick from models.dev": "models.dev から選ぶ", + "models.dev's list could not be read": "models.dev の一覧を読み込めませんでした", "No agents found": "エージェントが見つかりません", "Install Claude Code, Codex, Gemini CLI, OpenCode… and magpie will list them here.": "Claude Code、Codex、Gemini CLI、OpenCode… をインストールすると、magpie がここに表示します。", "Show {n} more": "さらに {n} 件表示", @@ -15723,6 +15729,8 @@ const I18N = { "Allowances refreshed": "Kontingente aktualisiert", "Quit": "Beenden", "Filter…": "Filtern…", + "Pick from models.dev": "Aus models.dev wählen", + "models.dev's list could not be read": "Die Liste von models.dev konnte nicht gelesen werden", "No agents found": "Keine Agenten gefunden", "Install Claude Code, Codex, Gemini CLI, OpenCode… and magpie will list them here.": "Installieren Sie Claude Code, Codex, Gemini CLI, OpenCode…, dann listet magpie sie hier auf.", "Show {n} more": "{n} weitere anzeigen", diff --git a/internal/gui/assets/modellimits.js b/internal/gui/assets/modellimits.js index 7b2550be4..b2ecc4b62 100644 --- a/internal/gui/assets/modellimits.js +++ b/internal/gui/assets/modellimits.js @@ -65,3 +65,36 @@ function modelSystemFill(at, m, changed) { at.append(box); return { i, own, again: () => { if (document.activeElement !== i) i.value = own() || ""; }, saved: () => m.system || 0 }; } + +// The Same as box's picker (timfang4162 on X): a button beside it opens the +// models of the models.dev catalog magpie has synced (/api/catalog/models) in +// the app's menu, filtered by id, name and maker. A pick fills the box, which +// stages it as a typed one does. +let catalogModels = null; +window.modelSamePick = (box, same) => { + const label = t("Pick from models.dev"), b = el("button", "text action mpick"); + b.type = "button"; + b.append(svg(CHEV, 12)); + b.title = label; + b.setAttribute("aria-label", label); + b.setAttribute("aria-haspopup", "menu"); + const wrap = el("div", "msame-wrap"); + box.replaceWith(wrap); + wrap.append(box, b); + b.onclick = async (e) => { + e.stopPropagation(); + if (!catalogModels) { + try { + const got = await api("catalog/models"); + if (Array.isArray(got) && got.length) catalogModels = got; + } catch {} + } + if (!catalogModels) { status(t("models.dev's list could not be read"), "warn"); return; } + const opts = catalogModels.map((c) => ({ + v: c.id, name: c.id, literalName: true, + note: [c.name, c.context ? tokenSize(c.context) : "", c.input || c.cost ? "$" + c.input + " / $" + c.cost : ""].filter(Boolean).join(" · "), + find: [c.name, c.maker].filter(Boolean).join(" "), + })); + openProtoMenu(b, opts, same.value.trim(), (v) => { same.value = v; same.onchange(); }, "Pick from models.dev", "mpick-menu", "left", false, "Filter…"); + }; +}; diff --git a/internal/gui/catalog_models.go b/internal/gui/catalog_models.go new file mode 100644 index 000000000..b71674523 --- /dev/null +++ b/internal/gui/catalog_models.go @@ -0,0 +1,77 @@ +package gui + +import ( + "net/http" + "slices" + "sort" + "strings" + + "github.com/yetone/magpie/internal/catalog" +) + +// catalogModel is one model of the synced models.dev catalog, as the model +// editor's "Same as" picker lists it. +type catalogModel struct { + ID string `json:"id"` + Name string `json:"name,omitempty"` + Maker string `json:"maker,omitempty"` + Context int `json:"context,omitempty"` + Output int `json:"output,omitempty"` + Input float64 `json:"input,omitempty"` + Cost float64 `json:"cost,omitempty"` + Images bool `json:"images,omitempty"` +} + +// catalogModels lists the models of the catalog magpie already synced +// (nothing is fetched), one a model: the providers that serve the same +// model (catalog.SameModel) are one entry, taken from the one that lists +// its window and price. Sorted by name. +func catalogModels() []catalogModel { + best := map[string]catalog.Model{} + score := func(m catalog.Model) int { + n := 0 + if m.Price != nil { + n += 2 + } + if m.Context > 0 { + n++ + } + return n + } + for _, pid := range catalog.Providers() { + for _, m := range catalog.Provider(pid) { + k := catalog.SameModel(m.ID) + if k == "" { + continue + } + if old, ok := best[k]; !ok || score(m) > score(old) { + best[k] = m + } + } + } + out := make([]catalogModel, 0, len(best)) + for _, m := range best { + c := catalogModel{ID: m.ID, Name: m.Name, Maker: catalog.ProviderName(m.Provider), Context: m.Context, Output: m.Output, Images: m.Images} + if m.Price != nil { + c.Input, c.Cost = m.Price.Input, m.Price.Output + } + if c.Name == c.ID { + c.Name = "" + } + out = append(out, c) + } + sort.Slice(out, func(i, j int) bool { + a, b := strings.ToLower(out[i].ID), strings.ToLower(out[j].ID) + if a != b { + return a < b + } + return out[i].ID < out[j].ID + }) + return slices.Clip(out) +} + +func catalogModelsRoutes(mux *http.ServeMux) { + mux.HandleFunc("GET /api/catalog/models", func(rw http.ResponseWriter, r *http.Request) { + writeJSON(rw, catalogModels()) + }) +} diff --git a/internal/gui/catalog_models_test.go b/internal/gui/catalog_models_test.go new file mode 100644 index 000000000..a6a499b17 --- /dev/null +++ b/internal/gui/catalog_models_test.go @@ -0,0 +1,48 @@ +package gui + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "testing" + + "github.com/yetone/magpie/internal/catalog" +) + +// The model editor's Same as picker lists the synced models.dev catalog, +// one entry a model, from the provider that lists its window and price. +func TestCatalogModelsListsTheSyncedCatalogOnce(t *testing.T) { + home := t.TempDir() + t.Setenv("HOME", home) + t.Setenv("USERPROFILE", home) + t.Setenv("XDG_CONFIG_HOME", filepath.Join(home, ".config")) + t.Setenv("XDG_CACHE_HOME", filepath.Join(home, ".cache")) + os.MkdirAll(filepath.Dir(catalog.CachePath()), 0o755) + os.WriteFile(catalog.CachePath(), []byte(`{ + "moonshotai":{"id":"moonshotai","name":"Moonshot AI","models":{"kimi-k3":{"id":"kimi-k3","name":"Kimi K3","cost":{"input":0.6,"output":2.5},"limit":{"context":262144,"output":32768},"modalities":{"input":["text","image"],"output":["text"]}}}}, + "relay":{"id":"relay","name":"Relay","models":{"moonshotai/kimi-k3":{"id":"moonshotai/kimi-k3","name":"Kimi K3"}, "other-1":{"id":"other-1","name":"Other"}}}}`), 0o644) + catalog.Reset() + t.Cleanup(catalog.Reset) + mux := http.NewServeMux() + catalogModelsRoutes(mux) + rw := httptest.NewRecorder() + mux.ServeHTTP(rw, httptest.NewRequest("GET", "/api/catalog/models", nil)) + var got []catalogModel + if err := json.Unmarshal(rw.Body.Bytes(), &got); err != nil { + t.Fatal(err, rw.Body.String()) + } + if len(got) != 2 { + t.Fatalf("%+v; want kimi-k3 once and other-1", got) + } + var k catalogModel + for _, m := range got { + if m.ID == "kimi-k3" { + k = m + } + } + if k.Input != 0.6 || k.Cost != 2.5 || k.Context != 262144 || k.Output != 32768 || !k.Images || k.Maker != "Moonshot AI" { + t.Errorf("kimi-k3 = %+v; want the provider that lists its window and price", k) + } +} diff --git a/internal/gui/providers.go b/internal/gui/providers.go index 3fd9d4ee7..a1d33e250 100644 --- a/internal/gui/providers.go +++ b/internal/gui/providers.go @@ -1438,6 +1438,7 @@ func providerRoutes(mux *http.ServeMux, w Windows) { tuneRoutes(mux) groupRoutes(mux) localHostsRoutes(mux) + catalogModelsRoutes(mux) // how each key's or account's requests stand under its limit on // requests at once (#892), read every two seconds while a provider's // rows are shown; empty when the gateway runs elsewhere diff --git a/internal/gui/tests/model-same-pick.test.cjs b/internal/gui/tests/model-same-pick.test.cjs new file mode 100644 index 000000000..5783be653 --- /dev/null +++ b/internal/gui/tests/model-same-pick.test.cjs @@ -0,0 +1,128 @@ +// timfang4162 (X): in a model's metadata a typed id is all the editor gave +// for binding it to models.dev's data. The Same as box now has a picker +// beside it: the app's own menu (never a