sessions: By tokens selects the small sessions, to delete them at once

A user asked for a way to delete every session under 10K or 20K tokens
(yansheng1003 on X). Selecting sessions on the Sessions page now has a
"By tokens" button beside Delete. It opens the app menu (openProtoMenu,
no native select) with 10K, 20K, 50K and 100K, each showing how many of
the sessions on screen it would select. A pick replaces the selection
with the deletable rows on screen (search and filters apply) that used
fewer tokens than that. Tokens are counted with sessTokens, the number
each row shows.

A session that is streaming now (speedOf().live) or was written in the
last minute is never picked. The server already refuses one written in
the last minute (sessions.Delete's ErrActive). Delete is the existing
path: each agent's own delete, gateway-only and forgotten sessions
handled as before, files moved to magpie's trash. The existing
confirmation names how many sessions go and that Trash puts them back.
When the selection is still the By tokens pick, it adds "Each used
fewer than 20K tokens". A selection changed by hand drops that line.

Only the Sessions plugin changes (client.js, i18n.js in en, zh, zh-TW,
ja and de, sessions.css). No server change.

New test: sessions-small-delete.test.cjs, in Chromium and WebKit, every
language, against a faked API. It covers the menu's head and counts,
the pick (running, live, read-only and larger sessions left out, cache
counted as the row counts it), a smaller size replacing the pick, a
search narrowing it, the dialog's size line, Cancel posting nothing,
Delete posting the 4 ids, a 420px bar, and no native select.

Run:
- At the pushed tree (on origin/main 31575f71a), mote: i18n-*, nav-timeout
  and sessions-small-delete: 19 of 19 pass.
- At this tree (c3e0a6bb5, on origin/main 31575f71a), mote, load ~40:
  - sessions-*, i18n-*, proto-menu-overflow, checkbox-look and
    library-sessions-mcp: 661 of 661 pass.
  - go test ./internal/gui -run
    'TestCoreScriptBudget|TestI18n|TestCSS|TestPlugin|TestAsset|TestBudget':
    ok.
- Before the rebase (on 7707ba9ad), mica: the new file 10 of 10, and
  the touched set 670 of 670.
- Whole GUI suite before the rebase (mote, --test-concurrency=4):
  the ssh session dropped about two-thirds through. 934 of 1586 files ran
  (to r*), 11193 ok and 397 not ok in 78 files, and no Sessions file was
  among them. Each red file ran again alone, at this change and at
  origin/main 32a181868, and the same tests failed on both:
  - 5 files: 68 of 82 red on both trees (#6709).
  - The 9 files not in #6709: 16 of 224 red on both trees, flaky WebKit
    subtests (#6807, #4784, #4071, #6038, #4210, #3951, #5109).
    provider-base-as-typed and provider-env-paste are #6038's class and
    were added to it.

Broken by hand, then put back: with the running and live exclusion
removed from smallOf, the chromium en case went red.

Not tried: the remaining 652 GUI files after the drop (both machines
were over their cores with other sessions' suites), and the real app
window with real sessions.
This commit is contained in:
yetone
2026-11-18 14:36:31 +08:00
parent 31575f71a1
commit 61c714ed01
4 changed files with 289 additions and 2 deletions
+42 -1
View File
@@ -45,6 +45,14 @@ magpie.plugin("sessions", (ctx) => {
let selecting = false;
let othersOpen = false; // the folders an app or the system made, unfolded
const picked = new Set(); // ids picked to delete, of the agent shown
// the sizes the bar's By tokens picks under, each session counted as its
// row shows it; smallPicked is the size last picked by, while the pick
// is still just those, so the dialog says it
const SMALL = [10e3, 20e3, 50e3, 100e3];
const small = (n) => fmtN(n).replace(/\.0(?=\D|$)/, "");
const smallOf = (list, n) => list.filter((s) => sessTokens(s) < n && !speedOf(s)?.live && Date.now() - Date.parse(s.last) >= 60e3);
let smallPicked = null;
const smallUnder = (ids) => smallPicked && ids.length === smallPicked.ids.size && ids.every((id) => smallPicked.ids.has(id)) ? smallPicked.n : 0;
const opened = new Set(); // folders unfolded, by cwd
const folderBoxes = new Map(); // each folder's box as drawn, by cwd
let openedFor = ""; // the agent the folders were first unfolded for
@@ -866,10 +874,40 @@ magpie.plugin("sessions", (ctx) => {
del.disabled = !picked.size;
del.append(svg(TRASH, 13, 1.4), el("span", "", t("Delete")));
del.onclick = () => askDelete([...picked], wholeFolder([...picked]));
bar.append(all, n, el("span", "grow"), del);
bar.append(all, n, el("span", "grow"), smallPick(list), del);
return bar;
}
// smallPick picks, of the sessions shown, every one that used fewer
// tokens than a size chosen from its menu, counted as each row shows
// them (yansheng1003 on X: 删除低于10k/20k的会话). One written to in the
// last minute, or streaming now, is not picked: its agent may be running
// it (and the delete would leave it anyway).
function smallPick(list) {
const b = el("button", "text sm-small");
b.type = "button";
b.setAttribute("aria-haspopup", "menu");
b.setAttribute("aria-expanded", "false");
b.append(el("span", "", t("By tokens")), svg(CHEV, 11, 1.6));
b.onclick = (e) => {
e.stopPropagation();
if (b.classList.contains("open")) return closeProtoMenu();
const opts = SMALL.map((n) => {
const k = smallOf(list, n).length;
return { v: String(n), name: t("{n} tokens", { n: small(n) }), note: t(k === 1 ? "{n} session" : "{n} sessions", { n: k }), literalName: true };
});
openProtoMenu(b, opts, "", (v) => {
const n = +v;
picked.clear();
for (const s of smallOf(list, n)) picked.add(s.id);
smallPicked = { n, ids: new Set(picked) };
redrawList();
page.querySelector(".sm-bar .sm-small")?.focus({ preventScroll: true });
}, "Select sessions under", "sm-small-menu", "right");
};
return b;
}
// wholeFolder: the folder (a cwd, "" for none) when ids are every
// session of that one folder, so the dialog names it
function wholeFolder(ids) {
@@ -1710,6 +1748,9 @@ magpie.plugin("sessions", (ctx) => {
: t("Delete {n} sessions?", { n: list.length })));
ed.append(h);
if (folder && folder !== GW && folder !== DRAFTS) ed.append(el("p", "sub sm-ask-path", folder));
// picked by size: the dialog says by which
const under = smallUnder(ids);
if (under) ed.append(el("p", "sm-ask-small", t("Each used fewer than {n} tokens", { n: small(under) })));
const names = el("ul", "sm-ask-list");
for (const s of list.slice(0, 5)) names.append(el("li", "", s.title || s.id));
if (list.length > 5) names.append(el("li", "more", t("+{n} more", { n: list.length - 5 })));
@@ -77,6 +77,9 @@ magpie.strings({
"Move sessions to {to}?": "把会话迁移到 {to}?",
"Deselect all": "取消全选",
"Invert selection": "反选",
"By tokens": "按 token 数",
"Select sessions under": "选中 token 数少于",
"Each used fewer than {n} tokens": "每个会话都少于 {n} token",
"Only the provider each one names is changed, in its files and in Codex's database: its messages, id, title and archive stay as they are. A copy of its files is kept in magpie's trash folder first, and Undo moves them back. A session written to in the last minute is left alone.": "只改每个会话在文件和 Codex 数据库里记录的供应商,消息、会话 ID、标题和归档状态都不变。改之前会先在 magpie 的回收站文件夹里备份一份文件,「撤销」可以迁移回去。最近一分钟内还在写入的会话不会改动。",
"Made with {from}: Codex's history lists only {to}'s sessions now": "用 {from} 创建:Codex 现在的历史列表只显示 {to} 的会话",
"{n} sessions moved to magpie's trash": "{n} 个会话已移到 magpie 的回收站",
@@ -181,6 +184,9 @@ magpie.strings({
"Move sessions to {to}?": "把會話遷移到 {to}?",
"Deselect all": "取消全選",
"Invert selection": "反選",
"By tokens": "依 token 數",
"Select sessions under": "選取 token 數少於",
"Each used fewer than {n} tokens": "每個會話都少於 {n} token",
"Only the provider each one names is changed, in its files and in Codex's database: its messages, id, title and archive stay as they are. A copy of its files is kept in magpie's trash folder first, and Undo moves them back. A session written to in the last minute is left alone.": "只改每個會話在檔案和 Codex 資料庫裡記錄的供應商,訊息、會話 ID、標題和歸檔狀態都不變。改之前會先在 magpie 的回收站資料夾裡備份一份檔案,「復原」可以遷移回去。最近一分鐘內還在寫入的會話不會改動。",
"Made with {from}: Codex's history lists only {to}'s sessions now": "用 {from} 建立:Codex 現在的歷史列表只顯示 {to} 的會話",
"{n} sessions moved to magpie's trash": "{n} 個會話已移到 magpie 的回收站",
@@ -285,6 +291,9 @@ magpie.strings({
"Move sessions to {to}?": "セッションを {to} に移行しますか?",
"Deselect all": "すべての選択を解除",
"Invert selection": "選択を反転",
"By tokens": "トークン数で",
"Select sessions under": "トークン数がこれ未満のセッションを選択",
"Each used fewer than {n} tokens": "いずれも {n} トークン未満",
"Only the provider each one names is changed, in its files and in Codex's database: its messages, id, title and archive stay as they are. A copy of its files is kept in magpie's trash folder first, and Undo moves them back. A session written to in the last minute is left alone.": "変更されるのは、ファイルと Codex のデータベースに記録されたプロバイダーだけです。メッセージ、ID、タイトル、アーカイブ状態はそのままです。変更前にファイルのコピーを magpie のゴミ箱フォルダーに保存し、「取り消す」で元に戻せます。直近 1 分以内に書き込まれたセッションは変更しません。",
"Made with {from}: Codex's history lists only {to}'s sessions now": "{from} で作成:Codex の履歴には現在 {to} のセッションだけが表示されます",
"{n} sessions moved to magpie's trash": "{n} 件のセッションを magpie のゴミ箱に移動しました",
@@ -389,6 +398,9 @@ magpie.strings({
"Move sessions to {to}?": "Sitzungen zu {to} umziehen?",
"Deselect all": "Alle abwählen",
"Invert selection": "Auswahl umkehren",
"By tokens": "Nach Tokens",
"Select sessions under": "Sitzungen auswählen mit weniger als",
"Each used fewer than {n} tokens": "Jede mit weniger als {n} Token",
"Only the provider each one names is changed, in its files and in Codex's database: its messages, id, title and archive stay as they are. A copy of its files is kept in magpie's trash folder first, and Undo moves them back. A session written to in the last minute is left alone.": "Geändert wird nur der Anbieter, den jede Sitzung in ihren Dateien und in der Datenbank von Codex nennt: Nachrichten, ID, Titel und Archivstatus bleiben, wie sie sind. Vorher wird eine Kopie der Dateien im Papierkorbordner von magpie abgelegt, und Rückgängig zieht sie zurück. Eine Sitzung, in die in der letzten Minute geschrieben wurde, bleibt unverändert.",
"Made with {from}: Codex's history lists only {to}'s sessions now": "Mit {from} erstellt: Der Verlauf von Codex zeigt jetzt nur Sitzungen von {to}",
"{n} sessions moved to magpie's trash": "{n} Sitzungen in den Papierkorb von magpie verschoben",
@@ -43,7 +43,7 @@ button.row.sm-else-row { width: 100%; gap: 10px; text-align: left; cursor: point
.sess-from { margin-bottom: 8px; }
.sm-bar { gap: 8px; padding: 0 11px; }
.sm-bar .grow { flex: 1; }
.sm-bar .sm-delete, .sm-bar .sm-empty { display: inline-flex; align-items: center; gap: 5px; }
.sm-bar .sm-delete, .sm-bar .sm-empty, .sm-bar .sm-small { display: inline-flex; align-items: center; gap: 5px; }
.sm-bar .sm-delete:disabled { opacity: .45; }
.sm-count { font-size: 11.5px; color: var(--muted); font-variant-numeric: tabular-nums; }
.sm-check { flex: none; margin: 0; width: 14px; height: 14px; accent-color: var(--accent); }
@@ -96,6 +96,7 @@ body.window .sm-group .row.sm-sess { padding-left: 32px; }
.sm-ask-list { grid-column: 1 / -1; min-width: 0; margin: 0; padding: 0; list-style: none; font-size: 12.5px; color: var(--fg); line-height: 1.6; }
.sm-ask-list li { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.sm-ask-list li.more { color: var(--muted); }
.sm-ask-small { grid-column: 1 / -1; min-width: 0; margin: 0; font-size: 12px; color: var(--muted); }
/* a field in a session dialog (#1991): its label above it, both across the
dialog, never squeezed into the form's 72px label column */
.editor label.sm-ask-field { grid-column: 1 / -1; min-width: 0; display: flex; flex-direction: column; gap: 6px; text-align: left; padding-top: 0; }
@@ -0,0 +1,233 @@
// Run with Node's test runner and Playwright on the module path; see README.md.
// The small sessions deleted together (yansheng1003 on X: 在会话管理中增加一个
// 低于10k/20k的会话删除的功能). While picking, the bar over the list has By
// tokens, magpie's own menu (never a native select) of 10K, 20K, 50K and
// 100K, each with how many of the sessions shown it picks. A choice picks
// every deletable session shown that used fewer tokens than it, counted as
// the row shows them (input and output; cache only with the Usage page's
// "with cache"), and only those. One written to in the last minute or
// streaming now is never picked, nor one magpie can't delete, and a filter
// picks among the ones it shows. Delete asks in magpie's dialog how many go,
// by what size, and that they go to magpie's trash, which puts them back;
// Cancel posts nothing; Delete posts sessions/delete with those ids. In all
// five languages, Chromium and WebKit; no backend, the API is faked here.
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 at = (min) => new Date(Date.now() - min * 60e3).toISOString();
const sess = (id, title, min, input, output, more = {}) => ({
agent: "codex", id, cwd: "/work/app", title, start: at(min + 5), last: at(min), input, output,
models: [{ model: "gpt-5.5", input, output, priced: true }],
resume: `codex resume ${id}`, path: `~/.codex/sessions/2026/11/01/rollout-${id}.jsonl`, size: 4096, messages: 4, files: 1, deletable: true, ...more,
});
function fixture() {
return {
codex: [
sess("s-run", "still running", 0.2, 300, 200), // 500 tokens, written to just now
sess("s-live", "streaming now", 5, 800, 200), // 1K, its reply streaming through the gateway
sess("s-tiny", "say hi", 30, 1200, 300), // 1.5K
sess("s-none", "no tokens", 40, 0, 0), // —
sess("s-cache", "mostly cache", 50, 3000, 1000, { cache_read: 400000 }), // 4K, 404K with cache
sess("s-mid", "fix the login form", 60, 12000, 3000), // 15K
sess("s-edge", "exactly twenty", 70, 15000, 5000), // 20K: not under 20K
sess("s-big", "refactor the router", 80, 60000, 20000), // 80K
sess("s-ro", "read only small", 90, 100, 100, { deletable: false, read_only: true }),
],
trash: [],
};
}
function serve(lang, calls) {
const store = fixture();
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({ agents: [], profiles: [], settings: { lang, theme: "light" } });
if (url.pathname === "/api/plugins") return json({ plugins: [] });
if (url.pathname === "/api/groups") return json({ groups: [] });
if (url.pathname === "/api/providers") return json({ providers: [], presets: [], excluded: [], gateway: { running: true, window: true } });
if (url.pathname === "/api/speeds") {
const curve = Array.from({ length: 120 }, (_, i) => (i < 110 ? null : 60));
return json([{ agent: "codex", session: "s-live", live: true, rated: true, now: 60, avg: 60, peak: 60, output: 200, curve, idle: 0 }]);
}
if (url.pathname === "/api/sessions/manage") {
return json({
agents: [{ agent: "codex", count: store.codex.length, deletable: true, name: "Codex", icon: "codex" }],
agent: "codex", sessions: store.codex, terminal: false, trash: store.trash, trashDir: "~/Library/Application Support/magpie/trash/sessions",
});
}
if (url.pathname === "/api/sessions/delete") {
const body = req.postDataJSON();
calls.push({ path: "delete", body });
const out = { deleted: [], refused: [] };
for (const id of body.ids) {
const s = store.codex.find((x) => x.id === id);
store.codex = store.codex.filter((x) => x.id !== id);
store.trash.push({ key: `codex/20261101-${id}`, agent: "codex", id, title: s.title, cwd: s.cwd, last: s.last, deleted: at(0), size: s.size,
items: [{ from: s.path, name: "0-" + id + ".jsonl" }], name: "Codex", icon: "codex" });
out.deleted.push(id);
}
return json(out);
}
if (url.pathname.startsWith("/api/")) {
if (req.method() === "POST" && url.pathname !== "/api/update/using" && url.pathname !== "/api/page-away") calls.push({ path: url.pathname });
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)];
try { await route.fulfill({ body: await fs.readFile(file), contentType }); } catch { await route.fulfill({ status: 404, body: "" }); }
};
}
const words = {
en: { nav: "Sessions", by: "By tokens", head: "Select sessions under", tok: (n) => `${n} tokens`, k: (n) => n === 1 ? "1 session" : `${n} sessions`,
picked: (n) => `${n} selected`, del: "Delete", cancel: "Cancel", ask: (n) => `Delete ${n} sessions?`, each: (n) => `Each used fewer than ${n} tokens`,
trash: "Trash puts them back", moved: (n) => `${n} sessions moved to magpie's trash` },
zh: { nav: "会话", by: "按 token 数", head: "选中 token 数少于", tok: (n) => `${n} token`, k: (n) => `${n} 个会话`,
picked: (n) => `已选 ${n} 个`, del: "删除", cancel: "取消", ask: (n) => `删除这 ${n} 个会话?`, each: (n) => `每个会话都少于 ${n} token`,
trash: "回收站", moved: (n) => `${n} 个会话已移到 magpie 的回收站` },
"zh-TW": { nav: "會話", by: "依 token 數", head: "選取 token 數少於", tok: (n) => `${n} token`, k: (n) => `${n} 個會話`,
picked: null, del: "刪除", cancel: "取消", ask: (n) => `刪除這 ${n} 個會話?`, each: (n) => `每個會話都少於 ${n} token`, trash: "回收", moved: null },
ja: { nav: null, by: "トークン数で", head: "トークン数がこれ未満のセッションを選択", tok: (n) => `${n} トークン`, k: (n) => `${n} 件のセッション`,
picked: null, del: null, cancel: null, ask: (n) => `${n} 件のセッションを削除しますか?`, each: (n) => `いずれも ${n} トークン未満`, trash: null, moved: null },
de: { nav: null, by: "Nach Tokens", head: "Sitzungen auswählen mit weniger als", tok: (n) => `${n} Token`, k: (n) => n === 1 ? "1 Sitzung" : `${n} Sitzungen`,
picked: null, del: null, cancel: null, ask: (n) => `${n} Sitzungen löschen?`, each: (n) => `Jede mit weniger als ${n} Token`, trash: null, moved: null },
};
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
for (const lang of Object.keys(words)) {
const w = words[lang];
test(`${engine} ${lang}: the sessions under a size are picked from By tokens and deleted to magpie's trash`, async (t) => {
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
const page = await (await browser.newContext({ viewport: { width: 900, height: 620 }, reducedMotion: "reduce" })).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}-sessions-small-delete.png`) });
}
await browser.close();
});
page.setDefaultTimeout(5000);
page.setDefaultNavigationTimeout(60000);
const errors = [];
page.on("pageerror", (e) => errors.push(e.message));
page.on("dialog", (d) => { errors.push("a browser dialog: " + d.message()); d.dismiss(); });
const calls = [];
await page.route("**/*", serve(lang, calls));
await page.goto("http://magpie.test/?view=providers");
// the nav's word in each language, from the page's own strings
const nav = await page.evaluate(() => t("Sessions"));
await page.locator("#nav").getByRole("button", { name: nav, exact: true }).click();
const view = page.locator("#view-sessions");
await view.locator('.row.sm-sess[data-id="s-big"]').waitFor();
// the streaming one's speed is in before anything is picked
await view.locator('.row.sm-sess[data-id="s-live"] .sm-speed').waitFor();
const tr = (k, v) => page.evaluate(([k, v]) => t(k, v), [k, v]);
const count = async () => (await view.locator(".sm-bar .sm-count").textContent()).trim();
const ticked = () => view.locator(".row.sm-sess input.sm-check").evaluateAll((cs) => cs.filter((c) => c.checked).map((c) => c.closest(".row").dataset.id).sort());
// not until Select
assert.equal(await view.locator(".sm-small").count(), 0);
await view.locator(".sm-select").click();
const by = view.locator(".sm-bar .sm-small");
assert.equal((await by.textContent()).trim(), w.by);
assert.equal(await by.getAttribute("aria-haspopup"), "menu");
assert.equal(await page.locator("#view-sessions select").count(), 0, "no native select");
// the menu: magpie's own, each size with how many it picks
const menu = page.locator(".proto-menu.sm-small-menu");
const open = async () => { await by.click(); await menu.waitFor(); };
await open();
assert.equal((await menu.locator(".pm-head").textContent()).trim(), w.head);
assert.deepEqual(await menu.locator(".pm-name").allTextContents(), ["10K", "20K", "50K", "100K"].map(w.tok));
// under 10K: tiny, none, cache (4K without cache); under 20K mid too;
// 50K edge (20K) too; 100K big too
assert.deepEqual(await menu.locator(".pm-note").allTextContents(), [3, 4, 5, 6].map(w.k));
const choose = async (i) => { await menu.locator(".pm-item").nth(i).click(); await menu.waitFor({ state: "detached" }); };
await choose(1);
assert.deepEqual(await ticked(), ["s-cache", "s-mid", "s-none", "s-tiny"], "under 20K, never the running, streaming or read-only one");
assert.equal(await count(), await tr("{n} selected", { n: 4 }));
if (w.picked) assert.equal(await count(), w.picked(4));
// a smaller size picks only those, not added to the last
await open();
await choose(0);
assert.deepEqual(await ticked(), ["s-cache", "s-none", "s-tiny"]);
// Delete asks how many, by what size, and that Trash puts them back;
// Cancel posts nothing
const ask = page.locator("#modal .sm-ask");
await view.locator(".sm-bar .sm-delete").click();
await ask.waitFor();
assert.equal((await ask.locator(".ehead b").textContent()).trim(), w.ask(3));
assert.equal((await ask.locator(".sm-ask-small").textContent()).trim(), w.each("10K"));
// one line across the dialog, not squeezed into its first column
assert(await ask.locator(".sm-ask-small").evaluate((e) => e.getBoundingClientRect().height < 24 && e.getBoundingClientRect().width > e.parentElement.getBoundingClientRect().width * 0.6), "the size line spans the dialog");
if (process.env.ARTIFACT_DIR) { await page.waitForTimeout(600); await page.screenshot({ path: path.join(process.env.ARTIFACT_DIR, `${engine}-${lang}-ask.png`) }); }
const confirm = await ask.locator(".lib-confirm").textContent();
assert(confirm.includes("~/Library/Application Support/magpie/trash/sessions"), "they go to magpie's trash");
if (w.trash) assert(confirm.includes(w.trash), "it says Trash puts them back: " + confirm);
await ask.getByRole("button", { name: await tr("Cancel"), exact: true }).click();
await ask.waitFor({ state: "detached" });
assert.deepEqual(calls, [], "Cancel deletes nothing");
// picked by hand after, the dialog no longer names a size
await view.locator('.row.sm-sess[data-id="s-mid"] input.sm-check').check();
await view.locator(".sm-bar .sm-delete").click();
await ask.waitFor();
assert.equal(await ask.locator(".sm-ask-small").count(), 0);
await ask.getByRole("button", { name: await tr("Cancel"), exact: true }).click();
await ask.waitFor({ state: "detached" });
// under a filter, only the ones it shows
await view.locator(".sm-filter").fill("login");
await page.waitForFunction(() => document.querySelectorAll("#view-sessions .row.sm-sess").length === 1);
await open();
assert.deepEqual(await menu.locator(".pm-note").allTextContents(), [0, 1, 1, 1].map(w.k));
await choose(1);
assert.equal(await count(), await tr("{n} selected", { n: 1 }));
await view.locator(".sm-filter").fill("");
await view.locator(".sm-filter").dispatchEvent("input");
await view.locator('.row.sm-sess[data-id="s-big"]').waitFor();
assert.deepEqual(await ticked(), ["s-mid"]);
// under 20K, deleted: those ids posted, the rest stay
await open();
await choose(1);
await view.locator(".sm-bar .sm-delete").click();
await ask.waitFor();
assert.equal((await ask.locator(".ehead b").textContent()).trim(), w.ask(4));
assert.equal((await ask.locator(".sm-ask-small").textContent()).trim(), w.each("20K"));
await ask.locator("button.danger-fill").click();
await ask.waitFor({ state: "detached" });
assert.equal(calls.length, 1);
assert.deepEqual(calls[0].body.agent, "codex");
assert.deepEqual(calls[0].body.ids.slice().sort(), ["s-cache", "s-mid", "s-none", "s-tiny"]);
await view.locator('.row.sm-sess[data-id="s-tiny"]').waitFor({ state: "detached" });
const moved = await tr("{n} sessions moved to magpie's trash", { n: 4 });
if (w.moved) assert.equal(moved, w.moved(4));
await page.waitForFunction((x) => document.querySelector("#status")?.textContent === x, moved);
assert.deepEqual(await view.locator(".row.sm-sess").evaluateAll((rs) => rs.map((r) => r.dataset.id).sort()), ["s-big", "s-edge", "s-live", "s-ro", "s-run"]);
// the bar fits a narrow window: nothing spills out of it
await page.setViewportSize({ width: 420, height: 620 });
await page.waitForTimeout(100);
const spill = await view.locator(".sm-bar").evaluate((b) => [...b.children].filter((c) => !c.hidden && c.getBoundingClientRect().right > b.getBoundingClientRect().right + 1).map((c) => c.className));
assert.deepEqual(spill, [], "the bar's buttons stay inside it");
const keys = ["By tokens", "Select sessions under", "Each used fewer than {n} tokens"];
if (lang !== "en") {
const missing = await page.evaluate(([l, ks]) => ks.filter((k) => !I18N[l]?.[k]), [lang, keys]);
assert.deepEqual(missing, [], "every string has its " + lang);
}
assert.deepEqual(errors, []);
});
}
}