diff --git a/internal/gui/assets/app.css b/internal/gui/assets/app.css index 5dd13dfe5..300ff2abd 100644 --- a/internal/gui/assets/app.css +++ b/internal/gui/assets/app.css @@ -2900,6 +2900,8 @@ body.window .ag-sk-icon { width: 22px; height: 22px; border-radius: 6px; } /* served with none picked: the vendor's list stands in for the picks. Drawn apart from a pick (no tick, no accent): a click picks it alone (#681) */ .mchip.auto { border-style: dashed; border-color: var(--muted); } +/* listed on none of the APIs the provider has a URL for: not offered (#2094) */ +.mchip.noapi { opacity: .5; } /* an image model in the editor: listed, not picked */ .mchip.ro, .mchip.ro:hover { cursor: default; color: var(--muted); border-color: var(--line); } .mchip.ro:active { transform: none; } diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index 4a0a303da..df7f96a67 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -8310,7 +8310,9 @@ function pickedOf(p) { const on = p.models.filter((m) => m.on); if (!Array.isArray(p.chosen)) return on.map((m) => m.id); // no picks said: those served, as before const picks = new Set(p.chosen); - return on.filter((m) => picks.has(m.id)).map((m) => m.id); + // a pick agents aren't offered for want of its API's URL stays picked + // (#2094): it is offered again once the URL is added + return p.models.filter((m) => (m.on || m.noAPI) && picks.has(m.id)).map((m) => m.id); } // baseAPIOf is the API a saved provider's Base URL is shown as: the one the @@ -10139,6 +10141,17 @@ function renderModels(p) { // staged as Names & levels stages it, and made with the Save const apis = modelAPIs(p); const apiNow = (id) => draft.modelPrefs?.[id]?.api ?? p.models.find((m) => m.id === id)?.api ?? ""; + // a model listed on none of the APIs the provider has a URL for (#2094: a + // relay's Claude on /messages alone, at a provider given its chat URL): + // agents aren't offered it, so Select all and Free only leave it, and it + // is drawn dimmed, saying why. As saved (m.noAPI), or as the API set for + // it in this editor makes it + const noAPI = (m) => { + const set = draft.modelPrefs?.[m.id]?.api; + if (set === undefined || !p.speaks?.length) return !!m.noAPI; + const on = set ? [set] : (m.auto || []); + return on.length > 0 && !on.some((a) => p.speaks.includes(a)); + }; const pickAPI = (c, id) => { const m = p.models.find((x) => x.id === id) || { id }; const auto = (m.auto || []).map(apiLabel).join(" · "); @@ -10266,7 +10279,7 @@ function renderModels(p) { // groups alone, those are what the groups use (#1818: drawn as none // while the card and the auto groups had all 17); after Select none, // none is served - const served = draft.chosen.length || decideOnly(p) || draft.none ? new Set() : new Set(p.models.slice(0, 24).map((m) => m.id)); + const served = draft.chosen.length || decideOnly(p) || draft.none ? new Set() : new Set(p.models.filter((m) => !noAPI(m)).slice(0, 24).map((m) => m.id)); // a filter is a search: what it doesn't match is left out, picked or not for (const m of p.models) { const on = draft.chosen.includes(m.id); @@ -10275,7 +10288,7 @@ function renderModels(p) { // asked for: a picked model is never out of sight (#685: 10 picked, // 7 shown, and "4 more, filter to find them" with no names to filter by) if (shown >= 80 && !f && !showAll && !on) { hidden++; continue; } - const c = el("button", "mchip" + (on ? " on" : served.has(m.id) ? " auto" : "")); + const c = el("button", "mchip" + (on ? " on" : served.has(m.id) ? " auto" : "") + (noAPI(m) ? " noapi" : "")); c.append(el("span", "", m.name && m.name !== m.id ? m.name : m.id)); // one the plan serves at no cost to it (WorkBuddy's x0.00 credits) // or one its vendor names free (#185) @@ -10288,6 +10301,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 (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 & 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"); tested(c, m.id); menu(c, m.id); @@ -10712,10 +10726,10 @@ function renderModels(p) { // every model at once (those the filter shows, when there is one), or none const bulk = el("div", "mbulk"); const allOn = el("button", "text action", t("Select all")); - allOn.title = t("Pick every model listed (those the filter shows)"); + allOn.title = t("Pick every model listed that this provider can serve (those the filter shows)"); allOn.onclick = () => { const f = (q?.value || "").trim().toLowerCase(); - const ids = p.models.filter((m) => !f || m.id.toLowerCase().includes(f) || (m.name || "").toLowerCase().includes(f) || (m.default || "").toLowerCase().includes(f)).map((m) => m.id); + const ids = p.models.filter((m) => !noAPI(m)).filter((m) => !f || m.id.toLowerCase().includes(f) || (m.name || "").toLowerCase().includes(f) || (m.default || "").toLowerCase().includes(f)).map((m) => m.id); draft.chosen = [...draft.chosen, ...ids.filter((id) => !draft.chosen.includes(id))]; draft.none = true; draw(); @@ -10733,7 +10747,7 @@ function renderModels(p) { freeOn.title = t("Pick only the free models (those the filter shows), unpicking the others"); freeOn.onclick = () => { const f = (q?.value || "").trim().toLowerCase(); - draft.chosen = p.models.filter((m) => isFree(m) && (!f || m.id.toLowerCase().includes(f) || (m.name || "").toLowerCase().includes(f) || (m.default || "").toLowerCase().includes(f))).map((m) => m.id); + draft.chosen = p.models.filter((m) => isFree(m) && !noAPI(m) && (!f || m.id.toLowerCase().includes(f) || (m.name || "").toLowerCase().includes(f) || (m.default || "").toLowerCase().includes(f))).map((m) => m.id); draft.none = true; draw(); }; diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index ff1229c14..63fdbf484 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -2060,7 +2060,8 @@ const I18N = { "Fold Names & levels": "收起名称与推理档位", "Rename the models agents see, or offer fewer of their reasoning levels": "重命名 Agent 看到的模型,或只提供部分推理档位", "Test models": "测试模型", - "Pick every model listed (those the filter shows)": "选中列出的所有模型(有筛选时只选筛出来的)", + "Pick every model listed that this provider can serve (those the filter shows)": "选中列出的、这个供应商能提供的所有模型(有筛选时只选筛出来的)", + "{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 & levels.": "{p} 没有它的列表所说接口({apis})的地址,所以 Agent 看不到它。填上那个地址,或在「名称与推理档位」里设定它走的接口。", "Unpick every model": "取消选中所有模型", "Send a tiny request to each model agents see, to find the ones that don't answer": "向 Agent 可见的每个模型发一个极小请求,找出无响应的模型", "{n} of {all} models didn't answer": "{all} 个模型中有 {n} 个没有响应", @@ -6199,7 +6200,8 @@ const I18N = { "Fold Names & levels": "收起名稱與推理檔位", "Rename the models agents see, or offer fewer of their reasoning levels": "重新命名 Agent 看到的模型,或只提供部分推理檔位", "Test models": "測試模型", - "Pick every model listed (those the filter shows)": "選中列出的所有模型(有篩選時只選篩出來的)", + "Pick every model listed that this provider can serve (those the filter shows)": "選中列出的、這個供應商能提供的所有模型(有篩選時只選篩出來的)", + "{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 & levels.": "{p} 沒有它的列表所說介面({apis})的位址,所以 Agent 看不到它。填上那個位址,或在「名稱與推理檔位」裡設定它走的介面。", "Unpick every model": "取消選中所有模型", "Send a tiny request to each model agents see, to find the ones that don't answer": "向 Agent 可見的每個模型發一個極小請求,找出無回應的模型", "{n} of {all} models didn't answer": "{all} 個模型中有 {n} 個沒有回應", @@ -10355,7 +10357,8 @@ const I18N = { "Fold Names & levels": "名前と推論レベルを折りたたむ", "Rename the models agents see, or offer fewer of their reasoning levels": "エージェントに見えるモデル名を変更するか、提供する推論レベルを絞ります", "Test models": "モデルをテスト", - "Pick every model listed (those the filter shows)": "一覧のすべてのモデルを選択(フィルター中は表示中のもの)", + "Pick every model listed that this provider can serve (those the filter shows)": "このプロバイダーが提供できる一覧のすべてのモデルを選択(フィルター中は表示中のもの)", + "{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 & levels.": "{p} には、一覧が示す API({apis})の URL がないため、エージェントには表示されません。その URL を追加するか、「名前と推論レベル」で使う API を設定してください。", "Unpick every model": "すべてのモデルの選択を解除", "Send a tiny request to each model agents see, to find the ones that don't answer": "エージェントに見える各モデルに小さなリクエストを送り、応答しないモデルを見つけます", "{n} of {all} models didn't answer": "{all} 個中 {n} 個のモデルが応答しませんでした", @@ -14520,7 +14523,8 @@ const I18N = { "Fold Names & levels": "Namen & Stufen einklappen", "Rename the models agents see, or offer fewer of their reasoning levels": "Die Modelle, die Agenten sehen, umbenennen oder weniger ihrer Reasoning-Stufen anbieten", "Test models": "Modelle testen", - "Pick every model listed (those the filter shows)": "Alle aufgeführten Modelle auswählen (die der Filter zeigt)", + "Pick every model listed that this provider can serve (those the filter shows)": "Alle aufgeführten Modelle auswählen, die dieser Anbieter bedienen kann (die der Filter zeigt)", + "{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 & levels.": "{p} hat keine URL für die API, auf der die Liste es anbietet ({apis}), daher sehen Agenten es nicht. Füge diese URL hinzu oder lege unter „Namen & Stufen“ die API fest, über die es angefragt wird.", "Unpick every model": "Auswahl aller Modelle aufheben", "Send a tiny request to each model agents see, to find the ones that don't answer": "Eine winzige Anfrage an jedes Modell senden, das Agenten sehen, um die nicht antwortenden zu finden", "{n} of {all} models didn't answer": "{n} von {all} Modellen haben nicht geantwortet", diff --git a/internal/gui/providers.go b/internal/gui/providers.go index b4210dc15..7a0335cfb 100644 --- a/internal/gui/providers.go +++ b/internal/gui/providers.go @@ -50,6 +50,7 @@ type modelJSON struct { RateWas float64 `json:"rateWas,omitempty"` // the rate before a discount running now API string `json:"api,omitempty"` // the one API the user said it is asked on Auto []string `json:"auto,omitempty"` // the APIs its vendor's list says it is served on, what Auto asks it on + NoAPI bool `json:"noAPI,omitempty"` // the provider has a URL for none of them: agents aren't offered it (provider.NoAPIFor, #2094) Same string `json:"same,omitempty"` // the model the user said it is the same as, for the groups magpie finds (#583) Merge string `json:"merge,omitempty"` // what those groups merge it by when the user says nothing Kind string `json:"kind,omitempty"` // what the user said it makes: image or video (#1399) @@ -176,9 +177,13 @@ type providerJSON struct { // AnonKey is the key Add another key adds when nothing is pasted // (provider.AnonymousKey: OpenCode Zen's public, #1795), while the // provider doesn't have it yet - AnonKey string `json:"anonKey,omitempty"` - Ready bool `json:"ready"` - Chosen []string `json:"chosen"` // the user's explicit picks, if any + AnonKey string `json:"anonKey,omitempty"` + Ready bool `json:"ready"` + Chosen []string `json:"chosen"` // the user's explicit picks, if any + // Speaks: the APIs a provider of keys has a URL for, which a model's + // own API set in the editor is checked against (NoAPI); none for a + // sign-in, whose models are never left out for it + Speaks []string `json:"speaks,omitempty"` Fallback []string `json:"fallback"` // where requests go when this one can't take them Routing string `json:"routing"` // how requests spread over its keys or accounts Affinity string `json:"affinity"` // how long a conversation stays with who answered it @@ -554,6 +559,11 @@ func providerInfo(p provider.Provider, agents []agentUse) providerJSON { if out.Fallback == nil { out.Fallback = []string{} } + if p.Account == nil { + for _, s := range p.Speaks() { + out.Speaks = append(out.Speaks, string(s)) + } + } if out.Chosen == nil { out.Chosen = []string{} } @@ -685,6 +695,7 @@ func providerInfo(p provider.Provider, agents []agentUse) providerJSON { j.Auto = append(j.Auto, string(a)) } } + j.NoAPI = p.NoAPIFor(m.ID) j.Same = sames[p.ID+"/"+m.ID] j.Kind = p.ModelKind(m.ID) j.Merge = provider.MergeName(m.ID) diff --git a/internal/gui/tests/models-select-all-api.test.cjs b/internal/gui/tests/models-select-all-api.test.cjs new file mode 100644 index 000000000..dc22fdb6d --- /dev/null +++ b/internal/gui/tests/models-select-all-api.test.cjs @@ -0,0 +1,145 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// #2094 (wangjianjq): Command Code's list serves its Claude models on +// /messages alone and the rest on chat and Responses. At a provider given +// only the chat and Responses URLs, Select all ticked the Claude models too, +// and agents were offered models no request could reach. A model listed on +// none of the APIs the provider has a URL for (noAPI) is drawn dimmed and +// says why; Select all and Free only leave it; the vendor's list (dashed) +// is the first 24 of the others; a model whose list says no API is picked +// as before. A pick of such a model made before stays picked and is saved +// again, to be offered once the URL is added. Nothing scrolls, no stripe, +// nothing runs off the side; every language, Chromium and WebKit, 1100 and +// 420 wide. +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 { strings } = require("./strings.cjs"); + +const assets = path.resolve(__dirname, "../assets"); +const { I18N } = strings(); +const fetched = new Date(Date.now() - 3600e3).toISOString(); +const relay = (id, name, models, chosen, extra = {}) => ({ + id, name, icon: "generic", host: id + ".example.com", chat: `https://${id}.example.com/v1`, responses: `https://${id}.example.com/v1`, anthropic: "", catalog: "", + speaks: ["chat", "responses"], models, chosen, fetched, agents: [], fallback: [], headers: {}, + key: { set: true, masked: "sk-…one" }, keyList: [], balanceToken: { takes: false, set: false }, proxy: "", ...extra, +}); +// as /api/providers has them: m.on is what agents are offered +const claude = (id) => ({ id, name: id, on: false, auto: ["anthropic"], noAPI: true }); +const gpt = (id, on, extra = {}) => ({ id, name: id, on, auto: ["chat", "responses"], ...extra }); +const CLAUDE = ["claude-sonnet-5-5", "claude-opus-5-5", "claude-haiku-4-5"]; +const CHAT = Array.from({ length: 26 }, (_, i) => `deepseek-v4.${i}`); +// a list's order, Claude first as Command Code's is; one model with no API +// listed, one free model on chat and one free Claude +const listed = [...CLAUDE.map(claude), ...CHAT.map((id, i) => gpt(id, i < 24)), { id: "plain-model", name: "plain-model", on: false }, + gpt("ling-3.1-flash:free", false, { free: true }), { ...claude("claude-free"), free: true }]; +const cc = relay("cc-chat", "Command Code chat", listed, []); +// picked before: a Claude model and a chat one; agents get the chat one +const picked = relay("cc-picked", "Command Code picked", [claude("claude-sonnet-5-5"), gpt("deepseek-v4.1", true), gpt("deepseek-v4.2", false)], ["claude-sonnet-5-5", "deepseek-v4.1"]); + +function serve(lang, posts) { + const providers = { providers: [cc, picked], 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 (req.method() === "POST" && url.pathname.startsWith("/api/")) posts.push({ path: url.pathname, body: req.postDataJSON() || {} }); + 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/groups") return json({ groups: [] }); + 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 TIP = "{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 & levels."; +const ALL_TIP = "Pick every model listed that this provider can serve (those the filter shows)"; + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + for (const lang of LANGS) { + for (const width of [1100, 420]) { + const tr = (k) => (lang === "en" ? k : I18N[lang][k]); + test(`${engine} ${lang} ${width}: Select all leaves the models the provider has no URL for`, async (t) => { + for (const k of [TIP, ALL_TIP, "Select all", "Free only", "Save"]) assert(tr(k), `${lang} lacks ${k}`); + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + const page = await (await browser.newContext({ viewport: { width, height: 760 }, 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}-select-all-api.png`) }); + } + await browser.close(); + }); + page.setDefaultTimeout(5000); + const errors = []; + page.on("pageerror", (e) => errors.push(e.message)); + const posts = []; + await page.route("**/*", serve(lang, posts)); + await page.goto("http://magpie.test/?view=providers"); + + const editor = page.locator("#modal:not([hidden]) .editor"); + const open = async (name) => { + await page.locator(".row.provider", { hasText: name }).click(); + await editor.locator(".ehead b", { hasText: name }).waitFor(); + await editor.locator(".mchips .mchip").first().waitFor(); + }; + const bulk = (name) => editor.locator(".mbulk").getByRole("button", { name, exact: true }); + const chipsOf = (cls) => editor.locator(`.mchips .mchip${cls}`).evaluateAll((cs) => cs.map((c) => c.querySelector("span").textContent).sort()); + const scrolled = () => page.evaluate(() => [window.scrollX, window.scrollY, ...[...document.querySelectorAll("*")].filter((e) => e.scrollTop > 0).map((e) => `${e.className}:${e.scrollTop}`)].join(" ")); + const save = async () => { + await editor.locator(".bar").getByRole("button", { name: tr("Save"), exact: true }).click(); + for (let i = 0; i < 100 && !posts.some((p) => p.path === "/api/provider/save"); i++) await page.waitForTimeout(30); + const saved = posts.find((p) => p.path === "/api/provider/save"); + assert(saved, "nothing saved"); + posts.length = 0; + return [...saved.body.models].sort(); + }; + + await open("Command Code chat"); + // the Claude models dimmed, saying why; the vendor's list (dashed) + // is the first 24 of the chat ones + assert.deepEqual(await chipsOf(".noapi"), [...CLAUDE, "claude-free"].sort()); + const tip = await editor.locator(".mchips .mchip.noapi", { hasText: "claude-opus-5-5" }).getAttribute("title"); + assert(tip.includes(tr(TIP).replace("{p}", "Command Code chat").split("{apis}")[0]), `tooltip: ${tip}`); + assert.deepEqual(await chipsOf(".auto"), CHAT.slice(0, 24).sort()); + assert.equal(await editor.locator(".mchips .mchip.noapi.auto").count(), 0); + assert(await editor.locator(".mchips .mchip.noapi").first().evaluate((e) => parseFloat(getComputedStyle(e).opacity) < 1), "not dimmed"); + assert.equal(await bulk(tr("Select all")).getAttribute("title"), tr(ALL_TIP)); + + // Free only: the free chat model, not the free Claude + await bulk(tr("Free only")).click(); + assert.deepEqual(await chipsOf(".on"), ["ling-3.1-flash:free"]); + + // Select all, the button scrolled into the editor's view first: the + // click moves nothing, and the Claude models are left + await editor.locator(".ebody").evaluate((b) => { b.scrollTop += b.querySelector(".mbulk").getBoundingClientRect().top - b.getBoundingClientRect().top - 8; }); + const before = await scrolled(); + await bulk(tr("Select all")).click(); + assert.equal(await scrolled(), before, "the click scrolled"); + const want = [...CHAT, "plain-model", "ling-3.1-flash:free"].sort(); + assert.deepEqual(await chipsOf(".on"), want); + assert.deepEqual(await save(), want); + + // nothing runs off the side, and no stripe + const over = await page.evaluate(() => [document.documentElement.scrollWidth - innerWidth, ...[...document.querySelectorAll("#modal .editor *")].filter((e) => getComputedStyle(e).borderLeftWidth !== getComputedStyle(e).borderRightWidth && parseFloat(getComputedStyle(e).borderLeftWidth) > 1).map((e) => e.className)]); + assert.deepEqual(over, [0], "overflow or stripe"); + // the fake save answers nothing, so the page is opened again + await page.goto("http://magpie.test/?view=providers"); + + // a Claude pick made before stays picked (dimmed), and is saved again + await open("Command Code picked"); + assert.deepEqual(await chipsOf(".on"), ["claude-sonnet-5-5", "deepseek-v4.1"]); + assert.deepEqual(await chipsOf(".on.noapi"), ["claude-sonnet-5-5"]); + assert.deepEqual(await save(), ["claude-sonnet-5-5", "deepseek-v4.1"]); + assert.deepEqual(errors, []); + }); + } + } +} diff --git a/internal/provider/exposed_apis_test.go b/internal/provider/exposed_apis_test.go new file mode 100644 index 000000000..ba741fb11 --- /dev/null +++ b/internal/provider/exposed_apis_test.go @@ -0,0 +1,154 @@ +package provider + +import ( + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "slices" + "strings" + "testing" + + "github.com/yetone/magpie/internal/catalog" +) + +// #2094 (wangjianjq): Command Code's Provider API lists its Claude models on +// /messages alone and the rest on chat and Responses. A provider given only +// the chat and Responses URLs, with every model picked (Select all, or the +// CLI's whole list), offered agents the Claude models too, which no request +// could reach; one given only the Anthropic URL offered every other model. +// What it offers is the models listed on an API it has a URL for, whatever +// was picked, and with nothing picked the first 24 of those; a model whose +// list says no API stays as it was. +func TestExposedOnlyOnTheAPIsTheProviderHas(t *testing.T) { + oneHome(t) + list, err := os.ReadFile(filepath.Join("testdata", "commandcode_models.json")) + if err != nil { + t.Fatal(err) + } + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if !strings.HasSuffix(r.URL.Path, "/models") { + http.NotFound(w, r) + return + } + _, _ = w.Write(list) + })) + defer srv.Close() + // the APIs each model is listed on, from the list itself + var body struct { + Data []struct { + ID string `json:"id"` + Endpoints []string `json:"supported_endpoints"` + } `json:"data"` + } + if err := json.Unmarshal(list, &body); err != nil { + t.Fatal(err) + } + var all, messages, chat []string + for _, m := range body.Data { + all = append(all, m.ID) + apis := catalog.EndpointAPIs(m.Endpoints) + if slices.Contains(apis, "anthropic") { + messages = append(messages, m.ID) + } + if slices.Contains(apis, "chat") || slices.Contains(apis, "responses") { + chat = append(chat, m.ID) + } + } + if len(messages) == 0 || len(chat) <= manyModels { + t.Fatalf("the fixture has %d models on /messages and %d on chat", len(messages), len(chat)) + } + base := srv.URL + "/provider" + for _, c := range []struct { + id string + chat, responses, anthropc string + want []string + }{ + {"cc-chat", base + "/v1", base + "/v1", "", chat}, + {"cc-messages", "", "", base, messages}, + {"cc-all", base + "/v1", base + "/v1", base, all}, + } { + t.Run(c.id, func(t *testing.T) { + p := Provider{ID: c.id, Name: c.id, Key: "sk-x", Chat: c.chat, Responses: c.responses, Anthropic: c.anthropc} + if err := Save(p); err != nil { + t.Fatal(err) + } + q, err := Find(c.id) + if err != nil { + t.Fatal(err) + } + if _, err := q.Fetch(context.Background()); err != nil { + t.Fatal(err) + } + if q, err = Find(c.id); err != nil { + t.Fatal(err) + } + if n := len(q.Available()); n != len(all) { + t.Fatalf("listed %d, want the whole list of %d", n, len(all)) + } + // nothing picked: the first 24 of those it can serve + got := idsOf(q.Exposed()) + if wantN := min(len(c.want), manyModels); len(got) != wantN { + t.Errorf("with none picked, exposed %d, want %d", len(got), wantN) + } + for _, id := range got { + if !slices.Contains(c.want, id) { + t.Errorf("with none picked, exposed %s, which it has no URL for", id) + } + } + // every model picked, as Select all or the CLI's whole list + // saves them, and one added by hand that no list names + q.Models = append(slices.Clone(all), "typed-by-hand") + if err := Save(*q); err != nil { + t.Fatal(err) + } + if q, err = Find(c.id); err != nil { + t.Fatal(err) + } + want := append(slices.Clone(c.want), "typed-by-hand") + got = idsOf(q.Exposed()) + slices.Sort(got) + slices.Sort(want) + if !slices.Equal(got, want) { + t.Errorf("with every model picked, exposed %d, want %d:\n got %v\nwant %v", len(got), len(want), got, want) + } + for _, e := range Catalog() { + if e.Provider.ID == c.id && !slices.Contains(want, e.Model) { + t.Errorf("agents are offered %s/%s", c.id, e.Model) + } + } + }) + } +} + +// The user's own API for a model is the one it is asked on (SetModelAPI): +// a model listed on /messages alone, set to Responses at a provider with a Responses +// URL, is offered; and a provider whose list says no API offers every pick. +func TestExposedKeepsTheUsersAPIAndUnlistedAPIs(t *testing.T) { + oneHome(t) + p := Provider{ID: "plain", Name: "plain", Key: "sk-x", Chat: "https://plain.example.invalid/v1", Responses: "https://plain.example.invalid/v1", Models: []string{"a", "b"}} + if err := Save(p); err != nil { + t.Fatal(err) + } + if err := catalog.SaveLive("plain", p.Chat, []catalog.Model{{ID: "a"}, {ID: "b", APIs: []string{"anthropic"}}}); err != nil { + t.Fatal(err) + } + q, err := Find("plain") + if err != nil { + t.Fatal(err) + } + if got := idsOf(q.Exposed()); !slices.Equal(got, []string{"a"}) { + t.Errorf("exposed %v, want [a]: b is listed on /messages alone", got) + } + if err := SetModelAPI("plain/b", string(Responses)); err != nil { + t.Fatal(err) + } + if q, err = Find("plain"); err != nil { + t.Fatal(err) + } + if got := idsOf(q.Exposed()); !slices.Equal(got, []string{"a", "b"}) { + t.Errorf("exposed %v, want [a b]: b was set to be asked on Responses", got) + } +} diff --git a/internal/provider/models.go b/internal/provider/models.go index e8aaec30c..eeda07207 100644 --- a/internal/provider/models.go +++ b/internal/provider/models.go @@ -1353,8 +1353,11 @@ func (p Provider) Exposed() []catalog.Model { picks = slices.DeleteFunc(slices.Clone(picks), p.Account.unusable) } if len(picks) > 0 { - return pick(p.withNewlyListed(picks, avail)) + return slices.DeleteFunc(pick(p.withNewlyListed(picks, avail)), func(m catalog.Model) bool { return p.NoAPIFor(m.ID) }) } + // a model listed on none of the APIs the provider has a URL for is + // left out before the first 24 are taken (#2094) + avail = slices.DeleteFunc(slices.Clone(avail), func(m catalog.Model) bool { return p.NoAPIFor(m.ID) }) // another magpie's list is already the models its user exposed if len(avail) <= manyModels || p.IsRemoteMagpie() { return avail @@ -1365,6 +1368,25 @@ func (p Provider) Exposed() []catalog.Model { return avail[:manyModels] } +// NoAPIFor says the provider has a URL for none of the APIs the vendor's +// list serves model on (or the one the user set for it): a relay's Claude +// listed on /messages alone, at a provider given only a chat URL. Agents +// aren't offered it, as no request for it could be answered (#2094). Only +// a provider of keys, whose URLs the user typed: a sign-in's APIs are +// magpie's own. A model whose list says no API, and a provider with no URL +// at all, are never left out here. +func (p Provider) NoAPIFor(model string) bool { + if p.Account != nil { + return false + } + apis := p.APIs(model) + if len(apis) == 0 { + return false + } + speaks := p.Speaks() + return len(speaks) > 0 && !slices.ContainsFunc(speaks, func(s Protocol) bool { return slices.Contains(apis, s) }) +} + // Picks are the models the user picked, with those the vendor has listed // since beside them (withNewlyListed): what agents are served of the // picks, and what an editor starts its picks from. None when nothing is