Files
plugins/packages/page-harnessweight/test/harnessweight.test.mjs
T
webkuborandwebkubor 186b642f5a page-harnessweight 0.4.0: weigh each agent harness behind the gateway (#922)
A page plugin that compares the agent harnesses behind magpie's gateway by agent: input tokens, cache hits, failures, latency and estimated tool-definition size. A local service on 127.0.0.1:3496 reads magpie's usage ledger, and a read-only gateway hook writes tool counts, sizes and names to <config>/harnessweight/tools.jsonl.

Since the review at e0a0ae97 (7c6cd626a, then main merged in):
- Port 3492 -> 3496 (window-warmup has 3492; 3496 is used by no other package).
- Config dir: input.directory, then a cwd probe, then an absolute XDG_CONFIG_HOME, then ~/.config/magpie. A relative XDG is ignored.
- tools.jsonl is append-only. Past 8 MiB it is renamed to tools.jsonl.1. Age is checked at most hourly. Appends from two hosts are serialized by a cross-process lock that is skipped after 100 ms.
- MAGPIE_ADDR is honoured; the UI has English and Chinese (zh-TW and ja read English); preview PNGs dropped; /%E0 returns 400.

Run at 961b20e63c7e00e1dcca723bc2aa1d302f5dd9a3, in WSL (magpie-desktop, Node 22.23.4):
- node --test test/*.test.mjs in the package: 60 pass, 0 fail.
- bun scripts/check.mjs: clean (registry.json ok; the package has hooks, so check skips it).
- Probes against createHandler:
  - Origin null without the token: 403. With the token: 200.
  - A foreign Origin, a loopback Origin on another port, a file:// Origin, a rebound Host and a localhost Host on another port: all 403.
  - The index HTML carries the token and no ACAO.
  - ..%2f: 400. /%E0: 400.
- Rollover with 40-tool rows (1306 B each), 9.5 MiB written: the file peaked at 8,388,590 B (cap 8,388,608) with one rename to .1. Append p50 was 1.35 ms, p99 9.2 ms and max 24 ms.
- Portable dir: the hook's cwd probe and the service's input.directory gave the same tools.jsonl.
- Broken by hand:
  - Size rotation turned off: two rollover tests went red.
  - The Host check removed: the service test "other hosts, other origins and path traversal are refused" went red.

Co-authored-by: webkubor <29485642+webkubor@users.noreply.github.com>
2026-11-10 17:37:33 +08:00

128 lines
7.8 KiB
JavaScript

import { test } from "node:test"
import assert from "node:assert/strict"
import { mkdtemp, readFile, writeFile, appendFile } from "node:fs/promises"
import { tmpdir } from "node:os"
import { join } from "node:path"
import { measureTools } from "../lib/measure.mjs"
import { parseUsageLine, protocolOf, kindOf, createUsageReader } from "../lib/usage.mjs"
import { summarize } from "../lib/summarize.mjs"
import { onRequest, onResponse } from "../harnessweight.hooks.mjs"
const schema = { type: "object", properties: { path: { type: "string" } } }
test("measureTools reads all four protocol shapes", () => {
assert.equal(measureTools({ tools: [{ name: "Read", description: "d", input_schema: schema }] }).count, 1) // anthropic
assert.deepEqual(measureTools({ tools: [{ type: "function", function: { name: "shell", parameters: schema } }] }).names, ["shell"]) // chat
assert.deepEqual(measureTools({ tools: [{ type: "namespace", tools: [{ type: "function", name: "a" }, { type: "function", name: "b" }] }] }).names, ["a", "b"]) // responses namespace
assert.deepEqual(measureTools({ tools: [{ functionDeclarations: [{ name: "g1" }, { name: "g2" }] }] }).names, ["g1", "g2"]) // gemini
assert.equal(measureTools({}).count, 0)
assert.ok(measureTools({ tools: [{ name: "x", input_schema: schema }] }).bytes > 0)
})
test("usage lines: protocol, failure, cancel, clients", () => {
assert.equal(protocolOf("/v1/chat/completions → /v1/messages"), "anthropic")
assert.equal(protocolOf("/v1/chat/completions → /v1internal:streamGenerateContent?alt=sse"), "gemini")
const ok = parseUsageLine(JSON.stringify({ t: "2026-11-09T10:00:00+08:00", agent: "dsh", model: "m", status: 200, in: 10, cache_read: 90, out: 5 }))
assert.equal(ok.failed, false); assert.equal(ok.cacheRead, 90)
assert.equal(parseUsageLine(JSON.stringify({ t: 1, agent: "a", status: 502 })).failed, true)
const c = parseUsageLine(JSON.stringify({ t: 1, agent: "a", status: 499 }))
assert.equal(c.failed, false); assert.equal(c.cancelled, true)
assert.equal(parseUsageLine("{broken"), null)
assert.equal(kindOf("curl"), "client"); assert.equal(kindOf("ai"), "client"); assert.equal(kindOf("magpie"), "client"); assert.equal(kindOf("dsh"), "agent")
})
test("summarize groups by agent, hides clients, computes cache rate", () => {
const now = Date.now()
const r = (agent, inp, cr, failed = false) => ({ t: now - 1000, agent, model: "m", protocol: "anthropic", in: inp, out: 1, cacheRead: cr, cacheWrite: 0, credits: 0, ms: 100, ttft: 10, failed, cancelled: false })
const usage = [...Array(30)].map(() => r("a", 10, 90)).concat([...Array(30)].map(() => r("b", 50, 50)), [r("curl", 1, 0)])
const s = summarize({ usage, period: "7d", now })
assert.deepEqual(s.agents.map((x) => x.agent).sort(), ["a", "b"])
assert.equal(s.hiddenClients, 1)
const a = s.agents.find((x) => x.agent === "a")
assert.equal(a.cacheRate, 0.9)
assert.ok(s.insights.some((i) => i.kind === "cache"))
assert.equal(summarize({ usage, period: "7d", now, showClients: true }).agents.length, 3)
})
test("usage reader is incremental and skips a half-written last line", async () => {
const dir = await mkdtemp(join(tmpdir(), "al-"))
const f = join(dir, "usage.jsonl")
const line = (n) => JSON.stringify({ t: new Date().toISOString(), agent: "x" + n, status: 200, in: 1 }) + "\n"
await writeFile(f, line(1) + line(2) + '{"t":"half')
const r = createUsageReader(f)
await r.refresh(); assert.equal(r.rows().length, 2)
await appendFile(f, '-written"}\n' + line(3))
await r.refresh(); assert.equal(r.rows().length, 3)
})
test("hook never changes the request and writes only names and numbers", async () => {
const dir = await mkdtemp(join(tmpdir(), "al-"))
const body = { model: "m", messages: [{ role: "user", content: "SECRET PROMPT" }], tools: [{ name: "Read", input_schema: schema }] }
const ctx = { agent: "dsh", protocol: "anthropic", model: "m", options: { dataDir: dir } }
assert.equal(await onRequest(structuredClone(body), ctx), undefined)
await onResponse({ usage: { input_tokens: 3, output_tokens: 4, cache_read_input_tokens: 5 } }, { ...ctx, request: body, success: true })
const text = await readFile(join(dir, "tools.jsonl"), "utf8")
const row = JSON.parse(text.trim())
assert.equal(row.agent, "dsh"); assert.equal(row.tools, 1); assert.deepEqual(row.toolNames, ["Read"]); assert.equal(row.cacheRead, 5)
assert.ok(!text.includes("SECRET"))
})
test("insights ignore clients and use display names", () => {
const now = Date.now()
const r = (agent, inp, cr) => ({ t: now - 1000, agent, model: "m", protocol: "chat", in: inp, out: 1, cacheRead: cr, cacheWrite: 0, credits: 0, ms: 1, ttft: 1, failed: false, cancelled: false })
const usage = [...Array(30)].flatMap(() => [r("a", 10, 90), r("b", 50, 50), r("curl", 1, 0)])
const s = summarize({ usage, period: "7d", now, showClients: true, nameOf: (x) => ({ a: "Agent A" })[x] || x })
assert.ok(s.insights.every((i) => !i.text.includes("curl")))
assert.ok(s.insights.some((i) => i.text.includes("Agent A")))
})
test("brands come from the gateway and fall back softly", async () => {
const { createBrands } = await import("../lib/brands.mjs")
const ok = createBrands({}, async () => ({ ok: true, json: async () => ({ agents: [{ id: "claude", name: "Claude Code", icon: "claudecode-color" }, { id: "x", name: "X", icon: "generic" }] }) }))
await ok.refresh()
assert.deepEqual(ok.of("claude"), { name: "Claude Code", icon: "claudecode-color.svg" })
assert.equal(ok.of("x").icon, null)
assert.match(await ok.dataUri("claudecode-color.svg"), /^data:image\/svg\+xml;base64,/)
const down = createBrands({}, async () => { throw new Error("down") })
await down.refresh()
assert.equal(down.of("codex").name, "codex")
})
test("session length is measured, and runaway sessions are counted not measured", () => {
const now = Date.now()
const r = (agent, session, t) => ({ t, agent, model: "m", protocol: "chat", in: 1, out: 1, cacheRead: 0, cacheWrite: 0, ms: 1, ttft: 1, failed: false, cancelled: false, session })
const usage = [
r("a", "s1", now - 600e3), r("a", "s1", now - 300e3), // 5 minutes
r("a", "s2", now - 20_000e3), r("a", "s2", now - 10_000e3), // 10 seconds
r("a", "s3", now - 30 * 3600e3), r("a", "s3", now - 10e3), // open for a day: not measured
]
const s = summarize({ usage, period: "7d", now, showClients: true })
const a = s.agents.find((x) => x.agent === "a")
assert.equal(a.session.count, 3)
assert.equal(a.session.measured, 2)
assert.equal(a.session.open, 1)
assert.equal(a.session.median, 10_000_000)
assert.ok(a.session.longest <= 6 * 3600e3)
})
test("agents without a session id report no session length", () => {
const now = Date.now()
const usage = [{ t: now, agent: "a", model: "m", protocol: "chat", in: 1, out: 1, cacheRead: 0, cacheWrite: 0, ms: 1, ttft: 1, failed: false, cancelled: false }]
const s = summarize({ usage, period: "7d", now, showClients: true })
const a = s.agents.find((x) => x.agent === "a")
assert.equal(a.session.count, 0)
assert.equal(a.session.median, null)
})
test("the protocol each agent speaks is reported", () => {
const now = Date.now()
const usage = [
{ t: new Date(now).toISOString(), agent: "a", model: "m", ep: "/v1/messages", status: 200, in: 1, out: 1, cache_read: 0, cache_write: 0, ms: 1, ttft_ms: 1 },
{ t: new Date(now).toISOString(), agent: "a", model: "m", ep: "/v1/messages", status: 200, in: 1, out: 1, cache_read: 0, cache_write: 0, ms: 1, ttft_ms: 1 },
{ t: new Date(now).toISOString(), agent: "a", model: "m", ep: "/v1/responses", status: 200, in: 1, out: 1, cache_read: 0, cache_write: 0, ms: 1, ttft_ms: 1 },
].map((d) => parseUsageLine(JSON.stringify(d)))
const s = summarize({ usage, period: "7d", now, showClients: true })
const a = s.agents.find((x) => x.agent === "a")
assert.deepEqual(a.protocols.map((p) => p.name), ["anthropic", "responses"])
})