From 1aeed754a21c6cc9f1bb652cb54296db6091d076 Mon Sep 17 00:00:00 2001 From: ework-agent Date: Wed, 14 Oct 2026 09:56:57 +0800 Subject: [PATCH 1/4] feat: download full session report as Markdown + PNG image MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Add one-click download of the complete session-detail report from the web UI detail page (基本信息 / 用量统计 / 上下文轨迹 / 缓存接缝事件 / 体稳定性 / 缓存经济学): - src/web/report.ts: pure, dependency-free, DOM-free builders rendering all sections as Markdown and as a closed-vector SVG (rasterizable to PNG by the browser without any new dependency). - src/server/admin.ts: new loopback-only GET /__bili/session-report (?session=&format=md|svg&mask=on|off&lang=zh|en), mirroring the existing /__bili/cache-report endpoint. Title/label (user PII) masked by default; upstream host + metrics kept for diagnosis. - src/web/client.ts: two buttons (Markdown / PNG) after the page header; fetches the server render and rasterizes SVG->PNG via native canvas. - i18n zh/en keys + tests/session-report.test.ts (8 tests). Closes #3057 --- src/server/admin.ts | 27 +++ src/web/client.ts | 55 +++++ src/web/i18n.ts | 16 ++ src/web/report.ts | 402 +++++++++++++++++++++++++++++++++++ tests/session-report.test.ts | 100 +++++++++ 5 files changed, 600 insertions(+) create mode 100644 src/web/report.ts create mode 100644 tests/session-report.test.ts diff --git a/src/server/admin.ts b/src/server/admin.ts index 9cd0e293f3..6dc7c8682e 100644 --- a/src/server/admin.ts +++ b/src/server/admin.ts @@ -29,6 +29,7 @@ import { formatUpstreamError, getUpstreamConnectionStatus, proxyDispatcher, reco import { detectStaleInstall } from "../update.js"; import { PACKAGE_NAME, VERSION, BUILD_COMMIT } from "../version.js"; import { buildOverview, buildSessionDetail, buildSessionList, buildSessionPage, handleConfigGet, handleConfigPut, hiddenEmptyCount, renderUI } from "../web/index.js"; +import { buildSessionReportMd, buildSessionReportSvg } from "../web/report.js"; import { queryLogLines } from "../web/logs-query.js"; import { buildDiagnostics } from "../web/diagnostics.js"; import { storageStatusWire } from "../storage/runtime-status.js"; @@ -156,6 +157,7 @@ export async function handleAdminRoute(req: http.IncomingMessage, res: http.Serv } if (req.method === "GET" && req.url === "/__bili/stats") return sendStats(res); if (req.method === "GET" && req.url?.startsWith("/__bili/cache-report")) return sendCacheReport(res, req.url); + if (req.method === "GET" && req.url?.startsWith("/__bili/session-report")) return sendSessionReport(res, req.url); if (req.method === "GET" && req.url === "/__bili/status") return sendStatus(res, opts); if (req.method === "GET" && req.url === "/__bili/resign") return sendResignStatus(res); if (req.method === "GET" && req.url === "/__bili/overview") return sendOverview(res, opts); @@ -1000,3 +1002,28 @@ async function sendWebSessionDetail(res: http.ServerResponse, url: string): Prom res.writeHead(200, { "content-type": "application/json" }); res.end(JSON.stringify(detail, null, 2)); } + +async function sendSessionReport(res: http.ServerResponse, url: string): Promise { + const q = new URL(url, "http://localhost").searchParams; + const id = q.get("session"); + if (!id) { + res.writeHead(400, { "content-type": "application/json" }); + res.end(JSON.stringify({ error: "missing session" })); + return; + } + const detail = await buildSessionDetail(id); + if (!detail) { + res.writeHead(404, { "content-type": "application/json" }); + res.end(JSON.stringify({ error: `unknown session: ${id}` })); + return; + } + const opts = { mask: q.get("mask") !== "off", lang: q.get("lang") === "en" ? "en" : "zh-CN" }; + if (q.get("format") === "svg") { + const r = buildSessionReportSvg(detail, opts); + res.writeHead(200, { "content-type": "application/json" }); + res.end(JSON.stringify({ svg: r.svg, w: r.w, h: r.h })); + return; + } + res.writeHead(200, { "content-type": "application/json" }); + res.end(JSON.stringify({ md: buildSessionReportMd(detail, opts) })); +} diff --git a/src/web/client.ts b/src/web/client.ts index fc45b16b37..60aea540a4 100644 --- a/src/web/client.ts +++ b/src/web/client.ts @@ -1176,6 +1176,7 @@ export const WEB_CLIENT = `(function () { const parts = []; parts.push('' + t("common.back") + ""); parts.push('

' + escapeHtml(d.title || d.label || d.id.slice(0, 16)) + '

' + escapeHtml(d.id) + "
" + detailBadges(d) + "
"); + parts.push('
' + t("det.report_note") + '
'); parts.push('
' + t("det.identity") + '
'); // Full title wraps in place, is hoverable (title attr) and carries a copy button. parts.push('
' + t("common.title") + '
' + (d.title ? escapeHtml(d.title) + ' " : '' + t("common.none") + "") + "
"); @@ -1514,6 +1515,7 @@ export const WEB_CLIENT = `(function () { bindHandoffActions(d); bindBlocksActions(d); bindCacheReportActions(d); + bindSessionReportActions(d); const cc = $("session-conflicts-clear"); if (cc) { cc.addEventListener("click", async () => { @@ -1608,6 +1610,59 @@ export const WEB_CLIENT = `(function () { d.blockDetails.forEach((b) => { L.push(""); L.push(buildBlockMd(b)); }); return L.join("\\n"); } + // #3057 report export: MD/SVG render server-side (/__bili/session-report); the browser downloads MD and rasterizes the closed-vector SVG to PNG. + function downloadUrl(url, name) { + var a = document.createElement("a"); + a.href = url; a.download = name; + document.body.appendChild(a); a.click(); a.remove(); + setTimeout(function () { URL.revokeObjectURL(url); }, 4000); + } + function svgToPngBlob(svgStr, w, h) { + return new Promise(function (resolve, reject) { + var scale = Math.max(1, Math.min(2, 1600 / w)); + var outW = Math.round(w * scale), outH = Math.round(h * scale); + if (outH > 14000) { scale = 14000 / h; outW = Math.round(w * scale); outH = Math.round(h * scale); } + var img = new Image(); + var url = URL.createObjectURL(new Blob([svgStr], { type: "image/svg+xml;charset=utf-8" })); + img.onload = function () { + try { + var canvas = document.createElement("canvas"); + canvas.width = outW; canvas.height = outH; + var ctx = canvas.getContext("2d"); + ctx.fillStyle = "#ffffff"; ctx.fillRect(0, 0, outW, outH); + ctx.drawImage(img, 0, 0, outW, outH); + URL.revokeObjectURL(url); + canvas.toBlob(function (b) { b ? resolve(b) : reject(new Error("PNG encode failed")); }, "image/png"); + } catch (e) { URL.revokeObjectURL(url); reject(e); } + }; + img.onerror = function () { URL.revokeObjectURL(url); reject(new Error("SVG rasterize failed")); }; + img.src = url; + }); + } + function bindSessionReportActions(d) { + var mdBtn = $("sessrpt-md"), pngBtn = $("sessrpt-png"); + if (!mdBtn && !pngBtn) return; + var safeId = String(d.id).replace(/[^A-Za-z0-9._-]/g, "_"); + var base = "billion-context-report-" + safeId; + var q = "session=" + encodeURIComponent(d.id) + "&mask=on&lang=" + (locale === "en" ? "en" : "zh-CN"); + if (mdBtn) mdBtn.addEventListener("click", async function () { + busy(mdBtn, true); + try { + var r = await json("/__bili/session-report?format=md&" + q); + if (!r || typeof r.md !== "string") throw new Error("no report"); + downloadUrl(URL.createObjectURL(new Blob([r.md], { type: "text/markdown;charset=utf-8" })), base + ".md"); + } catch (e) { toast(t("toast.failed", { msg: e.message }), "err"); } finally { busy(mdBtn, false); } + }); + if (pngBtn) pngBtn.addEventListener("click", async function () { + busy(pngBtn, true); + try { + var r = await json("/__bili/session-report?format=svg&" + q); + if (!r || !r.svg) throw new Error("no report"); + var blob = await svgToPngBlob(r.svg, r.w || 920, r.h || 800); + downloadUrl(URL.createObjectURL(blob), base + ".png"); + } catch (e) { toast(t("toast.failed", { msg: e.message }), "err"); } finally { busy(pngBtn, false); } + }); + } function bindBlocksActions(d) { if (!d.blockDetails || !d.blockDetails.length) return; const cp = $("blocks-copy"); diff --git a/src/web/i18n.ts b/src/web/i18n.ts index ab9bd855ad..8e0ced233e 100644 --- a/src/web/i18n.ts +++ b/src/web/i18n.ts @@ -324,6 +324,14 @@ export const MESSAGES: Record> = { "det.block_inactive": "已归档", "det.blocks_download": "下载块 (.md)", "det.report_dl": "下载缓存报告 (.md)", + "det.report_md": "下载完整报告 · Markdown", + "det.report_png": "下载完整报告 · 图片(PNG)", + "det.report_note": "标题等隐私默认掩码", + "det.report_masked": "[已掩码]", + "det.rpt_input": "输入", + "det.rpt_cached": "已缓存", + "det.rpt_missed": "未命中", + "det.rpt_hit": "命中率", "det.blocks_copy_md": "复制 Markdown", "det.handoff": "会话交接文档", "det.handoff_hint": "与 bili export 相同的内容 —— 复制粘贴到新会话即可继续", @@ -783,6 +791,14 @@ export const MESSAGES: Record> = { "det.block_inactive": "inactive", "det.blocks_download": "download blocks (.md)", "det.report_dl": "download cache report (.md)", + "det.report_md": "full report · Markdown", + "det.report_png": "full report · image (PNG)", + "det.report_note": "title & other PII masked by default", + "det.report_masked": "[masked]", + "det.rpt_input": "input", + "det.rpt_cached": "cached", + "det.rpt_missed": "missed", + "det.rpt_hit": "hit %", "det.blocks_copy_md": "copy Markdown", "det.handoff": "Handoff document", "det.handoff_hint": "Same content as bili export — paste into a new session to continue", diff --git a/src/web/report.ts b/src/web/report.ts new file mode 100644 index 0000000000..11fa366073 --- /dev/null +++ b/src/web/report.ts @@ -0,0 +1,402 @@ +import { MESSAGES } from "./i18n.js"; + +// Dependency-free, DOM-free builders so they run in both the proxy (/__bili/session-report) +// and unit tests; title/label (user PII) masked by default, upstream host + metrics kept. +type Locale = "zh-CN" | "en"; + +export interface ReportOpts { + /** Mask title/label (user PII). Defaults to true. */ + mask?: boolean; + /** Output locale. Defaults to zh-CN. */ + lang?: string; +} + +/** Loose structural view of the session-detail payload the builders read. Every field is + * optional so callers may pass either the full WebSessionDetail or a partial fixture. */ +export interface ReportData { + id?: string; + title?: string; + label?: string; + protocol?: string; + upstreamOrigin?: string; + requests?: number; + inputTokens?: number; + cachedTokens?: number; + outputTokens?: number; + systemPromptTokens?: number; + contextTokens?: number; + contextWindow?: number; + contextTokensSource?: string; + contextBest?: { tokens?: number }; + retrieveCalls?: number; + retrieveHits?: number; + retrieveMisses?: number; + blockDetails?: Array<{ active?: boolean }>; + ledger?: ({ + totals?: { newContent?: number; compRepay?: number; ttlRepay?: number; residual?: number; balanced?: boolean }; + seam?: { + suspects?: number; + missed?: number; + abortCorrelated?: number; + providerSide?: { count?: number; missed?: number }; + rewinds?: { count?: number; missed?: number }; + events?: Array<{ seq?: number | string; at?: number; hitPct?: number; input?: number; lcpBytes?: number; msgIndex?: number | null }>; + }; + stability?: { paired?: number; equal?: number; diverged?: number; head?: number; append?: number; mid?: number; unknownOffset?: number }; + folds?: Array<{ seq?: number | null; at?: number; S?: number; sigma?: number; hPct?: number | null; T?: number }>; + lines?: Array<{ input?: number; cached?: number }>; + }) | null; +} + +export interface SvgReport { + svg: string; + w: number; + h: number; +} + +function tr(lang: string, key: string, args?: Record): string { + const loc: Locale = lang === "en" ? "en" : "zh-CN"; + let s = MESSAGES[loc][key] ?? key; + if (args) for (const [k, v] of Object.entries(args)) s = s.split("{" + k + "}").join(String(v)); + return s; +} + +function escXml(s: unknown): string { + return String(s == null ? "" : s) + .replace(/&/g, "&").replace(//g, ">") + .replace(/"/g, """).replace(/'/g, "'"); +} + +function truncStr(s: unknown, n: number): string { + const v = String(s == null ? "" : s); + return v.length > n ? v.slice(0, Math.max(1, n - 1)) + "…" : v; +} + +interface Fmt { + none: string; + W: (n: unknown) => string; + B: (n: unknown) => string; + DT: (ms: number) => string; + host: (u?: string) => string; +} + +function makeFmt(lang: string): Fmt { + const none = tr(lang, "common.none"); + const W = (n: unknown): string => { + if (n === null || n === undefined || isNaN(Number(n))) return none; + const v = Math.round(Number(n)); + const a = Math.abs(v); + if (a >= 1e9) return (v / 1e9).toFixed(2) + "B"; + if (a >= 1e6) return (v / 1e6).toFixed(1) + "M"; + if (a >= 1e4) return Math.round(v / 1e3) + "K"; + if (a >= 1e3) return (v / 1e3).toFixed(1) + "K"; + return String(v); + }; + const B = (n: unknown): string => { + if (n == null || isNaN(Number(n))) return none; + let x = Number(n); + const units = ["B", "KB", "MB", "GB", "TB"]; + let i = 0; + while (Math.abs(x) >= 1024 && i < units.length - 1) { x /= 1024; i++; } + return (i > 0 ? x.toFixed(1) : String(Math.round(x))) + " " + units[i]; + }; + const DT = (ms: number): string => { + const d = new Date(ms || 0); + const p = (v: number) => String(v).padStart(2, "0"); + return p(d.getMonth() + 1) + "-" + p(d.getDate()) + " " + p(d.getHours()) + ":" + p(d.getMinutes()); + }; + const host = (u?: string): string => { + if (!u) return ""; + try { return new URL(u).host; } catch { return u; } + }; + return { none, W, B, DT, host }; +} + +function reportTitle(d: ReportData, mask: boolean, lang: string): string { + const raw = d.title || d.label || ""; + if (!mask && raw) return raw; + if (raw) return tr(lang, "det.report_masked"); + return String(d.id ?? "").slice(0, 16); +} + +function readLedger(d: ReportData) { + const led = d.ledger ?? {}; + const tot = led.totals ?? null; + const seam = led.seam && typeof led.seam === "object" ? led.seam : null; + const st = led.stability && typeof led.stability === "object" ? led.stability : null; + const folds = Array.isArray(led.folds) ? led.folds : []; + const lines = Array.isArray(led.lines) ? led.lines : []; + const seamEvents = seam && Array.isArray(seam.events) ? seam.events.filter((e) => e && (e.at ?? 0) > 0) : []; + const ctxBest = (d.contextBest && d.contextBest.tokens) ? d.contextBest.tokens : (Number(d.contextTokens) || 0); + const win = Number(d.contextWindow) || 0; + return { led, tot, seam, st, folds, lines, seamEvents, ctxBest, win }; +} + +export function buildSessionReportMd(d: ReportData, opts: ReportOpts = {}): string { + const mask = opts.mask !== false; + const lang = opts.lang === "en" ? "en" : "zh-CN"; + const t = (k: string, a?: Record) => tr(lang, k, a); + const f = makeFmt(lang); + const { tot, seam, st, folds, lines, seamEvents, ctxBest, win } = readLedger(d); + const NL = String.fromCharCode(10); + const L: string[] = []; + L.push("# billion-context session report"); + L.push(""); + L.push("- generated: " + new Date().toISOString()); + L.push("- masking: " + (mask ? "on (title/label redacted)" : "off")); + L.push("- session id: " + (d.id ?? "")); + L.push(""); + L.push("## " + t("det.identity")); + L.push(""); + L.push("- title: " + reportTitle(d, mask, lang)); + if (d.label && d.label !== d.id) L.push("- label: " + (mask ? t("det.report_masked") : truncStr(d.label, 80))); + L.push("- protocol: " + (d.protocol || f.none)); + L.push("- upstream: " + (f.host(d.upstreamOrigin) || f.none)); + L.push("- requests: " + (d.requests != null ? d.requests : f.none)); + L.push("- context: " + f.W(ctxBest) + (win ? " / " + f.W(win) + " (" + (ctxBest / win * 100).toFixed(1) + "%)" : "") + (d.contextTokensSource === "estimate" ? " (estimate)" : "")); + if (Number(d.systemPromptTokens)) L.push("- system prompt: " + f.W(d.systemPromptTokens)); + if (Array.isArray(d.blockDetails)) L.push("- blocks: " + d.blockDetails.filter((b) => b.active).length + " active / " + d.blockDetails.length + " total"); + L.push("- compressions (folds): " + folds.length); + L.push(""); + L.push("## " + t("det.usage")); + L.push(""); + L.push("| metric | value |"); + L.push("|---|---|"); + L.push("| input tokens | " + f.W(Number(d.inputTokens) || 0) + " |"); + L.push("| cached tokens | " + f.W(Number(d.cachedTokens) || 0) + " |"); + L.push("| output tokens | " + f.W(Number(d.outputTokens) || 0) + " |"); + L.push("| cache hit % | " + ((Number(d.inputTokens) > 0) ? ((Number(d.cachedTokens) || 0) / Number(d.inputTokens) * 100).toFixed(1) + "%" : f.none) + " |"); + if ((Number(d.retrieveCalls) || 0) > 0) L.push("| retrieve calls | " + d.retrieveCalls + " (hits " + (Number(d.retrieveHits) || 0) + " / misses " + (Number(d.retrieveMisses) || 0) + ") |"); + L.push(""); + L.push("## " + t("det.trajectory")); + L.push(""); + if (!lines.length) { L.push(t("det.trajectory_empty")); L.push(""); } + else { + L.push("| # | input | cached | missed | hit % |"); + L.push("|---|---|---|---|---|"); + const cap = 500; + lines.slice(0, cap).forEach((ln, i) => { + const inp = Number(ln.input) || 0, cac = Number(ln.cached) || 0; + L.push("| " + (i + 1) + " | " + f.W(inp) + " | " + f.W(cac) + " | " + f.W(inp - cac) + " | " + (inp > 0 ? (cac / inp * 100).toFixed(1) + "%" : "-") + " |"); + }); + if (lines.length > cap) L.push("| … +" + (lines.length - cap) + " more | | | | |"); + L.push(""); + } + L.push("## ⚠ " + t("det.seam_events", { n: seamEvents.length })); + L.push(""); + if (seamEvents.length) { + L.push("| # | time | hit % | input | divergence |"); + L.push("|---|---|---|---|---|"); + seamEvents.forEach((ev) => { + L.push("| " + ev.seq + " | " + (ev.at ? f.DT(ev.at) : "-") + " | " + (typeof ev.hitPct === "number" ? ev.hitPct.toFixed(1) + "%" : "-") + " | " + f.W(ev.input || 0) + " | " + f.B(ev.lcpBytes || 0) + " @m" + (ev.msgIndex != null ? ev.msgIndex : "?") + " |"); + }); + L.push(""); + if (Number(seam!.missed) > 0) L.push("- attributed missed: " + f.W(seam!.missed) + (seam!.suspects ? " (suspects ×" + seam!.suspects + ")" : "")); + if (seam!.providerSide && Number(seam!.providerSide.missed) > 0) L.push("- provider-side: " + f.W(seam!.providerSide.missed)); + if (seam!.rewinds && Number(seam!.rewinds.missed) > 0) L.push("- rewinds: " + f.W(seam!.rewinds.missed)); + if (seam!.abortCorrelated) L.push("- abort-correlated: " + seam!.abortCorrelated); + } else L.push(t("common.empty")); + L.push(""); + L.push("## " + t("det.stab_title")); + L.push(""); + if (st && (Number(st.paired) || 0) > 0) { + L.push("- paired: " + st.paired + ", identical: " + (Number(st.equal) || 0) + ", diverged: " + (Number(st.diverged) || 0)); + const kinds: string[] = []; + if (st.head) kinds.push("head " + st.head); + if (st.append) kinds.push("append " + st.append); + if (st.mid) kinds.push("mid " + st.mid); + if (st.unknownOffset) kinds.push("unknown " + st.unknownOffset); + if (kinds.length) L.push("- divergence kinds: " + kinds.join(", ")); + } else L.push(t("common.empty")); + L.push(""); + L.push("## " + t("det.cache_econ")); + L.push(""); + if (tot) { + L.push("| component | tokens |"); + L.push("|---|---|"); + L.push("| " + t("det.ce_new") + " | " + f.W(tot.newContent || 0) + " |"); + L.push("| " + t("det.ce_comp") + " | " + f.W(tot.compRepay || 0) + " |"); + L.push("| " + t("det.ce_ttl") + " | " + f.W(tot.ttlRepay || 0) + " |"); + L.push("| " + t("det.ce_residual") + " | " + f.W(tot.residual || 0) + " |"); + L.push(""); + L.push("- balanced: " + (tot.balanced ? "yes" : "no")); + } else L.push(t("common.empty")); + if (folds.length) { + L.push(""); + L.push("### folds (" + folds.length + ")"); + L.push(""); + L.push("| # | time | S | σ | hit % | T |"); + L.push("|---|---|---|---|---|---|"); + folds.forEach((fd, i) => { L.push("| " + (fd.seq != null ? fd.seq : i + 1) + " | " + (fd.at ? f.DT(fd.at) : "-") + " | " + f.W(fd.S) + " | " + f.W(fd.sigma) + " | " + (fd.hPct == null ? "-" : fd.hPct.toFixed(1) + "%") + " | " + f.W(fd.T) + " |"); }); + } + return L.join(NL); +} + +export function buildSessionReportSvg(d: ReportData, opts: ReportOpts = {}): SvgReport { + const mask = opts.mask !== false; + const lang = opts.lang === "en" ? "en" : "zh-CN"; + const t = (k: string, a?: Record) => tr(lang, k, a); + const f = makeFmt(lang); + const { tot, seam, st, folds, lines, seamEvents, ctxBest, win } = readLedger(d); + const W = 920, PAD = 28; + const INK = "#1f2328", MUT = "#6e7681", LINEC = "#d0d7de", ACC = "#0969da", RED = "#cf222e", AMB = "#bf8700", SOFT = "#f6f8fa"; + const SANS = "ui-sans-serif,-apple-system,'Segoe UI',Roboto,Helvetica,Arial,sans-serif"; + const MONO = "ui-monospace,SFMono-Regular,Menlo,Consolas,monospace"; + const body: string[] = []; + let y = 0; + function txt(x: number, yy: number, s: string, opt?: { size?: number; weight?: string; color?: string; anchor?: string; mono?: boolean }): void { + opt = opt ?? {}; + body.push('' + escXml(s) + ""); + } + function section(title: string): void { + y += 30; + body.push(''); + txt(PAD + 14, y, title, { size: 14, weight: "bold" }); + y += 8; + } + function kv(label: string, value: string, mono?: boolean): void { + y += 19; + txt(PAD, y, label, { size: 12, color: MUT }); + txt(PAD + 150, y, value == null || value === "" ? f.none : String(value), { size: 12, mono: !!mono, weight: "500" }); + } + function statRow(items: Array<[string, string, string?]>): void { + const gap = 12, n = items.length, cw = (W - PAD * 2 - gap * (n - 1)) / n; + items.forEach((it, i) => { + const bx = PAD + i * (cw + gap); + body.push(''); + txt(bx + 12, y + 19, it[0], { size: 11, color: MUT }); + txt(bx + 12, y + 39, String(it[1]), { size: 16, weight: "bold", color: it[2] ?? INK, mono: true }); + }); + y += 56; + } + function tableHead(cols: Array<{ t: string; w: number }>): void { + y += 18; + let x = PAD; + body.push(''); + cols.forEach((c) => { txt(x + 4, y + 14, c.t, { size: 10.5, weight: "bold", color: MUT }); x += c.w; }); + y += 4; + body.push(''); + } + function tableRow(cells: string[], widths: number[]): void { + y += 17; + let x = PAD; + cells.forEach((c, i) => { txt(x + 4, y, c, { size: 11, mono: true }); x += widths[i]; }); + } + function noteLine(s: string, color?: string): void { y += 16; txt(PAD, y, s, { size: 11, color: color ?? MUT }); } + body.push(''); + txt(PAD, 36, String(d.id ?? ""), { size: 15, weight: "bold", mono: true }); + const subBits = [d.protocol ?? "", f.host(d.upstreamOrigin)].filter(Boolean).join(" · "); + txt(PAD, 57, subBits || f.none, { size: 12, color: MUT }); + txt(PAD, 78, t("det.identity") + ": " + truncStr(reportTitle(d, mask, lang), 60), { size: 12 }); + txt(W - PAD, 36, "generated " + new Date().toISOString().slice(0, 16).replace("T", " "), { size: 11, color: MUT, anchor: "end" }); + if (mask) txt(W - PAD, 57, t("det.report_note"), { size: 11, color: AMB, anchor: "end" }); + y = 96; + section(t("det.identity")); + kv(t("common.title"), truncStr(reportTitle(d, mask, lang), 48)); + if (d.label && d.label !== d.id) kv("label", truncStr(mask ? t("det.report_masked") : String(d.label), 48)); + kv(t("common.protocol"), d.protocol || f.none); + kv(t("common.upstream"), f.host(d.upstreamOrigin) || f.none); + kv(t("common.requests"), d.requests != null ? String(d.requests) : f.none, true); + kv(t("common.context"), f.W(ctxBest) + (win ? " / " + f.W(win) + " (" + (ctxBest / win * 100).toFixed(1) + "%)" : "") + (d.contextTokensSource === "estimate" ? " (est.)" : ""), true); + if (Number(d.systemPromptTokens)) kv("system prompt", f.W(d.systemPromptTokens), true); + if (Array.isArray(d.blockDetails)) kv("blocks", d.blockDetails.filter((b) => b.active).length + " active / " + d.blockDetails.length + " total", true); + kv("compressions", String(folds.length), true); + section(t("det.usage")); + statRow([ + [t("ov.input_tokens"), f.W(Number(d.inputTokens) || 0)], + [t("ov.cached_tokens"), f.W(Number(d.cachedTokens) || 0)], + [t("ov.output_tokens"), f.W(Number(d.outputTokens) || 0)], + [t("det.rpt_hit"), (Number(d.inputTokens) > 0) ? ((Number(d.cachedTokens) || 0) / Number(d.inputTokens) * 100).toFixed(1) + "%" : f.none, ACC] + ]); + if ((Number(d.retrieveCalls) || 0) > 0) noteLine("retrieve " + d.retrieveCalls + " (hits " + (Number(d.retrieveHits) || 0) + " / misses " + (Number(d.retrieveMisses) || 0) + ")"); + section(t("det.trajectory")); + if (!lines.length) noteLine(t("det.trajectory_empty")); + else { + const CH = 150, PL = 52, PR = 14, PT = 8, PB = 20; + const top = y + PT, bot = y + CH - PB, left = PAD + PL, right = W - PAD - PR; + const vals = lines.map((l) => Number(l.input) || 0); + let maxV = Math.max.apply(null, vals.concat(win ? [win] : []).concat(Number(d.systemPromptTokens) ? [Number(d.systemPromptTokens)] : [])); + if (!(maxV > 0)) maxV = 1; + const Xp = (i: number) => left + (lines.length <= 1 ? (right - left) / 2 : (i / (lines.length - 1)) * (right - left)); + const Yp = (v: number) => bot - (v / maxV) * (bot - top); + body.push(''); + body.push(''); + [maxV, maxV / 2, 0].forEach((v) => { + const yy = Yp(v); + body.push(''); + txt(left - 8, yy + 3, f.W(v), { size: 9.5, color: MUT, anchor: "end", mono: true }); + }); + let areaPts = left + "," + bot + " "; + lines.forEach((l, i) => { areaPts += Xp(i).toFixed(1) + "," + Yp(Number(l.cached) || 0).toFixed(1) + " "; }); + areaPts += right + "," + bot; + body.push(''); + let linePts = ""; + lines.forEach((l, i) => { linePts += Xp(i).toFixed(1) + "," + Yp(Number(l.input) || 0).toFixed(1) + " "; }); + body.push(''); + if (win && win <= maxV) { + const wy = Yp(win); + body.push(''); + txt(right, wy - 4, t("det.legend_window") + " " + f.W(win), { size: 9.5, color: RED, anchor: "end" }); + } + y += CH + 8; + const cols = [{ t: "#", w: 56 }, { t: t("det.rpt_input"), w: 180 }, { t: t("det.rpt_cached"), w: 180 }, { t: t("det.rpt_missed"), w: 180 }, { t: t("det.rpt_hit"), w: W - PAD * 2 - 596 }]; + tableHead(cols); + const show = lines.slice(-12); + const off = lines.length - show.length; + show.forEach((ln, i) => { + const inp = Number(ln.input) || 0, cac = Number(ln.cached) || 0; + tableRow([String(off + i + 1), f.W(inp), f.W(cac), f.W(inp - cac), inp > 0 ? (cac / inp * 100).toFixed(1) + "%" : "-"], [cols[0].w, cols[1].w, cols[2].w, cols[3].w, cols[4].w]); + }); + if (lines.length > 12) noteLine("… +" + (lines.length - 12) + " earlier calls (see .md)"); + } + section("⚠ " + t("det.seam_events", { n: seamEvents.length })); + if (!seamEvents.length) noteLine(t("common.empty")); + else { + const scols = [{ t: "#", w: 48 }, { t: t("det.fold_time"), w: 120 }, { t: t("det.rpt_hit"), w: 90 }, { t: t("det.rpt_input"), w: 110 }, { t: "divergence", w: W - PAD * 2 - 368 }]; + tableHead(scols); + seamEvents.slice(0, 10).forEach((ev) => { + tableRow([String(ev.seq), ev.at ? f.DT(ev.at) : "-", typeof ev.hitPct === "number" ? ev.hitPct.toFixed(1) + "%" : "-", f.W(ev.input || 0), f.B(ev.lcpBytes || 0) + " @m" + (ev.msgIndex != null ? ev.msgIndex : "?")], [scols[0].w, scols[1].w, scols[2].w, scols[3].w, scols[4].w]); + }); + if (seamEvents.length > 10) noteLine("… +" + (seamEvents.length - 10) + " more (see .md)"); + if (Number(seam!.missed) > 0) noteLine("attributed missed " + f.W(seam!.missed) + (seam!.suspects ? " (×" + seam!.suspects + ")" : ""), RED); + if (seam!.providerSide && Number(seam!.providerSide.missed) > 0) noteLine("provider-side " + f.W(seam!.providerSide.missed), AMB); + if (seam!.rewinds && Number(seam!.rewinds.missed) > 0) noteLine("rewinds " + f.W(seam!.rewinds.missed), MUT); + } + section(t("det.stab_title")); + if (st && (Number(st.paired) || 0) > 0) { + statRow([ + ["paired", String(st.paired)], + ["identical", String(Number(st.equal) || 0)], + ["diverged", String(Number(st.diverged) || 0), (Number(st.mid) > 0) ? RED : INK] + ]); + const kk: string[] = []; + if (st.head) kk.push("head " + st.head); + if (st.append) kk.push("append " + st.append); + if (st.mid) kk.push("mid " + st.mid); + if (st.unknownOffset) kk.push("unknown " + st.unknownOffset); + if (kk.length) noteLine(kk.join(" · ")); + } else noteLine(t("common.empty")); + section(t("det.cache_econ")); + if (tot) { + statRow([ + [t("det.ce_new"), f.W(tot.newContent || 0)], + [t("det.ce_comp"), f.W(tot.compRepay || 0)], + [t("det.ce_ttl"), f.W(tot.ttlRepay || 0)], + [t("det.ce_residual"), f.W(tot.residual || 0), tot.balanced ? INK : AMB] + ]); + if (folds.length) { + const fcols = [{ t: "#", w: 48 }, { t: t("det.fold_time"), w: 120 }, { t: "S", w: 120 }, { t: "σ", w: 120 }, { t: t("det.rpt_hit"), w: 110 }, { t: "T", w: W - PAD * 2 - 518 }]; + tableHead(fcols); + folds.slice(-15).forEach((fd, i) => { + tableRow([String(fd.seq != null ? fd.seq : i + 1), fd.at ? f.DT(fd.at) : "-", f.W(fd.S), f.W(fd.sigma), fd.hPct == null ? "-" : fd.hPct.toFixed(1) + "%", f.W(fd.T)], [fcols[0].w, fcols[1].w, fcols[2].w, fcols[3].w, fcols[4].w, fcols[5].w]); + }); + if (folds.length > 15) noteLine("… +" + (folds.length - 15) + " earlier folds (see .md)"); + } + } else noteLine(t("common.empty")); + y += 24; + const H = Math.ceil(y); + const svg = '' + + '' + + body.join("") + ""; + return { svg, w: W, h: H }; +} diff --git a/tests/session-report.test.ts b/tests/session-report.test.ts new file mode 100644 index 0000000000..7d14721377 --- /dev/null +++ b/tests/session-report.test.ts @@ -0,0 +1,100 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { buildSessionReportMd, buildSessionReportSvg } from "../src/web/report.ts"; + +const D = { + id: "01a11bc7-2e24-763f-a52d-e2a87b07145d", + title: "SECRET-TITLE-XYZ", + protocol: "anthropic", + upstreamOrigin: "https://api.example.com/v1", + requests: 42, + inputTokens: 900000, + cachedTokens: 720000, + outputTokens: 30000, + systemPromptTokens: 8000, + contextTokens: 120000, + contextWindow: 200000, + contextTokensSource: "estimate", + blockDetails: [{ active: true }, { active: true }, { active: false }], + ledger: { + totals: { newContent: 100000, compRepay: 20000, ttlRepay: 5000, residual: 1234, balanced: true }, + seam: { + suspects: 2, + missed: 3000, + abortCorrelated: 1, + providerSide: { count: 1, missed: 100 }, + rewinds: { count: 1, missed: 50 }, + events: [{ seq: 3, at: 1700000000000, hitPct: 42.5, input: 80000, lcpBytes: 2048, msgIndex: 7 }] + }, + stability: { paired: 40, equal: 30, diverged: 10, head: 2, append: 5, mid: 3, unknownOffset: 0 }, + folds: [{ seq: 1, at: 1700000100000, S: 50000, sigma: 1200, hPct: 80.2, T: 120 }], + lines: [ + { input: 10000, cached: 5000 }, + { input: 20000, cached: 18000 }, + { input: 30000, cached: 28000 } + ] + } +}; + +// The only non-deterministic byte is the generation timestamp; neutralize it before comparing. +const stripTs = (s: string) => s.replace(/\d{4}-\d{2}-\d{2}[ T]\d{2}:\d{2}(?::\d{2})?(?:\.\d+Z)?/g, "TS"); + +test("markdown: masks title/label by default but keeps upstream host for diagnosis", () => { + const md = buildSessionReportMd(D); + assert.ok(!md.includes("SECRET-TITLE-XYZ"), "title must be masked by default"); + assert.ok(md.includes("api.example.com"), "upstream host is diagnostic and must stay visible"); +}); + +test("markdown: mask=false reveals the raw title", () => { + const md = buildSessionReportMd(D, { mask: false }); + assert.ok(md.includes("SECRET-TITLE-XYZ")); +}); + +test("markdown: renders every section heading + key metrics (zh default)", () => { + const md = buildSessionReportMd(D); + for (const h of ["# billion-context session report", "基本信息", "用量统计", "上下文轨迹", "缓存经济学"]) { + assert.ok(md.includes(h), "missing section: " + h); + } + assert.ok(md.includes("900K"), "input tokens formatted"); + assert.ok(md.includes("720K"), "cached tokens formatted"); + assert.ok(md.includes("42.5%"), "seam event hit % present"); + assert.ok(md.includes("diverged: 10"), "stability divergence present"); +}); + +test("markdown: locale switching changes headings (zh vs en)", () => { + const zh = buildSessionReportMd(D, { lang: "zh-CN" }); + const en = buildSessionReportMd(D, { lang: "en" }); + assert.notEqual(zh, en); + assert.ok(zh.includes("基本信息")); + assert.ok(!en.includes("基本信息"), "en output must not contain the zh identity heading"); + assert.ok(en.includes("api.example.com"), "host kept in en too"); +}); + +test("markdown: deterministic modulo timestamp", () => { + assert.equal(stripTs(buildSessionReportMd(D)), stripTs(buildSessionReportMd(D))); +}); + +test("svg: well-formed closed vector, correct dims, masks title, keeps host", () => { + const r = buildSessionReportSvg(D); + assert.ok(r.svg.startsWith('")); + assert.equal(r.w, 920); + assert.ok(r.h > 0); + assert.ok(r.svg.includes('width="920"') && r.svg.includes(`height="${r.h}"`)); + assert.ok(!r.svg.includes("SECRET-TITLE-XYZ"), "title masked in svg"); + assert.ok(r.svg.includes("api.example.com")); + assert.ok(!r.svg.includes(""), "must stay a closed vector doc"); +}); + +test("svg: mask=false reveals title; deterministic modulo timestamp", () => { + assert.ok(buildSessionReportSvg(D, { mask: false }).svg.includes("SECRET-TITLE-XYZ")); + assert.equal(stripTs(buildSessionReportSvg(D).svg), stripTs(buildSessionReportSvg(D).svg)); +}); + +test("empty payload: no crash, still emits a titled report", () => { + const md = buildSessionReportMd({}); + assert.ok(typeof md === "string" && md.length > 0); + assert.ok(md.includes("# billion-context session report")); + const sv = buildSessionReportSvg({}); + assert.ok(sv.svg.startsWith("") && sv.w === 920 && sv.h > 0); +}); From 662c08e0c5c06c2d7cde7bc9b3491353c2d7ee1c Mon Sep 17 00:00:00 2001 From: ework-agent Date: Wed, 14 Oct 2026 10:24:29 +0800 Subject: [PATCH 2/4] fix(web): drop duplicated warning glyph in session-report seam heading MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The det.seam_events i18n strings already start with a warning glyph in both locales, so the hard-coded prefix rendered '⚠ ⚠ 缓存接缝事件' / '⚠ ⚠ Cache-seam events' in both the Markdown and SVG reports. Remove the prefix from both render paths and pin it with a regression assertion. Found while reviewing #3099. --- src/web/report.ts | 4 ++-- tests/session-report.test.ts | 2 ++ 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/src/web/report.ts b/src/web/report.ts index 11fa366073..4e41f9b61a 100644 --- a/src/web/report.ts +++ b/src/web/report.ts @@ -182,7 +182,7 @@ export function buildSessionReportMd(d: ReportData, opts: ReportOpts = {}): stri if (lines.length > cap) L.push("| … +" + (lines.length - cap) + " more | | | | |"); L.push(""); } - L.push("## ⚠ " + t("det.seam_events", { n: seamEvents.length })); + L.push("## " + t("det.seam_events", { n: seamEvents.length })); L.push(""); if (seamEvents.length) { L.push("| # | time | hit % | input | divergence |"); @@ -349,7 +349,7 @@ export function buildSessionReportSvg(d: ReportData, opts: ReportOpts = {}): Svg }); if (lines.length > 12) noteLine("… +" + (lines.length - 12) + " earlier calls (see .md)"); } - section("⚠ " + t("det.seam_events", { n: seamEvents.length })); + section(t("det.seam_events", { n: seamEvents.length })); if (!seamEvents.length) noteLine(t("common.empty")); else { const scols = [{ t: "#", w: 48 }, { t: t("det.fold_time"), w: 120 }, { t: t("det.rpt_hit"), w: 90 }, { t: t("det.rpt_input"), w: 110 }, { t: "divergence", w: W - PAD * 2 - 368 }]; diff --git a/tests/session-report.test.ts b/tests/session-report.test.ts index 7d14721377..8f2e639a1c 100644 --- a/tests/session-report.test.ts +++ b/tests/session-report.test.ts @@ -59,6 +59,8 @@ test("markdown: renders every section heading + key metrics (zh default)", () => assert.ok(md.includes("720K"), "cached tokens formatted"); assert.ok(md.includes("42.5%"), "seam event hit % present"); assert.ok(md.includes("diverged: 10"), "stability divergence present"); + assert.ok(md.includes("## ⚠ 缓存接缝事件 · 1"), "seam heading present"); + assert.ok(!md.includes("⚠ ⚠"), "no doubled warning glyph (i18n string already carries it)"); }); test("markdown: locale switching changes headings (zh vs en)", () => { From c60dd97a6df3dccc05f11358997f019441866288 Mon Sep 17 00:00:00 2001 From: ework-agent Date: Wed, 14 Oct 2026 10:38:32 +0800 Subject: [PATCH 3/4] fix(web): un-export internal-only types in session-report module The unused-exports gate (#1440 P6) fails on this branch: ReportOpts/ReportData/SvgReport in src/web/report.ts are only referenced within their own file yet declared as exports. Drop the leading 'export' per the gate's prescribed INTERNAL_ONLY fix. No behavior change: admin.ts and the tests import only the two buildSessionReport* functions. Branch also rebased onto current master (6887bbdf6, +#3094; no file overlap with this PR). Found while reviewing #3099. --- src/web/report.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/web/report.ts b/src/web/report.ts index 4e41f9b61a..1886f02947 100644 --- a/src/web/report.ts +++ b/src/web/report.ts @@ -4,7 +4,7 @@ import { MESSAGES } from "./i18n.js"; // and unit tests; title/label (user PII) masked by default, upstream host + metrics kept. type Locale = "zh-CN" | "en"; -export interface ReportOpts { +interface ReportOpts { /** Mask title/label (user PII). Defaults to true. */ mask?: boolean; /** Output locale. Defaults to zh-CN. */ @@ -13,7 +13,7 @@ export interface ReportOpts { /** Loose structural view of the session-detail payload the builders read. Every field is * optional so callers may pass either the full WebSessionDetail or a partial fixture. */ -export interface ReportData { +interface ReportData { id?: string; title?: string; label?: string; @@ -48,7 +48,7 @@ export interface ReportData { }) | null; } -export interface SvgReport { +interface SvgReport { svg: string; w: number; h: number; From 7f81e5425f27748e013adc7ad76b51f063a6b1e2 Mon Sep 17 00:00:00 2001 From: ework-agent Date: Wed, 14 Oct 2026 11:17:03 +0800 Subject: [PATCH 4/4] test(gates): cover report.ts in web-i18n ref scan + family-gate array allowlist MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit #3099 adds src/web/report.ts, which references i18n keys via t()/tr() that the dead-key scanner (page.ts+client.ts only) never sees, and slices line/fold arrays for table tails. Both are array/code-level constructs, not string cuts — same class as the existing client.ts/conflict-watch.ts allowlist entries. --- tests/text-safe.test.ts | 1 + tests/web-i18n.test.ts | 3 +++ 2 files changed, 4 insertions(+) diff --git a/tests/text-safe.test.ts b/tests/text-safe.test.ts index 1f093e6972..7d729446c9 100644 --- a/tests/text-safe.test.ts +++ b/tests/text-safe.test.ts @@ -175,6 +175,7 @@ test("family gate: no raw negative string slices outside the allowlist", () => { const allowlist = new Map([ ["src/conflict-watch.ts", [/events\.slice\(-10\)/]], // array receiver ["src/web/client.ts", [/conflicts\.slice\(-10\)/]], // array receiver (#2102 session-detail card) + ["src/web/report.ts", [/lines\.slice\(-12\)/, /folds\.slice\(-15\)/]], // array receiver (#3099 session-report tables) ["src/text-safe.ts", [/\.slice\(/]], // the clamped implementation itself ]); const srcDir = path.join(import.meta.dirname, "..", "src"); diff --git a/tests/web-i18n.test.ts b/tests/web-i18n.test.ts index 3f4f708277..cc7d448f8b 100644 --- a/tests/web-i18n.test.ts +++ b/tests/web-i18n.test.ts @@ -41,10 +41,13 @@ test("#1024: translate() interpolates vars and falls back to the key", () => { function collectRefs(): Set { const pageSrc = readFileSync(join(here, "..", "src", "web", "page.ts"), "utf8"); const clientSrc = readFileSync(join(here, "..", "src", "web", "client.ts"), "utf8"); + const reportSrc = readFileSync(join(here, "..", "src", "web", "report.ts"), "utf8"); // #3099 server-side report renderer const refs = new Set(); for (const m of pageSrc.matchAll(/data-i18n(?:-ph|-title)?="([\w.]+)"/g)) refs.add(m[1]); for (const m of pageSrc.matchAll(/zh\("([\w.]+)"\)/g)) refs.add(m[1]); for (const m of clientSrc.matchAll(/\bt\("([\w.]+)"/g)) refs.add(m[1]); + for (const m of reportSrc.matchAll(/\bt\("([\w.]+)"/g)) refs.add(m[1]); + for (const m of reportSrc.matchAll(/\btr\(\s*\w+,\s*"([\w.]+)"/g)) refs.add(m[1]); return refs; }