peppa/packages/testkit/test/usage.test.ts
peppa-bot f3d10a4c25 PEP-243: платформа называется FORGE — название во всех текстах для людей и подсказках агентам, адрес forge.telecom.quest
«Peppa FACTORY» → «FORGE» в экранах, сообщениях, словарях en/kk, шаблоне и тестах; «Пеппа» → «FORGE» в подсказках
агентам и правилах; логотип, значок, версия кэша service worker; в словаре старые названия — в «Нельзя».
Внутренние имена (CLI peppa, PEPPA_*, MCP-сервер peppa, ключи PEP-N) не меняются. Второй адрес — в mac-route.sh.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-23 11:18:49 +05:00

96 lines
5.4 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// PEP-5: usage of sessions (statusLine + transcript) and subscription limit windows.
import assert from "node:assert/strict";
import { writeFileSync } from "node:fs";
import { join } from "node:path";
import { after, describe, test } from "node:test";
import { core, db, project, teardown } from "./helpers.ts";
after(teardown);
describe("Разбор данных Claude", () => {
test("statusLine: стоимость, контекст, окна (секунды и ISO, доля 0..1)", () => {
const d = core.parseStatusLine({
cost: { total_cost_usd: 0.42 },
context_window: { context_window_size: 200000, current_usage: { input_tokens: 40000, cache_read_input_tokens: 10000 } },
rate_limits: { five_hour: { used_percentage: 42, resets_at: 1_900_000_000 }, seven_day: { utilization: 0.18, resets_at: "2030-01-01T00:00:00Z" } },
model: { id: "claude-opus-4-6" },
});
assert.equal(d.costUsd, 0.42);
assert.deepEqual(d.context, { used: 50000, size: 200000, pct: 25 });
assert.deepEqual(d.windows.fiveHour, { pct: 42, resetsAt: 1_900_000_000_000 });
assert.equal(d.windows.sevenDay?.pct, 18);
assert.equal(d.windows.sevenDay?.resetsAt, Date.parse("2030-01-01T00:00:00Z"));
assert.equal(d.model, "claude-opus-4-6");
});
test("transcript: сумма по ответам без потоковых дублей", () => {
const path = join(process.env.PEPPA_HOME!, "t.jsonl");
const line = (id: string, input: number, output: number) => JSON.stringify({ type: "assistant", message: { id, model: "claude-sonnet-4-5", usage: { input_tokens: input, output_tokens: output, cache_read_input_tokens: 10 } } });
writeFileSync(path, [line("a", 100, 5), line("a", 100, 20), line("b", 50, 30), JSON.stringify({ type: "user", message: { content: "hi" } })].join("\n"));
const u = core.transcriptUsage(path)!;
assert.deepEqual(u.tokens, { input: 150, output: 50, cacheRead: 20, cacheWrite: 0 });
assert.equal(u.model, "claude-sonnet-4-5");
assert.equal(core.transcriptUsage(join(process.env.PEPPA_HOME!, "missing.jsonl")), null);
});
});
describe("Окна лимитов аккаунта", () => {
test("Данных нет — «нет данных»", async () => {
const accounts = await core.listAccountUsage(db);
assert.equal(accounts.length, 1);
assert.equal(accounts[0]!.fiveHour, null);
assert.match(core.describeAccount(accounts[0]!), /нет данных/);
});
test("Сброс прошёл — «сброшено», без процента", () => {
const now = Date.parse("2026-11-14T14:31:00");
const v = core.windowView({ pct: 90, resetsAt: Date.parse("2026-11-14T14:30:00") }, now)!;
assert.equal(v.reset, true);
assert.equal(v.pct, null);
assert.equal(core.windowView({ pct: 90, resetsAt: now + 60_000 }, now)!.pct, 90);
});
});
describe("Расход сессии из statusLine и transcript", () => {
test("Сессия сообщила расход", async () => {
const p = await project({ turns: [[{ usage: { input: 1200, output: 300, costUsd: 0.42, context: { used: 50000, size: 200000 }, fiveHour: 42, sevenDay: 18 } }, { say: "Готово." }]] });
const sid = await p.start();
await p.waitLog("statusline", (e) => e.ev === "statusline");
await p.waitStatus(sid, "idle");
const s = await core.getSession(db, sid);
const t = core.usageTotals(s.usage);
assert.equal(t.total, 1500);
assert.equal(t.costUsd, 0.42);
assert.equal(t.estimated, false);
assert.equal(t.context?.pct, 25);
// The status line shown in Claude names the story and the windows.
const line = String(p.log().find((e) => e.ev === "statusline")!.line);
assert.match(line, new RegExp(`FORGE ${p.taskKey}.*5ч 42%.*7д 18%`));
// Окна обновились — on this machine's login (no subscription).
const acc = (await core.listAccountUsage(db)).find((a) => a.subscriptionId === null)!;
assert.equal(acc.fiveHour?.pct, 42);
assert.equal(acc.sevenDay?.pct, 18);
assert.ok(acc.fiveHour?.resetsAt && acc.fiveHour.resetsAt.getTime() > Date.now());
assert.match(core.describeAccount(acc), /5 ч 42% \(сброс \d\d:\d\d\) · 7 д 18%/);
});
test("Стоимость неизвестна — оценка по прайсу с «≈»", async () => {
const p = await project({ turns: [] });
const s = await core.createSession(db, { projectId: (await p.task()).projectId, taskId: (await p.task()).id });
core.recordTranscriptUsage(db, s.id, "conv-1", { tokens: { input: 1_000_000, output: 0, cacheRead: 0, cacheWrite: 0 }, model: "claude-sonnet-4-5" });
const t = core.usageTotals((await core.getSession(db, s.id)).usage);
assert.equal(t.estimated, true);
assert.equal(t.costUsd!.toFixed(2), "3.00");
assert.equal(core.fmtCost(t), "≈ $3.00");
// A resumed conversation replaces its own total, another conversation adds up.
core.recordTranscriptUsage(db, s.id, "conv-1", { tokens: { input: 1_000_000, output: 100, cacheRead: 0, cacheWrite: 0 } });
core.recordTranscriptUsage(db, s.id, "conv-2", { tokens: { input: 10, output: 0, cacheRead: 0, cacheWrite: 0 } });
assert.equal(core.usageTotals((await core.getSession(db, s.id)).usage).total, 1_000_110);
});
test("Codex расход не сообщает — «нет данных»", () => {
assert.equal(core.describeUsage(null), "нет данных");
assert.equal(core.usageTotals({}).hasData, false);
});
});