diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index 1cf5310bf..7c8eaef70 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -939,11 +939,7 @@ function menuButton(a, cls = "ag-start") { b.dataset.key = "models"; fillMenuButton(b, a); b.onclick = (ev) => openAgentModels(a, b, ev); - // drawn again while its list is open: the list stays, held to it - if (agentModels?.a.id === a.id) { - b.classList.add("open"); - agentModels.anchor = b; - } + holdAgentModels(a, b); return b; } function fillMenuButton(b, a) { @@ -1323,11 +1319,7 @@ function connectPanel(a, { fields, fieldBtn }) { c.append(svg(CHEV_R, 10, 1.6)); pick.append(c); pick.onclick = (ev) => openAgentModels(a, pick, ev); - // drawn again while its list is open: the list stays, held to it - if (agentModels?.a.id === a.id) { - pick.classList.add("open"); - agentModels.anchor = pick; - } + holdAgentModels(a, pick); chips.append(pick); kv(t("Model list"), chips); } @@ -2184,13 +2176,7 @@ function modelsEntry(a) { b.type = "button"; fillModelsEntry(b, a); b.onclick = (ev) => openAgentModels(a, b, ev); - // the rows drawn again while its list is open: the list stays, held to - // the new line - if (agentModels?.a.id === a.id) { - b.classList.add("open"); - agentModels.anchor = b; - if (agentModels.count) { a.models = agentModels.count; fillModelsEntry(b, a); } - } + if (holdAgentModels(a, b) && agentModels.count) { a.models = agentModels.count; fillModelsEntry(b, a); } return b; } function fillModelsEntry(b, a) { @@ -2239,6 +2225,19 @@ function closeAgentModels() { m.saving.then(async () => { state = await api("state"); renderAgents(); }).catch(() => {}); } +// holdAgentModels: a button that opens an agent's list, drawn again while +// that list is open or still loading. The list stays, held to the new +// button: one loading came up at the old one, gone from the page, so a +// redraw while it loaded (a refresh, or the state re-read after a changed +// list) dropped the click. Says whether the list is open. +function holdAgentModels(a, b) { + if (agentModelsLoading?.id === a.id) agentModelsLoading.anchor = b; + if (agentModels?.a.id !== a.id) return false; + b.classList.add("open"); + agentModels.anchor = b; + return true; +} + async function openAgentModels(a, anchor, ev) { ev.stopPropagation(); const again = agentModels?.a.id === a.id || agentModelsLoading?.id === a.id; @@ -2248,7 +2247,8 @@ async function openAgentModels(a, anchor, ev) { // a click elsewhere while it loads is one away from it, as it is once open const loading = agentModelsLoading = { id: a.id, - away: (e) => { if (!anchor.contains(e.target)) loading.drop(); }, + anchor, + away: (e) => { if (!loading.anchor.contains(e.target)) loading.drop(); }, drop() { if (agentModelsLoading === loading) agentModelsLoading = null; document.removeEventListener("mousedown", loading.away, true); @@ -2265,6 +2265,8 @@ async function openAgentModels(a, anchor, ev) { } if (agentModelsLoading !== loading) return; loading.drop(); + // the button as it is drawn now + anchor = loading.anchor; if (!anchor.isConnected) return; const box = el("div", "pop am-pop"); box.setAttribute("role", "dialog"); @@ -5405,12 +5407,57 @@ function segs(items, current, onPick) { box.append(b); } queueMicrotask(() => { // once it is in the page - const home = box.isConnected && box.parentElement.closest("[id]"); - if (home) key = kind + "@" + home.id + ":" + [...home.querySelectorAll(".segs")].filter((x) => x.dataset.kind === kind).indexOf(box); + key = segsPlace(box) || key; slide(box, key); }); return box; } +// where a control is in the page: the nearest element with an id, and which +// of the same options it is there; "" for one not in the page +function segsPlace(box) { + const home = box.isConnected && box.parentElement.closest("[id]"); + return home ? box.dataset.kind + "@" + home.id + ":" + [...home.querySelectorAll(".segs")].filter((x) => x.dataset.kind === box.dataset.kind).indexOf(box) : ""; +} +// A press on an option still picks it when the control is drawn again +// before the button is let go: a save's answer redraws Settings, and a +// second option pressed while the first one's save came back was let go +// on a new button. Down and up were on two buttons, so the browser sent the +// click to neither and nothing was picked. Let go on the same option of the +// same control, the new one is clicked; let go anywhere else (dragged off +// to another option), nothing is, as for any button. A tap is left to the +// browser, which clicks what is under the finger as it lifts. +let segsPress = null; +const optAt = (b) => [...b.parentElement.querySelectorAll(":scope > .opt")].indexOf(b); +// the same control is at the same place, among as many of its kind, in rows +// that are the same by their data-* (an agent's, a provider's): a list drawn +// again with a row gone, come in or moved above it is another control there +function segsWho(box) { + const place = segsPlace(box); + if (!place) return ""; + const home = box.parentElement.closest("[id]"), rows = []; + for (let n = box.parentElement; n !== home; n = n.parentElement) rows.push(Object.entries(n.dataset).join()); + return [place, [...home.querySelectorAll(".segs")].filter((x) => x.dataset.kind === box.dataset.kind).length, ...rows].join(" "); +} +addEventListener("pointerdown", (e) => { + const b = e.isPrimary && e.button === 0 && e.pointerType !== "touch" && e.target.closest?.(".segs > .opt"); + segsPress = b ? { b, who: segsWho(b.parentElement), i: optAt(b) } : null; +}, true); +addEventListener("pointercancel", () => { segsPress = null; }, true); +addEventListener("pointerup", (e) => { + const p = segsPress; + segsPress = null; + if (!p?.who || p.b.isConnected || !e.isPrimary) return; + const b = document.elementFromPoint(e.clientX, e.clientY)?.closest(".segs > .opt"); + if (!b || segsWho(b.parentElement) !== p.who || optAt(b) !== p.i) return; + // after the browser's own click, should one come to it after all + let clicked = false; + const seen = (c) => { if (b.contains(c.target)) clicked = true; }; + addEventListener("click", seen, true); + setTimeout(() => { + removeEventListener("click", seen, true); + if (!clicked && b.isConnected) b.click(); + }); +}, true); // An installed list's order, the reader's pick, remembered for each list // (#481): its names A→Z or Z→A, and for a list that has one, a view of its @@ -18262,6 +18309,11 @@ function suffixed(name, by, own, mode = suffixMode()) { return name + " · " + by; } +// the menu bar's menu waiting on the allowances: the pill drawn last opens +// it, with what that drawing keeps. Opened at the pill a redraw took away +// (another setting saved meanwhile), it came up in the window's corner and +// saved the other setting back as it was. +let trayUsageLoading = null; function renderTrayUsage(s, keep) { $("#quotaLeftSegs").replaceChildren(segs([[false, t("Used")], [true, t("Left")]], !!s.quotaLeft, (on) => { if (on !== quotaLeft) setQuotaLeft(on); })); @@ -18319,10 +18371,10 @@ function renderTrayUsage(s, keep) { }; paint(); if (ids.length === 1 && !quotas) loadQuotas().then(paint); - pill.onclick = async (e) => { - e.stopPropagation(); - if (pill.classList.contains("open")) return closeProtoMenu(); - if (!quotas) { pill.classList.add("busy"); await loadQuotas(); pill.classList.remove("busy"); paint(); } + const open = () => { + pill.classList.remove("busy"); + paint(); + if (!pill.isConnected) return; const cards = (quotas || []).filter((q) => !q.error && (q.windows?.length || q.balance)); const opts = [{ v: "", name: "Off", note: "" }]; for (const q of cards) { @@ -18338,6 +18390,18 @@ function renderTrayUsage(s, keep) { if (!cards.length) opts.push({ v: "\x00", name: "No subscriptions yet", note: "Sign in to one, or add a plan's key, and it shows on the Usage page" }); openProtoMenu(pill, opts, ids, (trayUsages) => savePrefs({ ...keep, trayUsages }), "Shown beside the icon"); }; + pill.onclick = async (e) => { + e.stopPropagation(); + if (pill.classList.contains("open")) return closeProtoMenu(); + if (quotas) return open(); + const loading = trayUsageLoading = { open }; + pill.classList.add("busy"); + await loadQuotas(); + if (trayUsageLoading !== loading) return; + trayUsageLoading = null; + loading.open(); + }; + if (trayUsageLoading) { trayUsageLoading.open = open; pill.classList.add("busy"); } $("#trayUsagePick").replaceChildren(pill); // how often it is asked for again, and whether it reads as used or left — // the Usage page's choice too (#122) diff --git a/internal/gui/assets/caller-keys.js b/internal/gui/assets/caller-keys.js index 78734109b..16ed44478 100644 --- a/internal/gui/assets/caller-keys.js +++ b/internal/gui/assets/caller-keys.js @@ -213,6 +213,11 @@ function askGatewayKey(k, rotate) { // badge says it: by who is signed in, the id itself when no provider has it. const accountShown = (a) => gatewayAccountNames[a] || a; +// the key whose models menu waits on its list: the badge drawn last opens +// it, so a redraw of the keys while it loads (a rename's reply, the +// providers' poll) doesn't drop the click +let keyModelsLoading = null; + // gatewayModelsBadge picks the models and the accounts a key may use, in // the app's menu: "All models" on hover when it may use any, else which // it may, always shown. A pick is sent when the menu closes. @@ -229,12 +234,7 @@ function gatewayModelsBadge(k) { b.setAttribute("aria-label", t("Models this key may use")); b.setAttribute("aria-haspopup", "menu"); b.setAttribute("aria-expanded", "false"); - b.onclick = async (e) => { - e.preventDefault(); - e.stopPropagation(); - if (b.classList.contains("open")) return closeProtoMenu(); - let models = [], accounts = []; - try { ({ models, accounts } = await api("caller-keys/models")); } catch (err) { status(t(err.message), "err"); return; } + const open = (models, accounts) => { if (!b.isConnected) return; const opts = [{ v: "", name: "All models", note: "Any model and any account, now and later" }]; const seen = new Set(); @@ -300,6 +300,22 @@ function gatewayModelsBadge(k) { })(); }, "Models this key may use", "sess-menu", "right"); }; + b.onclick = async (e) => { + e.preventDefault(); + e.stopPropagation(); + if (b.classList.contains("open")) return closeProtoMenu(); + const loading = keyModelsLoading = { id: k.id, open }; + let models = [], accounts = []; + try { ({ models, accounts } = await api("caller-keys/models")); } catch (err) { + if (keyModelsLoading === loading) keyModelsLoading = null; + status(t(err.message), "err"); + return; + } + if (keyModelsLoading !== loading) return; + keyModelsLoading = null; + loading.open(models, accounts); + }; + if (keyModelsLoading?.id === k.id) keyModelsLoading.open = open; return b; } diff --git a/internal/gui/tests/README.md b/internal/gui/tests/README.md index b6e891720..830d95211 100644 --- a/internal/gui/tests/README.md +++ b/internal/gui/tests/README.md @@ -700,6 +700,26 @@ screenshot of each size: node --test --test-concurrency=1 internal/gui/tests/settings-sections.test.cjs internal/gui/tests/settings-groups.test.cjs ``` +`segs-press-redraw.test.cjs` presses a Settings option, redraws the page +(`renderSettings()`, as a save's answer does) while the button is held and +lets go on the same spot: Lightweight mode → On is posted once and shown on. +Dragged off to the other option, or to the same option of another control, +nothing is posted, and a plain click is posted once, not twice. It then +presses every option control on every Settings tab (49 in English, the +warm-up, check-in, sync and local network ones included) the same way and +checks that the control drawn in its place is clicked once on the same +option. Without the fix no click comes at all. A tap through the redraw is +posted once, not twice (Chromium only: Playwright can't hold a tap in +WebKit). A list of rows, each with its control, drawn again with a row gone, +come in or moved above the pressed one picks nothing, whether its rows have +`data-*` or not, and picks the pressed option when drawn again the same. +Chromium and WebKit, English, Chinese, Japanese and German, 900 and 440px +wide: + +```sh +node --test internal/gui/tests/segs-press-redraw.test.cjs +``` + `update-check.test.cjs` checks the version row: the button stays, dimmed, through a check, a second click asks nothing, and the answer puts it back. A read still out cannot draw "checking" over that answer. A row drawn again diff --git a/internal/gui/tests/agent-models-redraw.test.cjs b/internal/gui/tests/agent-models-redraw.test.cjs new file mode 100644 index 000000000..a093479a9 --- /dev/null +++ b/internal/gui/tests/agent-models-redraw.test.cjs @@ -0,0 +1,185 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// An agent's model list that is still loading when the Agents page is drawn +// again (the state re-read after a changed list closes, or any refresh): the +// click isn't dropped. The list comes up under the redrawn button, which is +// marked open and gets the focus back on Escape, and a click on the redrawn +// button while it loads takes it back, as one on the first would. For each +// button that opens the list: a connected row's Pick, Claude Desktop's model +// menu button, and the line under a name that counts the models. +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"); + +function fixture() { + const list = [ + { id: "openai/gpt-5.5", name: "GPT-5.5", group: "OpenAI", icon: "openai", context: 272e3 }, + { id: "openai/gpt-5.4", name: "GPT-5.4", group: "OpenAI", icon: "openai", context: 272e3 }, + { id: "zai/glm-5.2", name: "GLM-5.2", group: "Z.ai", icon: "zai", context: 1e6 }, + ]; + const fx = { load: 0, stateWait: 0, posts: 0 }; + const count = () => { + const on = list.filter((m) => !m.hidden); + return { shown: on.length, listed: list.length, names: on.map((m) => m.name) }; + }; + const state = () => ({ + agents: [ + { + id: "codex", name: "Codex", path: "/test/config.toml", icon: "codex-color", wired: true, + fields: [{ key: "model", label: "model", value: "magpie/openai/gpt-5.5", options: [{ value: "magpie/openai/gpt-5.5", label: "GPT-5.5", ref: "openai/gpt-5.5" }] }], + models: count(), + }, + { + id: "claude-desktop", name: "Claude Desktop", path: "/test/claude_desktop_config.json", icon: "claude-color", wired: true, + fields: [{ key: "provider", label: "provider", value: "magpie", options: [{ value: "magpie", label: "magpie", icon: "magpie" }] }], + models: count(), + }, + // nothing to connect: its models counted on the line under its name + { id: "plain", name: "Plain", path: "/test/plain.json", icon: "generic", fields: [], models: { shown: 0, listed: 0 } }, + ], + profiles: [], settings: { lang: "en", theme: "light" }, + }); + fx.serve = async (route) => { + const req = route.request(); + const url = new URL(req.url()); + const json = (data) => route.fulfill({ json: data }); + if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"en",theme:"light",web:true};` }); + if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" }); + if (url.pathname === "/api/state") { + if (fx.stateWait) await new Promise((r) => setTimeout(r, fx.stateWait)); + return json(state()); + } + if (url.pathname.startsWith("/api/agent-models/")) { + if (req.method() === "POST") { + fx.posts++; + const { hidden } = req.postDataJSON(); + for (const m of list) m.hidden = hidden.includes(m.id); + return json({ models: list, count: count() }); + } + if (fx.load) await new Promise((r) => setTimeout(r, fx.load)); + return json({ models: list }); + } + if (url.pathname === "/api/groups") return json({ groups: [] }); + if (url.pathname === "/api/agents/cli") return json({ agents: {}, pending: false }); + if (url.pathname === "/api/providers") return json({ providers: [], gateway: { running: true, window: true } }); + 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)]; + await route.fulfill({ body: await fs.readFile(file), contentType }); + }; + return fx; +} + +// the buttons that open an agent's model list, found again after each redraw +const BUTTONS = { + "a connected row's Pick": '.row.agent[data-id="codex"] .ag-exp .ag-chips .ag-quiet', + "Claude Desktop's model menu": '.row.agent[data-id="claude-desktop"] > .ag-menu', + "the line counting the models": '.row.agent[data-id="plain"] .ag-models', +}; + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + for (const width of [1100, 560]) { + test(`${engine} ${width}px: an agent's model list loading while the agents are drawn again`, async (t) => { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + const page = await browser.newPage({ viewport: { width, height: 700 } }); + page.setDefaultTimeout(5000); + const errors = []; + page.on("pageerror", (e) => errors.push(e.message)); + const fx = fixture(); + await page.route("**/*", fx.serve); + t.after(() => browser.close()); + await page.goto("http://magpie.test/"); + await page.locator('.row.agent[data-id="codex"] .ag-link').click(); + // Plain, with nothing set, is folded under the two connected ones + await page.locator("#agents .agent-more").click(); + await page.locator('#agents .agent-more[aria-expanded="true"]').waitFor(); + const pop = page.locator(".am-pop:not(.leaving)"); + const redraw = () => page.evaluate(() => renderAgents()); + + // every case is checked, so a run says which of them fail + const failed = []; + const check = (ok, said) => { if (!ok) failed.push(said); }; + const opened = () => pop.waitFor({ timeout: 2000 }).then(() => true, () => false); + const shut = async () => { + if (!await pop.count()) return; + await page.keyboard.press("Escape"); + await pop.waitFor({ state: "detached" }); + }; + + // in view and clear of the footer, scrolled to with the wheel: the + // page puts back a scroll that isn't the reader's (scrollIntoView, + // Playwright's own before a click) + const pressOn = async (btn) => { + const [y, top, bottom] = await btn.evaluate((e) => { + const r = e.getBoundingClientRect(), v = e.closest(".view").getBoundingClientRect(); + return [r.top + r.height / 2, v.top, Math.min(v.bottom, document.querySelector("footer.foot")?.getBoundingClientRect().top ?? v.bottom)]; + }); + if (y < top + 20 || y > bottom - 20) { + await page.mouse.move(width / 2, (top + bottom) / 2); + await page.mouse.wheel(0, y - (top + bottom) / 2); + await page.waitForTimeout(300); + } + await btn.click(); + }; + + for (const [name, sel] of Object.entries(BUTTONS)) { + const btn = page.locator(sel); + await btn.waitFor(); + const press = () => pressOn(btn); + fx.load = 400; + + // drawn again while it loads: the list still comes, at the new button + await press(); + await redraw(); + if (await opened()) { + assert.equal(await btn.count(), 1); + check(/\bopen\b/.test(await btn.getAttribute("class")), `${name}: the redrawn button isn't marked open`); + // where it was put, not where its opening animation has it now + const gap = await pop.evaluate((e, sel) => { + const r = document.querySelector(sel).getBoundingClientRect(); + return e.classList.contains("up") ? r.top - (innerHeight - parseFloat(e.style.bottom)) : parseFloat(e.style.top) - r.bottom; + }, sel); + check(Math.abs(gap - 8) <= 2, `${name}: the list is ${gap}px from its button`); + await page.keyboard.press("Escape"); + await pop.waitFor({ state: "detached" }); + check(await btn.evaluate((e) => e === document.activeElement), `${name}: Escape didn't give the redrawn button the focus`); + } else { + check(false, `${name}: the redraw dropped the click`); + await page.waitForTimeout(400); + } + + // drawn again while it loads, then the new button clicked: taken back + await press(); + await redraw(); + await press(); + await page.waitForTimeout(700); + check(await pop.count() === 0, `${name}: a second click on the redrawn button didn't take it back`); + await shut(); + check(!/\bopen\b/.test(await btn.getAttribute("class")), `${name}: the button stays marked open`); + } + + // the state re-read a changed list's close queues lands while the + // next list loads (agent-models.test.cjs: Escape, then Pick again) + const pick = page.locator(BUTTONS["a connected row's Pick"]); + fx.load = 0; + await pressOn(pick); + await pop.waitFor(); + await pop.locator(".am-mr", { hasText: "GLM-5.2" }).click(); + for (let i = 0; !fx.posts && i < 50; i++) await page.waitForTimeout(20); + fx.load = 900; + fx.stateWait = 350; + await page.keyboard.press("Escape"); + await pop.waitFor({ state: "detached" }); + await pressOn(pick); + check(await opened(), "the state re-read after a changed list dropped the click on Pick"); + assert.equal(fx.posts, 1); + await shut(); + assert.deepEqual(failed, []); + assert.deepEqual(errors, []); + }); + } +} diff --git a/internal/gui/tests/gateway-key-models-redraw.test.cjs b/internal/gui/tests/gateway-key-models-redraw.test.cjs new file mode 100644 index 000000000..65d5276c6 --- /dev/null +++ b/internal/gui/tests/gateway-key-models-redraw.test.cjs @@ -0,0 +1,51 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// A gateway key's models menu that is still loading when the key list is +// drawn again (a rename's reply, the providers' poll, coming back to the +// window): the click isn't dropped. The menu comes up at the redrawn badge, +// which is marked open, and what is picked is sent for that key. +const assert = require("node:assert/strict"); +const { test } = require("node:test"); +const { chromium, webkit } = require("playwright"); +const { fixture } = require("./fixtures/caller-keys.cjs"); + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + for (const width of [1000, 560]) { + test(`${engine} ${width}px: a key's models menu loading while the keys are drawn again`, 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: 700 }, reducedMotion: "reduce" })).newPage(); + page.setDefaultTimeout(6000); + const events = [], errors = []; + page.on("pageerror", (e) => errors.push(e.message)); + await page.route("**/*", fixture("en", "light", events, { lan: true })); + // the models the menu lists, slow to come + await page.route("**/api/caller-keys/models", async (route) => { + await new Promise((r) => setTimeout(r, 500)); + await route.fallback(); + }); + await page.goto("http://magpie.test/?view=gateway"); + const badge = page.locator('#gatewayKeys .acc[data-key="work"] .key-models'); + await badge.waitFor(); + const menu = page.locator(".proto-menu"); + + await badge.click(); + await page.evaluate(() => renderGatewayKeys()); + await menu.waitFor({ timeout: 2000 }).catch(() => assert.fail("the redraw dropped the click")); + assert.equal(await badge.getAttribute("aria-expanded"), "true", "the redrawn badge isn't marked open"); + const b = await badge.boundingBox(), m = await menu.boundingBox(); + const up = await menu.evaluate((e) => e.classList.contains("up")); + const gap = up ? b.y - (m.y + m.height) : m.y - (b.y + b.height); + assert(Math.abs(gap - 5) <= 2, `the menu is ${gap}px from its badge`); + + // a pick is sent for that key as the menu closes + await menu.locator(".pm-item", { hasText: "GPT-5" }).click(); + await page.keyboard.press("Escape"); + await menu.waitFor({ state: "detached" }); + await page.waitForFunction(() => document.querySelector('#gatewayKeys .acc[data-key="work"] .key-models')?.textContent.trim() === "openai/gpt-5"); + const sent = events.filter((e) => e.action === "models-key"); + assert.deepEqual(sent.map((e) => e.body), [{ key: "work", models: ["openai/gpt-5"] }]); + assert.equal(await badge.getAttribute("aria-expanded"), "false"); + assert.deepEqual(errors, []); + }); + } +} diff --git a/internal/gui/tests/segs-press-redraw.test.cjs b/internal/gui/tests/segs-press-redraw.test.cjs new file mode 100644 index 000000000..5018e4b6b --- /dev/null +++ b/internal/gui/tests/segs-press-redraw.test.cjs @@ -0,0 +1,286 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// A Settings option pressed while the page is drawn again still picks it: +// a save's answer redraws Settings (renderSettings), and a second option +// pressed while the first one's save came back was let go on a new button. +// Down and up were on two buttons, the browser sent the click to neither, +// and nothing was saved. Pressed, redrawn and let go on the same option, +// Lightweight mode → On is saved once; dragged off to another option, or to +// the same option of another control, nothing is; a click with no redraw +// is saved once. Every segs control on every Settings tab is pressed the +// same way and its new self clicked once. Chromium and WebKit, in English, +// Chinese, Japanese and German, in a wide and a narrow window, the API faked. +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 words = { en: { on: "On", off: "Off" }, zh: { on: "开启", off: "关闭" }, ja: { on: "オン", off: "オフ" }, de: { on: "An", off: "Aus" } }; + +function serve(lang, posted, st) { + const settings = () => ({ lang, theme: "light", searchVendors: [], searchAPIs: [], ...st }); + return async (r) => { + const url = new URL(r.request().url()); + const json = (data, status = 200) => r.fulfill({ status, json: data }); + if (url.pathname === "/boot.js") return r.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:false};` }); + if (url.pathname === "/wails/runtime.js") return r.fulfill({ contentType: "text/javascript", body: "export const Window = {};" }); + if (url.pathname === "/api/state") return json({ agents: [], profiles: [], settings: settings() }); + if (url.pathname.startsWith("/api/settings")) { + if (r.request().method() === "POST") { + const b = JSON.parse(r.request().postData()); + posted.push(b); + if (url.pathname === "/api/settings") Object.assign(st, b); + } + return json(settings()); + } + if (url.pathname === "/api/providers") return json({ providers: [], presets: [], excluded: [], gateway: { running: true, window: true, url: "http://127.0.0.1:3999" } }); + if (url.pathname === "/api/groups") return json({ models: [], groups: [], pools: [] }); + if (url.pathname === "/api/plugins") return json({ plugins: [] }); + if (url.pathname === "/api/usage/quotas") return json([]); + // sync set up, so its own controls are drawn + if (url.pathname === "/api/davsync") return json({ on: true, kind: "webdav", url: "https://dav.example.test/dav/", user: "u", auto: 3 }); + 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 r.fulfill({ body: await fs.readFile(file), contentType }); + }; +} + +async function open(engine, lang, width, tab, posted, st, t, touch = false) { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + t.after(() => browser.close()); + const page = await (await browser.newContext({ viewport: { width, height: 1000 }, hasTouch: touch })).newPage(); + page.setDefaultTimeout(5000); + const errors = []; + page.on("pageerror", (e) => errors.push(e.message)); + await page.route("**/*", serve(lang, posted, st)); + await page.goto("http://magpie.test/?view=settings&tab=" + tab); + await page.locator(`#setPage-${tab} .segs .opt`).first().waitFor(); + return { page, errors }; +} + +const settle = (page) => page.evaluate(() => new Promise((ok) => setTimeout(ok, 80))); +// brought out from under the header and the foot by the reader's wheel, as +// code's scrolls are put back, till the pointer at its middle is on it +async function reveal(page, loc) { + for (let i = 0; i < 40; i++) { + const b = await loc.boundingBox(); + const h = page.viewportSize().height; + if (b && await loc.evaluate((o, [x, y]) => o.contains(document.elementFromPoint(x, y)), mid(b))) return b; + await page.mouse.move(page.viewportSize().width / 2, h / 2); + await page.mouse.wheel(0, b && b.y < h / 2 ? -150 : 150); + await page.waitForTimeout(60); + } + throw new Error("could not bring the option into view"); +} +const mid = (b) => [b.x + b.width / 2, b.y + b.height / 2]; + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + for (const lang of ["en", "zh", "ja", "de"]) { + for (const width of [900, 440]) { + const w = words[lang]; + test(`${engine} ${lang} ${width}px: an option pressed while Settings is redrawn is picked once, and nothing when dragged off`, async (t) => { + const posted = [], st = {}; + const { page, errors } = await open(engine, lang, width, "general", posted, st, t); + const opt = (id, name) => page.locator(`#${id} .opt`, { hasText: new RegExp(`^${name}$`) }); + const on = () => page.locator("#lightweightSegs .opt.on").innerText(); + const saves = () => posted.filter((b) => "lightweight" in b).map((b) => b.lightweight); + assert.equal(await on(), w.off, "off by default"); + + // pressed, the page redrawn as a save's answer does, let go on the same spot + const b = await reveal(page, opt("lightweightSegs", w.on)); + await page.mouse.move(...mid(b)); + await page.mouse.down(); + const swapped = await page.evaluate(() => { + const was = document.querySelector("#lightweightSegs .opt:nth-of-type(2)"); + renderSettings(); + return !was.isConnected; + }); + assert(swapped, "the redraw left the pressed button in place, so this tested nothing"); + await page.mouse.up(); + for (let i = 0; i < 40 && !saves().length; i++) await page.waitForTimeout(50); + await settle(page); + assert.deepEqual(saves(), [true], `posted ${JSON.stringify(posted)}`); + assert.equal(st.lightweight, true); + assert.equal(await on(), w.on); + + // which control's option, and which of its options, the pointer is on + const under = () => page.evaluate(() => { + const o = document.elementFromPoint(...window.lastPointer)?.closest(".segs > .opt"); + return o ? o.parentElement.parentElement.id + " " + o.textContent : ""; + }); + await page.evaluate(() => addEventListener("pointermove", (e) => { window.lastPointer = [e.clientX, e.clientY]; }, true)); + + // dragged off to the other option: nothing, as for any button + const n = posted.length; + const off = await reveal(page, opt("lightweightSegs", w.off)); + await page.mouse.move(...mid(off)); + await page.mouse.down(); + await page.evaluate(() => renderSettings()); + await page.mouse.move(...mid(await opt("lightweightSegs", w.on).boundingBox()), { steps: 4 }); + assert.equal(await under(), "lightweightSegs " + w.on); + await page.mouse.up(); + await page.waitForTimeout(400); + assert.equal(posted.length, n, `dragged off, posted ${JSON.stringify(posted.slice(n))}`); + assert.equal(await on(), w.on); + + // dragged to the same option of another control (Keep awake's Off): nothing + await reveal(page, opt("keepAwakeSegs", w.off)); + await page.mouse.move(...mid(await reveal(page, opt("lightweightSegs", w.off)))); + await page.mouse.down(); + await page.evaluate(() => renderSettings()); + await page.mouse.move(...mid(await opt("keepAwakeSegs", w.off).boundingBox()), { steps: 4 }); + assert.equal(await under(), "keepAwakeSegs " + w.off); + await page.mouse.up(); + await page.waitForTimeout(400); + assert.equal(posted.length, n, `dragged to another control, posted ${JSON.stringify(posted.slice(n))}`); + assert.equal(await on(), w.on); + + // a plain click with no redraw is saved once, not twice + await page.mouse.click(...mid(await reveal(page, opt("lightweightSegs", w.off)))); + for (let i = 0; i < 40 && saves().length < 2; i++) await page.waitForTimeout(50); + await page.waitForTimeout(300); + assert.deepEqual(saves(), [true, false], `posted ${JSON.stringify(posted)}`); + assert.equal(await on(), w.off); + assert.deepEqual(errors, []); + }); + + // a tap is the browser's to click: it clicks what is under the finger + // as it lifts, the new On, and that is the only pick. Playwright can't + // hold a tap in WebKit, so it is Chromium's, through its DevTools. + if (engine === "chromium") test(`${engine} ${lang} ${width}px: an option tapped while Settings is redrawn is picked once, not twice`, async (t) => { + const posted = [], st = {}; + const { page, errors } = await open(engine, lang, width, "general", posted, st, t, true); + const opt = page.locator("#lightweightSegs .opt", { hasText: new RegExp(`^${w.on}$`) }); + const [x, y] = mid(await reveal(page, opt)); + const cdp = await page.context().newCDPSession(page); + await cdp.send("Input.dispatchTouchEvent", { type: "touchStart", touchPoints: [{ x, y }] }); + const swapped = await page.evaluate(() => { + const was = document.querySelector("#lightweightSegs .opt:nth-of-type(2)"); + renderSettings(); + return !was.isConnected; + }); + assert(swapped, "the redraw left the tapped button in place, so this tested nothing"); + await cdp.send("Input.dispatchTouchEvent", { type: "touchEnd", touchPoints: [] }); + for (let i = 0; i < 40 && !posted.length; i++) await page.waitForTimeout(50); + await page.waitForTimeout(500); + assert.deepEqual(posted.filter((b) => "lightweight" in b).map((b) => b.lightweight), [true]); + assert.equal(await page.locator("#lightweightSegs .opt.on").innerText(), w.on); + assert.deepEqual(errors, []); + }); + + test(`${engine} ${lang} ${width}px: every Settings option pressed through a redraw clicks its new self once`, async (t) => { + const posted = []; + // the warm-up and check-in tabs, two Codex accounts' own warm-up + // times, a card beside the tray icon and the local network's address + // shown, so their controls are drawn. Not here: Gateway mode (a + // browser's page only) and the Omarchy bar icon (Omarchy only). + const st = { workbuddy: true, trae: true, minimax: true, qoder: true, codexUsers: ["a@example.test", "b@example.test"], + checkinPlugins: [{ id: "one", name: "One", on: false }, { id: "two", name: "Two", on: true }], + trayUsages: ["codex|a@example.test"], lan: true, lanURLs: ["http://192.168.1.2:3999"] }; + const { page, errors } = await open(engine, lang, width, "general", posted, st, t); + // each click on an option is noted and stopped there, so no pick is + // saved and the page stays as it is from one control to the next + // a control is known by its place, as segs() knows it: the nearest + // element with an id, and which of the same options it is there + await page.evaluate(() => { + window.placeOf = (box) => { + const home = box.parentElement.closest("[id]"), kind = box.dataset.kind; + return kind + "@" + home.id + ":" + [...home.querySelectorAll(".segs")].filter((x) => x.dataset.kind === kind).indexOf(box); + }; + window.optClicks = []; + document.addEventListener("click", (e) => { + const b = e.target.closest?.(".segs > .opt"); + if (!b) return; + e.stopPropagation(); + optClicks.push({ place: placeOf(b.parentElement), i: [...b.parentElement.querySelectorAll(":scope > .opt")].indexOf(b), live: b.isConnected }); + }, true); + }); + const done = new Set(), missed = []; + const sweep = async (tab) => { + const boxes = page.locator(`#setPage-${tab} .segs`); + for (let k = 0; k < await boxes.count(); k++) { + const box = boxes.nth(k); + if (!await box.isVisible()) continue; + const place = await box.evaluate((x) => placeOf(x)); + if (done.has(place)) continue; + done.add(place); + const opts = box.locator(":scope > .opt"); + const now = await opts.evaluateAll((os) => os.findIndex((o) => o.classList.contains("on"))); + const i = (now + 1) % await opts.count(); + await page.mouse.move(...mid(await reveal(page, opts.nth(i)))); + await page.evaluate(() => { optClicks.length = 0; }); + await page.mouse.down(); + const swapped = await box.evaluate((x) => { renderSettings(); return !x.isConnected; }); + if (!swapped) { await page.mouse.up(); missed.push(place); continue; } + await page.mouse.up(); + await settle(page); + assert.deepEqual(await page.evaluate(() => optClicks), [{ place, i, live: true }], `${tab}: ${place} option ${i}`); + } + }; + for (const tab of ["general", "usage", "network", "models", "privacy", "otel", "sync", "about"]) { + await page.evaluate((tab) => document.querySelector("#setTab-" + tab).click(), tab); + await page.locator(`#setPage-${tab}`).waitFor(); + await settle(page); + if (tab === "usage") { + for (const id of ["codex", "claude", "wb", "trae", "minimax", "qoder", "plugins"]) { + await page.locator("#warmTab-" + id).click(); + await sweep(tab); + } + } else if (tab === "sync") { + // its form opened, for the kind of server it syncs to + await page.locator("#syncList .row.pref").first().locator(".val button").nth(1).click(); + await page.locator("#syncList .sync-form .segs").waitFor(); + await sweep(tab); + } else await sweep(tab); + } + assert.deepEqual(missed, [], "controls the redraw left in place"); + // Theme, Language, Text size, … each warm-up's and check-in's, Proxy, the local network's, Privacy's, OTel's, Sync's, About's + assert(done.size >= 49, `only ${done.size} controls: ${[...done].join(", ")}`); + assert.deepEqual(posted, [], "a stopped click saved something"); + assert.deepEqual(errors, []); + }); + } + } + + // The same, for a list of rows drawn again by what was saved (Library's + // way each agent gets its skills): a row gone or come in above the one + // pressed, or the rows moved, puts another row's control under the + // pointer at the same place, and that one is not clicked: nothing is, as + // before. The rows known by their data-* and the rows that aren't alike. + test(`${engine}: a press on a list's option picks nothing when the list is drawn again with its rows changed`, async (t) => { + const { page, errors } = await open(engine, "en", 900, "general", [], {}, t); + await page.evaluate(() => { + window.picks = []; + const host = document.createElement("div"); + host.id = "segsRows"; + host.style.cssText = "position: fixed; left: 20px; top: 80px; z-index: 999; padding: 8px; background: var(--card)"; + document.body.append(host); + window.drawRows = (names, keyed) => host.replaceChildren(...names.map((n) => { + const row = document.createElement("div"); + if (keyed) row.dataset.agent = n; + row.append(n, segs([["", "Library's way"], ["link", "Links"], ["copy", "Copies"]], "", (v) => picks.push(n + ":" + v))); + return row; + })); + }); + // Y's Copies pressed, the rows drawn again as `after`, let go on the same spot + const press = async (keyed, after) => { + await page.evaluate((keyed) => { picks.length = 0; drawRows(["X", "Y", "Z"], keyed); }, keyed); + await settle(page); + await page.mouse.move(...mid(await page.locator("#segsRows > div").nth(1).locator(".opt").nth(2).boundingBox())); + await page.mouse.down(); + await page.evaluate(([keyed, after]) => drawRows(after, keyed), [keyed, after]); + await page.mouse.up(); + await settle(page); + return page.evaluate(() => picks); + }; + for (const keyed of [true, false]) { + assert.deepEqual(await press(keyed, ["X", "Y", "Z"]), ["Y:copy"], `${keyed ? "keyed" : "plain"} rows drawn again the same`); + assert.deepEqual(await press(keyed, ["Y", "Z"]), [], `${keyed ? "keyed" : "plain"} rows, X gone: Z is where Y was`); + assert.deepEqual(await press(keyed, ["W", "X", "Y", "Z"]), [], `${keyed ? "keyed" : "plain"} rows, W come in: X is where Y was`); + } + assert.deepEqual(await press(true, ["X", "Z", "Y"]), [], "keyed rows moved: Z is where Y was"); + assert.deepEqual(errors, []); + }); +} diff --git a/internal/gui/tests/tray-usage-redraw.test.cjs b/internal/gui/tests/tray-usage-redraw.test.cjs new file mode 100644 index 000000000..16e4e39c4 --- /dev/null +++ b/internal/gui/tests/tray-usage-redraw.test.cjs @@ -0,0 +1,93 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// Settings → Allowances in the menu bar, clicked before the allowances are +// in, with Settings drawn again while they load (another setting saved, +// coming back to the window): the menu comes up at the redrawn pill, not in +// the window's corner, and what it saves keeps the setting changed meanwhile. +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 quotas = [ + { provider: "claude", name: "Claude Code", icon: "claude-color", user: "a@b.c", plan: "Max", windows: [{ name: "5-hour", used: 42 }] }, + { provider: "copilot", name: "Copilot", icon: "githubcopilot", windows: [{ name: "Premium", used: 63 }] }, +]; + +function server(posts) { + let cur = { + theme: "light", lang: "en", tray: "panel", quotaLeft: false, currency: "usd", + trayUsage: "", trayUsages: [], trayUsageEvery: 3, vision: "", imageGen: "", + version: "0.1.400", dir: "~/.config/magpie", gateway: "http://127.0.0.1:3425", + proxy: "", proxyNow: "none", proxySource: "none", login: false, redactWords: [], + visionModels: [], imageGenModels: [], workbuddyCheckins: [], lanURLs: [], + fx: { rate: 7.2, at: new Date().toISOString(), stale: false }, + }; + return async (route) => { + const req = route.request(), url = new URL(req.url()); + const json = (data) => route.fulfill({ json: data }); + if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"en",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({ agents: [], profiles: [], settings: { lang: "en", theme: "light" }, fx: cur.fx }); + if (url.pathname === "/api/settings") { + if (req.method() === "POST") { + const body = req.postDataJSON(); + posts.push(body); + cur = { ...cur, ...body, trayUsage: (body.trayUsages || [])[0] || "" }; + } + return json(cur); + } + if (url.pathname === "/api/usage/quotas") { + await new Promise((r) => setTimeout(r, 800)); // a vendor slow to answer + return json(quotas); + } + if (url.pathname === "/api/groups") return json({ groups: [], models: [] }); + 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 }); + }; +} + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + for (const width of [900, 560]) { + test(`${engine} ${width}px: the menu bar's allowances, picked while Settings is drawn again`, 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: 700 }, reducedMotion: "reduce" })).newPage(); + page.setDefaultTimeout(6000); + const errors = [], posts = []; + page.on("pageerror", (e) => errors.push(e.message)); + await page.route("**/*", server(posts)); + // from Agents: the Usage page would have read the allowances already + await page.goto("http://magpie.test/?view=agents"); + await page.locator("#prefs").click(); + await page.locator("#setTab-usage").click(); + const pill = page.locator("#trayUsagePick button"); + await pill.waitFor(); + assert.equal(await page.evaluate(() => quotas), null, "the allowances were read before the click"); + const menu = page.locator(".proto-menu"); + + // the allowances aren't in: the pill waits on them while CNY is saved + await pill.click(); + await page.locator("#currencySegs button", { hasText: "CNY" }).click(); + await page.waitForFunction(() => document.querySelector("#currencySegs .on")?.textContent.includes("CNY")); + await menu.waitFor({ timeout: 3000 }); + assert.equal(await pill.evaluate((b) => b.classList.contains("open")), true, "the redrawn pill isn't marked open"); + assert.equal(await pill.evaluate((b) => b.classList.contains("busy")), false, "the pill still waits"); + const b = await pill.boundingBox(), m = await menu.boundingBox(); + const up = await menu.evaluate((e) => e.classList.contains("up")); + const gap = up ? b.y - (m.y + m.height) : m.y - (b.y + b.height); + assert(Math.abs(gap - 5) <= 2, `the menu is ${gap}px from its pill, at ${m.x},${m.y}`); + + // ticked and closed: saved with CNY kept + await menu.locator(".pm-item", { hasText: "Copilot" }).click(); + await page.keyboard.press("Escape"); + await menu.waitFor({ state: "detached" }); + await page.waitForFunction(() => document.querySelector("#trayUsagePick button")?.textContent.trim() === "Copilot"); + assert.deepEqual(posts.map((p) => [p.currency, p.trayUsages]), [["cny", []], ["cny", ["copilot"]]]); + assert.deepEqual(errors, []); + }); + } +}