Files
plugins/packages/amp-usage/test/host.integration.mjs
T
ming_jiang 4b0aef5327 amp-usage: Amp usage page with background collection; day-card 0.3.1 (#1000)
Adds packages/amp-usage (@magpie-community/page-amp-usage 0.1.0). It is a magpie page that reads Amp's local thread files and the gateway's usage.jsonl and shows per-day usage. The service listens on loopback only and requires a per-start service token on every API call. The page that carries the token is served only to a navigation (Sec-Fetch-Mode). The gateway log is read incrementally from a saved offset, whole lines only, and is re-indexed on rotation. The UI words are in ui/words.js (en, zh).

Also bumps packages/day-card to 0.3.1.

Round 3 (13c1f33) adds three things:
- a test that bytes before the gateway-log offset are never re-read;
- ui.test.mjs, which checks that every error code the server can return has words in each language, and that an unknown code falls back;
- words.js, moved out of app.js, served at /words.js and included in the pack.

What ran, at 13c1f33 merged with main 14187408, on mica:
- amp-usage `node --test`: 47/47.
- `bun test packages/amp-usage packages/day-card`: 65 pass, 0 fail.
- `bun scripts/check.mjs`, all packages: ok.
- `npm pack --dry-run`: amp-usage 0.1.0 has 19 files including ui/words.js; day-card 0.3.1 has 17 files.
- Root `bun test` with a temp HOME: 8362 pass, 0 fail (8382 tests, 590 files).
- Render smoke in Chromium and WebKit at 1200 and 420px, en and zh: words.js loads, both languages show their own words, no page errors, no horizontal overflow.

Broken by hand, each run with node and bun:
- collector.mjs:102 made to re-read the whole file every scan: the new offset test goes red.
- `const cut = buf.length`, so a partial line is taken: red.
- Raw error codes shown instead of their words (`w.err[code] || code`): red.
- A zh string deleted: red.

Not tried:
- A real Amp account or the real `amp` CLI.
- Changing the auto-refresh default from 300 to 60 fails no test. The author left it untested and round 2 called it optional.

Rounds 1 and 2 also ran the 1M-line log probe (rss steady at about 363MB, scans of 70 to 114ms after the first), the bad-record and paging probes, and the full render matrix including dark mode.
2026-11-11 21:43:59 +08:00

98 lines
3.3 KiB
JavaScript

// Optional real-host test. All config, usage and session paths are isolated.
import { test } from "node:test";
import assert from "node:assert/strict";
import { spawn } from "node:child_process";
import { createServer } from "node:net";
import { mkdtemp, mkdir, writeFile, readFile, rm } from "node:fs/promises";
import { join } from "node:path";
import { tmpdir } from "node:os";
import { createCollector } from "../lib/collector.mjs";
test(
"reports into an isolated real Magpie ledger without duplication",
{ skip: !process.env.MAGPIE_BINARY, timeout: 30000 },
async (t) => {
const root = await mkdtemp(join(tmpdir(), "amp-magpie-"));
const config = join(root, ".config", "magpie");
await mkdir(config, { recursive: true });
const port = await new Promise((resolve) => {
const server = createServer();
server.listen(0, "127.0.0.1", () => {
const port = server.address().port;
server.close(() => resolve(port));
});
});
await writeFile(
join(config, "settings.json"),
JSON.stringify({ port, sessionReads: { asked: true, all: false } }),
);
const child = spawn(process.env.MAGPIE_BINARY, ["serve"], {
env: {
PATH: process.env.PATH,
HOME: root,
USERPROFILE: root,
XDG_CONFIG_HOME: join(root, ".config"),
XDG_CACHE_HOME: join(root, ".cache"),
XDG_DATA_HOME: join(root, ".local", "share"),
MAGPIE_ADDR: `127.0.0.1:${port}`,
},
stdio: "ignore",
});
const stopped = new Promise((resolve) => child.once("exit", resolve));
t.after(async () => {
child.kill("SIGTERM");
await stopped;
await rm(root, { recursive: true, force: true });
});
const base = `http://127.0.0.1:${port}`;
let up = false;
for (let i = 0; i < 100; i++) {
try {
if (
(
await fetch(`${base}/v1/models`, {
signal: AbortSignal.timeout(500),
})
).ok
) {
up = true;
break;
}
} catch {}
if (child.exitCode !== null) break;
await new Promise((resolve) => setTimeout(resolve, 100));
}
assert.ok(up, "sandbox gateway starts");
const fixture = JSON.parse(
await readFile(new URL("fixtures/amp-local.json", import.meta.url)),
);
let now = Date.now();
const collector = await createCollector({
dataDir: join(config, "amp-usage"),
configDir: config,
options: { gatewayURL: base, settleSeconds: 30 },
clock: () => now,
source: async () => ({ threads: [fixture] }),
});
t.after(() => collector.close());
assert.equal((await collector.run()).pending, 1);
now += 31000;
const first = await collector.run();
assert.deepEqual(first.errors, []);
assert.equal(first.imported, 1);
assert.equal((await collector.run()).imported, 0);
const ledger = await (
await fetch(`${base}/v1/magpie/usage/requests?period=all&agent=amp`)
).json();
assert.equal(ledger.total, 1);
assert.equal(ledger.rows[0].agent, "amp");
assert.equal(ledger.rows[0].source, "reported");
assert.equal(ledger.input, fixture.messages[0].usage.inputTokens);
assert.equal(ledger.output, fixture.messages[0].usage.outputTokens);
assert.equal(
ledger.cache_read,
fixture.messages[0].usage.cacheReadInputTokens || 0,
);
},
);