Files
magpie/internal/gui/tests/sessions-search.test.cjs
T
yetone 260ded9af4 sessions: the Sessions page's search finds a session by what was said in it, and a gateway session is titled by what it was first asked (YOU on Discord)
Why: the filter matched only titles, folders, ids and models, and a
session the gateway recorded was listed under its bare ses_… id, so one
couldn't be found by anything a person remembers about it.

What changed:
- sessions.GatewayTitle: the first user text of a recorded session (not
  a <…> context tag, # AGENTS.md or an image), made one line. It reads at
  most 8 complete turns of the oldest file of it, caches a finished
  file's answer by path, and costs one stat when nothing is recorded.
  gatewayListed applies it in every list (/api/sessions, /manage, /one,
  the stats summaries); ExternalSession gained Title.
- GET /api/sessions/search?agent=&q= (searchSessions): an agent's
  sessions, newest first, read by up to 4 workers, each only to its
  first match. Native files go through a byte prefilter (mayHold: the
  query's longest word, ASCII case folded without a copy, 1 MiB chunks,
  skipped for zstd and for queries JSON may escape), and of a Claude or
  Codex file only the lines holding every word are decoded
  (readTranscriptOf; claudeContentOf/codexContentOf take an optional
  line test, nil for every other caller); gateway sessions, and an
  unreadable agent's sessions (unread: true), through their recorded
  transcript. System prompts, tool definitions and images never match.
  It stops at 200 hits or 8s (cut, searched of total) and when the
  request's context ends. Each hit carries the match with 36 runes
  before and 120 after.
- sessions.js: the field says "Search sessions"; title/folder/id/model
  matches show at once, the server is asked 300ms after the last
  keystroke, a new query aborts the request in flight and its answer is
  dropped, under 2 letters asks nothing. A session found shows a line of
  the words round its match with the match in <mark> (text nodes, no
  innerHTML). A note says when it is searching, cut short, failed, or
  limited to recorded text. New strings in zh, zh-TW, ja and de.
- docs/subsystems/gateway-sessions.md describes both.

Run:
- Go: TestSearchSession* (snippet, case and line breaks, said text
  preferred over a tool call, cut ends, cancelled context, a Codex file,
  only matching lines decoded: 1 part of 3), TestContainsFold,
  TestMayHoldSkipsAFileWithoutTheWords (incl. a match across chunks),
  TestGatewayTitleAndSearch (context tag and system prompt skipped),
  TestSessionsSearchFindsGatewaySessionsByWhatWasSaid (endpoint + manage
  titles), TestSessionsSearchStopsWhenItsRequestEnds. Without the
  endpoint/title they fail (404, id as title).
- GUI: new sessions-search.test.cjs in chromium and webkit, en/zh at
  1100, zh-TW/ja at 560, de at 420: title shown, one letter no request,
  one debounced request, snippet mark, cancelled earlier request never
  shown, cut note, empty state, Escape, every language's strings, no
  overflow; 12/12, and 0/12 with the old sessions.js. The sessions-*,
  sess-*, session-* and i18n-keys tests pass in both engines
  (sessions-manage's placeholder updated to "Search sessions").
- gofmt -l, go vet ./..., GOOS=linux go vet -tags nogui ./...,
  GOOS=windows go vet ./..., the builds: clean. go test -tags nogui
  ./... at load ~25-60 (other sessions' runs): every package passed but
  internal/agent and internal/gateway, which hit the 30m timeout; run
  again alone, agent passed and gateway's only red was
  TestOTelWaterfallIncludesUnbilledFallback, filed as #1794 (passes
  alone, -count=3).
- Real data, read-only (a temporary probe, not committed, pointed at
  the owner's ~/.claude and ~/.codex; one worker, 8s, load ~50):
  Claude, 58 sessions / 3 GB: before the line filter one 1.3 GB session
  took the whole 8s ("redis": 1 of 58); after, all 58 in 4.7s ("redis",
  13 hits), 7.4s ("gateway session"), 2.8s (no match). Codex, 11534
  sessions / 65 GB: 245-656 sessions in 8s either way, which is what
  the cut note ("latest n of total") is for.

Not verified: the endpoint and page against a real recorded gateway
store (only fixtures and temp homes); the timings above were taken on
a machine at load ~50 and vary run to run.
2026-10-12 22:29:46 +08:00

169 lines
9.9 KiB
JavaScript

// Run with Node's test runner and Playwright on the module path; see README.md.
// The Sessions page's filter finds a session by what was said in it, not only
// by its title, folder, id or model (YOU on Discord: the gateway's sessions
// are named ses_…, and their words are how they are remembered). The page
// asks /api/sessions/search once typing pauses, a new query cancels the one
// in flight, one letter asks nothing, and each session found shows the words
// round its match, the match marked. A search cut short, or of an agent
// whose own files can't be read, says so. In every language, Chromium and
// WebKit, wide and narrow.
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 gw = (id, title, min) => ({
agent: "pi", id, cwd: "", title, gateway: true, start: at(min + 5), last: at(min), models: [{ model: "m" }], size: 2048, deletable: true,
});
// what each session said, as the server would search it
const said = {
"ses_01": "rename foo to bar in the parser",
"ses_02": "why does the build fail? The Redis client times out after 30 seconds on every request to the cache, and only in CI, never on a laptop",
"ses_03": "write a haiku about Kafka and autumn",
};
function serve(lang, log) {
const state = { agents: [], profiles: [], settings: { lang, theme: "light" } };
const sessions = [gw("ses_03", "write a haiku about Kafka and autumn", 1), gw("ses_02", "why does the build fail?", 5), gw("ses_01", "rename foo to bar in the parser", 9)];
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:${JSON.stringify(lang)},theme:"light",web:true};` });
if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" });
if (url.pathname === "/api/state") return json(state);
if (url.pathname === "/api/plugins") return json({ plugins: [] });
if (url.pathname === "/api/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") {
return json({
agents: [{ agent: "pi", count: sessions.length, deletable: true, name: "Pi", icon: "pi" }],
agent: "pi", sessions, terminal: false, trash: [], trashDir: "~/trash", recording: true, recorded: true,
});
}
if (url.pathname === "/api/sessions/search") {
const q = url.searchParams.get("q");
log.push({ agent: url.searchParams.get("agent"), q });
// long enough for the next keystroke to land while it is out
await new Promise((r) => setTimeout(r, log.slow ? 900 : 250));
const hits = [];
for (const [id, text] of Object.entries(said)) {
const i = text.toLowerCase().indexOf(q);
if (i >= 0) {
const after = text.slice(i + q.length);
hits.push({ id, role: "user", kind: "text", before: text.slice(0, i), match: text.slice(i, i + q.length), after: after.length > 60 ? after.slice(0, 60) + "…" : after });
}
}
return route.fulfill({ json: { hits, searched: log.cut ? 2 : 3, total: 3, cut: !!log.cut } }).catch(() => {});
}
if (url.pathname.startsWith("/api/")) return json({});
const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname);
const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)];
await route.fulfill({ body: await fs.readFile(file).catch(() => ""), contentType });
};
}
const KEYS = [
"Search sessions", "Searching what was said…", "Searched what was said in the latest {n} of {total} sessions.",
"Couldn't search what was said: {error}",
"{agent}'s own files of its sessions can't be read here, so only what magpie recorded through the gateway is searched.",
];
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
test(`${engine}: the filter finds sessions by what was said`, async (t) => {
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
t.after(() => browser.close());
for (const [lang, width] of [["en", 1100], ["zh", 1100], ["zh-TW", 560], ["ja", 560], ["de", 420]]) {
await t.test(`${lang} at ${width}`, async () => {
const context = await browser.newContext({ viewport: { width, height: 700 }, reducedMotion: "reduce" });
const page = await context.newPage();
page.setDefaultTimeout(5000);
const errors = [];
page.on("pageerror", (e) => errors.push(e.message));
const aborted = [];
page.on("requestfailed", (r) => { if (r.url().includes("/api/sessions/search")) aborted.push(new URL(r.url()).searchParams.get("q")); });
const log = [];
await page.route("**/*", serve(lang, log));
await page.goto("http://magpie.test/?view=providers");
await page.locator('#nav [data-view="sessions"]').first().click();
const view = page.locator("#view-sessions");
const row = (id) => view.locator(`.row.sm-sess[data-id="${id}"]`);
await row("ses_03").waitFor();
const filter = view.locator(".sm-filter");
const tr = (k, v) => page.evaluate(([k, v]) => t(k, v), [k, v]);
// a gateway session is titled by what it was asked, its id beside
assert.equal(await row("ses_02").locator(".name").textContent(), "why does the build fail?");
assert.match(await row("ses_02").locator(".sub").first().textContent(), /ses_02/);
assert.equal(await filter.getAttribute("placeholder"), await tr("Search sessions"));
// one letter asks nothing; typing asks once, when it pauses
await filter.pressSequentially("r", { delay: 20 });
await page.waitForTimeout(500);
assert.equal(log.length, 0, "one letter is no search");
await filter.pressSequentially("edis", { delay: 40 });
await view.locator(".sm-search-note").waitFor();
assert.equal(await view.locator(".sm-search-note").textContent(), await tr("Searching what was said…"));
await row("ses_02").locator(".sm-hit mark").waitFor();
assert.deepEqual(log.map((x) => x.q), ["redis"], "one request for the word typed");
assert.equal(log[0].agent, "pi");
assert.equal(await row("ses_02").locator(".sm-hit mark").textContent(), "Redis");
assert.equal(await row("ses_03").count(), 0, "a session that didn't say it is left out");
assert.equal(await view.locator(".sm-search-note").count(), 0, "nothing more to say once found");
// the words round it stay on one line, inside the page
const fit = await row("ses_02").evaluate((r) => {
const hit = r.querySelector(".sm-hit");
return { lines: Math.round(hit.getBoundingClientRect().height / parseFloat(getComputedStyle(hit).lineHeight || "15")), right: hit.getBoundingClientRect().right, page: document.querySelector("#view-sessions").getBoundingClientRect().right, over: document.documentElement.scrollWidth > innerWidth };
});
assert.ok(fit.right <= fit.page + 1 && !fit.over, `the snippet overflows: ${JSON.stringify(fit)}`);
// a new query cancels the one in flight, and its answer never shows
log.slow = true;
await filter.fill("parser");
await page.waitForTimeout(450); // past the pause: its request is out
await filter.fill("kafka");
await row("ses_03").locator(".sm-hit mark").waitFor();
await page.waitForTimeout(1000);
assert.deepEqual(log.slice(1).map((x) => x.q), ["parser", "kafka"]);
assert.deepEqual(aborted, ["parser"], "the earlier search was cancelled");
assert.equal(await row("ses_01").count(), 0, "the cancelled search's answer isn't shown");
assert.equal(await row("ses_03").locator(".sm-hit mark").textContent(), "Kafka");
// what a title or id matches is shown at once, before any answer
log.slow = false;
log.cut = true;
await filter.fill("ses_01");
await row("ses_01").waitFor({ timeout: 200 });
// a search cut short says how far it read
await view.locator(".sm-search-note").filter({ hasText: await tr("Searched what was said in the latest {n} of {total} sessions.", { n: 2, total: 3 }) }).waitFor();
// nothing found anywhere: no session matches, after the search
await filter.fill("zebra");
await view.locator(".empty-state").waitFor();
assert.equal(await view.locator(".empty-state").textContent(), await tr("No session matches."));
// Escape clears it and the list is whole again
await filter.press("Escape");
await row("ses_01").waitFor();
assert.equal(await view.locator(".sm-hit").count(), 0);
assert.equal(await view.locator(".sm-search-note").count(), 0);
if (lang !== "en") {
const missing = await page.evaluate(([lang, keys]) => keys.filter((k) => !I18N[lang]?.[k]), [lang, KEYS]);
assert.deepEqual(missing, [], `${lang} has every string`);
}
if (process.env.SCREENSHOT_DIR) {
await filter.fill("redis");
await row("ses_02").locator(".sm-hit mark").waitFor();
await fs.mkdir(process.env.SCREENSHOT_DIR, { recursive: true });
await page.screenshot({ path: path.join(process.env.SCREENSHOT_DIR, `${engine}-${lang}-${width}-sessions-search.png`) });
}
assert.deepEqual(errors, []);
await context.close();
});
}
});
}