diff --git a/internal/agent/agent.go b/internal/agent/agent.go index 505d9990c..9345f00b3 100644 --- a/internal/agent/agent.go +++ b/internal/agent/agent.go @@ -34,6 +34,10 @@ type Option struct { GroupIcon string `json:"groupIcon,omitempty"` Ref string `json:"ref,omitempty"` // the catalog model, the same in every agent Free bool `json:"free,omitempty"` // costs its subscription nothing + // Zero is a model its provider lists at $0 (provider.PricedFree), where + // Free is the vendor's own word: the picker says free by it too + // (jiangguochao666 on X) + Zero bool `json:"zero,omitempty"` // Rate and RateWas are the credits a request costs its subscription, // as a multiple, and before a discount running now (Qoder's 0.5×, // WorkBuddy's x0.03), when its vendor lists them diff --git a/internal/agent/route.go b/internal/agent/route.go index 5da9bb8ec..a516a168f 100644 --- a/internal/agent/route.go +++ b/internal/agent/route.go @@ -90,7 +90,7 @@ func sameList(a, b []Option) bool { func sameOption(a, b Option) bool { return a.Value == b.Value && a.Label == b.Label && a.Note == b.Note && a.Icon == b.Icon && slices.Equal(a.Icons, b.Icons) && a.Group == b.Group && a.GroupIcon == b.GroupIcon && - a.Ref == b.Ref && a.Free == b.Free && a.Rate == b.Rate && a.RateWas == b.RateWas && + a.Ref == b.Ref && a.Free == b.Free && a.Zero == b.Zero && a.Rate == b.Rate && a.RateWas == b.RateWas && a.Context == b.Context && a.Takes == b.Takes && a.Direct == b.Direct && a.Via == b.Via && a.Same == b.Same && a.Served == b.Served && a.Alias == b.Alias && a.FastFor == b.FastFor && a.Fast == b.Fast && a.OwnFast == b.OwnFast && a.UltraOK == b.UltraOK && a.Ultra == b.Ultra && @@ -148,6 +148,7 @@ func buildVia(agent, prefix string) []Option { return u } fast, ultra := provider.FastPicks(agent), provider.UltraPicks(agent) + set := settings.Shared() // the prices the user set, read once for the list var tiered map[string]bool // provider.UltraModels, read at the first fast model for _, e := range shown { if e.Group != "" { @@ -162,6 +163,9 @@ func buildVia(agent, prefix string) []Option { o := Option{Value: prefix + e.ID, Label: e.Name, Note: note, Icon: e.Provider.Icon, Group: e.Provider.Name, Ref: e.ID, Free: e.Free, Rate: e.Rate, RateWas: e.RateWas, Context: e.Context, own: own[e.Provider.ID], sub: e.Provider.Account != nil && (e.Provider.Account.Agent != "claude" || agent == "claude")} + if !e.Free { + o.Zero = e.Provider.PricedFree(set, e.Model) + } // a model with a fast mode is switched fast in the picker (#954) if provider.CanFast(e.Provider, e.Model) { o.FastFor, o.Fast = agent, slices.Contains(fast, e.ID) diff --git a/internal/agent/zero_option_test.go b/internal/agent/zero_option_test.go new file mode 100644 index 000000000..767b301ee --- /dev/null +++ b/internal/agent/zero_option_test.go @@ -0,0 +1,61 @@ +package agent + +import ( + "os" + "path/filepath" + "testing" + + "github.com/yetone/magpie/internal/catalog" + "github.com/yetone/magpie/internal/provider" + "github.com/yetone/magpie/internal/settings" +) + +// jiangguochao666 on X: an agent's model picker says free by a model its +// provider lists at $0 (Option.Zero, provider.PricedFree), as OpenRouter's +// foo:free, and not by the paid foo beside it. A price the user sets +// afterwards is seen at once: the list built for the old settings isn't +// kept. +func TestPickerSaysAZeroPricedModelIsFree(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")) + if err := os.MkdirAll(filepath.Dir(catalog.CachePath()), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(catalog.CachePath(), []byte(`{"zfree":{"models":{ + "foo:free":{"id":"foo:free","cost":{"input":0,"output":0}}, + "foo":{"id":"foo","cost":{"input":1,"output":2}}}}}`), 0o644); err != nil { + t.Fatal(err) + } + catalog.Reset() + t.Cleanup(catalog.Reset) + if err := provider.Save(provider.Provider{ID: "zf", Name: "ZF", Catalog: "zfree", Key: "k", Chat: "https://zf.example/v1", Models: []string{"foo:free", "foo"}}); err != nil { + t.Fatal(err) + } + of := func() map[string]Option { + out := map[string]Option{} + for _, o := range viaMagpie("opencode", "magpie/") { + out[o.Ref] = o + } + return out + } + got := of() + if o, ok := got["zf/foo:free"]; !ok || !o.Zero || o.Free { + t.Fatalf("the $0 model: %+v %v", o, ok) + } + if o, ok := got["zf/foo"]; !ok || o.Zero { + t.Fatalf("the paid model: %+v %v", o, ok) + } + + s := settings.Load() + one, zero := 1.0, 0.0 + s.ModelPrices = map[string]settings.ModelPrice{"zf/foo:free": {Input: &one, Output: &one, CacheRead: &zero, CacheWrite: &zero}} + if err := settings.Save(s); err != nil { + t.Fatal(err) + } + if o := of()["zf/foo:free"]; o.Zero { + t.Fatalf("a model the user pays for is still free: %+v", o) + } +} diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index a6b0b1747..f2ad18894 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -5225,10 +5225,14 @@ function namedFree(...names) { return names.some((n) => /(^|[^a-z])free($|[^a-z])/i.test(n || "")); } +// freeWhy: why a model is free: its plan's word, its provider's $0 price +// (provider.PricedFree, jiangguochao666 on X) or its name +const freeWhy = (plan, zero) => t(plan ? "free: it doesn't use the plan's credits" : zero ? "free: listed at $0 on this provider" : "free: so its name says"); + // freeBadge: the green FREE by a model, and why it is free -function freeBadge(plan) { +function freeBadge(plan, zero) { const f = el("span", "badge free", t("free")); - f.title = t(plan ? "free: it doesn't use the plan's credits" : "free: so its name says"); + f.title = freeWhy(plan, zero); return f; } @@ -5401,7 +5405,7 @@ function renderList() { words.append(el("span", "v", own ? t(o.label || o.value) : o.label || o.value)); const tell = tellTag(o.tell); if (tell) words.append(tell); - if (o.free || (pick.modelPicker && o.value && namedFree(o.value, o.label))) words.append(freeBadge(o.free)); + if (o.free || o.zero || (pick.modelPicker && o.value && namedFree(o.value, o.label))) words.append(freeBadge(o.free, o.zero)); const rate = rateTag(o.rate, o.rateWas); if (rate) words.append(rate); const ctx = contextTag(o.context, o.label); @@ -11196,8 +11200,8 @@ function renderModels(p) { const tell = tellTag(tells.get(m.id)); if (tell) c.append(tell); // one the plan serves at no cost to it (WorkBuddy's x0.00 credits) - // or one its vendor names free (#185) - const free = m.free || namedFree(m.id, m.name); + // or one its vendor names free (#185), or lists at $0 + const free = m.free || m.zero || namedFree(m.id, m.name); if (free) c.append(el("span", "badge free", t("free"))); const rate = rateTag(m.rate, m.rateWas); if (rate) c.append(rate); @@ -11213,7 +11217,7 @@ function renderModels(p) { } if (m.default) c.title = `${m.id} · ${m.default}`; else if (m.name && m.name !== m.id) c.title = m.id; - if (free) c.title = (c.title || m.id) + " · " + t(m.free ? "free: it doesn't use the plan's credits" : "free: so its name says"); + if (free) c.title = (c.title || m.id) + " · " + freeWhy(m.free, m.zero); if (noAPI(m)) c.title = (c.title || m.id) + "\n" + t("{p} has no URL for the API its list serves it on ({apis}), so agents aren't offered it. Add that URL, or set the API it is asked on in Names, prices & levels.", { p: p.name, apis: (apiNow(m.id) ? [apiNow(m.id)] : m.auto || []).map(apiLabel).join(" · ") }); if (served.has(m.id)) c.title = (c.title || m.id) + "\n" + t(draft.unlisted ? "Routing groups use it: none are picked, so the vendor's list is used" : "Agents see it: none are picked, so the vendor's list is used") + "\n" + t("Click to pick just this model"); else if (on && draft.unlisted && !decideOnly(p)) c.title = (c.title || m.id) + "\n" + t("Picked: the routing groups it is in use it. Agents don't see it."); @@ -11706,7 +11710,7 @@ function renderModels(p) { // just the free ones (Discord: 是否可以支持只选择免费模型), offered only // when the list has both free and paid models: with none free it would // pick nothing, with all free it is Select all - const isFree = (m) => m.free || namedFree(m.id, m.name); + const isFree = (m) => m.free || m.zero || namedFree(m.id, m.name); if (p.models.some(isFree) && !p.models.every(isFree)) { const freeOn = el("button", "text action", t("Free only")); freeOn.title = t("Pick only the free models (those the filter shows), unpicking the others"); diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index 22b6fde47..e0576d573 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -1614,6 +1614,7 @@ const I18N = { "costs {rate} credits a request, {was} before the discount": "每次请求消耗 {rate} 积分,折扣前 {was}", "free now, {was} before the discount": "限时免费,原价 {was}", "free: so its name says": "免费:模型名称如此标明", + "free: listed at $0 on this provider": "免费:此服务商标价为 $0", "holds {n} tokens": "上下文 {n} tokens", "{n} model": "{n} 个模型", "{n} models": "{n} 个模型", @@ -6173,6 +6174,7 @@ const I18N = { "costs {rate} credits a request, {was} before the discount": "每次請求消耗 {rate} 積分,折扣前 {was}", "free now, {was} before the discount": "限時免費,原價 {was}", "free: so its name says": "免費:模型名稱如此標明", + "free: listed at $0 on this provider": "免費:此服務商標價為 $0", "holds {n} tokens": "上下文 {n} tokens", "{n} model": "{n} 個模型", "{n} models": "{n} 個模型", @@ -10706,6 +10708,7 @@ const I18N = { "costs {rate} credits a request, {was} before the discount": "1 リクエストあたり {rate} クレジット(割引前は {was})", "free now, {was} before the discount": "現在無料(割引前は {was})", "free: so its name says": "無料:名前にそう記載されています", + "free: listed at $0 on this provider": "無料:このプロバイダーでの価格は $0 です", "holds {n} tokens": "{n} トークンまで", "{n} model": "{n} 件のモデル", "{n} models": "{n} 件のモデル", @@ -15270,6 +15273,7 @@ const I18N = { "costs {rate} credits a request, {was} before the discount": "kostet {rate} Credits pro Anfrage, {was} vor dem Rabatt", "free now, {was} before the discount": "derzeit kostenlos, {was} vor dem Rabatt", "free: so its name says": "kostenlos: laut Modellname", + "free: listed at $0 on this provider": "kostenlos: bei diesem Anbieter mit $0 gelistet", "holds {n} tokens": "fasst {n} Token", "{n} model": "{n} Modell", "{n} models": "{n} Modelle", diff --git a/internal/gui/assets/plugins/routing/client.js b/internal/gui/assets/plugins/routing/client.js index 1a180018d..564491db5 100644 --- a/internal/gui/assets/plugins/routing/client.js +++ b/internal/gui/assets/plugins/routing/client.js @@ -6654,7 +6654,8 @@ function routingPage(part) { const decides = d.members.some((m) => !subOf(m) && deciderOf(m)), chats = d.members.some((m) => subOf(m) || !deciderOf(m)); const subs = decides ? [] : groups.groups.filter((x) => !x.hidden && !x.decides && x.id !== g?.id && !(g && x.holds?.includes(g.id))) .map((x) => ({ value: "group/" + x.id, label: x.name, note: noted("group/" + x.id, "group/" + x.id), icons: groupIcons(x), group: ROUTING_GROUPS, ref: "group/" + x.id })); - const ref = (x) => ({ value: x.id, label: x.name || x.id, note: noted(x.providerName, x.id), icon: x.icon, group: x.providerName, ref: x.id, context: x.context }); + // free: the vendor's word, zero: listed at $0 there (jiangguochao666 on X) + const ref = (x) => ({ value: x.id, label: x.name || x.id, note: noted(x.providerName, x.id), icon: x.icon, group: x.providerName, ref: x.id, context: x.context, free: x.free, zero: x.zero }); // the image models after them, said as such (jzw690 on X): a group // of them is picked in Settings › Images, or named at the images API const drawRef = (x) => ({ ...ref(x), note: noted(`${x.providerName} · ${t("Image model")}`, x.id) }); @@ -7452,7 +7453,7 @@ function routingPage(part) { if (sg) cb.append(stackIcon(groupIcons(sg)), el("span", "", `${sg.name} · ${t("routing group")}`)); else if (d.classifier) cb.append(icon(m?.icon || "generic"), el("span", "", m ? `${m.name || m.id} · ${m.providerName}` : d.classifier)); else cb.append(el("span", "", t("choose a model"))); - const opt = (x) => ({ value: x.id, label: x.name || x.id, note: x.providerName, icon: x.icon, group: x.providerName, ref: x.id, context: x.context }); + const opt = (x) => ({ value: x.id, label: x.name || x.id, note: x.providerName, icon: x.icon, group: x.providerName, ref: x.id, context: x.context, free: x.free, zero: x.zero }); const subs = groups.groups.filter((x) => !x.hidden && x.id !== g?.id) .map((x) => ({ value: "group/" + x.id, label: x.name, note: "group/" + x.id, icons: groupIcons(x), group: ROUTING_GROUPS, ref: "group/" + x.id })); cb.onclick = (ev) => openPicker({ id: "", name: "", fields: [] }, { key: "classifier", label: "model", value: d.classifier, options: [...deciders.map(opt), ...subs, ...groups.models.map(opt)], diff --git a/internal/gui/groups.go b/internal/gui/groups.go index fe3b05c04..204569b13 100644 --- a/internal/gui/groups.go +++ b/internal/gui/groups.go @@ -12,6 +12,7 @@ import ( "github.com/yetone/magpie/internal/agent" "github.com/yetone/magpie/internal/gateway" "github.com/yetone/magpie/internal/provider" + "github.com/yetone/magpie/internal/settings" ) // groupsJSON is what the Routing view manages: the routing groups, the @@ -175,11 +176,16 @@ type modelRef struct { // whichever is named (a ChatGPT account's, #1865), which Settings › // Images says VendorPicks bool `json:"vendorPicks,omitempty"` + // Free: it costs its subscription nothing (the vendor's word); Zero: its + // provider lists it at $0 (provider.PricedFree). The add-a-model picker + // says free by either (jiangguochao666 on X) + Free bool `json:"free,omitempty"` + Zero bool `json:"zero,omitempty"` } // servedRef is a served model as the Routing page lists it -func servedRef(e provider.Entry) modelRef { - return modelRef{ID: e.ID, Name: e.Name, Provider: e.Provider.ID, PName: e.Provider.Name, Icon: e.Provider.Icon, Context: e.Context, Efforts: e.Efforts, CanFast: provider.CanFast(e.Provider, e.Model), OwnFast: provider.OwnFast(e.Provider, e.Model), Images: seesImages(e), ImagesUnknown: imagesUnknown(e), Sub: e.Provider.Account != nil} +func servedRef(e provider.Entry, s settings.Settings) modelRef { + return modelRef{Free: e.Free, Zero: !e.Free && e.Provider.PricedFree(s, e.Model), ID: e.ID, Name: e.Name, Provider: e.Provider.ID, PName: e.Provider.Name, Icon: e.Provider.Icon, Context: e.Context, Efforts: e.Efforts, CanFast: provider.CanFast(e.Provider, e.Model), OwnFast: provider.OwnFast(e.Provider, e.Model), Images: seesImages(e), ImagesUnknown: imagesUnknown(e), Sub: e.Provider.Account != nil} } type poolJSON struct { @@ -309,10 +315,11 @@ func groupsState() groupsJSON { out.Accounts = groupAccounts(all) served := provider.Served() chat := map[string]bool{} + set := settings.Shared() // the prices the user set, for each model's free tag for _, e := range served { if e.Group == "" { chat[e.ID] = true - out.Models = append(out.Models, servedRef(e)) + out.Models = append(out.Models, servedRef(e, set)) } } // the image models, as Settings › Images lists them: each provider's diff --git a/internal/gui/groups_sub_test.go b/internal/gui/groups_sub_test.go index aab5e69e9..c9f78158a 100644 --- a/internal/gui/groups_sub_test.go +++ b/internal/gui/groups_sub_test.go @@ -6,6 +6,7 @@ import ( "testing" "github.com/yetone/magpie/internal/provider" + "github.com/yetone/magpie/internal/settings" ) // #1839: a model a subscription account serves says so to the Routing page, @@ -13,11 +14,11 @@ import ( // request to that subscription; a key's model says nothing of it. func TestServedRefSaysASubscription(t *testing.T) { sub := servedRef(provider.Entry{ID: "codex/gpt-5-mini", Name: "gpt-5-mini", Model: "gpt-5-mini", - Provider: provider.Provider{ID: "codex", Name: "Codex", Account: &provider.Account{Agent: "codex", User: "a@x.y"}}}) + Provider: provider.Provider{ID: "codex", Name: "Codex", Account: &provider.Account{Agent: "codex", User: "a@x.y"}}}, settings.Settings{}) if !sub.Sub { t.Fatalf("a subscription's model: %+v", sub) } - key := servedRef(provider.Entry{ID: "or/flash", Name: "flash", Model: "flash", Provider: provider.Provider{ID: "or", Name: "OpenRouter", Key: "k"}}) + key := servedRef(provider.Entry{ID: "or/flash", Name: "flash", Model: "flash", Provider: provider.Provider{ID: "or", Name: "OpenRouter", Key: "k"}}, settings.Settings{}) if key.Sub { t.Fatalf("a key's model: %+v", key) } diff --git a/internal/gui/providers.go b/internal/gui/providers.go index cdc45a3c2..ee6dfe2f6 100644 --- a/internal/gui/providers.go +++ b/internal/gui/providers.go @@ -51,6 +51,7 @@ type modelJSON struct { Listed int `json:"listed,omitempty"` // its window before the user's: its vendor's list's, else models.dev's Max int `json:"max,omitempty"` // the most its context may be set to, above Listed Free bool `json:"free,omitempty"` // costs the subscription nothing + Zero bool `json:"zero,omitempty"` // listed at $0 on this provider (provider.PricedFree), where Free is the vendor's word Rate float64 `json:"rate,omitempty"` // the credits a request costs the subscription, as a multiple RateWas float64 `json:"rateWas,omitempty"` // the rate before a discount running now // Load is how busy its plugin last said the model is, a percent, when @@ -889,6 +890,7 @@ func providerInfoWith(p provider.Provider, ls provider.Listing, agents []agentUs } window := p.WindowOf(m) 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), Max: m.MaxContext, Free: m.Free, Rate: m.Rate, RateWas: m.RateWas, Images: images, ImageSet: imageSet, Own: own, Best: newest[m.ID]} + j.Zero = !m.Free && p.PricedFree(set, m.ID) // 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/zero-priced-free.test.cjs b/internal/gui/tests/zero-priced-free.test.cjs new file mode 100644 index 000000000..4066e22f0 --- /dev/null +++ b/internal/gui/tests/zero-priced-free.test.cjs @@ -0,0 +1,152 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// jiangguochao666 on X asked for each provider's free models to show in +// Routing and the pickers. A model its provider lists at $0 (zero, +// provider.PricedFree: OpenRouter's foo:free, NVIDIA NIM's) says free, with +// a hover that says why, in an agent's model picker, in the provider +// editor's model list, and in a routing group's Add a model picker. The +// paid model beside it says nothing, and one its plan serves free keeps +// the plan's hover. Every language, Chromium and WebKit, wide and narrow. +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 words = { + en: { edit: "Edit", free: "free", zero: "free: listed at $0 on this provider", plan: "free: it doesn't use the plan's credits" }, + zh: { edit: "编辑", free: "免费", zero: "免费:此服务商标价为 $0", plan: "免费:不消耗套餐积分" }, + "zh-TW": { edit: "編輯", free: "免費", zero: "免費:此服務商標價為 $0", plan: "免費:不消耗套餐積分" }, + ja: { edit: "編集", free: "無料", zero: "無料:このプロバイダーでの価格は $0 です", plan: "無料:プランのクレジットを消費しません" }, + de: { edit: "Bearbeiten", free: "kostenlos", zero: "kostenlos: bei diesem Anbieter mit $0 gelistet", plan: "kostenlos: verbraucht keine Credits des Tarifs" }, +}; + +// the agent's picker: the gateway's Option.Zero and Option.Free +const options = [ + { value: "magpie/or/nemotron-lite", ref: "or/nemotron-lite", label: "Nemotron Lite", group: "OpenRouter", icon: "openrouter", zero: true }, + { value: "magpie/or/glm-5", ref: "or/glm-5", label: "GLM-5", group: "OpenRouter", icon: "openrouter" }, + { value: "magpie/wb/kimi-k3", ref: "wb/kimi-k3", label: "Kimi K3", group: "WorkBuddy", icon: "generic", free: true }, +]; +// the editor's list: modelJSON.Zero +const fetched = new Date(Date.now() - 3600e3).toISOString(); +const relay = { + id: "or", name: "OpenRouter", icon: "openrouter", host: "openrouter.ai", chat: "https://openrouter.ai/api/v1", responses: "", anthropic: "", catalog: "openrouter", + models: [{ id: "nemotron-lite", name: "nemotron-lite", on: true, zero: true }, { id: "glm-5", name: "glm-5", on: true }], + chosen: ["nemotron-lite", "glm-5"], fetched, agents: [], fallback: [], headers: {}, + key: { set: true, masked: "sk-…one" }, keyList: [], balanceToken: { takes: false, set: false }, proxy: "", +}; +// the Routing page's models: modelRef.Zero +const models = [ + { id: "or/nemotron-lite", name: "nemotron-lite", provider: "or", providerName: "OpenRouter", icon: "openrouter", zero: true }, + { id: "or/glm-5", name: "glm-5", provider: "or", providerName: "OpenRouter", icon: "openrouter" }, +]; + +function serve(lang) { + const groups = () => ({ + models, deciders: [], pools: [], + groups: [{ id: "g", name: "G", members: ["or/glm-5"], off: [], routing: "order", ready: true, memberInfo: [{ id: "or/glm-5", ready: true, provider: "or", name: "OpenRouter", model: "glm-5" }] }], + }); + const state = { agents: [{ id: "codex", name: "Codex", path: "/test/config.toml", icon: "codex-color", wired: false, fields: [{ key: "model", label: "model", value: "magpie/or/glm-5", options }] }], profiles: [], settings: { lang, theme: "light" } }; + return async (r) => { + const url = new URL(r.request().url()); + const json = (data) => r.fulfill({ json: data }); + if (url.pathname === "/boot.js") return r.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:${JSON.stringify(lang)},theme:"light",web:true};` }); + if (url.pathname === "/wails/runtime.js") return r.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/agents/cli") return json({ agents: {}, pending: false }); + if (url.pathname === "/api/usage/quotas") return json([]); + if (url.pathname === "/api/gateway/trace") { + if (url.searchParams.get("wait")) return new Promise(() => {}); + 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 === "/api/groups") return json(groups()); + if (url.pathname.startsWith("/api/groups/")) return json(groups()); + if (url.pathname === "/api/providers") return json({ providers: [relay], presets: [], excluded: [], gateway: { running: true, window: true, url: "http://127.0.0.1:3999" } }); + 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 r.fulfill({ body: await fs.readFile(file), contentType }); + }; +} + +// a picker row's free tag: its text, its hover, and whether it sits in the row +const tagOf = (row) => row.evaluate((li) => { + const f = li.querySelector(".badge.free"); + if (!f) return null; + const r = li.getBoundingClientRect(), b = f.getBoundingClientRect(); + return { text: f.textContent, title: f.title, inside: b.width > 4 && b.left >= r.left && b.right <= r.right + 0.5 }; +}); + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + for (const width of [1100, 420]) { + for (const lang of Object.keys(words)) { + const w = words[lang]; + test(`${engine} ${width} ${lang}: a model listed at $0 says free in the agent's picker, the editor and a group's picker`, async (t) => { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + const page = await (await browser.newContext({ viewport: { width, height: 1100 }, reducedMotion: "reduce" })).newPage(); + t.after(() => browser.close()); + page.setDefaultTimeout(5000); + page.setDefaultNavigationTimeout(60000); + const errors = []; + page.on("pageerror", (e) => errors.push(e.message)); + await page.route("**/*", serve(lang)); + const sideways = () => page.evaluate(() => document.documentElement.scrollWidth > innerWidth); + + // the agent's model picker + await page.goto("http://magpie.test/"); + await page.locator('#nav [data-view="agents"]').click(); + await page.locator('#agents [data-key="model"]').first().click(); + const row = (label) => page.locator("#list li:not(.group):not(.custom)", { hasText: label }).first(); + await row("Nemotron Lite").waitFor(); + const zero = await tagOf(row("Nemotron Lite")); + assert.ok(zero, "the $0 model has no free tag in the agent's picker"); + assert.equal(zero.text, w.free); + assert.equal(zero.title, w.zero); + assert.ok(zero.inside, "the free tag is squeezed or out of its row"); + assert.equal(await tagOf(row("GLM-5")), null, "the paid model says free"); + const plan = await tagOf(row("Kimi K3")); + assert.equal(plan?.title, w.plan, "a plan's free model lost its own hover"); + assert.ok(!(await sideways()), "the page scrolls sideways"); + await page.keyboard.press("Escape"); + + // the provider editor's model list + await page.goto("http://magpie.test/?view=providers"); + await page.locator(".row.provider", { hasText: "OpenRouter" }).click(); + const editor = page.locator("#modal:not([hidden]) .editor"); + const chip = (id) => editor.locator(".mchips .mchip", { has: page.locator("span", { hasText: new RegExp(`^${id}$`) }) }); + await chip("nemotron-lite").waitFor(); + const free = chip("nemotron-lite").locator(".badge.free"); + assert.equal(await free.count(), 1, "the $0 model has no free tag in the editor"); + assert.equal((await free.textContent()).trim(), w.free); + const hover = await chip("nemotron-lite").getAttribute("title"); + assert.ok(hover.split("\n")[0].endsWith(" · " + w.zero), `the chip's hover doesn't say why it is free: ${hover}`); + assert.equal(await chip("glm-5").locator(".badge.free").count(), 0, "the paid model says free in the editor"); + assert.ok(!(await sideways()), "the page scrolls sideways"); + await page.keyboard.press("Escape"); + await page.locator("#modal").waitFor({ state: "hidden" }); + + // a routing group's Add a model picker + await page.goto("http://magpie.test/?view=routing"); + const card = page.locator('.rt-group[data-id="g"]'); + await card.waitFor(); + await card.locator("button", { hasText: w.edit }).click(); + await page.locator(".rt-gedit .rt-madds button.rt-gadd").click(); + const opt = (name) => page.locator("#pop li", { has: page.locator(".v", { hasText: new RegExp(`^${name}$`) }) }).first(); + await opt("nemotron-lite").waitFor(); + const rz = await tagOf(opt("nemotron-lite")); + assert.ok(rz, "the $0 model has no free tag in the group's picker"); + assert.equal(rz.text, w.free); + assert.equal(rz.title, w.zero); + assert.ok(rz.inside, "the free tag is squeezed or out of its row"); + assert.equal(await tagOf(opt("glm-5")), null, "the paid model says free in the group's picker"); + assert.ok(!(await sideways()), "the page scrolls sideways"); + + const stripes = await page.evaluate(() => [...document.querySelectorAll(".badge.free")].map((e) => getComputedStyle(e).borderLeftWidth).filter((b) => parseFloat(b) > 1)); + assert.deepEqual(stripes, [], "no border stripes"); + assert.deepEqual(errors, []); + }); + } + } +} diff --git a/internal/gui/zero_priced_test.go b/internal/gui/zero_priced_test.go new file mode 100644 index 000000000..2358e852c --- /dev/null +++ b/internal/gui/zero_priced_test.go @@ -0,0 +1,58 @@ +package gui + +import ( + "encoding/json" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/yetone/magpie/internal/catalog" + "github.com/yetone/magpie/internal/provider" +) + +// jiangguochao666 on X: the provider editor's model list and the Routing +// page's add-a-model picker say free by a model its provider lists at $0 +// (zero, provider.PricedFree), as OpenRouter's foo:free, and not by the +// paid foo beside it; a paid model sends no zero at all. +func TestZeroPricedModelsSayFree(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()) + if err := os.MkdirAll(filepath.Dir(catalog.CachePath()), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(catalog.CachePath(), []byte(`{"zfree":{"models":{ + "foo:free":{"id":"foo:free","cost":{"input":0,"output":0}}, + "foo":{"id":"foo","cost":{"input":1,"output":2}}}}}`), 0o644); err != nil { + t.Fatal(err) + } + catalog.Reset() + t.Cleanup(catalog.Reset) + p := provider.Provider{ID: "zf", Name: "ZF", Catalog: "zfree", Key: "k", Chat: "http://127.0.0.1:1/v1", Models: []string{"foo:free", "foo"}} + if err := provider.Save(p); err != nil { + t.Fatal(err) + } + + ms := []catalog.Model{{ID: "foo:free"}, {ID: "foo"}} + zero := map[string]bool{} + for _, m := range providerInfoWith(p, provider.Listing{Available: ms, Exposed: ms}, nil, nil).Models { + zero[m.ID] = m.Zero + b, _ := json.Marshal(m) + if !m.Zero && strings.Contains(string(b), `"zero"`) { + t.Errorf("a paid model sends zero: %s", b) + } + } + if !zero["foo:free"] || zero["foo"] { + t.Fatalf("the editor's zero: %v, want foo:free only", zero) + } + + zero = map[string]bool{} + for _, m := range groupsState().Models { + zero[m.ID] = m.Zero + } + if !zero["zf/foo:free"] || zero["zf/foo"] { + t.Fatalf("the Routing page's zero: %v, want zf/foo:free only", zero) + } +} diff --git a/internal/provider/models.go b/internal/provider/models.go index 2e8846dbb..a78faea1d 100644 --- a/internal/provider/models.go +++ b/internal/provider/models.go @@ -1905,6 +1905,72 @@ func (p Provider) FreeModel(model string) bool { return ok && pr.Input == 0 && pr.Output == 0 && pr.CacheRead == 0 && pr.CacheWrite == 0 } +// PricedFree says model is listed at $0 on p (ListPrice) on every count +// and at every size: a free model a catalog prices at 0 there, as +// OpenRouter's foo:free, OpenCode Zen's -free ones or NVIDIA NIM's. The +// pickers say free beside it (jiangguochao666 on X), where catalog.Model's +// Free has only the vendor's own word. It is p's price alone: the same id +// on another provider is that one's, and its maker's (makerListPrice) or +// a plan's catalog's says nothing of p's. A model nothing prices is not free, +// nor one the user set a price for that isn't 0: their word is the price +// Usage counts. +func (p Provider) PricedFree(s settings.Settings, model string) bool { + if pr, ok := userPrice(s, p, model); ok { + return zeroPrice(pr) + } + pr, ok, from := p.listPrice(model) + switch { + case !ok || !zeroPrice(pr): + return false + case from == pricedMaker: + // its maker gives it away (Zhipu's glm-4.7-flash): a relay that + // serves it may not + return false + case from == pricedCatalog: + // a plan's catalog (zai-coding-plan) lists what its members pay + // per token, nothing, not what the model costs: only a catalog + // that is no plan's says it is free + plain := slices.DeleteFunc(priceCatalogs(p.priceCatalogsOf()), func(c string) bool { return strings.Contains(c, "-plan") }) + for _, m := range p.priceNames(model) { + if pr, ok := catalog.PricedBy(plain, m); ok { + return zeroPrice(pr) + } + } + return false + } + return true +} + +// userPrice is the price the user set for p's model (settings' +// ModelPrices): for that model, for every model of p, then for the model +// from any provider (*/model), still the user's word, so before any list +// price. +func userPrice(s settings.Settings, p Provider, model string) (catalog.Price, bool) { + for _, key := range [...]string{p.ID + "/" + model, p.ID + "/*", AnyPriceKey(model)} { + if m, ok := s.ModelPrices[key]; ok { + if pr, bad := m.Price(); bad == "" { + // a Claude model's 1-hour cache write left out: 2× input + catalog.OneHourFor(model, &pr) + return pr, true + } + } + } + return catalog.Price{}, false +} + +// zeroPrice is a price of nothing on every count and every tier. +func zeroPrice(pr catalog.Price) bool { + if pr.Input != 0 || pr.Output != 0 || pr.CacheRead != 0 || pr.CacheWrite != 0 || pr.CacheWrite1h != 0 { + return false + } + for _, t := range pr.Tiers { + if t.Input != 0 || t.Output != 0 || t.CacheRead != 0 || t.CacheWrite != 0 { + return false + } + } + return true +} + // Known are the model's own reasoning levels, when known. func (p Provider) Known(model string) []string { for _, m := range p.Available() { @@ -2023,64 +2089,91 @@ var makerCatalogs = sync.OnceValue(func() []string { // auto-review through the Codex subscription costs nothing too, as OpenAI // serves it a ChatGPT sign-in (codexReviewFree). func (p Provider) ListPrice(model string) (catalog.Price, bool) { + pr, ok, _ := p.listPrice(model) + return pr, ok +} + +// Where ListPrice found a price: p's own word (its catalog, its plugin, +// its vendor's code), the catalog p names, or the model's maker's +// catalog, which says nothing of what p charges. +const ( + pricedOwn = iota + pricedCatalog + pricedMaker +) + +// listPrice is ListPrice, and where it found the price. +func (p Provider) listPrice(model string) (catalog.Price, bool, int) { if own := p.OwnModelID(model); own != model { // a model listed by an id the user gave it is priced as the // provider's own id of it first, then as the id it is listed by - if pr, ok := p.ListPrice(own); ok { - return pr, true + if pr, ok, from := p.listPrice(own); ok { + return pr, true, from } } if pr, ok := p.remotePrice(model); ok { - return pr, true + return pr, true, pricedOwn } if p.clineFreeModel(model) || p.kiloFreeModel(model) || p.codexReviewFree(model) { // served at no cost: not at the price of the model it is free of - return catalog.Price{}, true + return catalog.Price{}, true, pricedOwn } if pr, ok := p.cursorFastPrice(model); ok { - return pr, true + return pr, true, pricedOwn } if pr, ok := p.factoryFastPrice(model); ok { - return pr, true + return pr, true, pricedOwn } if pr, ok := p.grokFastPrice(model); ok { - return pr, true - } - names := pricedNames(model) - if p.kimiCodeMember() { - if id, ok := kimiCodeAPI[strings.ToLower(strings.TrimSpace(model))]; ok { - names = append(names, id) - } - } - cats := p.Catalogs() - if c := p.EndpointCatalog(); c != "" { - cats = []string{c} + return pr, true, pricedOwn } + names := p.priceNames(model) + cats := p.priceCatalogsOf() for _, m := range names { if pr, ok := catalog.PricedBy(priceCatalogs(cats), m); ok { - return pr, true + return pr, true, pricedCatalog } if pr, ok := makerListPrice(m); ok { - return pr, true + return pr, true, pricedMaker } } if slices.Contains(cats, "anthropic") { // a gated Claude model models.dev prices nowhere (Claude Mythos // 5.1): Anthropic's price, as it told Claude Code if pr, ok := claudeCodePrice(model); ok { - return pr, true + return pr, true, pricedMaker } } if pr, ok := p.vendorListPrice(model); ok { - return pr, true + return pr, true, pricedOwn } if pr, ok := p.pluginListPrice(model); ok { - return pr, true + return pr, true, pricedOwn } if p.pluginFree(model) { - return catalog.Price{}, true + return catalog.Price{}, true, pricedOwn } - return catalog.Price{}, false + return catalog.Price{}, false, pricedOwn +} + +// priceNames are the ids ListPrice looks model up by in a catalog. +func (p Provider) priceNames(model string) []string { + names := pricedNames(model) + if p.kimiCodeMember() { + if id, ok := kimiCodeAPI[strings.ToLower(strings.TrimSpace(model))]; ok { + names = append(names, id) + } + } + return names +} + +// priceCatalogsOf are the catalogs ListPrice prices p's models from: the +// ones it names, else the one at its endpoint (EndpointCatalog). +func (p Provider) priceCatalogsOf() []string { + if c := p.EndpointCatalog(); c != "" { + return []string{c} + } + return p.Catalogs() } // vendorCatalogs are the models.dev catalogs of the vendors a moved @@ -2496,21 +2589,12 @@ func (p Provider) PriceAt(s settings.Settings, model string, at time.Time) (cata // a vendor that bills by the hour (PeakOf). func tariffOf(s settings.Settings, p Provider, known bool, model string) (catalog.Price, bool) { id := p.ID - // then what they said the model costs from any provider (*/model): - // still the user's word, so before any list price - for _, key := range [...]string{id + "/" + model, id + "/*", AnyPriceKey(model)} { - if m, ok := s.ModelPrices[key]; ok { - if pr, bad := m.Price(); bad == "" { - // a Claude model's 1-hour cache write left out: 2× input - catalog.OneHourFor(model, &pr) - // a vendor that bills by the hour doubles any price in its - // peak hours: the user's is the off-peak one, as its list - // price is, so setting one keeps the split (treeman on - // Discord) - pr.Peak = p.PeakOf(model) - return pr, true - } - } + if pr, ok := userPrice(s, p, model); ok { + // a vendor that bills by the hour doubles any price in its peak + // hours: the user's is the off-peak one, as its list price is, so + // setting one keeps the split (treeman on Discord) + pr.Peak = p.PeakOf(model) + return pr, true } if !known { if p.codexReviewFree(model) { // signed out since: still a ChatGPT sign-in's diff --git a/internal/provider/pricedfree_test.go b/internal/provider/pricedfree_test.go new file mode 100644 index 000000000..24a9f92e6 --- /dev/null +++ b/internal/provider/pricedfree_test.go @@ -0,0 +1,88 @@ +package provider + +import ( + "os" + "testing" + + "github.com/yetone/magpie/internal/catalog" + "github.com/yetone/magpie/internal/settings" +) + +// jiangguochao666 on X asked the pickers to say which of each provider's +// models are free. PricedFree says so only where the provider's own price +// is $0: OpenRouter's foo:free, not foo, and not the same id another +// provider charges for. A model nothing prices is not free, nor one a +// plan's catalog lists at $0 (that is the plan's per-token price), nor one +// only its maker gives away (a relay serving Zhipu's free glm-4.7-flash +// may charge for it). A price the user set is theirs: one that isn't 0, at +// any size, makes the model paid, and a $0 one makes it free. +func TestPricedFreeIsTheProvidersOwnZero(t *testing.T) { + prefsHome(t) + data := `{ + "zfree":{"models":{ + "foo:free":{"id":"foo:free","cost":{"input":0,"output":0}}, + "foo":{"id":"foo","cost":{"input":1,"output":2}}, + "shared":{"id":"shared","cost":{"input":0,"output":0,"cache_read":0}}, + "cached":{"id":"cached","cost":{"input":0,"output":0,"cache_read":0.1}}, + "nocost":{"id":"nocost"} + }}, + "zpaid":{"models":{"shared":{"id":"shared","cost":{"input":3,"output":15}}}}, + "zz-coding-plan":{"models":{"plan-model":{"id":"plan-model","cost":{"input":0,"output":0}}}}, + "zhipuai":{"models":{"glm-4.7-flash":{"id":"glm-4.7-flash","cost":{"input":0,"output":0}}}} + }` + if err := os.WriteFile(catalog.CachePath(), []byte(data), 0o644); err != nil { + t.Fatal(err) + } + catalog.Reset() + + free := Provider{ID: "zf", Name: "ZF", Catalog: "zfree", Key: "k", Chat: "http://127.0.0.1:9/v1"} + paid := Provider{ID: "zp", Name: "ZP", Catalog: "zpaid", Key: "k", Chat: "http://127.0.0.1:9/v1"} + plan := Provider{ID: "zc", Name: "ZC", Catalog: "zz-coding-plan", Key: "k", Chat: "http://127.0.0.1:9/v1"} + zhipu := Provider{ID: "zh", Name: "ZH", Catalog: "zhipuai", Key: "k", Chat: "http://127.0.0.1:9/v1"} + relay := Provider{ID: "rl", Name: "RL", Key: "k", Chat: "http://127.0.0.1:9/v1"} + none := settings.Settings{} + for _, c := range []struct { + p Provider + model string + want bool + }{ + {free, "foo:free", true}, + {free, "foo", false}, + {free, "shared", true}, + {paid, "shared", false}, + {free, "cached", false}, + {free, "nocost", false}, + {free, "nobody-lists-this", false}, + {plan, "plan-model", false}, + {zhipu, "glm-4.7-flash", true}, + {relay, "glm-4.7-flash", false}, + } { + if got := c.p.PricedFree(none, c.model); got != c.want { + t.Errorf("%s's %s: PricedFree %v, want %v", c.p.ID, c.model, got, c.want) + } + } + + zero, one := 0.0, 1.0 + s := settings.Settings{ModelPrices: map[string]settings.ModelPrice{ + // a paid price over 1000 tokens of input + "zf/foo:free": {Input: &zero, Output: &zero, CacheRead: &zero, CacheWrite: &zero, Tiers: []catalog.Tier{{Above: 1000, Input: 1}}}, + // what the user pays their relay for it: nothing + "rl/glm-4.7-flash": {Input: &zero, Output: &zero, CacheRead: &zero, CacheWrite: &zero}, + // every model of ZH costs them something + "zh/*": {Input: &one, Output: &one, CacheRead: &zero, CacheWrite: &zero}, + }} + for _, c := range []struct { + p Provider + model string + want bool + }{ + {free, "foo:free", false}, + {relay, "glm-4.7-flash", true}, + {zhipu, "glm-4.7-flash", false}, + {free, "shared", true}, + } { + if got := c.p.PricedFree(s, c.model); got != c.want { + t.Errorf("with the user's prices, %s's %s: PricedFree %v, want %v", c.p.ID, c.model, got, c.want) + } + } +}