The Sessions page's list and its session count came from two different
lengths: the count is over every session (statsFor's Overview), while
GET /api/sessions fell back to sessions.Limit (200) when the page asked for
no number — and the page never asks for one. So the page said "238 sessions"
over a list of 200, and each agent whose sessions were oldest lost them
whole: Codex had 121 sessions here and the list showed 7, OpenCode 33 showed
2, ZCode 20 showed 3.
* sessions.All (5000) is what a listing that means every session asks for,
and the endpoint reads it when no number is asked of it; a caller that
asks for one still gets it. It lives in internal/sessions so the page, the
TUI and the CLI ask for the same number.
* sessions.Limit stays 200 and is not raised: traceRecentFiles sizes the
window gateway attribution is judged over by it (TraceSessionVisible
decides whether a session has a readable local transcript), so raising it
would change which calls count as magpie's.
* The page draws that list in pages: SESS_PAGE (200) rows, and "Show N
more" appends the next. A filter click or a keystroke in Search draws the
first page and no more, so the cost does not grow with the history. The
data stays complete, so the count and the list still agree. A list served
4000 sessions long rebuilt every row on every keystroke — 275–320 ms a
keystroke on a fast Mac with very small rows, worse on Windows — and now
draws 200.
* The note under the list counts the list the filters kept, not every
session on the computer: it says "showing {drawn} of {n}" while pages are
left and "{n} session"/"{n} sessions" once the whole list is drawn. Before
it counted the whole history beside the drawn rows, so a search matching
one session read "the list holds all 2600, 1 drawn" — as if 2599 were
behind a "Show more" that isn't there. It also no longer says "drawn",
which is how the page is built, not what a reader sees.
* The CLI read sessions.List(0) — 200 — and then cut to its own --limit, so
--limit 500 could never show more than 200 and the "%d more with --limit"
foot was counted off the truncated list. It reads the whole set now; only
o.limit rows are printed, so that costs a parse, not output.
* The TUI read List(0) beside a head that says how many sessions there are,
and then List(sessions.Limit+1) — 201, still not the whole set. It reads
sessions.All now.
What the wider list costs is unchanged: every session file is read either way
to sort by last activity. Measured here with 384 sessions and 84.5k calls:
cold List(200) 10.3 s, List(5000) 10.5 s. What it adds is per-row work while
List holds the lock — a Codex session's titles stat, a pi session's omp
look-up, 25× the rows of JSON — hundreds of milliseconds, not seconds.
Tests, each failing without its change:
* TestSessionsListIsAsLongAsTheCount (internal/gui): 205 Claude Code
sessions as Claude Code keeps them; all 205 with no number asked, 5 with
?limit=5, 201 with ?limit=201. Fails with the list holding 200.
* TestSessionsListIsNotCutAtTheLimit (internal/tui): 210 sessions, of which
the ten past sessions.Limit are all in the list. Fails at 201.
* TestSessionsMoreCountsTheWholeSet (root): the default --limit 20 over 212
sessions says "192 more with --limit", and --limit 205 prints 205 rows.
Fails saying 180 (counted off the truncated list).
* sessions-paging.test.cjs (Chromium and WebKit, en and zh): 2600 sessions;
the first page is 200 rows with "Show 200 more", the button appends to
600 with the rows above left in place, a keystroke in Search draws a page
in under 250 ms and starts the pages again, a search matching one session
reads "1 session" and never the 2600 on the computer, and the note follows
the list the filters kept (200 of 1111 after that search). Fails on
origin/main (200 rows are not a page there) and with the pages taken out;
counting every session again, or writing "1 sessions", fails it too.
Verified: go vet; go build (windows); go test ./internal/sessions
./internal/tui ./internal/gui . — only what origin/main fails (TestCursor,
TestGatewayFixQuitsOnlyAMagpie, TestPurposeAssetMatchesUsage,
TestUpdateThatWontStart, TestPluginListSaysMiddleware,
TestPluginOnOffRmShortName); node --check app.js and i18n.js; the browser
suites above plus sessions-overview, sessions-today, sessions-usage-open,
sessions-toolbar, sessions-calendar-fill, usage-sessions-agents-fit,
i18n-keys, usage-ledger and click-scroll.
Co-authored-by: wizzy-yang <wizzy-yang@users.noreply.github.com>
169 lines
9.9 KiB
JavaScript
169 lines
9.9 KiB
JavaScript
// Run with Node's test runner and Playwright on the module path; see README.md.
|
|
// The Sessions tab's list is every session the filters keep, drawn a page at a
|
|
// time: a filter click or a keystroke in Search draws the first page and no
|
|
// more, "Show N more" appends the next, and the note under the list says how
|
|
// many of how many are drawn. Without the pages a history of thousands was
|
|
// rebuilt whole on every keystroke (~300 ms a keystroke on a fast Mac, and
|
|
// worse on Windows: yetone, #1019). The data stays complete, so the count
|
|
// beside the list and the list still agree. English and Chinese, Chromium and
|
|
// WebKit.
|
|
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 reader = require("./reader.cjs");
|
|
|
|
const assets = path.resolve(__dirname, "../assets");
|
|
const to = new Date(2026, 8, 28);
|
|
const iso = (d) => [d.getFullYear(), d.getMonth() + 1, d.getDate()].map((n) => String(n).padStart(2, "0")).join("-");
|
|
const N = 2600; // past two pages of 200, so a third page is left over
|
|
const DAYS = 30;
|
|
|
|
// N sessions, newest first, one every few minutes; every 25th names another
|
|
// model, so a filter has something to narrow to
|
|
const sessions = Array.from({ length: N }, (_, i) => ({
|
|
agent: "claude", name: "Claude Code", icon: "claude", id: "s" + i,
|
|
cwd: i % 2 ? "/work/alpha" : "/work/beta", title: i === 0 ? "Fix the session list" : "Session " + i,
|
|
start: new Date(to.getTime() - (i + 30) * 60e3).toISOString(),
|
|
last: new Date(to.getTime() - (i + 1) * 60e3).toISOString(),
|
|
input: 1000 + i, output: 100, cache_read: 0, cache_write: 0, cost: 0.01, priced: true,
|
|
models: [{ model: i % 25 === 0 ? "claude-opus-4" : "claude-sonnet-5", input: 1000 + i, output: 100, cost: 0.01, priced: true }],
|
|
resume: "claude --resume s" + i,
|
|
}));
|
|
const days = Array.from({ length: DAYS }, (_, i) => {
|
|
const d = new Date(to); d.setDate(d.getDate() - (DAYS - 1 - i));
|
|
return { date: iso(d), usage: [{ agent: "claude", cwd: "/work/alpha", model: "claude-opus-4", input: 30000, output: 4000, cache_read: 0, cache_write: 0, cost: 1.5, priced: true }], active: [] };
|
|
});
|
|
|
|
function serve(lang) {
|
|
const state = { agents: [{ id: "claude", name: "Claude Code", path: "/t.json", fields: [] }], profiles: [], settings: { lang, theme: "light" } };
|
|
return async (route) => {
|
|
const url = new URL(route.request().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/sessions/progress") return json({ indexing: false });
|
|
if (url.pathname === "/api/sessions") return json({ sessions, dirs: ["/test/sessions"] });
|
|
if (url.pathname === "/api/sessions/stats") return json({ from: days[0].date, to: iso(to), days, agents: { claude: "Claude Code" } });
|
|
if (url.pathname === "/api/sessions/overview") return json({
|
|
count: N, median: 120000, p90: 880000, days: days.map(() => 1),
|
|
top: { tokens: [], cost: [], active: [] }, messages: days.map(() => 30), output: days.map(() => 0),
|
|
shape: {
|
|
messages: { edges: [1, 6, 16, 31, 61, 121], counts: [3, 10, 14, 9, 4, 2], total: N },
|
|
minutes: { edges: [1, 6, 16, 31, 61, 121], counts: [20, 12, 6, 3, 1, 0], total: N },
|
|
autonomy: { edges: [0, 1, 3, 6, 11, 21], counts: [5, 7, 10, 12, 6, 2], total: N },
|
|
},
|
|
tools: { calls: 0, sessions: 0, top: [], categories: [], weeks: [] },
|
|
skills: { calls: 0, count: 0, top: [] },
|
|
});
|
|
if (url.pathname === "/api/groups") return json({ groups: [], models: [] });
|
|
if (url.pathname === "/api/usage/quotas") return json([]); // an array, as the Go side writes it
|
|
if (url.pathname === "/api/usage/quotas/history") return json({ days: [] });
|
|
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)];
|
|
const body = await fs.readFile(file).catch(() => null);
|
|
return body ? route.fulfill({ body, contentType }) : route.fulfill({ status: 404, body: "" });
|
|
};
|
|
}
|
|
|
|
const words = {
|
|
en: {
|
|
more: /^Show 200 more$/,
|
|
// The note counts the list the filters kept, not every session on the
|
|
// computer: a page of them reads "showing 200 of 2600", and a list drawn
|
|
// whole reads its own length — "1 session" for one, "N sessions" for
|
|
// more. The number picks the word, so the regex does too: `sessions?`
|
|
// would let "1 sessions" through.
|
|
showing: (drawn, total) => new RegExp(`showing ${drawn} of ${total}`),
|
|
whole: (n) => new RegExp(`· ${n} ${n === 1 ? "session" : "sessions"} ·`),
|
|
none: "No session matches.",
|
|
},
|
|
zh: {
|
|
more: /^显示其余 200 个$/,
|
|
showing: (drawn, total) => new RegExp(`显示 ${total} 个中的 ${drawn} 个`),
|
|
// Chinese has no plural: one word either way
|
|
whole: (n) => new RegExp(`· ${n} 个会话 ·`),
|
|
none: "没有匹配的会话。",
|
|
},
|
|
};
|
|
|
|
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
|
|
for (const lang of ["en", "zh"]) {
|
|
test(`${engine} ${lang}: the Sessions list is drawn in pages over a long history`, async (t) => {
|
|
const w = words[lang];
|
|
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
|
|
const page = await (await browser.newContext({ viewport: { width: 1000, height: 760 }, reducedMotion: "reduce" })).newPage();
|
|
t.after(() => browser.close());
|
|
page.setDefaultTimeout(10000);
|
|
const errors = [];
|
|
page.on("pageerror", (e) => errors.push(e.message));
|
|
// the Sessions tab, over all ranges, as it was left
|
|
await page.addInitScript(() => { localStorage.setItem("magpie.usageTab", "sessions"); localStorage.setItem("magpie.sessRange", "all"); });
|
|
await page.route("**/*", serve(lang));
|
|
await page.goto("http://magpie.test/?view=usage");
|
|
await page.locator("#sessGrid:not([hidden])").waitFor();
|
|
const rows = page.locator("#sessList .row.sess");
|
|
const more = page.locator("#sessList .sess-page-more");
|
|
|
|
// the first page and no more: 200 rows of the 2600 the list holds
|
|
assert.equal(await rows.count(), 200, "the first page");
|
|
assert.equal(await more.count(), 1, "a way to the next page");
|
|
assert.match(await more.innerText(), w.more);
|
|
assert.match(await page.locator("#sessNote").innerText(), w.showing(200, N));
|
|
|
|
// The next page appends 200 more, and the note follows. The button is
|
|
// under 200 rows, so it is pressed through the DOM: what this test is
|
|
// about is the pages, not bringing a control into sight (click-scroll
|
|
// and reader.cjs cover that).
|
|
await more.evaluate((b) => b.click());
|
|
assert.equal(await rows.count(), 400, "the second page, on top of the first");
|
|
assert.match(await page.locator("#sessNote").innerText(), w.showing(400, N));
|
|
// and the rows already drawn are the same elements, not rebuilt
|
|
const first = await rows.first().getAttribute("data-key");
|
|
await more.evaluate((b) => b.click());
|
|
assert.equal(await rows.count(), 600, "the third page");
|
|
assert.equal(await rows.first().getAttribute("data-key"), first, "the rows above stayed where they were");
|
|
assert.match(await page.locator("#sessNote").innerText(), w.showing(600, N));
|
|
|
|
// a keystroke in Search is a new list: it starts at the first page again
|
|
// and, over 2600 sessions, does not take the time the whole list would.
|
|
// 1111 of them name "Session 1" ("1", "1x", "1xx", "1xxx"), so the note
|
|
// counts that list — 200 of 1111, not of the 2600 on the computer
|
|
const q = page.locator("#sessQ");
|
|
const at = Date.now();
|
|
await q.fill("Session 1");
|
|
const took = Date.now() - at;
|
|
assert(await rows.count() <= 200, "a search draws a page, not the history");
|
|
assert.equal(await rows.count(), 200, "a page of the matches");
|
|
assert.match(await page.locator("#sessNote").innerText(), w.showing(200, 1111));
|
|
assert(took < 250, `a keystroke over ${N} sessions took ${took}ms`);
|
|
|
|
// a filter that keeps nothing says so, and the note counts nothing
|
|
await q.fill("nothing matches this at all");
|
|
await page.locator("#sessList .empty-state").waitFor();
|
|
assert.equal(await rows.count(), 0);
|
|
assert.match(await page.locator("#sessNote").innerText(), w.whole(0));
|
|
await q.press("Escape");
|
|
await page.locator("#sessList .row.sess").first().waitFor();
|
|
assert.equal(await rows.count(), 200, "clearing the search draws the first page again");
|
|
assert.match(await page.locator("#sessNote").innerText(), w.showing(200, N));
|
|
|
|
// A search that matches fewer than a page holds them all: the note says
|
|
// "1 session", not "1 of 2600" — there is no "Show more" for the other
|
|
// 2599, and saying so would send the reader looking for one. The whole
|
|
// list is drawn, so it is the length and not "1 of 1" (yetone, #1019).
|
|
await q.fill("Fix the session list");
|
|
await page.locator("#sessList .row.sess").first().waitFor();
|
|
assert.equal(await rows.count(), 1, "the one match");
|
|
assert.equal(await more.count(), 0, "a list shorter than a page has no way to more");
|
|
assert.match(await page.locator("#sessNote").innerText(), w.whole(1));
|
|
assert.doesNotMatch(await page.locator("#sessNote").innerText(), new RegExp(String(N)), "the note doesn't count the whole history");
|
|
|
|
assert.deepEqual(errors, []);
|
|
});
|
|
}
|
|
}
|