gui: the Agents list's footer has Manage, to hide or unhide many agents at once (#1302, eryajf)

Users who use a few agents had to hide the others one row menu at a time,
and disconnecting doesn't help: most are unconnected already. The Agents
list's footer now has Manage beside the fold control (shown even when
nothing is folded). Its dialog lists every agent, folded and hidden ones
too, with search by name or id, select or invert the search results,
select the unconnected ones, and clear. Hide selected / Unhide selected
save one arrangement each through the existing POST /api/agents/arrange,
keeping the order and every agent outside the selection; a failed save
keeps the selection for a retry. While it saves, Done, Escape and the
backdrop can't close it, and a state read that left before the save can't
put the old arrangement back (agentsVisibilityRevision). Nothing connects,
disconnects or edits an agent's files; the tray panel is unchanged.
Strings in en, zh, zh-TW, ja and de. docs/subsystems/gui-shell.md says
how it works. mobile-web's desktop comparison leaves the new footer out
while the baseline hasn't it.

Squashed from PR head 2a24d59e onto main, without the PR's unrelated
parts: the plugins.js search redraw and its plugin-market test change,
the purpose-filter and redact-rule-row test workarounds (main fixed those
flakes at their cause), and a .warm-at input min-width. Conflicts: load()
keeps main's reads with the PR's revision guard, i18n.js and app.css keep
both sides, the gui-shell doc keeps main's window-corners note.

Run (both engines; every agent* test, gui-de/ja/zh-tw, i18n-keys,
mobile-web, panel-fold, library-mcp-tools, click-scroll): 516 pass. Two
webkit zh-TW agent-failover failures were ENOSPC launching the browser
and pass on a rerun. mobile-web's 1280 comparison and a narrow-width
measure in agent-bulk-visibility needed fixes, in the next two commits.
Broken by hand: without closeConfirmAsk's saving guard, "saving blocks
Escape and backdrop" fails (success and failure); without the
visibilitySince block in load(), "an older state read cannot undo a
completed bulk save" fails.
Not tried: the real app with real agents.
This commit is contained in:
eryajf
2026-10-13 10:41:51 +08:00
committed by yetone
parent a069f224c0
commit 88f237e91b
9 changed files with 578 additions and 7 deletions
+30
View File
@@ -257,6 +257,11 @@ dirty group draft; Cancel retains the draft and Discard opens the new editor.
`newGroupWith` applies the same guard when creating a group from a model and
waits for `show` to accept navigation before creating its draft.
The Plugins page updates the npm search-results section when a search answers,
leaving suggested plugin cards in place so a click begun before the answer still
opens the intended plugin. `plugin-market.test.cjs` holds the search response
between pointerdown and pointerup to check this in Chromium and WebKit.
## Verification
The session readers include Cursor CLI chat stores, Cursor editor project
@@ -302,3 +307,28 @@ Apple silicon), they check a program that names its SDK in
`LC_VERSION_MIN_MACOSX`, as go test links one for an Intel Mac. Their
presses are sent within the test's own process, and no system setting
changes.
### Agent visibility management
The Agents page's Manage button sits inside the list's footer beside the fold
control, and stays available when nothing is folded. The tray panel keeps its
existing fold control. The Manage agents dialog includes folded and hidden agents.
Search matches names and IDs; select all and invert apply to the search results,
while Select unconnected agents replaces the selection with matching agents not
on magpie (neither wired, added nor drifting). Selection survives search changes.
Hide selected and Unhide selected each save one arrangement through the existing
`POST /api/agents/arrange`, preserving order and agents outside the operation.
Only a successful save changes the list; a failure keeps the selection for retry.
While saving, Done, Escape and the backdrop cannot close the manager and expose
conflicting row actions. Closing is restored on either success or failure.
A completed save invalidates older in-flight state reads for the arrangement
fields only. Fresh reads still accept other windows' visibility changes; bulk
unhide does not add a lasting client-side override. These races are covered by
`agent-visibility-saving.test.cjs`.
While the manager is open, state refreshes update its visibility labels and
action availability in place, preserving the search, selection and keyboard focus.
These operations never connect, disconnect or edit an agent's files. Unhiding
still follows the existing Not set up folding rules. The dialog explains that
restoring visibility does not pin an unconfigured agent into the main list.
See `agent-bulk-visibility.test.cjs` for persistence, partial selection, failed
saves, narrow layouts and all five languages in Chromium and WebKit.
+21
View File
@@ -3825,5 +3825,26 @@ input[type="checkbox"]:focus-visible { outline: 2px solid var(--accent); outline
input[type="checkbox"]:disabled { opacity: .45; }
.editor .pair .side .key-count { white-space: nowrap; font-size: 11.5px; font-variant-numeric: tabular-nums; }
/* Agent visibility manager: selection stays separate from connection controls. */
.ag-manage-bar { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, auto) minmax(max-content, 1fr); align-items: center; gap: 6px; padding: 3px 8px; border-top: 1px solid var(--line-2); }
.ag-manage-bar > .agent-more { grid-column: 2; min-width: 0; border: 0; border-radius: 6px; padding: 6px; }
.ag-manage-bar > .agent-more > span:first-child { display: block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.ag-manage-bar .chev { flex: none; }
.ag-manage-button { grid-column: 3; justify-self: end; display: inline-flex; align-items: center; gap: 5px; padding: 6px 8px; border: 0; border-radius: 6px; background: none; color: var(--muted); font: inherit; font-size: 12px; white-space: nowrap; transition: color .2s, background-color .2s; }
.ag-manage-button:hover { color: var(--fg); background: var(--card-2); }
.ag-manage-button:focus-visible { color: var(--fg); background: var(--card-2); outline: 2px solid var(--accent); outline-offset: -2px; }
.ag-manage-button:disabled { opacity: .45; }
.ag-manager .ag-manage-search { width: 100%; box-sizing: border-box; }
.ag-manage-actions { display: flex; flex-wrap: wrap; gap: 6px; margin: 12px 0; }
.ag-manage-count, .ag-manage-state { color: var(--fg-2); font-size: 12px; }
.ag-manage-row { display: flex; align-items: center; gap: 10px; padding: 10px 0; }
.ag-manage-row > input { flex: none; }
.ag-manage-row > .ic { width: 22px; height: 22px; flex: none; }
.ag-manage-name { flex: 1; min-width: 0; overflow-wrap: anywhere; }
.ag-manage-state { flex: none; }
.ag-manager > .bar { flex-wrap: wrap; }
.ag-manage-result { font-size: 13px; overflow-wrap: anywhere; }
.modal .editor.ag-manager > .ebody { grid-template-columns: minmax(0, 1fr); grid-auto-rows: max-content; }
/* a disabled model's pattern, as typed (#1867): an id or a glob */
.disabled-model .name { font-family: var(--code); font-size: 12px; overflow-wrap: anywhere; }
+144 -1
View File
@@ -685,6 +685,8 @@ function renderAgents() {
list.append(more, fold);
}
agentsManageButton(list);
confirmAsk?.refreshAgents?.();
paintUpdateAll();
paintInstalls();
renderProfiles();
@@ -2464,6 +2466,140 @@ async function saveArrangement(order, hidden, shown) {
}
}
// Bulk visibility changes only magpie's arrangement, never agent configs.
let agentsVisibilitySaving = false;
// Ignore state reads begun before a completed visibility write. A fresh read
// still owns the truth, including changes made by the tray or another window.
let agentsVisibilityRevision = 0;
function agentsManageButton(list) {
if (mode === "panel" || !state.agents.length) return;
let bar = $("#agentsManage");
if (!bar) {
bar = el("div", "ag-manage-bar");
bar.id = "agentsManage";
const more = list.querySelector(":scope > .agent-more");
if (more) { more.before(bar); bar.append(more); }
else list.append(bar);
const button = el("button", "ag-manage-button");
button.type = "button";
button.append(svg("M2 3.5h2M6 3.5h8M2 8h2M6 8h8M2 12.5h2M6 12.5h8", 14, 1.5), el("span", "", t("Manage")));
button.setAttribute("aria-label", t("Manage agents"));
button.title = t("Manage agents");
button.onclick = openAgentsManager;
bar.append(button);
}
bar.querySelector(".ag-manage-button").disabled = agentsVisibilitySaving;
}
function openAgentsManager() {
if (agentsVisibilitySaving) return;
const selected = new Set();
const ed = el("div", "editor ag-manager");
const head = el("div", "ehead");
head.append(el("b", "", t("Manage agents")));
const note = el("p", "lib-confirm", t("Hiding only changes this list, not an agent's connection or settings. Unhidden agents may stay under Not set up."));
const search = el("input", "words ag-manage-search");
search.type = "search";
search.placeholder = t("Search agents…");
search.setAttribute("aria-label", t("Search agents…"));
const actions = el("div", "ag-manage-actions");
const rows = el("div", "ag-manage-rows");
const count = el("span", "ag-manage-count");
const result = el("p", "ag-manage-result");
result.setAttribute("role", "status");
const bar = el("div", "bar");
const button = (label, run, parent = actions) => {
const b = el("button", "text", t(label));
b.type = "button";
b.onclick = run;
parent.append(b);
return b;
};
const matching = () => arrangeAgents().all.filter((a) =>
(a.name + " " + a.id).toLocaleLowerCase().includes(search.value.trim().toLocaleLowerCase()));
button("Select search results", () => { matching().forEach((a) => selected.add(a.id)); draw(); });
button("Invert search selection", () => { matching().forEach((a) => selected.has(a.id) ? selected.delete(a.id) : selected.add(a.id)); draw(); });
button("Select unconnected agents", () => {
selected.clear();
matching().filter((a) => !onMagpie(a)).forEach((a) => selected.add(a.id));
draw();
});
button("Clear selection", () => { selected.clear(); draw(); });
const hide = button("Hide selected", () => save(true), bar);
const show = button("Unhide selected", () => save(false), bar);
bar.append(el("span", "grow"));
button("Done", () => closeConfirmAsk(), bar);
const controls = () => {
ed.querySelectorAll("button, input").forEach((b) => { b.disabled = agentsVisibilitySaving; });
hide.disabled ||= ![...selected].some((id) => !hiddenIds().includes(id));
show.disabled ||= ![...selected].some((id) => hiddenIds().includes(id));
count.textContent = t(selected.size === 1 ? "{n} agent selected" : "{n} agents selected", { n: selected.size });
};
// Update status in place: a state refresh must keep search, selection and
// keyboard focus on the control the reader is using.
ed.refreshAgents = () => {
const hidden = new Set(hiddenIds());
for (const row of rows.querySelectorAll(".ag-manage-row")) {
row.querySelector(".ag-manage-state").textContent = t(hidden.has(row.dataset.id) ? "Hidden" : "Not hidden");
}
controls();
};
function draw() {
rows.replaceChildren();
for (const a of matching()) {
const row = el("label", "ag-manage-row");
row.dataset.id = a.id;
const check = el("input");
check.type = "checkbox";
check.checked = selected.has(a.id);
check.setAttribute("aria-label", a.name);
check.onchange = () => { check.checked ? selected.add(a.id) : selected.delete(a.id); controls(); };
row.append(check, icon(a.icon), el("span", "ag-manage-name", a.name), el("span", "ag-manage-state", t(isHidden(a) ? "Hidden" : "Not hidden")));
rows.append(row);
}
if (!rows.children.length) rows.append(el("p", "lib-confirm", t("No matching agents")));
controls();
}
async function save(hidden) {
if (agentsVisibilitySaving) return;
const ids = [...selected].filter((id) => hiddenIds().includes(id) !== hidden);
if (!ids.length) return;
const next = new Set(hiddenIds());
ids.forEach((id) => hidden ? next.add(id) : next.delete(id));
agentsVisibilitySaving = true;
controls();
result.textContent = "";
agentsManageButton($("#agents"));
try {
// Commit once, then publish only the arrangement returned by the server.
// A failed save leaves both the visible list and selection unchanged.
const s = await api("agents/arrange", {
order: state.settings?.agentOrder || [], hidden: [...next], shown: state.settings?.agentsShown || [],
});
if (hidden) ids.forEach((id) => unhid.delete(id));
agentsVisibilityRevision++;
state.settings = { ...state.settings, agentOrder: s.agentOrder || [], agentsHidden: s.agentsHidden || [], agentsShown: s.agentsShown || [] };
selected.clear();
result.textContent = hidden
? t(ids.length === 1 ? "{n} agent hidden" : "{n} agents hidden", { n: ids.length })
: t(ids.length === 1 ? "{n} agent unhidden" : "{n} agents unhidden", { n: ids.length });
renderAgents();
} catch (e) {
result.textContent = e.message;
} finally {
agentsVisibilitySaving = false;
agentsManageButton($("#agents"));
draw();
}
}
search.oninput = draw;
ed.append(head, note, search, actions, count, rows, result, bar);
draw();
confirmAsk = ed;
openModal(ed);
$("#modal").classList.add("lib");
}
// moveAgent puts the agent at index `to` among the rows in view; the folded
// ones keep their places after them.
function moveAgent(id, to) {
@@ -3637,7 +3773,7 @@ async function load(again) {
if (view === "providers" && !providers) renderProvidersLoading();
if (view === "gateway" && !providers) renderGatewayLoading();
try {
const since = prefsWrites, hid = hiddenIds().join();
const since = prefsWrites, hid = hiddenIds().join(), visibilitySince = agentsVisibilityRevision;
const asked = api("state");
// the first load draws the state magpie kept from its last read while
// the fresh one is read (#1519, fatkun): reading every agent's config,
@@ -3663,6 +3799,10 @@ async function load(again) {
// a setting changed while this was on its way (it can take seconds):
// what came back is from before it, and would put the old theme back
if (!prefsSettled(since) && load.done) next.settings = state.settings;
if (visibilitySince !== agentsVisibilityRevision) {
const { agentOrder, agentsHidden, agentsShown } = state.settings;
next.settings = { ...next.settings, agentOrder, agentsHidden, agentsShown };
}
state = next;
load.done = true;
// the library may have drawn itself before the saved language was known
@@ -16720,6 +16860,9 @@ function askReset(q) {
}
function closeConfirmAsk() {
if (!confirmAsk) return;
// Escape and the backdrop must not expose row actions while a bulk write
// still holds an older full arrangement. Done is disabled for the same reason.
if (agentsVisibilitySaving && confirmAsk.classList.contains("ag-manager")) return;
// one asked from an editor goes back to it rather than close it too
const back = confirmAsk.back;
confirmAsk = null;
+72
View File
@@ -4,6 +4,24 @@
// works. {name} slots are filled by t(str, vars).
const I18N = {
zh: {
"Manage": "管理",
"Manage agents": "批量管理",
"Hiding only changes this list, not an agent's connection or settings. Unhidden agents may stay under Not set up.": "隐藏只改变列表显示,不影响 Agent 的接入或设置。取消隐藏后,Agent 仍可能留在「未设置」中。",
"Search agents…": "搜索 Agent…",
"Select search results": "全选搜索结果",
"Invert search selection": "反选搜索结果",
"Select unconnected agents": "选择未接入项",
"Clear selection": "清空选择",
"Hide selected": "隐藏所选",
"Unhide selected": "取消隐藏所选",
"{n} agent selected": "已选择 {n} 个 Agent",
"{n} agents selected": "已选择 {n} 个 Agent",
"Not hidden": "未隐藏",
"No matching agents": "没有匹配的 Agent",
"{n} agent hidden": "已隐藏 {n} 个 Agent",
"{n} agents hidden": "已隐藏 {n} 个 Agent",
"{n} agent unhidden": "已取消隐藏 {n} 个 Agent",
"{n} agents unhidden": "已取消隐藏 {n} 个 Agent",
"Get started": "快速上手",
"{n} of {m} done": "已完成 {n}/{m}",
"Hide Get started": "隐藏快速上手",
@@ -4567,6 +4585,24 @@ const I18N = {
"zh-TW": {
"Codex thread descriptions": "Codex 對話描述",
"Description": "描述",
"Manage": "管理",
"Manage agents": "批次管理",
"Hiding only changes this list, not an agent's connection or settings. Unhidden agents may stay under Not set up.": "隱藏只改變清單顯示,不影響 Agent 的連線或設定。取消隱藏後,Agent 仍可能留在「未設定」中。",
"Search agents…": "搜尋 Agent…",
"Select search results": "全選搜尋結果",
"Invert search selection": "反選搜尋結果",
"Select unconnected agents": "選取未連線項目",
"Clear selection": "清除選取",
"Hide selected": "隱藏所選項目",
"Unhide selected": "取消隱藏所選項目",
"{n} agent selected": "已選取 {n} 個 Agent",
"{n} agents selected": "已選取 {n} 個 Agent",
"Not hidden": "未隱藏",
"No matching agents": "沒有符合的 Agent",
"{n} agent hidden": "已隱藏 {n} 個 Agent",
"{n} agents hidden": "已隱藏 {n} 個 Agent",
"{n} agent unhidden": "已取消隱藏 {n} 個 Agent",
"{n} agents unhidden": "已取消隱藏 {n} 個 Agent",
"Get started": "快速上手",
"{n} of {m} done": "已完成 {n}/{m}",
"Hide Get started": "隱藏快速上手",
@@ -9109,6 +9145,24 @@ const I18N = {
"~/.dsh/settings.yaml sets its own DeepSeek endpoint or key, which dsh puts over magpie's; clear it in dsh's Models page to go through magpie.": "~/.dsh/settings.yaml 設定了自己的 DeepSeek 位址或 Key,dsh 會優先用它而不是 magpie 的;請在 dsh 的 Models 頁面清除它,才能走 magpie。",
},
ja: {
"Manage": "管理",
"Manage agents": "エージェントを一括管理",
"Hiding only changes this list, not an agent's connection or settings. Unhidden agents may stay under Not set up.": "非表示は一覧の表示のみを変更し、エージェントの接続や設定には影響しません。非表示を解除しても「未設定」に残る場合があります。",
"Search agents…": "エージェントを検索…",
"Select search results": "検索結果をすべて選択",
"Invert search selection": "検索結果の選択を反転",
"Select unconnected agents": "未接続のエージェントを選択",
"Clear selection": "選択を解除",
"Hide selected": "選択項目を非表示",
"Unhide selected": "選択項目の非表示を解除",
"{n} agent selected": "{n} 個のエージェントを選択中",
"{n} agents selected": "{n} 個のエージェントを選択中",
"Not hidden": "表示中",
"No matching agents": "一致するエージェントはありません",
"{n} agent hidden": "{n} 個のエージェントを非表示にしました",
"{n} agents hidden": "{n} 個のエージェントを非表示にしました",
"{n} agent unhidden": "{n} 個のエージェントの非表示を解除しました",
"{n} agents unhidden": "{n} 個のエージェントの非表示を解除しました",
"Get started": "はじめに",
"{n} of {m} done": "{m} 件中 {n} 件完了",
"Hide Get started": "「はじめに」を隠す",
@@ -13655,6 +13709,24 @@ const I18N = {
"~/.dsh/settings.yaml sets its own DeepSeek endpoint or key, which dsh puts over magpie's; clear it in dsh's Models page to go through magpie.": "~/.dsh/settings.yaml に独自の DeepSeek エンドポイントやキーがあり、dsh は magpie のものよりそちらを優先します。magpie を経由するには dsh の Models ページで消してください。",
},
de: {
"Manage": "Verwalten",
"Manage agents": "Agents verwalten",
"Hiding only changes this list, not an agent's connection or settings. Unhidden agents may stay under Not set up.": "Ausblenden ändert nur die Liste, nicht die Verbindung oder Einstellungen eines Agents. Nach dem Einblenden können Agents unter „Nicht eingerichtet“ bleiben.",
"Search agents…": "Agents suchen…",
"Select search results": "Suchergebnisse auswählen",
"Invert search selection": "Auswahl der Suchergebnisse umkehren",
"Select unconnected agents": "Nicht verbundene Agents auswählen",
"Clear selection": "Auswahl aufheben",
"Hide selected": "Auswahl ausblenden",
"Unhide selected": "Auswahl einblenden",
"{n} agent selected": "{n} Agent ausgewählt",
"{n} agents selected": "{n} Agents ausgewählt",
"Not hidden": "Nicht ausgeblendet",
"No matching agents": "Keine passenden Agents",
"{n} agent hidden": "{n} Agent ausgeblendet",
"{n} agents hidden": "{n} Agents ausgeblendet",
"{n} agent unhidden": "{n} Agent eingeblendet",
"{n} agents unhidden": "{n} Agents eingeblendet",
"Get started": "Erste Schritte",
"{n} of {m} done": "{n} von {m} erledigt",
"Hide Get started": "Erste Schritte ausblenden",
@@ -0,0 +1,137 @@
// Visibility changes use one arrangement write and never touch agent configs.
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 = process.env.MAGPIE_AGENT_ASSETS || path.resolve(__dirname, '../assets');
const names = {
en: ['Manage agents', 'Hide selected', 'Unhide selected', 'Select search results', 'Invert search selection', 'Select unconnected agents', 'Clear selection'],
zh: ['批量管理', '隐藏所选', '取消隐藏所选', '全选搜索结果', '反选搜索结果', '选择未接入项', '清空选择'],
'zh-TW': ['批次管理', '隱藏所選項目', '取消隱藏所選項目', '全選搜尋結果', '反選搜尋結果', '選取未連線項目', '清除選取'],
ja: ['エージェントを一括管理', '選択項目を非表示', '選択項目の非表示を解除', '検索結果をすべて選択', '検索結果の選択を反転', '未接続のエージェントを選択', '選択を解除'],
de: ['Agents verwalten', 'Auswahl ausblenden', 'Auswahl einblenden', 'Suchergebnisse auswählen', 'Auswahl der Suchergebnisse umkehren', 'Nicht verbundene Agents auswählen', 'Auswahl aufheben'],
};
for (const engine of process.env.BROWSER ? [process.env.BROWSER] : ['chromium', 'webkit']) {
for (const lang of Object.keys(names)) {
test(`${engine} ${lang}: bulk visibility, retry and persistence`, async (t) => {
const browser = await (engine === 'webkit' ? webkit.launch() : chromium.launch({ channel: 'chromium' }));
t.after(() => browser.close());
const page = await browser.newPage({ viewport: { width: lang === 'en' ? 1240 : 560, height: 760 }, reducedMotion: 'reduce' });
page.setDefaultTimeout(5000);
const agent = (id, wired = false) => ({ id, name: id, icon: 'generic', wired, fields: [{ key: 'model', label: 'model', value: wired ? 'relay/m1' : '', options: [{ value: 'relay/m1', label: 'm1', ref: 'relay/m1' }] }] });
const theme = lang === 'de' ? 'dark' : 'light';
const state = { agents: [agent('Codex', true), agent('Pi'), agent('Zed'), agent('Hidden')], profiles: [], settings: { lang, theme, agentOrder: ['Zed', 'Codex', 'Pi', 'Hidden'], agentsHidden: ['Hidden'] } };
const posts = [], errors = [];
let reject = false;
page.on('pageerror', (e) => errors.push(e.message));
await page.route('**/*', async (route) => {
const req = route.request(), url = new URL(req.url());
const json = (data) => route.fulfill({ json: data });
if (req.method() === 'POST') posts.push([url.pathname, req.postDataJSON()]);
if (url.pathname === '/boot.js') return route.fulfill({ contentType: 'text/javascript', body: `window.bootPrefs = ${JSON.stringify({lang, theme, 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/agents/arrange') {
if (reject) return route.fulfill({ status: 500, json: { error: 'Save refused' } });
await new Promise((r) => setTimeout(r, 80));
const b = req.postDataJSON();
Object.assign(state.settings, { agentOrder: b.order, agentsHidden: b.hidden, agentsShown: b.shown });
return json(state.settings);
}
if (url.pathname === '/api/plugins') return json({ plugins: [] });
if (url.pathname === '/api/usage/quotas') return json([]);
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: [], presets: [], gateway: { running: true } });
if (url.pathname.startsWith('/api/')) return json({});
const file = path.join(assets, url.pathname === '/' ? 'index.html' : url.pathname);
try { return await route.fulfill({ body: await fs.readFile(file), contentType: {'.js':'text/javascript','.css':'text/css','.html':'text/html','.svg':'image/svg+xml'}[path.extname(file)] }); }
catch { return route.fulfill({ status: 404, body: '' }); }
});
await page.goto('http://magpie.test/');
const [manage, hide, show, all, invert, unconnected, clear] = names[lang];
const footer = page.locator('#agents > .ag-manage-bar');
await footer.waitFor();
assert.equal(await page.locator('#view-agents > .ag-manage-bar').count(), 0, 'no separate toolbar above the list');
assert.equal(await footer.locator('.agent-more').count(), 1, 'fold and manage share the footer');
for (const width of [1240, 360]) {
await page.setViewportSize({width, height:760});
const boxes = await footer.evaluate((f) => {
const more = f.querySelector('.agent-more').getBoundingClientRect(), manage = f.querySelector('.ag-manage-button').getBoundingClientRect();
return {right:more.right, left:manage.left, bottom:more.bottom, top:manage.top, overflow:f.scrollWidth > f.clientWidth};
});
assert(boxes.right <= boxes.left, 'footer controls do not overlap');
assert(boxes.bottom > boxes.top, 'footer controls share a row');
assert.equal(boxes.overflow, false);
}
await page.setViewportSize({width:lang === 'en' ? 1240 : 560, height:760});
if (process.env.FOOTER_SHOT && lang === 'zh') await page.screenshot({path:process.env.FOOTER_SHOT});
await page.getByRole('button', { name: manage, exact: true }).click();
const dialog = page.getByRole('dialog'), search = dialog.locator('input[type=search]');
const button = (name) => dialog.getByRole('button', { name, exact: true });
assert.equal(await dialog.getByRole('checkbox').count(), 4, 'hidden and folded agents are manageable');
assert(await button(hide).isDisabled());
await search.fill('not-an-agent');
assert.equal(await dialog.getByRole('checkbox').count(), 0);
await search.fill('Pi');
await button(all).click();
await button(invert).click();
assert.equal(await dialog.locator('input:checked').count(), 0);
await button(all).click();
await search.fill('');
assert.equal(await dialog.locator('input:checked').count(), 1, 'search preserves selection');
await button(clear).click();
await button(unconnected).click();
assert.equal(await dialog.locator('input:checked').count(), 3);
assert.equal(await dialog.getByRole('checkbox', {name:'Codex',exact:true}).isChecked(), false);
reject = true;
await button(hide).click();
await page.waitForFunction(() => document.querySelector('.ag-manage-result')?.textContent === 'Save refused');
assert.deepEqual(state.settings.agentsHidden, ['Hidden']);
assert.equal(await dialog.locator('input:checked').count(), 3, 'failed save keeps selection');
reject = false;
await button(hide).click();
await page.waitForFunction(() => document.querySelector('.ag-manage-result')?.textContent.includes('2'));
assert.deepEqual(new Set(state.settings.agentsHidden), new Set(['Hidden', 'Pi', 'Zed']));
assert.deepEqual(state.settings.agentOrder, ['Zed', 'Codex', 'Pi', 'Hidden']);
assert.equal(posts.length, 2, 'one write per attempt');
assert(posts.every(([url]) => url === '/api/agents/arrange'), 'no agent connection writes');
await page.reload();
await page.getByRole('button', {name:manage,exact:true}).click();
await dialog.getByRole('checkbox', {name:'Pi',exact:true}).check();
await dialog.getByRole('checkbox', {name:'Zed',exact:true}).check();
assert(await button(hide).isDisabled(), 'saved hidden state survives reload');
await button(show).click();
await page.waitForFunction(() => document.querySelector('.ag-manage-result')?.textContent.includes('2'));
assert.deepEqual(state.settings.agentsHidden, ['Hidden']);
assert.equal(state.agents[0].wired, true);
assert.equal(await dialog.locator('input:checked').count(), 0);
assert(await dialog.evaluate((d) => d.scrollWidth <= d.clientWidth), 'narrow dialog does not overflow');
// Hiding every agent keeps the manager available; connected agents stay wired.
await button(all).click();
await button(hide).click();
await page.waitForFunction(() => document.querySelector('.ag-manage-result')?.textContent.includes('3'));
assert.equal(state.settings.agentsHidden.length, 4);
assert.equal(state.agents[0].wired, true);
await page.keyboard.press('Escape');
await page.locator('#modal[hidden]').waitFor({ state: 'attached' });
await page.getByRole('button', {name:manage,exact:true}).click();
await button(all).click();
await button(show).click();
await page.waitForFunction(() => document.querySelector('.ag-manage-result')?.textContent.includes('4'));
assert.deepEqual(state.settings.agentsHidden, []);
assert.equal(posts.length, 5);
if (process.env.BULK_SHOT && lang === 'zh') {
await dialog.evaluate(async (d) => { await Promise.all(d.parentElement.getAnimations({subtree:true}).map((a) => a.finished.catch(() => {}))); });
await page.screenshot({path:process.env.BULK_SHOT});
}
state.agents.forEach((a) => { a.wired = true; });
await page.reload();
await page.getByRole('button', {name:manage,exact:true}).waitFor();
assert.equal(await footer.locator('.agent-more').count(), 0, 'no fold control when every agent is shown');
assert.equal(await footer.locator('.ag-manage-button').count(), 1, 'management remains available without folded agents');
assert.deepEqual(errors, []);
});
}
}
+1 -1
View File
@@ -125,7 +125,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
// the fold says something is hidden; opened, its Show is there with
// the pointer away, and brings the row back
const more = page.locator("#agents > .agent-more");
const more = page.locator("#agents .agent-more");
assert.match(await more.textContent(), /1/);
await more.click();
await page.mouse.move(1, 1);
@@ -0,0 +1,141 @@
// Deferred responses exercise close paths and state reads across a visibility save.
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 deferred = () => { let resolve; const promise = new Promise((r) => { resolve = r; }); return {promise, resolve}; };
async function fixture(t, engine) {
const browser = await (engine === 'webkit' ? webkit.launch() : chromium.launch({channel:'chromium'}));
t.after(() => browser.close());
const page = await browser.newPage({viewport:{width:1000,height:800}, reducedMotion:'reduce'});
page.setDefaultTimeout(5000);
const agent = (id, wired = false) => ({id, name:id, icon:'generic', wired, fields:[{key:'model',label:'model',value:wired ? 'relay/m1' : '',options:[{value:'relay/m1',label:'m1',ref:'relay/m1'}]}]});
const f = {page, state:{agents:[agent('Main',true),agent('Pi'),agent('Zed')],profiles:[],settings:{lang:'en',theme:'light',agentsHidden:['Pi']}}, posts:[], save:null, read:null};
await page.route('**/*', 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:true};'});
if (url.pathname === '/wails/runtime.js') return route.fulfill({contentType:'text/javascript',body:'export const Window = {};'});
if (url.pathname === '/api/state') {
const snapshot = JSON.parse(JSON.stringify(f.state));
const gate = f.read; f.read = null;
if (gate) { gate.started.resolve(); await gate.release.promise; }
return json(snapshot);
}
if (url.pathname === '/api/agents/arrange') {
const b = req.postDataJSON(); f.posts.push(b);
const gate = f.save; f.save = null;
if (gate) { gate.started.resolve(); await gate.release.promise; }
if (gate?.fail) return route.fulfill({status:500,json:{error:'Save refused'}});
Object.assign(f.state.settings,{agentOrder:b.order,agentsHidden:b.hidden,agentsShown:b.shown});
return json(f.state.settings);
}
if (url.pathname === '/api/plugins') return json({plugins:[]});
if (url.pathname === '/api/groups') return json({groups:[]});
if (url.pathname === '/api/usage/quotas') return json([]);
if (url.pathname === '/api/agents/cli') return json({agents:{},pending:false});
if (url.pathname === '/api/providers') return json({providers:[],presets:[],gateway:{running:true}});
if (url.pathname.startsWith('/api/')) return json({});
const file = url.pathname === '/app.js' && process.env.AGENT_VISIBILITY_APP
? process.env.AGENT_VISIBILITY_APP : path.join(assets,url.pathname === '/' ? 'index.html' : url.pathname);
try { return await route.fulfill({body:await fs.readFile(file),contentType:{'.js':'text/javascript','.css':'text/css','.html':'text/html','.svg':'image/svg+xml'}[path.extname(file)]}); }
catch { return route.fulfill({status:404,body:''}); }
});
await page.goto('http://magpie.test/');
await page.getByRole('button',{name:'Manage agents',exact:true}).click();
return f;
}
const gate = () => ({started:deferred(),release:deferred()});
const close = async (page) => { await page.keyboard.press('Escape'); await page.locator('#modal[hidden]').waitFor({state:'attached'}); };
for (const engine of process.env.BROWSER ? [process.env.BROWSER] : ['chromium','webkit']) {
test(`${engine}: visibility counts use singular for one agent`, async (t) => {
const {page:p} = await fixture(t,engine);
const count = p.locator('.ag-manage-count');
assert.equal(await count.textContent(),'0 agents selected');
await p.getByRole('checkbox',{name:'Pi',exact:true}).check();
assert.equal(await count.textContent(),'1 agent selected');
await p.getByRole('button',{name:'Unhide selected',exact:true}).click();
await p.waitForFunction(() => document.querySelector('.ag-manage-result')?.textContent === '1 agent unhidden');
await p.getByRole('checkbox',{name:'Pi',exact:true}).check();
await p.getByRole('button',{name:'Hide selected',exact:true}).click();
await p.waitForFunction(() => document.querySelector('.ag-manage-result')?.textContent === '1 agent hidden');
await p.getByRole('checkbox',{name:'Pi',exact:true}).check();
await p.getByRole('checkbox',{name:'Zed',exact:true}).check();
assert.equal(await count.textContent(),'2 agents selected');
});
test(`${engine}: an open manager refreshes visibility without losing selection or focus`, async (t) => {
const f = await fixture(t,engine), p = f.page;
const search = p.locator('.ag-manage-search');
await search.fill('Pi');
const check = p.getByRole('checkbox',{name:'Pi',exact:true});
await check.check();
await check.focus();
const label = p.locator('.ag-manage-row[data-id="Pi"] .ag-manage-state');
assert.equal(await label.textContent(),'Hidden');
for (const hidden of [false,true]) {
f.state.settings.agentsHidden = hidden ? ['Pi'] : [];
await p.evaluate(() => load());
assert.equal(await label.textContent(),hidden ? 'Hidden' : 'Not hidden');
assert(await check.isChecked(),'refresh keeps the selection');
assert(await check.evaluate((c) => c === document.activeElement),'refresh keeps keyboard focus');
assert.equal(await search.inputValue(),'Pi','refresh keeps the search');
assert.equal(await p.getByRole('button',{name:'Hide selected',exact:true}).isDisabled(),hidden);
assert.equal(await p.getByRole('button',{name:'Unhide selected',exact:true}).isDisabled(),!hidden);
}
assert.equal(f.posts.length,0,'refresh never saves the arrangement');
});
for (const fail of [false,true]) test(`${engine}: saving blocks Escape and backdrop, then releases on ${fail ? 'failure' : 'success'}`,async (t) => {
const f = await fixture(t,engine), p = f.page;
const pending = f.save = {...gate(),fail};
t.after(() => pending.release.resolve());
await p.getByRole('checkbox',{name:'Zed',exact:true}).check();
await p.getByRole('button',{name:'Hide selected',exact:true}).click();
await pending.started.promise;
await p.keyboard.press('Escape');
assert.equal(await p.locator('#modal').evaluate((m) => m.hidden || m.classList.contains('out')),false,'Escape must not dismiss an in-flight save');
await p.locator('#modal').click({position:{x:2,y:2}});
assert.equal(await p.locator('#modal').evaluate((m) => m.hidden || m.classList.contains('out')),false,'backdrop must not dismiss an in-flight save');
assert(await p.getByRole('button',{name:'Done',exact:true}).isDisabled());
assert.equal(f.posts.length,1);
pending.release.resolve();
await p.waitForFunction(() => !document.querySelector('.ag-manage-button').disabled);
if (fail) {
assert.equal(await p.locator('.ag-manage-result').textContent(),'Save refused');
assert(await p.getByRole('checkbox',{name:'Zed',exact:true}).isChecked());
assert.deepEqual(f.state.settings.agentsHidden,['Pi']);
} else assert.deepEqual(new Set(f.state.settings.agentsHidden),new Set(['Pi','Zed']));
await close(p);
});
test(`${engine}: a later hide from another window is accepted after bulk unhide`,async(t) => {
const f = await fixture(t,engine), p=f.page;
await p.getByRole('checkbox',{name:'Pi',exact:true}).check();
await p.getByRole('button',{name:'Unhide selected',exact:true}).click();
await p.waitForFunction(() => document.querySelector('.ag-manage-result')?.textContent === '1 agent unhidden');
await close(p);
f.state.settings.agentsHidden=['Pi'];
await p.evaluate(() => load()); // the same state refresh used when the window regains focus
await p.getByRole('button',{name:'Manage agents',exact:true}).click();
assert.equal(await p.locator('.ag-manage-row[data-id="Pi"] .ag-manage-state').textContent(),'Hidden');
await p.getByRole('checkbox',{name:'Zed',exact:true}).check();
await p.getByRole('button',{name:'Hide selected',exact:true}).click();
await p.waitForFunction(() => document.querySelector('.ag-manage-result')?.textContent === '1 agent hidden');
assert.deepEqual(new Set(f.state.settings.agentsHidden),new Set(['Pi','Zed']),'next save preserves the other window’s hide');
});
test(`${engine}: an older state read cannot undo a completed bulk save`,async(t) => {
const f=await fixture(t,engine),p=f.page;
const pending=f.read=gate();
t.after(() => pending.release.resolve());
await p.evaluate(() => { window.visibilityRead = load(); });
await pending.started.promise;
await p.getByRole('checkbox',{name:'Pi',exact:true}).check();
await p.getByRole('button',{name:'Unhide selected',exact:true}).click();
await p.waitForFunction(() => document.querySelector('.ag-manage-result')?.textContent === '1 agent unhidden');
pending.release.resolve();
await p.evaluate(() => window.visibilityRead);
await close(p);
await p.getByRole('button',{name:'Manage agents',exact:true}).click();
assert.equal(await p.locator('.ag-manage-row[data-id="Pi"] .ag-manage-state').textContent(),'Not hidden');
});
}
+30 -3
View File
@@ -2,8 +2,11 @@
// Phone navigation and content stay usable in both languages (#391). The
// desktop screenshots match BASE_REF within a small rendering tolerance
// (origin/main by default), but for the Agents page while BASE_REF hasn't its
// 「接入」 rows yet; only API boundaries are faked, never the page's layout or
// scrolling helpers.
// 「接入」 rows yet. Until BASE_REF has the visibility manager, its new footer
// alone is excluded; agent-bulk-visibility and agent-grip cover that footer's
// layout and controls. Its height is rounded only for the pixel comparison,
// so unchanged text below keeps the baseline's subpixel antialiasing. API
// boundaries are faked; the page's scrolling helpers are left intact.
const assert = require("node:assert/strict");
const fs = require("node:fs/promises");
const path = require("node:path");
@@ -312,6 +315,22 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
await current.mouse.move(0, 0); await original.mouse.move(0, 0);
// Removing hover can repaint the tab's shadow in a later frame.
await current.waitForTimeout(350); await original.waitForTimeout(350);
// The new management footer intentionally differs from main.
// Compare the rest at its new position: the footer also moves
// Profiles down. Compare the footer too once main contains it.
// Do not skip the Agents page or increase the pixel tolerance.
let addedFooter = view === "agents" && !baselineFile("app.js").includes("function agentsManageButton")
? await current.locator("#agentsManage").boundingBox() : null;
if (addedFooter) {
// A fractional new height changes text antialiasing below it,
// even after translating the screenshot back. Normalize only
// that new height; the footer's real layout is tested separately.
await current.locator("#agentsManage").evaluate((bar, height) => {
bar.style.boxSizing = "border-box";
bar.style.height = Math.ceil(height) + "px";
}, addedFooter.height);
addedFooter = await current.locator("#agentsManage").boundingBox();
}
const before = PNG.sync.read(await still(original));
const after = PNG.sync.read(await still(current));
const sameSize = before.width === after.width && before.height === after.height;
@@ -319,9 +338,17 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
// Chromium can repaint antialiased edges differently even when
// comparing HEAD with itself. Count a pixel once only when one
// of its channels changes by more than 48; size changes always fail.
const scale = before.width / width;
if (sameSize) for (let i = 0; i < before.data.length; i += 4) {
const row = Math.floor(i / 4 / before.width);
const shifted = addedFooter && row >= Math.floor(addedFooter.y * scale)
? Math.round(addedFooter.height * scale) : 0;
// Both images retain their real viewport size. The added
// footer pushes this last slice below the current viewport.
if (row + shifted >= after.height) continue;
const j = i + shifted * after.width * 4;
for (let channel = 0; channel < 4; channel++) {
if (Math.abs(before.data[i + channel] - after.data[i + channel]) > 48) {
if (Math.abs(before.data[i + channel] - after.data[j + channel]) > 48) {
changedPixels++;
break;
}
+2 -2
View File
@@ -67,7 +67,7 @@ async function stays(page, what, sel, watch = sel) {
// are in sight or the button is at the view's top.
async function unrolls(page, what) {
await page.evaluate(() => {
const more = document.querySelector(".agent-more"), above = more.previousElementSibling;
const more = document.querySelector(".agent-more"), above = (more.closest(".ag-manage-bar") || more).previousElementSibling;
window.frames = [];
window.ro?.disconnect();
window.ro = new ResizeObserver(() => {
@@ -76,7 +76,7 @@ async function unrolls(page, what) {
});
window.ro.observe(document.querySelector("#agents"));
});
const gap = await page.locator(".agent-more").evaluate((m) => m.getBoundingClientRect().top - m.previousElementSibling.getBoundingClientRect().top);
const gap = await page.locator(".agent-more").evaluate((m) => m.getBoundingClientRect().top - (m.closest(".ag-manage-bar") || m).previousElementSibling.getBoundingClientRect().top);
await page.locator(".agent-more").click();
await page.waitForTimeout(1200);
const frames = await page.evaluate(() => window.frames);