providers: a provider can be moved up or down the Providers tab (#499: 供应商 tab 希望添加调整顺序的操作,比如我后面添加的想要挪到前面使用) — they were listed only in the order they were added. A provider that is on now 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, 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 keeps its place. The order is saved in providers.json ("order", POST /api/providers/arrange), follows a rename, and puts a provider added later after the rest. It is the order they are tried in too: the agents' pickers list them in it, a bare model id goes to the first that serves it, and a group magpie finds of a model several serve tries the higher one first, which the handle's tooltip says. dragRows put a row held at the top one place short of it, since the first row is a pixel shorter than the rest (they carry a border); held at either end it now goes there. TestProviderOrder and provider-order.test.cjs (Chromium and WebKit, English and Chinese) fail without the change. go vet, go build -tags nogui (darwin, GOOS=linux), GOOS=windows go build, go test -tags nogui ./... (but TestClaudeSignedOut, which fails on the base too), go test ./internal/gui, and agent-grip, account-arrange and click-scroll (WebKit) pass.

This commit is contained in:
yetone
2026-10-02 11:31:11 +08:00
parent 8dbdcfc8b3
commit 7e3b53b43c
9 changed files with 383 additions and 5 deletions
+9
View File
@@ -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; }
+79 -3
View File
@@ -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.
+2
View File
@@ -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": "拖动以调整顺序 · 点击查看更多",
+14
View File
@@ -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
+141
View File
@@ -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();
});
}
});
}
+7 -2
View File
@@ -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.
+61
View File
@@ -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)
}
+65
View File
@@ -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)
}
}
}
+5
View File
@@ -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 {