Files
magpie/internal/gui/tests/sessions-folder-delete.test.cjs
T
yetone 6835e8d297 sessions: every session of a project folder can be deleted at once, from the folder's row (#527: 有些codex会话多,有些特别老的项目,希望能直接删除整个项目文件夹下所有会话) — the Sessions page lists an agent's sessions by the folder they ran in, but deleting a folder's took picking each one or the per-row trash one by one. Each folder's row now has Delete all (全部删除, titled "Delete every session in this folder" / 删除这个文件夹下的全部会话; the label folds to its icon under 420px) where magpie can delete the agent's sessions. It opens the same dialog of magpie's own as a delete of picked sessions (never confirm()), headed "Delete all {n} sessions in {folder}?" (删除 {folder} 下的全部 {n} 个会话?) with the folder's path under it, the first titles and how many more, and the note that they go to magpie's trash; the confirm posts sessions/delete with every id of the folder, the path a single delete takes, so each goes to magpie's trash as one deleted alone does (Trash restores it) and one written to in the last minute is left and said so. A filter hiding some of the folder's sessions doesn't keep them: the button is the folder's, and the dialog says how many. A folder of one asks as a single delete does; an agent whose sessions magpie can't delete (OpenCode) has no button; the click doesn't fold the folder or move the page. Deleting 200 of 600 sessions one id at a time took about 0.5 s in a sandbox, so the route is unchanged and there is no Go change. The CLI's magpie sessions only lists sessions and what they cost, with no delete, trash or restore, so no folder delete was added there: deleting from a terminal with nothing to put it back would be a new, one-way thing. sessions-folder-delete.test.cjs (new; WebKit, en and zh): the button on every folder in its row, Cancel posting nothing, a filtered folder's Delete all posting all fourteen ids, a folded folder's two posted and the folder gone with the others kept, the running one left and said so, a folder of one asking as one, none for OpenCode, no click moving the page, no left-border accent, every string in Chinese, no browser dialog; it fails without the change (no Delete all). sessions-manage, sessions-purge, click-scroll, sessions-toolbar, session-terminal, sessions-bar-names and sessions-overview pass in WebKit. go vet ./internal/..., go build -tags nogui (darwin, GOOS=linux), GOOS=windows go build, go test -tags nogui ./... pass (TestFXInState and TestUserPath failed once under load, pass on the rerun; untouched).
2026-10-02 15:48:17 +08:00

229 lines
13 KiB
JavaScript

// Run with Node's test runner and Playwright on the module path; see README.md.
// Every session of a project folder deleted at once (#527: 有些codex会话多,
// 有些特别老的项目,希望能直接删除整个项目文件夹下所有会话). Each folder's row
// on the Sessions page has Delete all: it asks in magpie's own dialog (never
// confirm()), naming the folder, how many and its path, then posts
// sessions/delete with every id of the folder, as a pick of them would, so
// they go to magpie's trash as one deleted alone does; a filter hiding some
// of them doesn't keep them. Cancel posts nothing; a session still being
// written to is left and said so; other folders stay. An agent magpie can't
// delete from has none. Clicks leave the page where it is. In English and
// Chinese, 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, cwd, title, min) => ({
agent: "codex", id, cwd, title, start: at(min + 5), last: at(min), models: [],
resume: `cd ${cwd} && codex resume ${id}`, path: `~/.codex/sessions/2026/10/01/rollout-${id}.jsonl`, size: 4096, messages: 6, files: 1, deletable: true,
});
function fixture() {
const app = [sess("a-run", "/work/app", "still running", 0.2), sess("a-login", "/work/app", "fix the login form", 30)];
for (let i = 0; i < 12; i++) app.push(sess(`a-${i}`, "/work/app", `older task ${i}`, 60 + i * 10));
return {
codex: [...app, sess("b-1", "/work/old-blog", "write the post", 600), sess("b-2", "/work/old-blog", "", 700), sess("n-1", "", "no folder chat", 800)],
opencode: [{ ...sess("o-1", "/work/app", "an opencode chat", 5), agent: "opencode", deletable: false, resume: "opencode -s o-1" }],
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/sessions/manage") {
const agent = url.searchParams.get("agent") === "opencode" ? "opencode" : "codex";
return json({
agents: [
{ agent: "codex", count: store.codex.length, deletable: true, name: "Codex", icon: "codex" },
{ agent: "opencode", count: store.opencode.length, deletable: false, name: "OpenCode", icon: "opencode" },
],
agent, sessions: store[agent], 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) {
if (id === "a-run") { out.refused.push({ id, error: "it was written to in the last minute; it may still be running", active: true }); continue; }
const s = store.codex.find((x) => x.id === id);
store.codex = store.codex.filter((x) => x.id !== id);
store.trash.push({ key: `codex/20261001-${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") 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", del: "Delete", cancel: "Cancel", all: "Delete all", title: "Delete every session in this folder",
askApp: "Delete all 14 sessions in app?", askBlog: "Delete all 2 sessions in old-blog?", askOne: "Delete this session?",
moved: "2 sessions moved to magpie's trash", moved13: "13 sessions moved to magpie's trash",
active: "still running is still being written to; close it in Codex and try again in a minute",
},
zh: {
nav: "会话", del: "删除", cancel: "取消", all: "全部删除", title: "删除这个文件夹下的全部会话",
askApp: "删除 app 下的全部 14 个会话?", askBlog: "删除 old-blog 下的全部 2 个会话?", askOne: "删除这个会话?",
moved: "2 个会话已移到 magpie 的回收站", moved13: "13 个会话已移到 magpie 的回收站",
active: "「still running」仍在写入;请在 Codex 中关闭它,一分钟后再试",
},
};
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
for (const lang of ["en", "zh"]) {
const w = words[lang];
test(`${engine} ${lang}: every session of a folder is deleted at once, after magpie's own dialog`, async (t) => {
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
const page = await (await browser.newContext({ viewport: { width: 900, height: 560 }, 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-folder-delete.png`) });
}
await browser.close();
});
page.setDefaultTimeout(5000);
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");
await page.locator("#nav").getByRole("button", { name: w.nav, exact: true }).click();
const view = page.locator("#view-sessions");
const row = (id) => view.locator(`.row.sm-sess[data-id="${id}"]`);
await row("a-run").waitFor();
const folder = (name) => view.locator(".row.sm-folder").filter({ has: page.locator(".fold .name", { hasText: new RegExp("^" + name + "$") }) });
const said = (text) => page.waitForFunction((x) => document.querySelector("#status")?.textContent === x, text)
.catch(async () => assert.equal(await page.locator("#status").textContent(), text));
const top = (l) => l.evaluate((e) => e.getBoundingClientRect().top);
// the reader's wheel brings it into sight (a scroll by code is put back)
const reach = async (l) => {
const box = await view.boundingBox();
await page.mouse.move(box.x + box.width / 2, box.y + box.height / 2);
for (let k = 0; k < 80; k++) {
const b = await l.boundingBox();
if (b.y >= box.y + 40 && b.y + b.height <= box.y + box.height - 40) break;
await page.mouse.wheel(0, b.y < box.y + 40 ? -40 : 40);
await page.waitForTimeout(20);
}
await page.waitForTimeout(300);
};
const ask = page.locator("#modal .sm-ask");
// Delete all on a folder's row, the page held still and the folder
// left folded or open as it was
const askAll = async (name) => {
const r = folder(name);
const btn = r.locator(".sm-folder-del");
await reach(btn);
const before = await top(r), open = await r.locator(".fold").getAttribute("aria-expanded");
await btn.click();
await ask.waitFor();
assert.equal(await top(r), before, "Delete all moved the page");
assert.equal(await r.locator(".fold").getAttribute("aria-expanded"), open, "Delete all folded or unfolded the folder");
};
// every folder has it, named and inside its row
const btns = view.locator(".row.sm-folder .sm-folder-del");
assert.equal(await btns.count(), 3);
for (const b of await btns.all()) {
assert.equal((await b.textContent()).trim(), w.all);
assert.equal(await b.getAttribute("title"), w.title);
const inside = await b.evaluate((e) => { const q = e.getBoundingClientRect(), r = e.closest(".row").getBoundingClientRect(); return q.width > 0 && q.left >= r.left && q.right <= r.right; });
assert(inside, "the button is inside its row");
}
// filtered to one of app's sessions, Delete all still means the whole
// folder, and says so; Cancel posts nothing
await view.locator(".sm-filter").fill("login");
await view.locator(".row.sm-sess").first().waitFor();
assert.equal(await view.locator(".row.sm-sess").count(), 1);
await askAll("app");
assert.equal((await ask.locator(".ehead b").textContent()).trim(), w.askApp);
assert.equal((await ask.locator(".sm-ask-path").textContent()).trim(), "/work/app");
assert.equal(await ask.locator(".sm-ask-list li").count(), 6, "five titles and the rest counted");
await ask.getByRole("button", { name: w.cancel, exact: true }).click();
await ask.waitFor({ state: "detached" });
assert.deepEqual(calls, [], "Cancel deletes nothing");
await view.locator(".sm-filter").fill("");
await view.locator(".sm-filter").dispatchEvent("input");
await row("a-run").waitFor();
// a folded folder: its two go, the others stay
assert.equal(await folder("old-blog").locator(".fold").getAttribute("aria-expanded"), "false");
const shot = async (name) => {
if (!process.env.ARTIFACT_DIR) return;
await fs.mkdir(process.env.ARTIFACT_DIR, { recursive: true });
await page.screenshot({ path: path.join(process.env.ARTIFACT_DIR, `${engine}-${lang}-sessions-folder-${name}.png`) });
};
await shot("list");
await askAll("old-blog");
await page.waitForTimeout(400);
await shot("ask");
assert.equal((await ask.locator(".ehead b").textContent()).trim(), w.askBlog);
assert.deepEqual(await ask.locator(".sm-ask-list li").allTextContents(), ["write the post", "b-2"]);
assert((await ask.locator(".lib-confirm").textContent()).includes("~/Library/Application Support/magpie/trash/sessions"), "they go to magpie's trash");
await ask.getByRole("button", { name: w.del, exact: true }).click();
await ask.waitFor({ state: "detached" });
assert.deepEqual(calls, [{ path: "delete", body: { agent: "codex", ids: ["b-1", "b-2"] } }]);
await folder("old-blog").waitFor({ state: "detached" });
await said(w.moved);
assert.equal(await folder("app").count(), 1);
assert.equal(await view.locator(".sm-trash-btn em").textContent(), "2");
// app: every one posted; the one still running is left, and said so
await askAll("app");
await ask.getByRole("button", { name: w.del, exact: true }).click();
await ask.waitFor({ state: "detached" });
assert.deepEqual(calls[1].body.ids, ["a-run", "a-login", ...Array.from({ length: 12 }, (_, i) => `a-${i}`)]);
await said(w.active);
await view.locator(".row.sm-sess").first().waitFor();
assert.deepEqual(await view.locator(".row.sm-sess").evaluateAll((rs) => rs.map((r) => r.dataset.id)), ["a-run"]);
// a folder of one asks as a single delete does
await askAll(lang === "zh" ? "无文件夹" : "No folder");
assert.equal((await ask.locator(".ehead b").textContent()).trim(), w.askOne);
await ask.getByRole("button", { name: w.cancel, exact: true }).click();
await ask.waitFor({ state: "detached" });
assert.equal(calls.length, 2);
// no left-border accent in the page or the dialog
const border = await page.evaluate(() => [...document.querySelectorAll("#view-sessions, #view-sessions *")]
.filter((e) => parseFloat(getComputedStyle(e).borderLeftWidth) > 1 && getComputedStyle(e).borderLeftColor !== getComputedStyle(e).borderRightColor).map((e) => e.className));
assert.deepEqual(border, [], "no left-border accent");
// an agent magpie can't delete from has none
await view.locator(".sm-agents .opt", { hasText: "OpenCode" }).click();
await view.locator('.row.sm-sess[data-id="o-1"]').waitFor();
assert.equal(await view.locator(".sm-folder-del").count(), 0);
const missing = await page.evaluate(() => ["Delete all", "Delete every session in this folder", "Delete all {n} sessions in {folder}?"].filter((k) => !I18N.zh[k]));
assert.deepEqual(missing, [], "every string has its Chinese");
assert.deepEqual(errors, []);
});
}
}