Files
magpie/internal/gui/tests/recent-call-bodies.test.cjs
T
yetoneandxiaohei-info 3144868538 gui, gateway: the Providers and Gateway pages no longer download every recent call's bodies; an opened call reads its own (#1521, xiaohei-info)
GET /api/providers carried up to 40 recent gateway calls with their
request and response previews (up to 256 KB each) in gateway.calls,
and every provider write returned the same state. The Providers page
never shows them; only an opened row on Gateway does. With 40 calls of
~300 KB each, /api/providers was 21,019,635 bytes on origin/main.

Taken from xiaohei-info's patch (bb26b802, attached to #1521 as
external PRs are closed): providersState drops the bodies from the
calls it sends; GET /api/gateway/call returns one call's previews and
truncation flags with Cache-Control: no-store, 404 once it has left
the ring; the page fetches on open, dedupes a pending read, keeps
loaded bodies across refreshes, drops them with their call, shows
"Fetching…" and a "Try again" on a failed read; the strings in zh,
zh-TW, ja and de; the Go and Playwright tests; the gui-shell note.

Changed from the patch: a call is asked for by a number the gateway
gives it in the ring (Call.ID, Server.RecentCall), not by time, agent
and model, which two calls of one agent to one model can share. The
page keys a row by that id too (callRow), so two such calls no longer
open, or show the bodies of, each other. The tests ask with ids, and
the Playwright fixture gives two calls the same time, agent and model.

The route is on the same mux as the rest of the API, so magpie web's
key guard covers it, and the gateway's own port doesn't serve it. The
bodies are the ones the ring kept, masked as before (redacted runs
before capture). Nothing else reads gateway.calls' bodies: Routing
reads /api/gateway/trace, and the tray, TUI, CLI and /api/state don't
read the ring.

Run:
- Real use: magpie web built from origin/main and from this commit,
  sandbox HOME, a local upstream answering 300 KB, 40 calls of 300 KB.
  /api/providers 21,019,635 bytes before, 45,525 after (calls: 14,503
  bytes). Opening a row in Chromium and WebKit fetched
  /api/gateway/call once (524,412 bytes) and showed both bodies with
  their "first 256 KB" marks. Without the key: 401, also for a
  rebound Host; on the gateway port: 404; an evicted id: 404.
- TestRecentCallBodiesOnDemand fails with the bodies left in
  providersState ("providers must keep call metadata without sending
  bodies"), and with RecentCall ignoring the id ("the second call's
  detail isn't its own").
- recent-call-bodies.test.cjs fails on main's app.js, and with callRow
  keyed by time|agent|model again.
- GUI: gateway-fold, json-tree, phone-rows, recent-calls-more,
  request-archive, recent-call-bodies, sse-body: 24/24 in Chromium and
  24/24 in WebKit (en, zh, zh-TW, ja, de).
- gofmt -l clean; GOOS=linux and GOOS=windows go vet -tags nogui on
  internal/gui and internal/gateway.
- Full GUI suite: 5225 tests, 71 failures under load ~200, none in a
  gateway or recent-call file. The 20 files with failures, rerun on
  this commit and on origin/main: 54 and 58 fail; what fails on one
  only (Sessions checkbox colour, Sessions paging scroll, account
  dragging, ZCode block) moves between runs on both.
- go test -tags nogui ./...: every package ok on the rebased head.

Co-authored-by: xiaohei-info <14011749+xiaohei-info@users.noreply.github.com>
2026-10-11 03:12:46 +08:00

111 lines
7.2 KiB
JavaScript

// Recent calls send bodies only when expanded, independent of the S3 archive.
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_RECENT_ASSETS || path.resolve(__dirname, "../assets");
// the three calls share their agent and model, and two their second
const at = new Date(Date.now() - 1000).toISOString();
const calls = [0, 1, 2].map((i) => ({ id: 30 - i, time: i ? at : new Date().toISOString(), agent: "codex", model: "fixture/m", from: "chat", to: "chat", status: i === 0 ? 400 : 200, error: i === 0 ? "vendor declined" : "", ms: 900 }));
const bodies = { requestBody: '{"messages":[{"role":"user","content":"hello"}]}', responseBody: '{"reply":"world"}', requestTruncated: true, responseTruncated: true };
const words = {
en: { loading: "Fetching…", retry: "Try again" },
zh: { loading: "取回中…", retry: "重试" },
"zh-TW": { loading: "取回中…", retry: "重試" },
ja: { loading: "取得中…", retry: "再試行" },
de: { loading: "Wird abgerufen…", retry: "Erneut versuchen" },
};
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
for (const lang of Object.keys(words)) {
test(`${engine} ${lang}: recent bodies are fetched once on expansion, with retry and eviction`, 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" ? 1100 : 560, height: 900 }, reducedMotion: "reduce" });
page.setDefaultTimeout(5000);
const errors = [];
page.on("pageerror", (e) => errors.push(e.message));
const seen = [];
let shown = calls;
let release;
const pending = new Promise((resolve) => { release = resolve; });
await page.route("**/*", async (route) => {
const url = new URL(route.request().url());
const json = (data, status = 200) => route.fulfill({ json: data, status });
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/providers") return json({ presets: [], excluded: [], providers: [{ id: "fixture", name: "Fixture", icon: "generic", key: { set: true, masked: "fixture" }, models: [{ id: "m", name: "M", on: true }], agents: [] }], gateway: { running: true, window: true, mine: true, url: "http://127.0.0.1:3999", calls: shown, groups: [] } });
if (url.pathname === "/api/gateway/call") {
const c = calls.find((c) => url.searchParams.get("id") === String(c.id));
assert(c, "detail identifies the exact call");
seen.push(c.id);
if (c === calls[0]) { await pending; return json(bodies); }
if (c === calls[2]) return json({ error: "This request is no longer in the recent calls." }, 404);
if (seen.filter((id) => id === c.id).length === 1) return json({ error: "temporarily unavailable" }, 503);
return json({ requestBody: "", responseBody: "" });
}
if (url.pathname === "/api/groups") return json({ groups: [] });
if (url.pathname === "/api/plugins") return json({ plugins: [] });
if (url.pathname === "/api/gateway/trace") {
if (url.searchParams.has("wait")) await new Promise((r) => setTimeout(r, 1000));
return json({ mine: true, now: calls[0].time, seq: 1, totals: {}, routes: [] });
}
if (url.pathname === "/api/archive") assert.fail("recent bodies must not depend on the archive");
if (url.pathname.startsWith("/api/")) return json({});
const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname);
return route.fulfill({ body: await fs.readFile(file), contentType: { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml" }[path.extname(file)] });
});
await page.goto("http://magpie.test/?view=providers");
await page.locator("#providers .provider").first().waitFor();
assert.equal(seen.length, 0, "Providers never fetches bodies");
await page.locator('[data-view="gateway"]').first().click();
const rows = page.locator("#activity .call-item");
await rows.first().waitFor();
await page.locator("#foldConnect").click();
assert.equal(seen.length, 0, "the recent list is metadata only");
await rows.first().locator(".call").click();
await rows.first().getByText(words[lang].loading, { exact: true }).waitFor();
assert.equal(seen.length, 1);
assert.equal(await rows.first().locator(".call-body").count(), 0, "pending is not an empty body");
await rows.first().locator(".call").press("Enter");
await rows.first().locator(".call").press("Space");
assert.equal(seen.length, 1, "reopening a pending call does not duplicate it");
release();
await rows.first().locator(".call-body pre").first().waitFor();
assert((await rows.first().innerText()).includes("hello"));
assert((await rows.first().innerText()).includes("world"));
assert.equal(await rows.first().locator(".call-body-truncated").count(), 2);
await page.evaluate(() => loadProviders());
await rows.first().locator(".call-body pre").first().waitFor();
assert.equal(seen.length, 1, "a summary refresh preserves loaded detail");
await rows.first().locator(".call").click();
await rows.first().locator(".call").click();
assert.equal(seen.length, 1, "reopening a loaded body uses the in-memory copy");
await rows.first().locator(".call").click();
await rows.nth(1).locator(".call").click();
await rows.nth(1).getByText("temporarily unavailable", { exact: true }).waitFor();
await rows.nth(1).getByRole("button", { name: words[lang].retry, exact: true }).click();
await rows.nth(1).locator(".call-body pre").first().waitFor();
assert.equal(seen.length, 3);
assert.equal(await rows.nth(1).locator(".call-body code.empty").count(), 2);
await rows.nth(1).locator(".call").click();
await rows.nth(2).locator(".call").click();
const gone = await page.evaluate(() => t("This request is no longer in the recent calls."));
await rows.nth(2).getByText(gone, { exact: true }).waitFor();
assert.equal(await rows.nth(2).locator(".call-body").count(), 0, "an evicted call isn't an empty body");
await rows.nth(2).locator(".call").click();
shown = [calls[1]];
await page.evaluate(() => loadProviders());
shown = calls;
await page.evaluate(() => loadProviders());
await rows.first().locator(".call").click();
await page.waitForFunction(() => document.querySelector("#activity .call-item .call-body pre"));
assert.equal(seen.length, 5, "an evicted body's browser cache is discarded");
assert.deepEqual(errors, []);
});
}
}