diff --git a/internal/gui/api.go b/internal/gui/api.go index f6db422b1..cb83c7430 100644 --- a/internal/gui/api.go +++ b/internal/gui/api.go @@ -758,6 +758,7 @@ func Handler(w Windows, gw *gateway.Server) http.Handler { in.RedactRules = cur.RedactRules // the masking rules, set on their own // used or left is the Usage page's toggle as much as Settings', set on its own in.QuotaLeft = cur.QuotaLeft + in.UsageOrder = cur.UsageOrder // the Usage page's, dragged there // how agents' lists name models, set on its own for the agents to be told in.PlainNames, in.PlainOwnNames = cur.PlainNames, cur.PlainOwnNames in.CodexAgentsV1 = cur.CodexAgentsV1 @@ -953,6 +954,21 @@ func Handler(w Windows, gw *gateway.Server) http.Handler { } writeJSON(rw, settingsState()) }) + // the Usage page's order of its cards, in magpie's settings + mux.HandleFunc("POST /api/usage/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 + } + s := settings.Load() + s.UsageOrder = in.Order + if err := settings.Save(s); err != nil { + fail(rw, err) + return + } + writeJSON(rw, settingsState()) + }) mux.HandleFunc("POST /api/settings/login", func(rw http.ResponseWriter, r *http.Request) { var in struct{ On bool } if err := json.NewDecoder(r.Body).Decode(&in); err != nil { diff --git a/internal/gui/assets/app.css b/internal/gui/assets/app.css index a0decf2b5..a95e5fb48 100644 --- a/internal/gui/assets/app.css +++ b/internal/gui/assets/app.css @@ -2398,8 +2398,16 @@ body.panel .modal { padding: 16px 12px; } .accts.sorting > [data-account-id] { animation: none; transition: transform .16s cubic-bezier(.22, 1, .36, 1); } .accts.sorting > .dragging { position: relative; z-index: 2; background: var(--card-2); box-shadow: 0 0 0 1px var(--line); cursor: grabbing; transition: none; will-change: transform; } .accts[aria-busy=true] > [data-account-id] { cursor: progress; } +/* the Usage page's cards, dragged by their logos: a grip by the logo on hover */ +.subscription-head .us-handle { position: relative; width: 24px; height: 24px; margin: -4px -3px; } +.subscription-head .us-handle::before { content: ""; position: absolute; left: -7px; 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; } +.subscription-card:is(:hover, .dragging) .us-handle::before, .us-handle:focus-visible::before { opacity: 1; } +.subscription-usage.sorting { user-select: none; -webkit-user-select: none; } +.subscription-usage.sorting > .subscription-card { transition: transform .22s cubic-bezier(.22, 1, .36, 1); } +.subscription-usage.sorting .us-handle { cursor: grabbing; } +.subscription-usage > .subscription-card.dragging { position: relative; z-index: 2; box-shadow: 0 8px 22px rgba(20, 22, 30, .14), 0 0 0 1px var(--line); transition: none; } @media (prefers-reduced-motion: reduce) { - .accts.sorting > [data-account-id], #agents.sorting > .row { transition: none; } + .accts.sorting > [data-account-id], #agents.sorting > .row, .subscription-usage.sorting > .subscription-card { transition: none; } } /* the show while the session files are indexed: the words on the left, a field of dots that light up as the files land on the right, a hairline diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index b760efd00..25687748b 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -1096,6 +1096,102 @@ function dragRows(e, handle, row, list, rows, commit, start = () => {}, idle = ( return true; } +// dragCards is dragRows for cards laid out in a grid: the card follows the +// pointer both ways, the slot nearest its middle is where it goes, and the +// cards between move a slot over to make room. +function dragCards(e, handle, card, list, cards, commit, idle = () => {}) { + if (e.button !== 0 || e.isPrimary === false || cards.length < 2) return false; + const from = cards.indexOf(card); + if (from < 0) return false; + const rects = cards.map((c) => c.getBoundingClientRect()); + let scroll = list.parentElement; + while (scroll && !/(auto|scroll)/.test(getComputedStyle(scroll).overflowY)) scroll = scroll.parentElement; + scroll ||= document.scrollingElement; + const bounds = scroll.getBoundingClientRect(), scroll0 = scroll.scrollTop; + let dragging = false, ended = false, to = from, x = e.clientX, y = e.clientY, frame = 0, lastTime = 0; + const x0 = x, y0 = y, pointer = e.pointerId; + const r0 = rects[from]; + const paint = (time) => { + frame = 0; + if (!card.isConnected) return finish(false); + if (!dragging) return; + const dt = Math.min(32, lastTime ? time - lastTime : 16); + lastTime = time; + const edge = 36; + const speed = y < bounds.top + edge ? -Math.min(1, (bounds.top + edge - y) / edge) + : y > bounds.bottom - edge ? Math.min(1, (y - bounds.bottom + edge) / edge) : 0; + if (speed) scroll.scrollTop += speed * dt * .6; + const dx = x - x0, dy = y - y0 + scroll.scrollTop - scroll0; + card.style.transform = `translate(${dx}px, ${dy}px)`; + const cx = r0.left + r0.width / 2 + dx, cy = r0.top + r0.height / 2 + dy; + let best = Infinity; + rects.forEach((r, i) => { + const d = (cx - r.left - r.width / 2) ** 2 + (cy - r.top - r.height / 2) ** 2; + if (d < best) { best = d; to = i; } + }); + cards.forEach((c, i) => { + if (i === from) return; + const j = i > from && i <= to ? i - 1 : i < from && i >= to ? i + 1 : i; + c.style.transform = j !== i ? `translate(${rects[j].left - rects[i].left}px, ${rects[j].top - rects[i].top}px)` : ""; + }); + if (speed) frame = requestAnimationFrame(paint); + }; + const move = (ev) => { + if (ev.pointerId !== pointer) return; + if (!card.isConnected || !handle.isConnected) return finish(false, ev); + x = ev.clientX; + y = ev.clientY; + if (!dragging) { + if (Math.hypot(x - x0, y - y0) < 4) return; + dragging = true; + handle.dataset.dragged = "1"; + list.classList.add("sorting"); + card.classList.add("dragging"); + getSelection()?.removeAllRanges(); + handle.setPointerCapture(pointer); + } + ev.preventDefault(); + if (!frame) frame = requestAnimationFrame(paint); + }; + const finish = (save, ev) => { + if (ended || (ev?.pointerId != null && ev.pointerId !== pointer)) return; + if (save && dragging && ev) { + x = ev.clientX; + y = ev.clientY; + cancelAnimationFrame(frame); + paint(performance.now()); + } + if (ended) return; + ended = true; + cancelAnimationFrame(frame); + document.removeEventListener("pointermove", move); + document.removeEventListener("pointerup", up); + document.removeEventListener("pointercancel", cancel); + document.removeEventListener("keydown", keys, true); + handle.removeEventListener("lostpointercapture", cancel); + removeEventListener("blur", cancel); + removeEventListener("resize", cancel); + if (handle.hasPointerCapture(pointer)) handle.releasePointerCapture(pointer); + list.classList.remove("sorting"); + card.classList.remove("dragging"); + cards.forEach((c) => { c.style.transform = ""; }); + if (save && dragging && to !== from) commit(to); + idle(); + setTimeout(() => delete handle.dataset.dragged, 0); + }; + const up = (ev) => finish(true, ev); + const cancel = (ev) => finish(false, ev); + const keys = (ev) => { if (ev.key === "Escape") { ev.preventDefault(); ev.stopImmediatePropagation(); finish(false); } }; + document.addEventListener("pointermove", move, { passive: false }); + document.addEventListener("pointerup", up); + document.addEventListener("pointercancel", cancel); + document.addEventListener("keydown", keys, true); + handle.addEventListener("lostpointercapture", cancel); + addEventListener("blur", cancel); + addEventListener("resize", cancel); + return true; +} + // ---------- an agent's model list ---------- // modelsEntry: the line under an agent's name counting the models its @@ -8885,18 +8981,20 @@ function renderQuotas() { } return; } + if (usageArranging) { usageRenderPending = true; return; } subscriptions.hidden = !quotas.length; // an agent with several accounts is one card, a section per account const groups = []; - for (const sub of quotas) { + for (const sub of byUsageOrder(quotas)) { const g = sub.user && groups.find((x) => x[0].user && x[0].provider === sub.provider); if (g) g.push(sub); else groups.push([sub]); } for (const subs of groups) { const first = subs[0]; const card = el("div", "subscription-card" + (first.user ? " several" : "")); + card.dataset.key = first.provider; const head = el("div", "subscription-head"); - head.append(icon(first.icon), el("b", "", first.name)); + head.append(groups.length > 1 ? usageHandle(first, card) : icon(first.icon), el("b", "", first.name)); if (!first.user && (first.plan || first.until)) head.append(planSpan(first)); card.append(head); for (const sub of subs) { @@ -8944,6 +9042,70 @@ function renderQuotas() { } } +// The Usage page's cards in the order they were dragged to (settings +// usageOrder, by provider id), as the Agents page's rows are; one it doesn't +// name keeps magpie's own order after them. The tray panel's Usage tab +// follows it too. +function byUsageOrder(list) { + const order = state.settings?.usageOrder || []; + const rank = (q) => { const i = order.indexOf(q.provider); return i < 0 ? order.length : i; }; + return list.map((q, i) => [q, i]).sort(([a, i], [b, j]) => rank(a) - rank(b) || i - j).map(([q]) => q); +} + +// usageHandle is a card's logo, which is also its handle: drag it to move +// the card among the others, Alt+arrows move it from the keyboard. The grip +// that says so shows by the logo on hover (app.css). +let usageArranging = false, usageRenderPending = false; +function usageHandle(sub, card) { + const b = el("button", "ag-handle us-handle"); + b.type = "button"; + b.setAttribute("aria-label", t("Arrange {agent}", { agent: sub.name })); + b.title = t("Drag to reorder · Alt+arrow keys to move"); + b.append(icon(sub.icon)); + b.onkeydown = (e) => { + const step = { ArrowUp: -1, ArrowLeft: -1, ArrowDown: 1, ArrowRight: 1 }[e.key]; + if (!e.altKey || !step) return; + e.preventDefault(); + const keys = usageKeys(); + moveUsage(sub.provider, keys.indexOf(sub.provider) + step); + // the cards were drawn anew: keep the keyboard on this one + $(`#subscriptionUsage > [data-key="${CSS.escape(sub.provider)}"] .us-handle`)?.focus({ preventScroll: true }); + }; + b.onpointerdown = (e) => { + if (usageArranging) return; + const list = $("#subscriptionUsage"); + usageArranging = dragCards(e, b, card, list, [...list.children], (to) => moveUsage(sub.provider, to), () => { + usageArranging = false; + if (usageRenderPending) { usageRenderPending = false; renderQuotas(); } + }); + }; + return b; +} + +const usageKeys = () => [...new Set([...$("#subscriptionUsage").children].map((c) => c.dataset.key))]; + +// moveUsage puts the card at index `to` among those on the page; what the +// order named that isn't on it now (an account signed out) keeps its place +// after them. Drawn at once, put back if the save fails. +async function moveUsage(key, to) { + const keys = usageKeys(); + const from = keys.indexOf(key); + if (from < 0 || to < 0 || to >= keys.length || to === from) return; + keys.splice(to, 0, ...keys.splice(from, 1)); + const prev = state.settings; + const order = [...keys, ...(prev.usageOrder || []).filter((k) => !keys.includes(k))]; + state.settings = { ...prev, usageOrder: order }; + renderQuotas(); + try { + const s = await api("usage/arrange", { order }); + state.settings = { ...state.settings, usageOrder: s.usageOrder || [] }; + } catch (e) { + state.settings = prev; + renderQuotas(); + status(e.message, "err"); + } +} + // creditDays: the credits an account used each day of the period, as // magpie counted them from its readings of the vendor's meter, which tells // only what the cycle has used so far — a bar a day, and the period's sum; @@ -9454,7 +9616,7 @@ function renderPanelUse() { function renderPanelQuota() { const box = $("#panelQuota"); if (mode !== "panel" || !box) return; - const subs = (quotas || []).filter((q) => q.balance || q.error || q.windows?.length); + const subs = byUsageOrder((quotas || []).filter((q) => q.balance || q.error || q.windows?.length)); const none = !!quotas && !subs.length; const usageTab = $('#ptabs [data-ptab="usage"]'); if (usageTab.hidden !== none) { diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index 2713ffd97..ce18c3447 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -113,6 +113,7 @@ const I18N = { "Add magpie": "添加 magpie", "{agent} hidden · find it under Hidden at the bottom": "已隐藏 {agent} · 可在列表底部「已隐藏」里找回", "Drag to reorder · Alt+↑/↓ to move": "按住拖动调整位置 · Alt+↑/↓ 移动", + "Drag to reorder · Alt+arrow keys 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": "供应商顺序已保存", diff --git a/internal/gui/settings_keep_test.go b/internal/gui/settings_keep_test.go index a1f275a47..778f9e204 100644 --- a/internal/gui/settings_keep_test.go +++ b/internal/gui/settings_keep_test.go @@ -128,6 +128,7 @@ func TestSettingsSaveKeepsWhatItDoesNotSend(t *testing.T) { RequestArchive: true, RequestArchiveMaxMB: 64, QuotaLeft: true, + UsageOrder: []string{"kimi", "codex"}, PlainNames: true, PlainOwnNames: true, CodexAgentsV1: true, diff --git a/internal/gui/tests/usage-arrange.test.cjs b/internal/gui/tests/usage-arrange.test.cjs new file mode 100644 index 000000000..e2d3ed588 --- /dev/null +++ b/internal/gui/tests/usage-arrange.test.cjs @@ -0,0 +1,131 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// The Usage page's cards are arranged as the Agents page's rows are (the +// owner: 用量页面能否支持供应商排序?像 agents 页面一样): a card's logo is +// its handle, with a grip by it only while the pointer is on the card; it +// is dragged across the grid, or moved with Alt+arrows, and the order is +// saved (usage/arrange) and drawn again from settings. The tray panel's +// Usage tab follows the same order. No click moves the page. 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 win = (name, used) => ({ name, used, resetSecs: 3 * 3600 }); +const quotas = [ + { provider: "codex", name: "Codex", icon: "openai", user: "a@x.dev", plan: "plus", windows: [win("5h", 40), win("Weekly", 20)] }, + { provider: "codex", name: "Codex", icon: "openai", user: "b@x.dev", plan: "pro", windows: [win("5h", 10)] }, + { provider: "claude", name: "Claude", icon: "claude", plan: "max", windows: [win("5h", 70)] }, + { provider: "kimi", name: "Kimi", icon: "kimi", windows: [win("Weekly", 55)] }, + { provider: "zai", name: "Z.ai", icon: "zai", windows: [win("5h", 5)] }, +]; + +function serve(lang, panel, settings, saved) { + return async (route) => { + const url = new URL(route.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:${!panel}};` }); + if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" }); + if (url.pathname === "/api/state") return json({ agents: [], profiles: [], settings }); + if (url.pathname === "/api/settings") return json(settings); + if (url.pathname === "/api/usage/arrange") { + const { order } = route.request().postDataJSON(); + saved.push(order); + settings.usageOrder = order; + return json(settings); + } + if (url.pathname === "/api/providers") return json({ providers: [], presets: [], excluded: [], gateway: { running: true, window: true } }); + if (url.pathname === "/api/usage/quotas") return json(quotas); + if (url.pathname === "/api/groups") return json({ groups: [], models: [] }); + if (url.pathname === "/api/plugins") return json({ plugins: [] }); + 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)]; + try { await route.fulfill({ body: await fs.readFile(file), contentType }); } catch { await route.fulfill({ status: 404, body: "" }); } + }; +} + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + for (const lang of ["en", "zh"]) { + test(`${engine} ${lang}: the Usage page's cards are dragged into an order that holds`, async (t) => { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + const pages = []; + t.after(async () => { + if (process.env.ARTIFACT_DIR) { + await fs.mkdir(process.env.ARTIFACT_DIR, { recursive: true }); + for (const [name, p] of pages) await p.screenshot({ path: path.join(process.env.ARTIFACT_DIR, `${engine}-${lang}-usage-arrange-${name}.png`) }); + } + await browser.close(); + }); + const settings = { theme: "light", lang, tray: "panel", currency: "usd" }; + const saved = [], errors = []; + const open = async (name, url, viewport) => { + const page = await (await browser.newContext({ viewport })).newPage(); + pages.push([name, page]); + page.setDefaultTimeout(5000); + page.on("pageerror", (e) => errors.push(e.message)); + await page.route("**/*", serve(lang, url.includes("mode=panel"), settings, saved)); + await page.goto(url); + return page; + }; + const page = await open("usage", "http://magpie.test/?view=usage", { width: 1100, height: 760 }); + const cards = page.locator("#subscriptionUsage > .subscription-card"); + const order = () => cards.evaluateAll((cs) => cs.map((c) => c.dataset.key)); + const handle = (key) => page.locator(`#subscriptionUsage > [data-key="${key}"] .us-handle`); + await handle("kimi").waitFor(); + assert.deepEqual(await order(), ["codex", "claude", "kimi", "zai"], "magpie's own order first"); + + // the grip only while the pointer is on the card + const grip = (key) => handle(key).evaluate((h) => getComputedStyle(h, "::before").opacity); + await page.mouse.move(5, 5); + await page.waitForTimeout(250); + assert.equal(await grip("kimi"), "0", "no grip without the pointer"); + await page.locator('#subscriptionUsage > [data-key="kimi"] .subscription-head b').hover(); + await page.waitForTimeout(250); + assert.equal(await grip("kimi"), "1", "a grip on hover"); + + // dragged across the grid onto the first card's place + const scrollY = () => page.evaluate(() => [document.scrollingElement.scrollTop, ...[...document.querySelectorAll("*")].filter((e) => e.scrollTop).map((e) => e.scrollTop)].join()); + const before = await scrollY(); + const h = await handle("kimi").boundingBox(), to = await cards.first().boundingBox(); + await page.mouse.move(h.x + h.width / 2, h.y + h.height / 2); + await page.mouse.down(); + for (let i = 1; i <= 12; i++) await page.mouse.move(h.x + (to.x + 30 - h.x) * i / 12, h.y + (to.y + 30 - h.y) * i / 12); + await page.waitForTimeout(250); + assert.equal(await page.locator("#subscriptionUsage.sorting > .dragging").count(), 1, "the card is held while dragged"); + await page.mouse.up(); + await page.waitForTimeout(250); + assert.deepEqual(await order(), ["kimi", "codex", "claude", "zai"]); + assert.deepEqual(saved.at(-1), ["kimi", "codex", "claude", "zai"], "the order is saved"); + assert.equal(await scrollY(), before, "the drag doesn't move the page"); + + // Alt+arrows from the keyboard, the focus kept on the card moved + await handle("claude").focus(); + await page.keyboard.press("Alt+ArrowRight"); + await page.waitForTimeout(150); + assert.deepEqual(await order(), ["kimi", "codex", "zai", "claude"]); + assert.equal(await page.evaluate(() => document.activeElement?.closest(".subscription-card")?.dataset.key), "claude"); + await page.keyboard.press("Alt+ArrowUp"); + await page.waitForTimeout(150); + assert.deepEqual(await order(), ["kimi", "codex", "claude", "zai"]); + + // a click on the handle doesn't move anything + await handle("zai").click(); + await page.waitForTimeout(150); + assert.deepEqual(await order(), ["kimi", "codex", "claude", "zai"]); + assert.equal(await scrollY(), before, "no click moves the page"); + + // drawn again from settings, and the tray panel follows it + await page.reload(); + await handle("kimi").waitFor(); + assert.deepEqual(await order(), ["kimi", "codex", "claude", "zai"]); + const panel = await open("panel", "http://magpie.test/?mode=panel", { width: 400, height: 680 }); + await panel.locator('#ptabs [data-ptab="usage"]').click(); + await panel.locator("#panelQuota .pq-gn").first().waitFor(); + assert.deepEqual(await panel.locator("#panelQuota .pq-gn").allTextContents(), ["Kimi", "Codex", "Claude", "Z.ai"]); + assert.deepEqual(errors, []); + }); + } +} diff --git a/internal/settings/settings.go b/internal/settings/settings.go index 035dc7967..73d27dbe6 100644 --- a/internal/settings/settings.go +++ b/internal/settings/settings.go @@ -211,6 +211,11 @@ type Settings struct { AgentOrder []string `json:"agentOrder,omitempty"` AgentsHidden []string `json:"agentsHidden,omitempty"` AgentsShown []string `json:"agentsShown,omitempty"` + // UsageOrder is how the Usage page's cards are listed, by provider id, + // as they were dragged there; one it doesn't name follows in magpie's + // own order. Only the page's: the order providers are tried in is the + // Providers page's. + UsageOrder []string `json:"usageOrder,omitempty"` // Visible narrows the models an agent is shown, by agent id: the // families (the tag a provider or group is given), provider ids and // group ids its lists hold. An agent it doesn't name is shown them all. @@ -634,6 +639,7 @@ func Save(s Settings) error { } s.RedactRules = rules s.AgentOrder, s.AgentsHidden, s.AgentsShown = ids(s.AgentOrder), ids(s.AgentsHidden), ids(s.AgentsShown) + s.UsageOrder = ids(s.UsageOrder) s.TrayUsages = ids(s.TrayUsages) for i, u := range s.CodexAutoReset { s.CodexAutoReset[i] = strings.ToLower(u)