diff --git a/internal/access/access.go b/internal/access/access.go index 6b7a7853d..50dfeda45 100644 --- a/internal/access/access.go +++ b/internal/access/access.go @@ -303,7 +303,8 @@ type Change struct { // "reset-limit-key" resets (#2227), counted from 0: one past the last // adds a limit, a nil Limit there removes that one. Without it, // "limit-key" makes Limit the key's only limit, and "reset-limit-key" - // resets every one. + // resets every one. For "move-key" it is the place in the list the key + // goes to, counted from 0. Index *int `json:"index,omitempty"` // Models is what "models-key" sets; none lets the key use every model. Models []string `json:"models,omitempty"` @@ -473,12 +474,21 @@ func Update(action string, in Change) (string, error) { mirror = &k } keys = slices.Delete(keys, i, i+1) + case "move-key": + // the keys are listed in the order they are kept in, which the + // user sets by dragging one (alextjy on Discord); nothing else + // about the key changes + if in.Index == nil || *in.Index < 0 || *in.Index >= len(keys) { + return "", errors.New("There is no such place in the list of keys") + } + k := keys[i] + keys = slices.Insert(slices.Delete(keys, i, i+1), *in.Index, k) case "copy-key": return keys[i].Secret, nil default: return "", fmt.Errorf("unknown key action %q", action) } - if defaultKey && action != "remove-key" && action != "rename-key" && action != "limit-key" && action != "reset-limit-key" && action != "models-key" && action != "accounts-key" && action != "quotas-key" && action != "access-key" { + if defaultKey && action != "remove-key" && action != "rename-key" && action != "limit-key" && action != "reset-limit-key" && action != "models-key" && action != "accounts-key" && action != "quotas-key" && action != "access-key" && action != "move-key" { mirror = &keys[i] } } diff --git a/internal/access/move_test.go b/internal/access/move_test.go new file mode 100644 index 000000000..9df3b4a6b --- /dev/null +++ b/internal/access/move_test.go @@ -0,0 +1,132 @@ +package access + +import ( + "encoding/json" + "os" + "slices" + "testing" + + "github.com/yetone/magpie/internal/settings" +) + +// The keys are kept in the order the user drags them into (alextjy on +// Discord): move-key puts one at a place, the store on disk keeps it, so a +// restart lists them the same way, and nothing else about any key changes, +// the sharing key's mirror in the settings included. +func TestMoveKeyKeepsOrder(t *testing.T) { + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + var ids []string + for _, name := range []string{"Laptop", "Phone", "Desk display", "CI"} { + if _, err := Update("add-key", Change{Name: name, ReadOnly: name == "Desk display"}); err != nil { + t.Fatal(err) + } + } + keys, _ := List() + for _, k := range keys { + ids = append(ids, k.ID) + } + // the first is the sharing key, with a limit and models of its own + s := settings.Load() + s.LAN, s.LANKeyID = true, ids[0] + if err := settings.Save(s); err != nil { + t.Fatal(err) + } + if _, err := Update("models-key", Change{Key: ids[0], Models: []string{"openai/*"}}); err != nil { + t.Fatal(err) + } + if _, err := Update("off-key", Change{Key: ids[3]}); err != nil { + t.Fatal(err) + } + before, _ := Export() + if !before[0].LAN || before[0].Limit != nil { + t.Fatal("the sharing key as set up:", before[0]) + } + lan := settings.Load() + + move := func(id string, to int) { + t.Helper() + if _, err := Update("move-key", Change{Key: id, Index: &to}); err != nil { + t.Fatal(err) + } + } + order := func() []string { + t.Helper() + // read from the file itself, as a magpie started again would + b, err := os.ReadFile(Path()) + if err != nil { + t.Fatal(err) + } + var ks []Key + if err := json.Unmarshal(b, &ks); err != nil { + t.Fatal(err) + } + var out []string + for _, k := range ks { + out = append(out, k.Name) + } + return out + } + move(ids[2], 0) // Desk display to the top + if got := order(); !slices.Equal(got, []string{"Desk display", "Laptop", "Phone", "CI"}) { + t.Fatal("to the top:", got) + } + move(ids[0], 3) // the sharing key to the foot + if got := order(); !slices.Equal(got, []string{"Desk display", "Phone", "CI", "Laptop"}) { + t.Fatal("to the foot:", got) + } + move(ids[3], 2) // where it is: nothing moves + if got := order(); !slices.Equal(got, []string{"Desk display", "Phone", "CI", "Laptop"}) { + t.Fatal("in place:", got) + } + keys, _ = List() + if got := []string{keys[0].Name, keys[1].Name, keys[2].Name, keys[3].Name}; !slices.Equal(got, order()) { + t.Fatal("List:", got) + } + + // each key is as it was, but for its place + after, _ := Export() + byID := func(ks []Key) map[string]string { + m := map[string]string{} + for _, k := range ks { + b, _ := json.Marshal(k) + m[k.ID] = string(b) + } + return m + } + a, b := byID(before), byID(after) + for id := range a { + if a[id] != b[id] { + t.Fatalf("key %s changed:\n%s\n%s", id, a[id], b[id]) + } + } + if len(a) != len(b) { + t.Fatal("keys:", len(a), len(b)) + } + if now := settings.Load(); now.LANKeyID != lan.LANKeyID || now.LANKey != lan.LANKey { + t.Fatalf("the sharing key's mirror moved: %q %q, was %q %q", now.LANKeyID, now.LANKey, lan.LANKeyID, lan.LANKey) + } + if who, ok := Authenticate(lanSecretOf(t, after, ids[0])); !ok || who.KeyID != ids[0] { + t.Fatal("the sharing key after moving:", who, ok) + } + + for _, bad := range []int{-1, 4} { + if _, err := Update("move-key", Change{Key: ids[1], Index: &bad}); err == nil { + t.Fatal("a place out of the list:", bad) + } + } + if _, err := Update("move-key", Change{Key: ids[1]}); err == nil { + t.Fatal("no place") + } + if got := order(); !slices.Equal(got, []string{"Desk display", "Phone", "CI", "Laptop"}) { + t.Fatal("after refused moves:", got) + } +} + +func lanSecretOf(t *testing.T, ks []Key, id string) string { + t.Helper() + i := slices.IndexFunc(ks, func(k Key) bool { return k.ID == id }) + if i < 0 { + t.Fatal("no key", id) + } + return ks[i].Secret +} diff --git a/internal/cli/gateway_keys_cli.go b/internal/cli/gateway_keys_cli.go index 12d521999..89f504175 100644 --- a/internal/cli/gateway_keys_cli.go +++ b/internal/cli/gateway_keys_cli.go @@ -44,6 +44,10 @@ func gatewayKeysTo(out io.Writer, args []string) error { access.MigrateLegacyLANKeyBestEffort() return gatewayKeyAccess(out, args[1:]) } + if action == "move" { + access.MigrateLegacyLANKeyBestEffort() + return gatewayKeyMove(out, args[1:]) + } // add --read-only: a key that reads stats and uses no model // (Steven on Discord: a desk display) readOnly := false @@ -72,7 +76,7 @@ func gatewayKeysTo(out io.Writer, args []string) error { args = args[:2] } if (action == "list" && len(args) != 1) || (action != "list" && len(args) != 2) { - return fmt.Errorf("usage: magpie gateway-key list | add [--key | --key -] [--read-only] | rotate | remove | limit [list | off | reset [] | remove | [add] day|week|month|d|h [--tokens N] [--cost USD] [--cache-reads]] | models [all | /|/* ...] | accounts [all | /|/ ...] | quotas [on | off] | access [read-only | full]") + return fmt.Errorf("usage: magpie gateway-key list | add [--key | --key -] [--read-only] | rotate | remove | limit [list | off | reset [] | remove | [add] day|week|month|d|h [--tokens N] [--cost USD] [--cache-reads]] | models [all | /|/* ...] | accounts [all | /|/ ...] | quotas [on | off] | access [read-only | full] | move ") } switch action { case "list", "add", "rotate", "remove": @@ -558,3 +562,29 @@ func gatewayKeyAccess(out io.Writer, args []string) error { } return err } + +// gatewayKeyMove puts a key at a place in the list, counted from 1 as +// `magpie gateway-key list` shows them, the order the app's Gateway page +// lists them in too, where a key is dragged to its place (alextjy on +// Discord): +// +// magpie gateway-key move +func gatewayKeyMove(out io.Writer, args []string) error { + if len(args) != 2 { + return fmt.Errorf("usage: magpie gateway-key move ") + } + keys, err := access.List() + if err != nil { + return err + } + n, err := strconv.Atoi(args[1]) + if err != nil || n < 1 || n > len(keys) { + return fmt.Errorf("a key's place is 1 to %d, as `magpie gateway-key list` lists them: %q", len(keys), args[1]) + } + n-- + if _, err := access.Update("move-key", access.Change{Key: args[0], Index: &n}); err != nil { + return err + } + _, err = fmt.Fprintf(out, "Gateway key moved to place %d\n", n+1) + return err +} diff --git a/internal/cli/gateway_keys_cli_test.go b/internal/cli/gateway_keys_cli_test.go index 51df153c9..907d6cfac 100644 --- a/internal/cli/gateway_keys_cli_test.go +++ b/internal/cli/gateway_keys_cli_test.go @@ -447,3 +447,44 @@ func TestGatewayKeyQuotasCLI(t *testing.T) { t.Fatal("not kept off") } } + +// magpie gateway-key move puts a key at a place, counted from 1 as list +// shows them, and list shows the keys in that order (alextjy on Discord). +func TestGatewayKeyCLIMove(t *testing.T) { + t.Setenv("HOME", t.TempDir()) + t.Setenv("USERPROFILE", os.Getenv("HOME")) + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + call := func(args ...string) (string, error) { + var out bytes.Buffer + err := gatewayKeysTo(&out, append([]string{"gateway-key"}, args...)) + return out.String(), err + } + for _, name := range []string{"Laptop", "Phone", "CI"} { + if _, err := call("add", name); err != nil { + t.Fatal(err) + } + } + keys, _ := access.List() + if _, err := call("move", keys[2].ID, "1"); err != nil { + t.Fatal(err) + } + list, err := call("list") + if err != nil { + t.Fatal(err) + } + ci, laptop, phone := strings.Index(list, "CI"), strings.Index(list, "Laptop"), strings.Index(list, "Phone") + if ci < 0 || !(ci < laptop && laptop < phone) { + t.Fatal("list after moving CI to 1:\n" + list) + } + for _, bad := range []string{"0", "4", "top"} { + if _, err := call("move", keys[0].ID, bad); err == nil { + t.Fatal("place", bad) + } + } + if _, err := call("move", "nope", "1"); err == nil { + t.Fatal("no such key") + } + if _, err := call("move", keys[0].ID); err == nil { + t.Fatal("no place") + } +} diff --git a/internal/cli/main.go b/internal/cli/main.go index e6cc9708d..e833befaf 100644 --- a/internal/cli/main.go +++ b/internal/cli/main.go @@ -126,6 +126,7 @@ const usage = `magpie — one place to pick every agent's model magpie gateway-key models [all|/|/* ...] the models a key may use, every one unless it names some magpie gateway-key quotas [on|off] whether a key held to a budget, models or accounts is told the quotas of what it may use magpie gateway-key access [read-only|full] read-only: the key reads quotas and usage (GET /, /v1/magpie/quotas, /v1/magpie/usage) and uses no model, MCP server or write + magpie gateway-key move put a key at a place in the list (from 1), the order list and the app show them in magpie mcp image the image and video generation MCP server an agent is given from the library (stdio) magpie tools [] the tools magpie's MCP servers give agents (images, vision, web search, plugins'), with their parameters magpie tool [-- …] [] [-o ] [--json] call one through the running magpie; an image or video it makes is saved diff --git a/internal/gui/assets/app.css b/internal/gui/assets/app.css index 29aa31bf5..d85470c0b 100644 --- a/internal/gui/assets/app.css +++ b/internal/gui/assets/app.css @@ -2367,6 +2367,20 @@ body.window .ag-sk-icon { width: 22px; height: 22px; border-radius: 6px; } Not the Providers keys list's rules (.accts.keys): Limit and Models keep their room there while hidden, so a hover doesn't push the row about */ .gw-keys .acc > .plan { flex: 0 6 auto; min-width: 3em; overflow: hidden; text-overflow: ellipsis; } +/* the keys in the order the user drags them into (alextjy on Discord), by + a row anywhere off its buttons, as the search APIs are; the grip in the + row's margin shows only on the row under the pointer */ +.gw-keys > .acc { position: relative; } +.gw-keys.reorderable > .acc { cursor: grab; touch-action: pan-y; } +.gw-keys.reorderable > .acc:focus-visible { outline: 2px solid var(--accent); outline-offset: -2px; } +.gw-keys > .acc > .grip { position: absolute; left: 3px; top: 19px; translate: 0 -50%; width: 6px; height: 11px; background: radial-gradient(circle, var(--muted) .9px, transparent 1.2px) 0 0 / 3px 3.75px; opacity: 0; transition: opacity .15s; pointer-events: none; } +.gw-keys > .acc:is(:hover, .dragging) > .grip { opacity: 1; } +/* apart: Safari before 15.4 drops a whole selector list with :focus-visible in it */ +.gw-keys > .acc:focus-visible > .grip { opacity: 1; } +@media (hover: none) { .gw-keys > .acc > .grip { opacity: 1; } } +.gw-keys.sorting { user-select: none; -webkit-user-select: none; } +.gw-keys.sorting > .acc { transition: transform .16s cubic-bezier(.22, 1, .36, 1); cursor: grabbing; } +.gw-keys.sorting > .acc.dragging { z-index: 2; background: var(--card-2); box-shadow: 0 0 0 1px var(--line); transition: none; will-change: transform; } .gw-keys .gw-key-more { flex: none; color: var(--muted); } .gw-keys .gw-key-more:is(:hover, .open) { color: var(--fg); } #view-gateway .row-head, #view-usage .row-head { margin: 14px 0 6px; padding: 0 2px; } diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index 309243b89..65d12a9d5 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -564,6 +564,8 @@ const I18N = { "Drag to reorder · Alt+↑/↓ to move": "按住拖动调整位置 · Alt+↑/↓ 移动", "Drag to reorder · Alt+arrow keys to move": "按住拖动调整位置 · Alt+方向键移动", "Account order saved": "账号位置已保存", + "Gateway key order saved": "网关密钥的顺序已保存", + "There is no such place in the list of keys": "密钥列表里没有这个位置", "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": "拖动以调整顺序 · 点击可移动或隐藏", @@ -4790,6 +4792,8 @@ const I18N = { "Drag to reorder · Alt+↑/↓ to move": "按住拖動調整位置 · Alt+↑/↓ 移動", "Drag to reorder · Alt+arrow keys to move": "按住拖動調整位置 · Alt+方向鍵移動", "Account order saved": "帳號位置已儲存", + "Gateway key order saved": "閘道金鑰的順序已儲存", + "There is no such place in the list of keys": "金鑰清單裡沒有這個位置", "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": "拖動以調整順序 · 點選可移動或隱藏", @@ -8982,6 +8986,8 @@ const I18N = { "Drag to reorder · Alt+↑/↓ to move": "ドラッグで並べ替え · Alt+↑/↓ で移動", "Drag to reorder · Alt+arrow keys to move": "ドラッグで並べ替え · Alt+矢印キーで移動", "Account order saved": "アカウントの順番を保存しました", + "Gateway key order saved": "ゲートウェイキーの順番を保存しました", + "There is no such place in the list of keys": "キーの一覧にその位置はありません", "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": "ドラッグで並べ替え · クリックで移動・非表示", @@ -13191,6 +13197,8 @@ const I18N = { "Drag to reorder · Alt+↑/↓ to move": "Ziehen zum Umsortieren · Alt+↑/↓ zum Verschieben", "Drag to reorder · Alt+arrow keys to move": "Ziehen zum Umsortieren · Alt+Pfeiltasten zum Verschieben", "Account order saved": "Reihenfolge der Konten gespeichert", + "Gateway key order saved": "Reihenfolge der Gateway-Schlüssel gespeichert", + "There is no such place in the list of keys": "Diese Stelle gibt es in der Schlüsselliste nicht", "Drag to reorder — a model several providers serve goes to the higher one first · Alt+↑/↓ to move": "Ziehen zum Umsortieren — ein Modell mehrerer Anbieter geht zuerst an den höheren · Alt+↑/↓ zum Verschieben", "Provider order saved": "Reihenfolge der Anbieter gespeichert", "Drag to reorder · click to move or hide": "Ziehen zum Umsortieren · klicken zum Verschieben oder Ausblenden", diff --git a/internal/gui/assets/plugins/gateway/keys.js b/internal/gui/assets/plugins/gateway/keys.js index 9bb0a08c6..f61b4c3ad 100644 --- a/internal/gui/assets/plugins/gateway/keys.js +++ b/internal/gui/assets/plugins/gateway/keys.js @@ -201,6 +201,8 @@ function copyCallerKeyBtn(k) { } function renderGatewayKeys() { + // a drag in progress keeps its rows: the list is drawn when it ends + if (gatewayKeysArranging) { gatewayKeysRenderPending = true; return; } const box = $("#gatewayKeys"); $("#gatewayKeysBlock").hidden = !providers?.gateway.lan; box.replaceChildren(); @@ -212,8 +214,10 @@ function renderGatewayKeys() { if (gatewayKeysErr) list.append(el("div", "none", t(gatewayKeysErr))), box.append(list); return; } + const rows = []; for (const k of gatewayKeys) { const row = el("div", "acc" + (k.off ? " off" : " in-use")); + rows.push(row); row.dataset.key = k.id; const tick = el("button", "dot tick"); tick.title = t(k.off ? "Enable key" : "Disable key"); @@ -230,10 +234,64 @@ function renderGatewayKeys() { if (gatewayKeyDraft !== null) list.append(gatewayKeyForm()); else if (!gatewayKeys.length) list.append(el("div", "none", t("No gateway keys yet"))); box.append(list); + gatewayKeysArrange(list, rows); const page = gatewayKeyPage(); if (page) box.append(page); } +// gatewayKeysArrange: the keys are listed in the order the user puts them +// in (alextjy on Discord), dragged by a row anywhere off its buttons, or +// moved with Alt+↑/↓ on it, as the search APIs are (searchArrange); the +// grip that says so shows on the row under the pointer. The order is kept +// with the keys (move-key), so `magpie gateway-key list`, Connect's key +// picker and the Requests page's key filter list them the same way. The +// new order shows at once, and the list is read again when it can't be +// saved. +let gatewayKeysArranging = false, gatewayKeysRenderPending = false; +function gatewayKeysArranged() { + gatewayKeysArranging = false; + if (gatewayKeysRenderPending) { gatewayKeysRenderPending = false; renderGatewayKeys(); } +} +function gatewayKeysArrange(list, rows) { + if (rows.length < 2) return; + list.classList.add("reorderable"); + const move = async (row, to) => { + const from = rows.indexOf(row); + if (gatewayKeysBusy || to < 0 || to >= rows.length || to === from) return; + const id = row.dataset.key, focus = document.activeElement === row; + const next = [...gatewayKeys]; + next.splice(to, 0, ...next.splice(from, 1)); + gatewayKeys = next; + renderGatewayKeys(); + const refocus = () => { if (focus) $(`#gatewayKeys .acc[data-key="${CSS.escape(id)}"]`)?.focus({ preventScroll: true }); }; + refocus(); + if (await gatewayKeyAction("move-key", { key: id, index: to })) status(t("Gateway key order saved"), "ok"); + else await loadGatewayKeys(); // not saved: the order as it is kept + refocus(); + }; + for (const row of rows) { + const name = row.querySelector(".n")?.textContent || ""; + row.tabIndex = 0; + row.setAttribute("role", "group"); + row.setAttribute("aria-label", name + " · " + t("Drag to reorder · Alt+↑/↓ to move")); + row.title = t("Drag to reorder · Alt+↑/↓ to move"); + row.prepend(el("span", "grip")); + row.addEventListener("click", (e) => { + if (row.dataset.dragged) { e.preventDefault(); e.stopImmediatePropagation(); } + }, true); + row.onkeydown = (e) => { + if (e.target !== row || !e.altKey || !["ArrowUp", "ArrowDown"].includes(e.key) || gatewayKeysArranging) return; + e.preventDefault(); e.stopPropagation(); + move(row, rows.indexOf(row) + (e.key === "ArrowUp" ? -1 : 1)); + }; + row.onpointerdown = (e) => { + if (gatewayKeysArranging || gatewayKeysBusy || e.target.closest("input, textarea, select, a, button, .key-limit-ed")) return; + gatewayKeysArranging = dragRows(e, row, row, list, rows, (to) => move(row, to), () => { closeProtoMenu(); closeAgentMenu(); }, + gatewayKeysArranged); + }; + } +} + // the key page (the gateway's /me): where a key's holder, with their key // alone, sees what it has used and may use and the setup for their agents // (zytszone on X: a department shares one magpie, whose app its people diff --git a/internal/gui/tests/fixtures/caller-keys.cjs b/internal/gui/tests/fixtures/caller-keys.cjs index 270bf9b91..d327f8bd0 100644 --- a/internal/gui/tests/fixtures/caller-keys.cjs +++ b/internal/gui/tests/fixtures/caller-keys.cjs @@ -170,6 +170,12 @@ function fixture(lang, theme, events, options = {}) { if (action === "accounts-key") k.accounts = body.accounts?.length ? body.accounts : undefined; if (action === "quotas-key") k.quotas = body.quotas || undefined; if (action === "access-key") k.readOnly = body.readOnly || undefined; + // a key put at a place in the list, as access.Update keeps it; + // options.refuseMove: the store can't be written + if (action === "move-key") { + if (options.refuseMove) return route.fulfill({ status: 500, json: { error: "There is no such place in the list of keys" } }); + keys.splice(body.index, 0, ...keys.splice(keys.indexOf(k), 1)); + } if (action === "copy-key") secret = k.id === lanKeyID ? lanSecret : secrets.get(k.id); return json({ keys, secret }); } diff --git a/internal/gui/tests/gateway-key-arrange.test.cjs b/internal/gui/tests/gateway-key-arrange.test.cjs new file mode 100644 index 000000000..661684464 --- /dev/null +++ b/internal/gui/tests/gateway-key-arrange.test.cjs @@ -0,0 +1,96 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// Gateway keys in the order the user puts them in (alextjy on Discord): a +// key is dragged by its row, anywhere off its buttons, to another place, the +// grip in its margin shown only on the row under the pointer; the order is +// sent once as move-key and Saved is said; Alt+↑/↓ on a focused row moves it +// a place, the keyboard staying on it; an order that can't be saved is put +// back as it is kept; and the page opened again lists the keys in the order +// saved. In every language, Chromium and WebKit, 1100px and 420px wide, with +// the API faked. +const assert = require("node:assert/strict"); +const { test } = require("node:test"); +const { chromium, webkit } = require("playwright"); +const { fixture } = require("./fixtures/caller-keys.cjs"); + +const saved = { en: "Gateway key order saved", zh: "网关密钥的顺序已保存", "zh-TW": "閘道金鑰的順序已儲存", ja: "ゲートウェイキーの順番を保存しました", de: "Reihenfolge der Gateway-Schlüssel gespeichert" }; + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + for (const lang of ["en", "zh", "zh-TW", "ja", "de"]) for (const width of [1100, 420]) { + test(`${engine} ${lang} ${width}px: gateway keys are dragged into order`, async (t) => { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + t.after(() => browser.close()); + const page = await (await browser.newContext({ viewport: { width, height: 900 } })).newPage(); + page.setDefaultTimeout(6000); + page.setDefaultNavigationTimeout(60000); + const errors = [], events = [], options = { lan: true }; + page.on("pageerror", (e) => errors.push(e.message)); + await page.route("**/*", fixture(lang, "light", events, options)); + await page.goto("http://magpie.test/?view=gateway"); + const rows = page.locator("#gatewayKeys .acc[data-key]"); + await rows.last().waitFor(); + const order = () => rows.evaluateAll((rs) => rs.map((r) => r.dataset.key).join(",")); + const waitOrder = (want) => page.waitForFunction((want) => [...document.querySelectorAll("#gatewayKeys .acc[data-key]")].map((r) => r.dataset.key).join(",") === want, want); + const moves = () => events.filter((e) => e.action !== "ledger"); + assert.equal(await order(), "laptop,server,work"); + assert(await page.evaluate(() => document.scrollingElement.scrollWidth <= innerWidth), "nothing wider than the window"); + + // the grip shows only on the row under the pointer + const grip = (i) => rows.nth(i).locator(".grip").evaluate((g) => getComputedStyle(g).opacity); + await page.mouse.move(2, 2); + await page.waitForFunction(() => getComputedStyle(document.querySelector("#gatewayKeys .acc[data-key] .grip")).opacity === "0"); + await rows.nth(1).hover({ position: { x: 40, y: 10 } }); + await page.waitForFunction(() => getComputedStyle(document.querySelectorAll("#gatewayKeys .acc[data-key] .grip")[1]).opacity === "1"); + assert.equal(await grip(0), "0", "only the row under the pointer has its grip"); + const box = await rows.nth(1).locator(".grip").boundingBox(), row = await rows.nth(1).boundingBox(); + assert(box.x >= row.x && box.x + box.width <= (await rows.nth(1).locator(".dot").boundingBox()).x, "the grip is in the row's margin, before its tick"); + + const clear = () => page.evaluate(() => { const s = document.querySelector("#status"); s.className = "status"; s.textContent = ""; }); + const said = () => page.waitForFunction(() => document.querySelector("#status")?.classList.contains("ok")).then(() => page.locator("#status").textContent()); + const y0 = await page.evaluate(() => scrollY); + + // drag Work, by its masked key, above Laptop + await clear(); + const from = await rows.nth(2).locator(".plan").boundingBox(), to = await rows.nth(0).boundingBox(); + const fx = from.x + from.width / 2, fy = from.y + from.height / 2; + await page.mouse.move(fx, fy); + await page.mouse.down(); + for (let i = 1; i <= 12; i++) await page.mouse.move(fx, fy + (to.y + 4 - fy) * i / 12); + await page.mouse.up(); + await waitOrder("work,laptop,server"); + assert.equal((await said()).trim(), saved[lang]); + assert.deepEqual(moves(), [{ action: "move-key", body: { key: "work", index: 0 } }], "letting go sent the order once, and clicked nothing"); + + // Alt+↓ on Work moves it a place, the keyboard staying on it + await clear(); + await rows.nth(0).focus(); + await page.keyboard.press("Alt+ArrowDown"); + await waitOrder("laptop,work,server"); + await said(); + assert.deepEqual(moves().at(-1), { action: "move-key", body: { key: "work", index: 1 } }); + await page.waitForFunction(() => document.activeElement?.matches?.('#gatewayKeys .acc[data-key="work"]') && document.activeElement.isConnected); + + // an order that can't be saved is put back as it is kept + options.refuseMove = true; + await rows.nth(2).focus(); + await page.keyboard.press("Alt+ArrowUp"); + await page.waitForFunction(() => document.querySelector("#status")?.classList.contains("err")); + await waitOrder("laptop,work,server"); + options.refuseMove = false; + assert.equal(moves().length, 3); + + // a click on a row's buttons still does what it did, and moves nothing + await rows.nth(0).locator(".tick").click(); + await page.waitForFunction(() => document.querySelector('#gatewayKeys .acc[data-key="laptop"]')?.classList.contains("off")); + assert.equal(moves().at(-1).action, "off-key"); + assert.equal(await order(), "laptop,work,server"); + assert.equal(await page.evaluate(() => scrollY), y0, "arranging moved the page"); + + // opened again, the keys are in the order saved + await page.reload(); + await rows.last().waitFor(); + assert.equal(await order(), "laptop,work,server"); + assert(await page.evaluate(() => document.scrollingElement.scrollWidth <= innerWidth), "nothing wider than the window"); + assert.deepEqual(errors, []); + }); + } +} diff --git a/internal/usageapi/key_order_test.go b/internal/usageapi/key_order_test.go new file mode 100644 index 000000000..36c771bfb --- /dev/null +++ b/internal/usageapi/key_order_test.go @@ -0,0 +1,38 @@ +package usageapi + +import ( + "path/filepath" + "slices" + "testing" + + "github.com/yetone/magpie/internal/access" + "github.com/yetone/magpie/internal/usage" +) + +// The Requests page's Gateway key filter lists the keys in the order the +// user gave them on the Gateway page (alextjy on Discord), not by what +// each used; a key removed since goes after them, as it came. +func TestLedgerKeyFilterInKeyOrder(t *testing.T) { + home := t.TempDir() + t.Setenv("XDG_CONFIG_HOME", filepath.Join(home, ".config")) + for _, name := range []string{"Laptop", "Phone", "CI"} { + if _, err := access.Update("add-key", access.Change{Name: name}); err != nil { + t.Fatal(err) + } + } + keys, _ := access.List() + to := 0 + if _, err := access.Update("move-key", access.Change{Key: keys[2].ID, Index: &to}); err != nil { + t.Fatal(err) + } + g := func(id string) Group { return Group{Group: usage.Group{ID: id, CallerKeyID: id}} } + // by tokens, as the ledger ranks them: gone first, then Phone, Laptop, CI + got := inKeyOrder([]Group{g("gone"), g(keys[1].ID), g(keys[0].ID), g(keys[2].ID)}) + var ids []string + for _, x := range got { + ids = append(ids, x.CallerKeyID) + } + if want := []string{keys[2].ID, keys[0].ID, keys[1].ID, "gone"}; !slices.Equal(ids, want) { + t.Fatalf("filter order %v, want CI, Laptop, Phone, then the removed key: %v", ids, want) + } +} diff --git a/internal/usageapi/usageapi.go b/internal/usageapi/usageapi.go index 494fcd78d..bffbc7849 100644 --- a/internal/usageapi/usageapi.go +++ b/internal/usageapi/usageapi.go @@ -192,6 +192,29 @@ func callerGroups(s usage.Summary) []Group { return keys } +// inKeyOrder puts the Gateway key filter's keys in the order the user +// gave the keys on the Gateway page (alextjy on Discord), not by what each +// used: a key removed since, which the store no longer lists, goes after +// them, in the order it came. The Overview's list stays a ranking. +func inKeyOrder(groups []Group) []Group { + current, err := access.List() + if err != nil { + return groups + } + place := make(map[string]int, len(current)) + for i, k := range current { + place[k.ID] = i + } + at := func(g Group) int { + if i, ok := place[g.CallerKeyID]; ok { + return i + } + return len(current) + } + slices.SortStableFunc(groups, func(a, b Group) int { return at(a) - at(b) }) + return groups +} + // PeriodOf is the period a ?period= names: a preset, or days picked as // "2026-10-01..2026-10-07" (#1492); 30 days for anything else. func PeriodOf(s string) usage.Period { @@ -328,7 +351,7 @@ func LedgerPage(p usage.Period, f usage.Filter, offset, limit int) Ledger { out.Bucket, out.Series = l.Bucket, l.Series out.Purposes = l.Purposes out.Day = f.Day - out.CallerKeys = callerGroups(usage.Summary{CallerKeys: l.CallerKeys}) + out.CallerKeys = inKeyOrder(callerGroups(usage.Summary{CallerKeys: l.CallerKeys})) callerLabels := map[string]string{} for _, g := range out.CallerKeys { callerLabels[g.CallerKeyID] = g.Name