gui: a segmented control's thumb glides once, one way, and no other thumb moves when a save redraws the page

Settings' Off/On (Lightweight mode in the report) shook back and forth when
clicked, and the first click on the page replayed every thumb's animation.

Why, in the old slide():
- Every save's answer runs renderSettings(), which draws a new control and
  a new thumb for each one. The new thumb took its place from what was
  remembered: within 300ms of the click it started from the position
  before the click, so a redraw mid-glide sent the thumb back to Off and
  slid it again.
- Settings is drawn while hidden (at start, or from another tab), so every
  control was remembered 0 wide. thumbsUnderPicks put the DOM right when
  the tab was shown but never the memory, so the first save's redraw grew
  every thumb on the page in from the left.

#1211 (700315dff) only kept a press made across a redraw (pointerdown on
one button, pointerup on its replacement); it never touched how the thumb
moves across a redraw, which is why the shake stayed.

Now:
- A redrawn control takes over the old thumb element itself, with its
  running animation, so a glide in flight just goes on. No clock math.
- slide() glides only when the target changes, from where the thumb is
  drawn now (computed transform), with a WAAPI animation; the CSS
  transform/width transition is gone so nothing else starts one.
- One shared ResizeObserver puts a thumb under its option, without motion,
  when its control is shown or resized. A control drawn hidden is never
  measured. thumbsUnderPicks and the two per-bar ResizeObservers go.

Run:
- segs-glide.test.cjs (new): records every thumb on General per frame and
  between frames, for an answer mid-glide, an answer at once with two more
  redraws on the way, and a refused save; Chromium and WebKit, en zh zh-TW
  ja de, 900 and 440px. 80/80 over two runs; on the old code 20/20 fail
  (thumb jumps back to 0).
- Full GUI suite, concurrency 6: 6157 tests, 10 fail. Each fails the same
  alone on origin/main 96de5cac2 (library-mcp-tool-switch #1609,
  privacy-hides-accounts and usage-stale-answer #1632) or passes alone on
  both (purpose-filter, routing-signin, filed in #1632). tencent-cloud's
  WebKit flake also happens on the old code (#1620).
- Checked by hand against a sandbox magpie web (real server, sandbox
  HOME): the clicked thumb moves one way, no other thumb moves, including
  Settings opened from Usage first.
- gofmt, go vet (darwin, linux nogui, windows), go test ./internal/gui.

Not tried: the Wails app itself, Windows and Linux webviews.
This commit is contained in:
yetone
2026-10-11 23:04:12 +08:00
parent f156d90460
commit b0e25696eb
4 changed files with 280 additions and 60 deletions
+1 -1
View File
@@ -2480,7 +2480,7 @@ body.window .ag-sk-icon { width: 22px; height: 22px; border-radius: 6px; }
.thumb {
position: absolute; top: 2px; bottom: 2px; left: 0; width: 0; border-radius: 6px;
background: var(--card); box-shadow: 0 1px 2px rgba(0, 0, 0, .12), 0 0 0 .5px rgba(0, 0, 0, .06);
transition: transform .28s var(--ease), width .28s var(--ease), opacity .15s;
transition: opacity .15s; /* the glide is slide()'s, which only it starts */
pointer-events: none;
}
.segs .thumb { border-radius: 5px; }
+84 -59
View File
@@ -8155,7 +8155,23 @@ $("#modal").onclick = (e) => { if (modalBackdrop(e)) cancelEdit(); };
// ---------- sliding thumb ----------
// Pills (the nav, every segmented control) have one thumb that glides to the
// selected option instead of each option lighting up on its own.
const thumbs = new Map(); // control position → where a re-rendered thumb resumes its slide
//
// A thumb glides only when the option picked changes, and only from where
// it is on the screen. Most controls are drawn again on every save (all of
// Settings is), and a redrawn control takes the thumb of the one it
// replaces, the glide under way with it: the same element, so nothing about
// its motion is worked out again. It glides on to the option picked if that
// is another (a save refused puts one back), and otherwise is left as it
// is. A thumb is placed only where the control is laid out: one drawn
// hidden (Settings at start, a tab not shown) is put under its option,
// still, when it is shown or sized again (thumbFit). Before, a redrawn
// control made a new thumb and replayed what was remembered of the old
// one's glide from its start (a click's thumb jumped back and slid again),
// and positions taken while Settings was hidden, 0 wide, made every thumb
// on the page grow in from the left on the first save.
const thumbs = new Map(); // control position → { th, pick, to }: its thumb, the option it is under or going to, and where that is
const THUMB_MS = 280, THUMB_EASE = "cubic-bezier(.2, .8, .2, 1)"; // --ease
const thumbKeys = new WeakMap(); // box → its key, for thumbFit
function thumbKey(box, choices) {
const path = [];
for (let node = box; node?.parentElement; node = node.parentElement) {
@@ -8164,31 +8180,78 @@ function thumbKey(box, choices) {
}
return null;
}
function slide(box, key) {
let th = box.querySelector(":scope > .thumb");
const fresh = !th;
if (fresh) { th = el("span", "thumb"); box.prepend(th); }
const on = box.querySelector(":scope > .on");
if (!on) { th.style.opacity = "0"; return; }
th.style.opacity = "";
// where the thumb goes under the option picked; null while it isn't laid out
function thumbTo(box, on) {
if (!on.offsetParent || !on.offsetWidth) return null;
const to = { x: on.offsetLeft, w: on.offsetWidth };
// a strip that wraps (the editor's Base URL APIs, narrow): the row of
// the one picked (top: 2px is the first's), and that row's height, not
// the strip's
if (box.clientHeight > on.offsetHeight + 8) Object.assign(to, { y: on.offsetTop - 2, h: on.offsetHeight });
return to;
}
const thumbAt = (p) => ({ transform: p.y ? `translate(${p.x}px, ${p.y}px)` : `translateX(${p.x}px)`, width: p.w + "px" });
const thumbGlide = (th) => th.getAnimations().find((a) => a.id === "thumb" && a.playState === "running");
// a thumb put at p at once, any glide of it stopped
function thumbPut(th, p) {
for (const a of th.getAnimations()) if (a.id === "thumb") a.cancel();
th.classList.add("still");
Object.assign(th.style, thumbAt(p), { height: p.h ? p.h + "px" : "" });
void th.offsetWidth;
th.classList.remove("still");
}
// where a thumb in the page is drawn now, partway through a glide included
function thumbNow(th) {
if (!th.style.width || !th.isConnected) return null;
const cs = getComputedStyle(th), m = new DOMMatrixReadOnly(cs.transform === "none" ? undefined : cs.transform);
return { x: m.m41, y: m.m42, w: parseFloat(cs.width), h: th.style.height ? parseFloat(cs.height) : 0 };
}
// which option is picked: its place among the options
const thumbPick = (box, on) => [...box.children].filter((c) => !c.classList.contains("thumb")).indexOf(on);
const thumbSame = (a, b) => Math.abs(a.x - b.x) < 0.5 && Math.abs((a.y || 0) - (b.y || 0)) < 0.5 && Math.abs(a.w - b.w) < 0.5;
// a control shown, or sized again (the fonts come in, the language changes,
// the window narrows): its thumb is put under its option, still
const thumbFit = new ResizeObserver((es) => {
for (const { target: box } of es) {
if (!box.isConnected) { thumbFit.unobserve(box); continue; }
const th = box.querySelector(":scope > .thumb"), on = box.querySelector(":scope > .on");
const to = th && on && thumbTo(box, on);
if (!to) continue;
const control = thumbKey(box, thumbKeys.get(box));
const last = control && thumbs.get(control);
const pick = thumbPick(box, on);
if (last?.th === th && last.pick === pick && thumbSame(last.to, to) && th.style.width) continue;
thumbPut(th, to);
if (control) thumbs.set(control, { th, pick, to });
}
});
function slide(box, key) {
const control = thumbKey(box, key);
const last = control && thumbs.get(control);
let from = to;
const put = (p) => { th.style.transform = p.y ? `translate(${p.x}px, ${p.y}px)` : `translateX(${p.x}px)`; th.style.width = p.w + "px"; th.style.height = p.h ? p.h + "px" : ""; };
if (fresh) {
from = last ? (performance.now() - last.at < 300 ? last.from : last) : to;
th.classList.add("still");
put(from);
void th.offsetWidth;
th.classList.remove("still");
} else if (last) from = { x: last.x, w: last.w, y: last.y, h: last.h };
put(to);
if (control) thumbs.set(control, { ...to, from, at: performance.now() });
let th = box.querySelector(":scope > .thumb");
if (!th) {
// drawn again: the thumb of the control it replaces, glide and all
th = last?.th && !last.th.isConnected ? last.th : el("span", "thumb");
box.prepend(th);
}
thumbKeys.set(box, key);
thumbFit.observe(box);
const on = box.querySelector(":scope > .on");
if (!on) { th.style.opacity = "0"; return; }
th.style.opacity = "";
const to = thumbTo(box, on);
if (!to) return; // hidden: thumbFit puts it once it is shown
const pick = thumbPick(box, on);
if (control) thumbs.set(control, { th, pick, to });
// already there, or on its way there
if (last?.th === th && thumbSame(last.to, to) && (thumbGlide(th) || (th.style.width && thumbSame(thumbNow(th), to)))) return;
const from = thumbNow(th);
thumbPut(th, to);
if (!from || thumbSame(from, to)) return;
// the height is the strip's unless it wraps: only a wrapped one's glides
const f = thumbAt(from), t = thumbAt(to);
if (from.h && to.h) { f.height = from.h + "px"; t.height = to.h + "px"; }
th.animate([f, t], { duration: THUMB_MS, easing: THUMB_EASE, id: "thumb" });
}
const PROTOS = [["chat", "OpenAI", "Chat Completions — most agents"], ["responses", "Responses", "OpenAI Responses — what Codex speaks"], ["anthropic", "Anthropic", "Anthropic Messages — what Claude Code speaks"], ["gemini", "Gemini", "Gemini generateContent — what the Gemini CLI speaks"], ["decide", "System One", "A decision API on System One (TypeSafe's Jev, a gateway's, or Bailian's decision model) — what a routing group asks as a turn begins"]];
@@ -14957,20 +15020,9 @@ if (mode === "panel") {
// Allowances picked is the reader opening them (#1588)
b.onclick = () => { setPanelTab(b.dataset.ptab); if (panelTab === "usage") quotasOpened(); };
}
// the bar drawn before the panel has its width: slide's thumbFit puts
// the card again, still, once it has one
setPanelTab(panelTab);
// the bar drawn before the panel has its width puts the card again, still;
// the panel's height moving (a tab's own, a row opening) leaves it gliding
let width = 0;
new ResizeObserver(([e]) => {
const w = Math.round(e.contentRect.width);
if (w === width) return;
width = w;
const th = tabs.querySelector(":scope > .thumb");
th?.classList.add("still");
slide(tabs, "ptabs");
void th?.offsetWidth;
th?.classList.remove("still");
}).observe(tabs);
}
// The panel's Usage tab: what the requests of a period add up to — four
@@ -19465,20 +19517,6 @@ function setWarmTab(tab, remember) {
b.setAttribute("aria-selected", String(on));
b.tabIndex = on ? 0 : -1;
$("#" + list).hidden = !on;
if (on) thumbsUnderPicks($("#" + list));
}
}
// a pill drawn while its card was hidden measured nothing: its thumb is
// put under the option picked, still, once the card is shown
function thumbsUnderPicks(box) {
for (const th of box.querySelectorAll(".segs > .thumb")) {
const opt = th.parentElement.querySelector(":scope > .on");
if (!opt || !opt.offsetParent || parseFloat(th.style.width) === opt.offsetWidth) continue;
th.classList.add("still");
th.style.transform = `translateX(${opt.offsetLeft}px)`;
th.style.width = opt.offsetWidth + "px";
void th.offsetWidth;
th.classList.remove("still");
}
}
// A tab list's keys: the arrows, Home and End move along its shown tabs,
@@ -19541,7 +19579,6 @@ function setSetTab(tab, remember) {
b.setAttribute("aria-selected", String(on));
b.tabIndex = on ? 0 : -1;
$("#setPage-" + id).hidden = !on;
if (on) thumbsUnderPicks($("#setPage-" + id));
}
setShown = tab;
$("#setTabs").setAttribute("aria-label", t("Settings"));
@@ -19615,7 +19652,6 @@ function findSettings() {
}
page.dataset.part = tab.textContent;
page.hidden = !hits;
if (hits) thumbsUnderPicks(page);
any ||= hits > 0;
}
const none = $("#setNone");
@@ -22558,17 +22594,6 @@ function fitTop() {
}
const topFit = new ResizeObserver(fitTop);
for (const e of [".top", ".brand", ".actions"]) topFit.observe($(e));
// the nav's tabs change size after its thumb was put under one — the header
// tightening, the fonts arriving, another language — so it's put there again
if (mode === "window") new ResizeObserver(() => {
const th = $("#nav > .thumb"), on = $("#nav > .on");
if (!th || !on) return;
th.classList.add("still");
th.style.transform = `translateX(${on.offsetLeft}px)`;
th.style.width = on.offsetWidth + "px";
thumbs.set(thumbKey($("#nav"), "nav"), { x: on.offsetLeft, w: on.offsetWidth });
requestAnimationFrame(() => th.classList.remove("still"));
}).observe($("#nav"));
document.fonts?.ready.then(fitTop);
document.addEventListener("visibilitychange", () => { if (!document.hidden) { load(true); wag(); } });
+16
View File
@@ -765,6 +765,22 @@ wide:
node --test internal/gui/tests/segs-press-redraw.test.cjs
```
`segs-glide.test.cjs` records every thumb on Settings → General frame by
frame while Lightweight mode is clicked. General is opened from another tab
first (drawn while hidden): every thumb is under its option. A save whose
answer comes back mid-glide, one answered at once, and one with the page
drawn twice more on the way each move the clicked thumb one way only, never
back, and end under the option, while every other thumb on the page doesn't
move at all; a refused save glides it back to Off. The click doesn't scroll
the page. Before the fix the redraw restarted the glide from Off and every
thumb on the page grew in from the left on the first save. Chromium and
WebKit, en, zh, zh-TW, ja and de, 900 and 440px wide (`THROTTLE=4` slows
Chromium's CPU):
```sh
node --test internal/gui/tests/segs-glide.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
+179
View File
@@ -0,0 +1,179 @@
// Run with Node's test runner and Playwright on the module path; see README.md.
// A segmented control's thumb glides once, from where it is, to the option
// picked, and no other thumb on the page moves. Every save's answer draws
// Settings again, a new thumb for every control, and a new thumb took its
// place from what was remembered: a redraw mid-glide started the glide over
// (Lightweight mode's thumb went most of the way to On, jumped back to Off
// and slid again), and Settings drawn while hidden (opened on another tab,
// or at start) was remembered 0 wide, so the first save grew every thumb on
// the page in from the left. Checked frame by frame: General shown from
// another tab has every thumb under its option; a click whose save comes
// back mid-glide, one whose save comes back at once, and one redrawn twice
// on the way all move the thumb one way only and end under the option, with
// every other thumb still; a refused save glides it back. Chromium and
// WebKit, en, zh, zh-TW, ja and de, 900 and 440px, 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");
function serve(lang, st, ctl) {
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 === "/api/settings" && r.request().method() === "POST") {
await new Promise((ok) => setTimeout(ok, ctl.hold));
if (ctl.refuse) return json({ error: "refused" }, 500);
Object.assign(st, JSON.parse(r.request().postData()));
return json(settings());
}
if (url.pathname.startsWith("/api/settings")) 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([]);
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 });
};
}
// every thumb on General: where it is drawn, and where its option is
const THUMBS = `[...document.querySelectorAll("#setPage-general .segs")].filter((s) => s.offsetParent).map((s) => {
const th = s.querySelector(":scope > .thumb"), on = s.querySelector(":scope > .on"), b = s.getBoundingClientRect();
const r = th?.getBoundingClientRect(), o = on?.getBoundingClientRect();
return { id: s.parentElement.id || s.dataset.kind, x: r ? r.left - b.left : -1, w: r ? r.width : -1, ox: o ? o.left - b.left : -1, ow: o ? o.width : -1 };
})`;
// records every thumb on General at each frame, and between them
async function record(page) {
await page.evaluate((src) => {
const read = new Function("return " + src);
window.frames_ = [];
window.recording = true;
const tick = () => { window.frames_.push(read()); if (window.recording) requestAnimationFrame(tick); };
requestAnimationFrame(tick);
window.between = setInterval(() => window.frames_.push(read()), 4);
}, THUMBS);
}
async function stop(page) {
return page.evaluate(() => { window.recording = false; clearInterval(window.between); return window.frames_; });
}
// one control's thumb moved one way only, from its start to its end, and
// every other control's thumb didn't move at all
function oneWay(frames, id, label) {
const xs = frames.map((f) => f.find((c) => c.id === id)).filter(Boolean);
assert.ok(xs.length > 3, label + ": frames recorded");
const up = xs[xs.length - 1].x >= xs[0].x;
for (let i = 1; i < xs.length; i++) {
const d = xs[i].x - xs[i - 1].x;
assert.ok(up ? d > -0.75 : d < 0.75, `${label}: ${id}'s thumb went back from ${xs[i - 1].x.toFixed(1)} to ${xs[i].x.toFixed(1)} (${xs.map((p) => p.x.toFixed(0)).join(" ")})`);
assert.ok(xs[i].w > 4, `${label}: ${id}'s thumb ${xs[i].w.toFixed(1)} wide`);
}
for (const c of frames[0]) {
if (c.id === id) continue;
for (const f of frames) {
const n = f.find((x) => x.id === c.id);
if (!n) continue;
assert.ok(Math.abs(n.x - c.x) < 0.75 && Math.abs(n.w - c.w) < 0.75, `${label}: ${c.id}'s thumb moved (${c.x.toFixed(1)}/${c.w.toFixed(1)} → ${n.x.toFixed(1)}/${n.w.toFixed(1)}) when ${id} was clicked`);
}
}
}
// every shown thumb under its option once it has come to rest
async function underPicks(page, label) {
await page.waitForTimeout(400);
for (const c of await page.evaluate((src) => new Function("return " + src)(), THUMBS)) {
assert.ok(Math.abs(c.x - c.ox) < 1 && Math.abs(c.w - c.ow) < 1, `${label}: ${c.id}'s thumb at ${c.x.toFixed(1)}/${c.w.toFixed(1)}, its option at ${c.ox.toFixed(1)}/${c.ow.toFixed(1)}`);
}
}
// 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)), [b.x + b.width / 2, b.y + b.height / 2])) return;
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");
}
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 [900, 440]) {
test(`${engine} ${lang} ${width}px: a thumb glides once, one way, and no other thumb moves`, 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: 1000 } })).newPage();
page.setDefaultTimeout(5000);
if (process.env.THROTTLE && engine === "chromium") await (await page.context().newCDPSession(page)).send("Emulation.setCPUThrottlingRate", { rate: +process.env.THROTTLE });
const errors = [];
// WebKit's notice of a ResizeObserver loop is no error of the page's
page.on("pageerror", (e) => { if (!/ResizeObserver loop/.test(e.message)) errors.push(e.message); });
const st = {}, ctl = { hold: 0, refuse: false };
await page.route("**/*", serve(lang, st, ctl));
// opened on another tab: General is drawn while hidden
await page.goto("http://magpie.test/?view=settings&tab=about");
await page.locator("#setTab-general").waitFor();
await page.waitForTimeout(300);
await page.locator("#setTab-general").click();
await page.locator("#lightweightSegs .opt").first().waitFor();
await underPicks(page, "General shown from another tab");
const opt = (i) => page.locator("#lightweightSegs .opt").nth(i);
const scroll = () => page.evaluate(() => document.querySelector("#view-settings").scrollTop);
await reveal(page, opt(1));
await page.waitForTimeout(300);
const top = await scroll();
// the save's answer comes back mid-glide, and draws the page again
ctl.hold = 120;
await record(page);
await opt(1).click();
await page.waitForTimeout(700);
oneWay(await stop(page), "lightweightSegs", "answer mid-glide");
assert.equal(st.lightweight, true);
await underPicks(page, "after On");
// the answer at once, then the page drawn twice more on the way
ctl.hold = 0;
await record(page);
await opt(0).click();
await page.waitForTimeout(60);
await page.evaluate(() => renderSettings());
await page.waitForTimeout(60);
await page.evaluate(() => renderSettings());
await page.waitForTimeout(600);
oneWay(await stop(page), "lightweightSegs", "drawn again on the way");
assert.equal(st.lightweight, false);
await underPicks(page, "after Off");
// a refused save puts Off back: the thumb glides back to it
ctl.refuse = true;
ctl.hold = 300;
await record(page);
await opt(1).click();
await page.waitForTimeout(1000);
const frames = await stop(page);
const lw = frames.map((f) => f.find((c) => c.id === "lightweightSegs")).filter(Boolean);
assert.ok(lw.some((p) => p.x > lw[0].x + 8), "it went towards On first");
await underPicks(page, "a refused save");
assert.equal(await opt(0).evaluate((b) => b.classList.contains("on")), true, "Off is back");
assert.equal(await scroll(), top, "a click never moves the page");
assert.deepEqual(errors, []);
});
}
}
}