gui: Fetch models again leaves the provider's dialog where it was (indexyz)

Pressing Fetch models again (重新获取模型) in a provider's editor moved the
whole dialog down about 30px and left it there. The redraw that brings the
list back built the models' "Expand the list" fold shown and hid it a
requestAnimationFrame later, once the chips were measured. The dialog had
been pressed, so holdModal keeps the pressed button where it is, and it took
the button's place with the fold showing (30px lower) as the place to hold:
when the fold went, it moved the dialog down by the fold's height.

The fold now starts as it was last measured for that provider (foldNeeded)
and is measured in a microtask, after openModal has put the editor on the
page in the same task and before any frame is drawn; a redraw while the
editor is already on the page measures at once. A fold that really comes
or goes (the list grew or shrank past the box) still does, a frame sooner
than before.

Measured frame by frame, before and after, on mote (Chromium and WebKit,
900x820, 420x820, 1300x900; lists of 5 and 150, picked and unpicked, the
same list back, grown and shrunk): before, Chromium's dialog went 58 -> 89
and stayed, WebKit's button jumped 32px for a frame; after, nothing moves
more than the redraw's own 2px swap.

Run on mote (the new test and the budget again at this head, cb0c97cb4's tree):
- provider-fetch-holds.test.cjs (new): 12/12 ok, Chromium and WebKit, zh
  900 and 420, en 1300, a list with no fold and one with. Broken by hand
  (origin/main's app.js): 6 of 12 red, every no-fold case in both engines
  ("the dialog moved 31.4px (58,...,60,89,89,88,...)", "the button moved
  31.7px"); the fold cases stay green, which is what they guard.
- models-fold, provider-fetch-again, provider-picks-stay,
  provider-retrieval-only, azure-endpoint, modal-centred-late, modal-morph,
  i18n-keys, i18n-en-no-cjk, under lockf suite.lock: 89 of 109 ok. The 20
  red are red the same on origin/main's app.js, run the same way:
  provider-fetch-again (#5057, #5232), provider-picks-stay (#5233, #4397),
  models-fold webkit (#4071; webkit en and zh both red on main, zh only
  with this), i18n-keys "a plugin's words are its own" (#5332, #5426,
  #5482).
- go test -tags nogui ./internal/gui -run Budget: TestCoreScriptBudget ok
  (app.js 1,311,491 of 1,316,874; no raise).

Not tried: the real app's WebKit (Wails on macOS) or WebView2 by hand; the
whole GUI suite runs after the push. Not changed: at 420px the footer's
"vendor list · 1小时前" becoming "刚刚" rewraps the footer and the body's
scroll is clamped, which is the content changing, not this.

Reported-by: indexyz on Discord
This commit is contained in:
yetone
2026-11-07 17:42:46 +08:00
parent f13d5f16f4
commit e4fdf9ed3d
2 changed files with 137 additions and 4 deletions
+12 -4
View File
@@ -11141,6 +11141,8 @@ const servedIds = (p) => draft.chosen.length ? draft.chosen : draft.none || draf
// modelsOpen: models let out to full height (#833). MCHIPS_MAX: .mchips' max-height
let modelsOpen = false;
// whether a provider's chips were last tall enough to fold, by its id
const foldNeeded = {};
// unpickedShown: the editor showing unpicked models under Picked only (yyddbds)
let unpickedShown = null;
// picksLeft: picks set aside, given back when Picked only is clicked again (yyddbds)
@@ -11298,13 +11300,19 @@ function renderModels(p) {
fold.setAttribute("aria-expanded", modelsOpen);
foldLabel.textContent = t(modelsOpen ? "Collapse the list" : "Expand the list");
fold.title = t(modelsOpen ? "Hold the models to a few lines again" : "Show every model at once, not in a small box to scroll");
// laid out first: the editor is put on the page after it is drawn.
// Held, the box is MCHIPS_LINES tall (app.css .mchips); open, it is as
// tall as its chips, which must be more than that to fold
requestAnimationFrame(() => {
const measure = () => {
if (!chips.isConnected) return;
const most = Math.min(MCHIPS_MAX, innerHeight * 0.4);
fold.hidden = !(chips.scrollHeight > (modelsOpen ? most : chips.clientHeight) + 1);
});
fold.hidden = !(foldNeeded[p.id] = chips.scrollHeight > (modelsOpen ? most : chips.clientHeight) + 1);
};
// put on the page in this same task: measured there, till then as the
// last one was, or a redraw (Fetch models again, indexyz) showed the
// fold a frame and the dialog, holding the press, moved by it
fold.hidden = !foldNeeded[p.id];
if (chips.isConnected) measure();
else queueMicrotask(() => chips.isConnected ? measure() : requestAnimationFrame(measure));
};
const draw = () => {
if (agentMenu && chips.contains(agentMenu.anchor)) closeAgentMenu();
@@ -0,0 +1,125 @@
// Run with Node's test runner and Playwright on the module path; see README.md.
// Fetch models again leaves the provider's dialog where it was (indexyz on
// Discord: 打开供应商列表点重新获取模型整个 Modal 会往下移动). The redraw
// that brings the list back built the models' "Expand the list" fold shown
// and hid it a frame later, once measured; the dialog, holding the pressed
// button's place, took the frame with the fold as that place and moved down
// by its height when it went. Every frame from the press until the list is
// back is sampled: the dialog and the button stay put, and the fold is never
// shown or hidden for a frame, for a list short enough to need no fold and
// one long enough to need it. Chinese and English, Chromium and WebKit, wide
// and narrow, with motion on as the reporter has it.
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(process.env.MAGPIE_ASSETS || path.resolve(__dirname, "../assets"));
const fetched = new Date(Date.now() - 3600e3).toISOString();
const ids = (n) => Array.from({ length: n }, (_, i) => `relay-model-${i}`);
const relay = (models, on) => ({
id: "relay", name: "Some Relay", icon: "generic", host: "relay.example.com", chat: "https://relay.example.com/v1", responses: "", anthropic: "", catalog: "",
models: models.map((m) => ({ id: m, name: m, on: on.includes(m) })), chosen: on, fetched, agents: [], fallback: [], headers: {},
key: { set: true, masked: "sk-…aaa" }, keyList: [], balanceToken: { takes: false, set: false }, proxy: "",
});
function serve(lang, p, calls) {
const state = { agents: [], profiles: [], settings: { lang, theme: "light" } };
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:"${lang}",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") return json(state);
if (url.pathname === "/api/plugins") return json({ plugins: [] });
if (url.pathname === "/api/providers") return json({ providers: [p], presets: [], excluded: [], gateway: { running: true, window: true } });
if (url.pathname === "/api/groups") return json({ groups: [] });
if (url.pathname === "/api/provider/models") {
calls.push(req.postDataJSON());
// the vendor takes a moment, as a real one does; the same list comes back
await new Promise((r) => setTimeout(r, 300));
return json({ count: p.models.length, provider: p });
}
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 });
};
}
// a few picks: the chips fit, no fold; none picked out of 150: every chip, folded
const lists = { picked: relay(ids(6), ["relay-model-0", "relay-model-1"]), long: relay(ids(150), []) };
const sizes = { zh: [[900, 820], [420, 820]], en: [[1300, 900]] };
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
for (const [lang, views] of Object.entries(sizes)) {
for (const [width, height] of views) {
for (const [kind, p] of Object.entries(lists)) {
test(`${engine} ${lang} ${width}px ${kind}: Fetch models again leaves the dialog where it was`, async (t) => {
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
const page = await (await browser.newContext({ viewport: { width, height } })).newPage();
t.after(async () => {
if (process.env.ARTIFACT_DIR) {
await fs.mkdir(process.env.ARTIFACT_DIR, { recursive: true });
await page.screenshot({ path: path.join(process.env.ARTIFACT_DIR, `${engine}-${lang}-${width}-${kind}-provider-fetch-holds.png`) });
}
await browser.close();
});
page.setDefaultTimeout(5000);
page.setDefaultNavigationTimeout(60000);
const errors = [];
page.on("pageerror", (e) => errors.push(e.message));
const calls = [];
await page.route("**/*", serve(lang, p, calls));
await page.goto("http://magpie.test/?view=providers");
const again = await page.evaluate(([l, s]) => (l === "en" ? s : I18N[l][s]), [lang, "Fetch models again"]);
assert.ok(again, `Fetch models again has its ${lang}`);
await page.locator(".row.provider", { hasText: "Some Relay" }).click();
const editor = page.locator("#modal:not([hidden]) .editor");
await editor.locator(".mchips .mchip").first().waitFor();
const button = editor.locator(".mfoot").getByRole("button", { name: again, exact: true });
await button.scrollIntoViewIfNeeded();
// opened and settled: no animation left on the dialog
await page.waitForFunction(() => {
const d = document.querySelector("#modal").firstElementChild;
return !d.getAnimations({ subtree: true }).some((a) => a.playState === "running");
});
await page.waitForTimeout(300);
const fold = editor.locator(".mchips-fold");
assert.equal(await fold.isVisible(), kind === "long", "the fold is there only for a list that needs it");
// every frame from the press until a while after the list is back
await page.evaluate(() => {
const d = document.querySelector("#modal").firstElementChild;
window.frames_ = [];
const go = () => {
const b = d.querySelector(".mfoot .fetch-models"), f = d.querySelector(".mchips-fold");
window.frames_.push({ top: d.getBoundingClientRect().top, button: b?.getBoundingClientRect().top, fold: f ? !f.hidden : null });
if (!window.framesStop) requestAnimationFrame(go);
};
go();
d.querySelector(".mfoot .fetch-models").dataset.old = "";
});
const before = await page.evaluate(() => window.frames_[0]);
await button.click();
for (let i = 0; i < 100 && !calls.length; i++) await page.waitForTimeout(20);
assert.equal(calls.length, 1, "the list is asked for");
// the list is back: the editor drawn again, its button a new one
await editor.locator(".mfoot .fetch-models:not([data-old])").waitFor();
await page.waitForTimeout(800);
const frames = await page.evaluate(() => { window.framesStop = true; return window.frames_; });
assert.ok(frames.length > 10, "frames were sampled");
assert.ok(await button.isVisible(), "the button is still there");
// the redraw's own soft swap moves it 2px at most
const moved = (k) => Math.max(...frames.map((f) => Math.abs(f[k] - before[k])));
assert.ok(moved("top") <= 3, `the dialog moved ${moved("top").toFixed(1)}px (${frames.map((f) => Math.round(f.top)).join(",")})`);
assert.ok(moved("button") <= 3, `the button moved ${moved("button").toFixed(1)}px`);
assert.deepEqual([...new Set(frames.map((f) => f.fold))], [before.fold], "the fold never came or went for a frame");
assert.deepEqual(errors, []);
});
}
}
}
}