From 7e3b53b43cdaaf1b8ce62fca64b80938e71ba4db Mon Sep 17 00:00:00 2001 From: yetone Date: Fri, 2 Oct 2026 11:29:15 +0800 Subject: [PATCH] =?UTF-8?q?providers:=20a=20provider=20can=20be=20moved=20?= =?UTF-8?q?up=20or=20down=20the=20Providers=20tab=20(#499:=20=E4=BE=9B?= =?UTF-8?q?=E5=BA=94=E5=95=86=20tab=20=E5=B8=8C=E6=9C=9B=E6=B7=BB=E5=8A=A0?= =?UTF-8?q?=E8=B0=83=E6=95=B4=E9=A1=BA=E5=BA=8F=E7=9A=84=E6=93=8D=E4=BD=9C?= =?UTF-8?q?=EF=BC=8C=E6=AF=94=E5=A6=82=E6=88=91=E5=90=8E=E9=9D=A2=E6=B7=BB?= =?UTF-8?q?=E5=8A=A0=E7=9A=84=E6=83=B3=E8=A6=81=E6=8C=AA=E5=88=B0=E5=89=8D?= =?UTF-8?q?=E9=9D=A2=E4=BD=BF=E7=94=A8)=20=E2=80=94=20they=20were=20listed?= =?UTF-8?q?=20only=20in=20the=20order=20they=20were=20added.=20A=20provide?= =?UTF-8?q?r=20that=20is=20on=20now=20has=20its=20logo=20for=20a=20handle,?= =?UTF-8?q?=20as=20an=20agent=20row=20has:=20the=20grip=20in=20the=20row's?= =?UTF-8?q?=20margin=20is=20drawn=20only=20with=20the=20pointer=20on=20the?= =?UTF-8?q?=20row,=20dragging=20it=20moves=20the=20row,=20Alt+=E2=86=91/?= =?UTF-8?q?=E2=86=93=20moves=20it=20from=20the=20keyboard=20and=20keeps=20?= =?UTF-8?q?the=20keyboard=20on=20it,=20and=20a=20click=20opens=20the=20row?= =?UTF-8?q?=20as=20before,=20without=20moving=20the=20page;=20one=20switch?= =?UTF-8?q?ed=20off=20keeps=20its=20place.=20The=20order=20is=20saved=20in?= =?UTF-8?q?=20providers.json=20("order",=20POST=20/api/providers/arrange),?= =?UTF-8?q?=20follows=20a=20rename,=20and=20puts=20a=20provider=20added=20?= =?UTF-8?q?later=20after=20the=20rest.=20It=20is=20the=20order=20they=20ar?= =?UTF-8?q?e=20tried=20in=20too:=20the=20agents'=20pickers=20list=20them?= =?UTF-8?q?=20in=20it,=20a=20bare=20model=20id=20goes=20to=20the=20first?= =?UTF-8?q?=20that=20serves=20it,=20and=20a=20group=20magpie=20finds=20of?= =?UTF-8?q?=20a=20model=20several=20serve=20tries=20the=20higher=20one=20f?= =?UTF-8?q?irst,=20which=20the=20handle's=20tooltip=20says.=20dragRows=20p?= =?UTF-8?q?ut=20a=20row=20held=20at=20the=20top=20one=20place=20short=20of?= =?UTF-8?q?=20it,=20since=20the=20first=20row=20is=20a=20pixel=20shorter?= =?UTF-8?q?=20than=20the=20rest=20(they=20carry=20a=20border);=20held=20at?= =?UTF-8?q?=20either=20end=20it=20now=20goes=20there.=20TestProviderOrder?= =?UTF-8?q?=20and=20provider-order.test.cjs=20(Chromium=20and=20WebKit,=20?= =?UTF-8?q?English=20and=20Chinese)=20fail=20without=20the=20change.=20go?= =?UTF-8?q?=20vet,=20go=20build=20-tags=20nogui=20(darwin,=20GOOS=3Dlinux)?= =?UTF-8?q?,=20GOOS=3Dwindows=20go=20build,=20go=20test=20-tags=20nogui=20?= =?UTF-8?q?./...=20(but=20TestClaudeSignedOut,=20which=20fails=20on=20the?= =?UTF-8?q?=20base=20too),=20go=20test=20./internal/gui,=20and=20agent-gri?= =?UTF-8?q?p,=20account-arrange=20and=20click-scroll=20(WebKit)=20pass.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- internal/gui/assets/app.css | 9 ++ internal/gui/assets/app.js | 82 +++++++++++- internal/gui/assets/i18n.js | 2 + internal/gui/providers.go | 14 ++ internal/gui/tests/provider-order.test.cjs | 141 +++++++++++++++++++++ internal/provider/provider.go | 9 +- internal/provider/provider_order.go | 61 +++++++++ internal/provider/provider_order_test.go | 65 ++++++++++ internal/provider/rename.go | 5 + 9 files changed, 383 insertions(+), 5 deletions(-) create mode 100644 internal/gui/tests/provider-order.test.cjs create mode 100644 internal/provider/provider_order.go create mode 100644 internal/provider/provider_order_test.go diff --git a/internal/gui/assets/app.css b/internal/gui/assets/app.css index ae714d55d..becac6a6b 100644 --- a/internal/gui/assets/app.css +++ b/internal/gui/assets/app.css @@ -416,6 +416,15 @@ body.window .agent-fold-cap { padding: 10px 14px 3px; } #agents.sorting .ag-handle { cursor: grabbing; } #agents > .row.dragging { position: relative; z-index: 2; background: var(--card); box-shadow: 0 6px 18px rgba(20, 22, 30, .12), 0 0 0 1px var(--line); border-radius: 8px; } #agents > .row.dragging { transition: none; } +/* a provider on is moved as an agent is (#499): its logo is the handle, + the grip in its margin drawn only with the pointer on the row */ +#providers > .row .pv-handle { position: relative; } +#providers > .row .pv-handle::before { content: ""; position: absolute; left: -6px; top: 50%; width: 5px; height: 11px; margin-top: -5.5px; background: radial-gradient(circle, var(--muted) .9px, transparent 1.2px) 0 0 / 3.5px 3.75px; opacity: 0; transition: opacity .15s; } +#providers > .row:is(:hover, .dragging) .pv-handle::before, #providers > .row .pv-handle:focus-visible::before { opacity: 1; } +#providers.sorting { user-select: none; -webkit-user-select: none; } +#providers.sorting > .row { transition: transform .22s cubic-bezier(.22, 1, .36, 1); } +#providers.sorting .pv-handle { cursor: grabbing; } +#providers > .row.dragging { position: relative; z-index: 2; background: var(--card); box-shadow: 0 6px 18px rgba(20, 22, 30, .12), 0 0 0 1px var(--line); border-radius: 8px; transition: none; } .pop.row-menu { width: auto; min-width: 176px; max-height: none; padding: 4px; border: 1px solid var(--line); display: grid; gap: 1px; } .row-menu .rm-item { display: flex; align-items: center; gap: 8px; width: 100%; height: 28px; padding: 0 8px; border: 0; border-radius: 7px; background: none; color: var(--fg); font: inherit; font-size: 12.5px; text-align: left; cursor: default; outline: none; } diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index a452bdd77..138a7624f 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -967,12 +967,18 @@ function dragRows(e, handle, row, list, rows, commit, start = () => {}, idle = ( : y > bounds.bottom - edge ? Math.min(1, (y - bounds.bottom + edge) / edge) : 0; if (speed) scroll.scrollTop += speed * dt * .6; const dy = y - y0 + scroll.scrollTop - scroll0; - const d = Math.max(tops[0] - tops[from], Math.min(tops.at(-1) + heights.at(-1) - h - tops[from], dy)); + const lo = tops[0] - tops[from], hi = tops.at(-1) + heights.at(-1) - h - tops[from]; + const d = Math.max(lo, Math.min(hi, dy)); row.style.transform = `translateY(${d}px)`; const mid = tops[from] + d + h / 2; to = from; if (d > 0) { while (to < rows.length - 1 && mid >= tops[to + 1] + heights[to + 1] / 2) to++; } else { while (to > 0 && mid <= tops[to - 1] + heights[to - 1] / 2) to--; } + // held at the top or the foot it goes there, though the first row is a + // pixel shorter than the rest (they have a border over them) and its + // middle was out of reach (#499) + if (d <= lo && from > 0) to = 0; + else if (d >= hi && from < rows.length - 1) to = rows.length - 1; rows.forEach((r, i) => { if (i === from) return; const shift = i > from && i <= to ? -h : i < from && i >= to ? h : 0; @@ -2702,7 +2708,7 @@ $("#foldOff").onclick = () => { // One row per provider: logo, name, the agents pointed at it, key status. // Everything else lives in the editor, a dialog over the page. function renderProviders() { - if (accountArranging) { accountRenderPending = true; return; } + if (accountArranging || providerArranging) { accountRenderPending = true; return; } // Rebuilding the list empties the page for a moment, which clamps its // scroll to the top; put it back so closing the editor leaves the reader // where they were. @@ -2772,7 +2778,9 @@ function renderProviders() { if (!key.title.includes(label)) key.title = (p.account && !lapsed ? accountPlan(p.account) : label) + " · " + key.title; const chev = el("span", "chev"); chev.append(svg(CHEV_R, 11, 1.7)); - row.append(icon(p.icon || "generic"), who, uses, key, providerSwitch(p), chev); + // a provider on is listed, and tried, in the order the user puts it in + // (#499): its logo is the handle, as an agent row's is + row.append(p.off ? icon(p.icon || "generic") : providerHandle(p, row), who, uses, key, providerSwitch(p), chev); row.onclick = () => { editing = open ? null : p.id; draft = null; renderProviders(); }; // the preset sheet stays as it is under the dialog list.append(row); if (open) dialog = renderEditor(p); @@ -2788,6 +2796,74 @@ function renderProviders() { if (dialog) openModal(dialog); else closeModal(); } +// providerHandle is an on row's logo, which is also its handle (#499): +// drag it to move the row among the ones on, Alt+↑/↓ moves it from the +// keyboard, and a click opens the row as a click anywhere on it does. The +// grip that says so is drawn in the row's margin on hover (app.css). The +// order is the one providers are tried in too: a model several serve goes +// to the higher one first. +let providerArranging = false; +function providerHandle(p, row) { + const b = el("button", "ag-handle pv-handle"); + b.type = "button"; + b.setAttribute("aria-label", t("Arrange {agent}", { agent: p.name })); + b.title = t("Drag to reorder — a model several providers serve goes to the higher one first · Alt+↑/↓ to move"); + b.append(icon(p.icon || "generic")); + b.onkeydown = (e) => { + if (!e.altKey || (e.key !== "ArrowUp" && e.key !== "ArrowDown")) return; + e.preventDefault(); + e.stopPropagation(); + const ids = providers.providers.filter((x) => !x.off).map((x) => x.id); + arrangeProvider(p.id, ids.indexOf(p.id) + (e.key === "ArrowUp" ? -1 : 1), true); + }; + // the click that ends a drag doesn't open the row + b.addEventListener("click", (e) => { if (b.dataset.dragged) { e.stopPropagation(); e.preventDefault(); } }); + b.onpointerdown = (e) => { + if (providerArranging) return; + const list = $("#providers"); + providerArranging = dragRows(e, b, row, list, [...list.children].filter((r) => r.classList.contains("provider")), + (to) => arrangeProvider(p.id, to), closeProtoMenu, () => { + providerArranging = false; + if (accountRenderPending && !accountArranging) { accountRenderPending = false; renderProviders(); } + }); + }; + return b; +} + +// arrangeProvider puts the provider at index `to` among the ones on; the +// ones switched off keep their places among the rest. The list is drawn in +// its new order at once and put back if the save fails. +async function arrangeProvider(id, to, keyboard) { + const prev = providers; + const on = prev.providers.filter((p) => !p.off).map((p) => p.id); + const from = on.indexOf(id); + if (from < 0 || to < 0 || to >= on.length || to === from) return; + on.splice(to, 0, ...on.splice(from, 1)); + let k = 0; + const order = prev.providers.map((p) => (p.off ? p.id : on[k++])); + const byId = new Map(prev.providers.map((p) => [p.id, p])); + const handle = () => $(`#providers .row.provider[data-id="${CSS.escape(id)}"] .pv-handle`); + providers = { ...prev, providers: order.map((x) => byId.get(x)) }; + renderProviders(); + if (keyboard) handle()?.focus({ preventScroll: true }); + const seq = ++providerArrangeSeq; + let next; + try { + next = await api("providers/arrange", { order }); + status(t("Provider order saved"), "ok"); + } catch (e) { + next = prev; + status(e.message, "err"); + } + // a later move, made while this one was saved, has the last word + if (seq !== providerArrangeSeq) return; + const held = document.activeElement === handle(); + providers = next; + renderProviders(); + if (held) handle()?.focus({ preventScroll: true }); +} +let providerArrangeSeq = 0; + // providerSwitch turns a provider off and on (#163): off, it stays with its // keys and settings, but agents are given none of its models and no request // goes to it (a key out of quota, say), without removing it. diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index c13eb90e2..799df4ecc 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -83,6 +83,8 @@ const I18N = { "{agent} hidden · find it under Hidden at the bottom": "已隐藏 {agent} · 可在列表底部「已隐藏」里找回", "Drag to reorder · Alt+↑/↓ to move": "按住拖动调整位置 · Alt+↑/↓ 移动", "Account order saved": "账号位置已保存", + "Drag to reorder — a model several providers serve goes to the higher one first · Alt+↑/↓ to move": "拖动调整顺序——多个供应商都有的模型,优先用排在前面的 · Alt+↑/↓ 移动", + "Provider order saved": "供应商顺序已保存", "Drag to reorder · click to move or hide": "拖动以调整顺序 · 点击可移动或隐藏", "Arrange {agent}": "调整 {agent}", "Drag to reorder · click for more": "拖动以调整顺序 · 点击查看更多", diff --git a/internal/gui/providers.go b/internal/gui/providers.go index 5fe9acd12..a07fdc643 100644 --- a/internal/gui/providers.go +++ b/internal/gui/providers.go @@ -496,6 +496,20 @@ func providerRoutes(mux *http.ServeMux, w Windows) { mux.HandleFunc("GET /api/providers", func(rw http.ResponseWriter, r *http.Request) { writeJSON(rw, providersState()) }) + // the order the Providers tab lists them in, which is the order they + // are tried in too (#499) + mux.HandleFunc("POST /api/providers/arrange", func(rw http.ResponseWriter, r *http.Request) { + var in struct{ Order []string } + if err := json.NewDecoder(r.Body).Decode(&in); err != nil { + fail(rw, err) + return + } + if err := provider.SetOrder(in.Order); err != nil { + fail(rw, err) + return + } + writeJSON(rw, providersState()) + }) // a picture for a provider, picked in the editor: kept by content before // the provider is saved, which then points at it. The page sends it as // base64 in JSON — the app's web view hands a scheme handler no body for diff --git a/internal/gui/tests/provider-order.test.cjs b/internal/gui/tests/provider-order.test.cjs new file mode 100644 index 000000000..1568cc63a --- /dev/null +++ b/internal/gui/tests/provider-order.test.cjs @@ -0,0 +1,141 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// #499: a provider added later couldn't be put first on the Providers tab. +// Now a provider that is on has its logo for a handle, as an agent row has: +// the grip in the row's margin is drawn only with the pointer on the row, +// dragging it moves the row and saves the order (the one providers are +// tried in too), Alt+↑/↓ moves it from the keyboard and keeps the keyboard +// on it, and a click opens the row as before, without moving the page. One +// switched off has no handle and keeps its place. Chromium and WebKit, +// English and Chinese; no backend, the API is faked here. +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 prov = (id, extra = {}) => ({ + id, name: id.toUpperCase(), icon: "generic", host: id + ".example.com", chat: "https://" + id + ".example.com/v1", responses: "", anthropic: "", catalog: "", + models: [{ id: "m", name: "M", on: true }], agents: [], fallback: [], headers: {}, + key: { set: true, masked: "sk-…" + id }, keyList: [], balanceToken: { takes: false, set: false }, proxy: "", ...extra, +}); + +function fixture(lang) { + const providers = { providers: [prov("a"), prov("b"), prov("c"), prov("d", { off: true })], presets: [], excluded: [], gateway: { running: true, window: true } }; + const state = { agents: [], profiles: [], settings: { lang, theme: "light" } }; + const posted = []; + const route = async (route) => { + const request = route.request(), url = new URL(request.url()); + const json = (data) => route.fulfill({ json: data }); + if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:false};` }); + if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" }); + if (url.pathname === "/api/state") return json(state); + if (url.pathname === "/api/providers/arrange") { + const { order } = request.postDataJSON(); + posted.push(order); + providers.providers = order.map((id) => providers.providers.find((p) => p.id === id)); + return json(providers); + } + if (url.pathname === "/api/providers") return json(providers); + if (url.pathname === "/api/groups") return json({ groups: [] }); + if (url.pathname === "/api/plugins") return json({ plugins: [] }); + if (url.pathname === "/api/usage/quotas") return json([]); + 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 }); + }; + return { posted, route }; +} + +const order = (page) => page.locator("#providers > .row.provider").evaluateAll((rs) => rs.map((r) => r.dataset.id)); +const grips = (page) => page.locator("#providers > .row.provider").evaluateAll((rs) => rs.map((r) => { + const h = r.querySelector(".pv-handle"); + if (!h) return { id: r.dataset.id }; + const s = getComputedStyle(h, "::before"), hb = h.getBoundingClientRect(), rb = r.getBoundingClientRect(); + const left = hb.left + parseFloat(s.left), w = parseFloat(s.width); + return { id: r.dataset.id, handle: true, opacity: Number(s.opacity), image: s.backgroundImage, inRow: left >= rb.left && left + w <= hb.left + 0.5, x: hb.left + hb.width / 2, y: hb.top + hb.height / 2 }; +})); +const scrolled = (page) => page.evaluate(() => [scrollY, document.querySelector("#view-providers").scrollTop]); + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + test(engine + ": a provider can be moved up the list", { timeout: 120000 }, async (t) => { + assert(["chromium", "webkit"].includes(engine), "BROWSER must be chromium or webkit"); + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + const errors = []; + t.after(async () => { + await browser.close(); + assert.deepEqual(errors, []); + }); + for (const lang of ["en", "zh"]) { + await t.test(lang, async () => { + const ctx = await browser.newContext({ viewport: { width: 1000, height: 640 }, reducedMotion: "reduce" }); + const page = await ctx.newPage(), f = fixture(lang); + page.setDefaultTimeout(5000); + page.on("pageerror", (e) => errors.push(e.message)); + await page.route("**/*", f.route); + await page.goto("http://magpie.test/?view=providers"); + await page.locator("#providers > .row.provider").nth(2).waitFor(); + await page.mouse.move(1, 1); + assert.deepEqual(await order(page), ["a", "b", "c"]); + + // the ones on have a handle with a grip in their margin, drawn only + // with the pointer on the row; the one off has none + await page.waitForFunction(() => [...document.querySelectorAll("#providers .pv-handle")].every((h) => getComputedStyle(h, "::before").opacity === "0")); + let g = await grips(page); + for (const x of g) { + assert(x.handle, `${x.id} has no handle`); + assert.match(x.image, /gradient/, `${x.id}'s grip draws nothing`); + assert(x.inRow, `${x.id}'s grip is off its row or over its logo`); + } + assert.equal(await page.locator("#offProviders .pv-handle").count(), 0, "a provider switched off has a handle"); + const tip = await page.evaluate(() => t("Drag to reorder — a model several providers serve goes to the higher one first · Alt+↑/↓ to move")); + if (lang === "zh") assert.match(tip, /拖动/); + assert.equal(await page.locator("#providers .pv-handle").first().getAttribute("title"), tip); + await page.locator("#providers > .row.provider").nth(1).locator(".name").hover(); + await page.waitForFunction(() => { + const o = [...document.querySelectorAll("#providers .pv-handle")].map((h) => getComputedStyle(h, "::before").opacity); + return o[1] === "1" && o[0] === "0" && o[2] === "0"; + }); + + // dragging c's handle to the top puts it first, saves the order with + // the one off kept, and opens nothing + const y0 = await scrolled(page); + await page.mouse.move(g[2].x, g[2].y); + await page.mouse.down(); + await page.mouse.move(g[2].x, g[0].y - 14, { steps: 12 }); + await page.locator("#providers > .row.dragging").waitFor(); + await page.mouse.up(); + await page.waitForFunction(() => document.querySelector("#providers > .row.provider").dataset.id === "c"); + await page.locator("#status").filter({ hasText: await page.evaluate(() => t("Provider order saved")) }).waitFor(); + assert.deepEqual(f.posted.at(-1), ["c", "a", "b", "d"]); + assert.deepEqual(await order(page), ["c", "a", "b"]); + assert.equal(await page.locator("#providers > .row.provider.selected").count(), 0, "the drag opened the row"); + assert.deepEqual(await scrolled(page), y0); + + // from the keyboard: Alt+↓ moves it down one, and it keeps the keyboard + await page.locator('#providers > .row.provider[data-id="c"] .pv-handle').focus(); + await page.keyboard.press("Alt+ArrowDown"); + await page.waitForFunction(() => [...document.querySelectorAll("#providers > .row.provider")].map((r) => r.dataset.id).join() === "a,c,b"); + await page.waitForFunction(() => document.activeElement?.closest(".row.provider")?.dataset.id === "c"); + await new Promise((r) => setTimeout(r, 200)); + assert.deepEqual(f.posted.at(-1), ["a", "c", "b", "d"]); + assert.equal(await page.evaluate(() => document.activeElement?.closest(".row.provider")?.dataset.id), "c"); + // the first can't go up + const n = f.posted.length; + await page.locator('#providers > .row.provider[data-id="a"] .pv-handle').focus(); + await page.keyboard.press("Alt+ArrowUp"); + await new Promise((r) => setTimeout(r, 200)); + assert.equal(f.posted.length, n); + + // a click on the handle opens the row, as a click on the row does, + // and the page stays where it is + const y1 = await scrolled(page); + await page.locator('#providers > .row.provider[data-id="b"] .pv-handle').click(); + await page.locator('#providers > .row.provider.selected[data-id="b"]').waitFor(); + assert.deepEqual(await scrolled(page), y1); + await ctx.close(); + }); + } + }); +} diff --git a/internal/provider/provider.go b/internal/provider/provider.go index 74f3a9d0d..9b677c563 100644 --- a/internal/provider/provider.go +++ b/internal/provider/provider.go @@ -192,6 +192,10 @@ type file struct { // NoAutoGroups: the user turned off the groups magpie finds on its // own (SetAutoGroups); the groups they made or changed stay. NoAutoGroups bool `json:"noAutoGroups,omitempty"` + // Order is the order the user put the providers in on the Providers + // tab (#499), by id; one not in it follows those that are, in the + // order it was added (see SetOrder). + Order []string `json:"order,omitempty"` } // Path is the file the user's providers live in. @@ -276,7 +280,8 @@ func store(f file) error { // the signed-in agents. An entry in the file with no URL is only the // model picks for one of those accounts. func All() []Provider { - stored := load().Providers + f := load() + stored := f.Providers picks := map[string]Provider{} var out []Provider for _, p := range stored { @@ -302,7 +307,7 @@ func All() []Provider { } out = append(out, a) } - return out + return ordered(out, f.Order) } // Hidden lists the signed-in accounts the user removed from magpie. diff --git a/internal/provider/provider_order.go b/internal/provider/provider_order.go new file mode 100644 index 000000000..479efe276 --- /dev/null +++ b/internal/provider/provider_order.go @@ -0,0 +1,61 @@ +package provider + +import ( + "fmt" + "slices" +) + +// ordered is ps in the order the user put them in (#499): those order +// names first, as it has them, then the rest as they came (the order they +// were added). The order is more than the list's: the agents' pickers list +// the models in it, a bare model id goes to the first provider serving it, +// and a group magpie finds of a model more than one provider serves tries +// them in it. +func ordered(ps []Provider, order []string) []Provider { + if len(order) == 0 { + return ps + } + at := map[string]int{} + for i, id := range order { + if _, dup := at[id]; !dup { + at[id] = i + } + } + rank := func(p Provider) int { + if i, ok := at[p.ID]; ok { + return i + } + return len(order) + } + slices.SortStableFunc(ps, func(a, b Provider) int { return rank(a) - rank(b) }) + return ps +} + +// SetOrder saves the order the providers are listed and tried in, by id. +// Every id must be a provider's, once; the ones left out follow those +// named, as they are now, so a provider added later goes after them all. +func SetOrder(ids []string) error { + f, err := read() + if err != nil { + return err + } + all := All() + seen := map[string]bool{} + for _, id := range ids { + if seen[id] { + return fmt.Errorf("%s is in the order twice", id) + } + seen[id] = true + if _, ok := find(all, id); !ok { + return fmt.Errorf("no provider %q", id) + } + } + order := slices.Clone(ids) + for _, p := range all { + if !seen[p.ID] { + order = append(order, p.ID) + } + } + f.Order = order + return store(f) +} diff --git a/internal/provider/provider_order_test.go b/internal/provider/provider_order_test.go new file mode 100644 index 000000000..855462e56 --- /dev/null +++ b/internal/provider/provider_order_test.go @@ -0,0 +1,65 @@ +package provider + +import ( + "slices" + "testing" +) + +// #499: a provider added later can be put first. The order is the list's +// and the one they are tried in: a bare model id goes to the first that +// serves it, and the group magpie finds of a model several serve tries +// the first one first. One added after stays last; a rename keeps its place. +func TestProviderOrder(t *testing.T) { + t.Setenv("HOME", t.TempDir()) + t.Setenv("USERPROFILE", t.TempDir()) + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + t.Setenv("XDG_CACHE_HOME", t.TempDir()) + for _, id := range []string{"a", "b", "c"} { + if err := Save(Provider{ID: id, Name: id, Key: "sk-" + id, Chat: "https://" + id + ".example.com/v1", Models: []string{"m"}}); err != nil { + t.Fatal(err) + } + } + ids := func() []string { + var out []string + for _, p := range All() { + out = append(out, p.ID) + } + return out + } + if got := ids(); !slices.Equal(got, []string{"a", "b", "c"}) { + t.Fatalf("as added: %v", got) + } + if err := SetOrder([]string{"c", "a"}); err != nil { + t.Fatal(err) + } + if got := ids(); !slices.Equal(got, []string{"c", "a", "b"}) { + t.Fatalf("after SetOrder(c, a): %v", got) + } + if p, _, ok := Resolve("m"); !ok || p.ID != "c" { + t.Fatalf("m resolves to %q, not c", p.ID) + } + g := slices.IndexFunc(autoGroups(providerEntries()), func(g Group) bool { return g.ID == AutoGroupID("m") }) + if g < 0 { + t.Fatal("no group found of m") + } + if ms := autoGroups(providerEntries())[g].Members; !slices.Equal(ms, []string{"c/m", "a/m", "b/m"}) { + t.Fatalf("group of m tries %v", ms) + } + if err := Save(Provider{ID: "d", Name: "d", Key: "sk-d", Chat: "https://d.example.com/v1", Models: []string{"m"}}); err != nil { + t.Fatal(err) + } + if got := ids(); !slices.Equal(got, []string{"c", "a", "b", "d"}) { + t.Fatalf("d added: %v", got) + } + if err := Rename("c", "cc"); err != nil { + t.Fatal(err) + } + if got := ids(); !slices.Equal(got, []string{"cc", "a", "b", "d"}) { + t.Fatalf("c renamed: %v", got) + } + for _, bad := range [][]string{{"a", "a"}, {"nope"}} { + if err := SetOrder(bad); err == nil { + t.Fatalf("SetOrder(%v) taken", bad) + } + } +} diff --git a/internal/provider/rename.go b/internal/provider/rename.go index 814df6dd5..713361c1f 100644 --- a/internal/provider/rename.go +++ b/internal/provider/rename.go @@ -72,6 +72,11 @@ func Rename(from, to string) error { f.Providers[j].Fallback[k] = renamedRef(m, from, to) } } + for j, id := range f.Order { + if id == from { + f.Order[j] = to + } + } for j := range f.Groups { g := &f.Groups[j] for k, m := range g.Members {