diff --git a/.gitattributes b/.gitattributes index bc168ec843..d59bfcb6e5 100644 --- a/.gitattributes +++ b/.gitattributes @@ -10,6 +10,9 @@ dsh.bundle.patch.yml text eol=lf # #2489: same failure class for the multi-line trajectory SVG golden. tests/golden/web-trajectory/*.svg text eol=lf +# #3484: same failure class for the multi-line hit-rate SVG golden. +tests/golden/web-hitrate/*.svg text eol=lf + # #1305 class again, new path: the Vertex fixture's manifest pins each artifact's # byte size and sha256, and turn-streaming.meta.json is 42 lines — Git-for-Windows' # autocrlf=true checked it out at 1941 bytes against the recorded 1899, so diff --git a/scripts/update-web-hitrate-golden.ts b/scripts/update-web-hitrate-golden.ts new file mode 100644 index 0000000000..6960cd607e --- /dev/null +++ b/scripts/update-web-hitrate-golden.ts @@ -0,0 +1,23 @@ +// #3484: regenerates tests/golden/web-hitrate/small-full.svg. +// Usage: node --import tsx scripts/update-web-hitrate-golden.ts +// Justify any content change in the PR body (wire-contract golden discipline, #1304). +process.env.TZ = "UTC"; +import { mkdirSync, writeFileSync } from "node:fs"; +import { dirname, join } from "node:path"; +import { seamEventsOf, smallFixture } from "../tests/web-trajectory-fixture.ts"; +import { runWebClient } from "../tests/web-trajectory-harness.ts"; + +const rejectFetch = async () => ({ ok: false, status: 503, json: async () => ({ error: "stub" }) }); + +type HitSvgFn = (lines: unknown[], folds: unknown[], seams: unknown[]) => string; + +const h = runWebClient({ hash: "#/", fetchImpl: rejectFetch }); +const hitSvg = h.window.bili_hitSvg as HitSvgFn | undefined; +if (typeof hitSvg !== "function") throw new Error("window.bili_hitSvg test seam missing in src/web/client.ts"); + +const fx = smallFixture(); +const svg = hitSvg(fx.lines, fx.folds, seamEventsOf(fx.seam)); +const file = join(import.meta.dirname, "..", "tests", "golden", "web-hitrate", "small-full.svg"); +mkdirSync(dirname(file), { recursive: true }); +writeFileSync(file, svg); +console.log(`wrote ${file} (${svg.length} bytes)`); diff --git a/src/web/client.ts b/src/web/client.ts index dfce0e086b..955453f3f7 100644 --- a/src/web/client.ts +++ b/src/web/client.ts @@ -818,8 +818,7 @@ export const WEB_CLIENT = `(function () { } detEl.hidden = true; listEl.hidden = false; - trajState = null; - trajRange = null; + chartZooms.forEach((z) => { z.state = null; z.range = null; }); await refreshSessions(true); } let hiddenEmptyN = 0; @@ -898,52 +897,26 @@ export const WEB_CLIENT = `(function () { // #2489: chart geometry shared by the renderer and the brush interaction below. const TRAJ_W = 960, TRAJ_H = 260, TRAJ_PL = 56, TRAJ_PR = 16, TRAJ_PT = 14, TRAJ_PB = 26; const TRAJ_MIN_SAMPLES = 5; - function trajectorySvg(lines, folds, win, baseIn, seamEvents) { - lines = (lines || []).filter((l) => Boolean(l)); - if (!lines.length) return ""; - const W = TRAJ_W, H = TRAJ_H, PL = TRAJ_PL, PR = TRAJ_PR, PT = TRAJ_PT, PB = TRAJ_PB; - const iw = W - PL - PR, ih = H - PT - PB; - let maxY = 0; - lines.forEach((l) => { if ((l.input || 0) > maxY) maxY = l.input; }); - if (win && win > maxY) maxY = win * 1.05; - if (maxY <= 0) maxY = 1; - const x = (i) => PL + (lines.length === 1 ? iw / 2 : (i / (lines.length - 1)) * iw); - const y = (v) => PT + ih - (Math.max(0, v) / maxY) * ih; - const dt = (ms) => fmtDT(ms); - let grid = "", ticks = ""; - for (let g = 0; g <= 4; g++) { - const v = (maxY / 4) * g; - const yy = y(v); - grid += ''; - ticks += '' + fmtW(v) + ""; - } - let area = "M" + x(0).toFixed(1) + "," + y(lines[0].input || 0).toFixed(1); - let stroke = ""; - lines.forEach((l, i) => { - area += " L" + x(i).toFixed(1) + "," + y(l.cached || 0).toFixed(1); - stroke += (i === 0 ? "M" : "L") + x(i).toFixed(1) + "," + y(l.input || 0).toFixed(1) + " "; - }); - area += " L" + x(lines.length - 1).toFixed(1) + "," + (PT + ih).toFixed(1) + " L" + x(0).toFixed(1) + "," + (PT + ih).toFixed(1) + " Z"; - // Cache-gap causes: color each sample's un-cached band (input − cached) - // by its most likely cause so gaps on the chart explain themselves. - // #2929: mirror the ledger's fold cold-tail window — a fold owns the - // first sample after it AND the cold continuation (hit < 85%) up to 4 - // samples, closing on the first warm line. Ledger lines carry foldSeq - // directly; the fold-between-times heuristic stays as the opener and - // for pre-#2929 ledgers whose lines have no foldSeq. The tail counter - // arms ONLY on that opener path: foldSeq-stamped lines are the - // ledger's own attribution and must not re-arm, or the chart keeps - // coloring comp up to 4 lines past the ledger retiring the window. + // #3484: per-sample miss-cause palette + labels shared by the trajectory gap bands + // (#2929) and the hit-rate line markers — one definition so both charts paint the + // same bucket membership the economics card aggregates. + const CAUSE_COLOR = { cold: "#6e7681", comp: "#bf8700", seam: "#cf222e", pt: "#1a7f37", ps: "#f0883e", rw: "#57606a", ci: "#0969da", rest: "#9aa1a8" }; + const CAUSE_KEY = { cold: "det.cause_cold", comp: "det.cause_comp", seam: "det.legend_seam", pt: "det.leg_pttl", ps: "det.leg_pside", rw: "det.leg_rewind", ci: "det.leg_client", rest: "det.cause_ttl" }; + // #2929/#3484: per-sample causes follow the LEDGER's authoritative attribution + // (foldSeq / seam / prov), not a parallel heuristic — the charts paint the same + // bucket membership the economics card aggregates. The gap heuristic remains only + // as the legacy fallback for old ledgers whose lines carry no attribution fields. + // The fold cold-tail window mirrors the ledger's own: a fold owns the first sample + // after it AND the cold continuation (hit < 85%) up to 4 samples, closing on the + // first warm line. Ledger lines carry foldSeq directly; the fold-between-times + // heuristic stays as the opener and for pre-#2929 ledgers without foldSeq. The + // tail counter arms ONLY on that opener path: foldSeq-stamped lines are the + // ledger's own attribution and must not re-arm, or the chart keeps coloring comp + // up to 4 lines past the ledger retiring the window. + function classifyLineCauses(lines, folds) { const GAP_MS = 600_000; - // #2929: per-sample causes follow the LEDGER's authoritative attribution - // (foldSeq / seam / prov), not a parallel heuristic — the chart paints - // the same bucket membership the economics card aggregates. The gap - // heuristic remains only as the legacy fallback for old ledgers whose - // lines carry no attribution fields. - const CAUSE_COLOR = { cold: "#6e7681", comp: "#bf8700", seam: "#cf222e", pt: "#1a7f37", ps: "#f0883e", rw: "#57606a", ci: "#0969da", rest: "#9aa1a8" }; - const CAUSE_KEY = { cold: "det.cause_cold", comp: "det.cause_comp", seam: "det.legend_seam", pt: "det.leg_pttl", ps: "det.leg_pside", rw: "det.leg_rewind", ci: "det.leg_client", rest: "det.cause_ttl" }; let foldTailClaims = 0; - const causes = lines.map((l, i) => { + return lines.map((l, i) => { if (i === 0) return !(l.cached || 0) ? "cold" : "new"; const p = lines[i - 1]; const missed = (l.input || 0) - (l.cached || 0); @@ -973,28 +946,13 @@ export const WEB_CLIENT = `(function () { if (l.foldSeq == null && l.seam === undefined && l.prov === undefined && (l.at || 0) - (p.at || 0) > GAP_MS && missed > growth + 2048) return "rest"; return "new"; }); - let bands = "", hovers = ""; - const swSeg = lines.length === 1 ? iw : iw / (lines.length - 1); - lines.forEach((l, i) => { - const c = causes[i]; - const yIn = y(l.input || 0), yCa = y(l.cached || 0); - const x0 = Math.max(PL, x(i) - swSeg / 2), x1 = Math.min(W - PR, x(i) + swSeg / 2); - if (c !== "new") { - bands += ''; - // Vertical spine: the miss band floats above the cache line, so drop - // a thin same-colour rule down to the baseline — the bar the band - // belongs to becomes self-evident instead of floating free. - bands += ''; - } - const hitPctLine = (l.input || 0) > 0 ? ((l.cached || 0) / l.input * 100).toFixed(1) + "%" : t("common.none"); - hovers += '' - + (l.seq != null ? "#" + l.seq + " · " : "") + dt(l.at) - + "\\nin " + fmtW(l.input || 0) + " · cached " + fmtW(l.cached || 0) + " · missed " + fmtW((l.input || 0) - (l.cached || 0)) + " · hit " + hitPctLine - + (c === "new" ? "" : "\\n" + t(CAUSE_KEY[c])) + ""; - }); + } + // #2489/#3484: vertical event marks shared by both detail charts. Folds stay + // dashed red, seams solid red (#1609 visual language); burst-folds share + // (near-)identical timestamps and thus the same pixel — merge them into one + // marker per pixel-bucket so stacked marks don't ghost into doubled lines. + function foldMarkLines(folds, lines, x, PT, ih) { let foldMarks = ""; - // Burst-folds share (near-)identical timestamps and thus the same pixel — merge them - // into one marker per pixel-bucket so stacked marks don't ghost into doubled lines. const foldBuckets = []; (folds || []).forEach((f) => { let idx = -1; @@ -1008,10 +966,13 @@ export const WEB_CLIENT = `(function () { const n = bk.items.length; const seqs = bk.items.map((m) => m.seq != null ? "#" + m.seq : "").filter(Boolean).slice(0, 5).join("·"); foldMarks += '' - + t("det.fold_short") + (n > 1 ? " ×" + n : "") + (seqs ? " " + seqs + (bk.items.length > 5 ? "…" : "") + " · " : " ") + dt(bk.items[0].at) + " · " + fmtW(bk.items.reduce((a, m) => a + (m.S || 0), 0)) + ""; + + t("det.fold_short") + (n > 1 ? " ×" + n : "") + (seqs ? " " + seqs + (bk.items.length > 5 ? "…" : "") + " · " : " ") + fmtDT(bk.items[0].at) + " · " + fmtW(bk.items.reduce((a, m) => a + (m.S || 0), 0)) + ""; }); - // #1609: cache-seam suspects (#1606) get SOLID red marks at the first sample at/after - // the divergence time — folds stay dashed, so both read in the same visual language. + return foldMarks; + } + // #1609: cache-seam suspects (#1606) get SOLID red marks at the first sample at/after + // the divergence time — folds stay dashed, so both read in the same visual language. + function seamMarkLines(seamEvents, lines, x, PT, ih) { let seamMarks = ""; (seamEvents || []).forEach((ev) => { if (!ev || !(ev.at > 0)) return; @@ -1025,8 +986,83 @@ export const WEB_CLIENT = `(function () { const prev = ev.prevMsgs != null ? ev.prevMsgs : "?"; const cur = ev.curMsgs != null ? ev.curMsgs : "?"; seamMarks += '' - + t("det.seam_mark_tip", { seq: ev.seq != null ? ev.seq : "?", at: dt(ev.at), hit, lcp, msg, prev, cur }) + ""; + + t("det.seam_mark_tip", { seq: ev.seq != null ? ev.seq : "?", at: fmtDT(ev.at), hit, lcp, msg, prev, cur }) + ""; }); + return seamMarks; + } + // #2929/#3484: pixel-driven seq ticks shared by both detail charts — every band must map + // to a visible index, not "somewhere between 5 and 10". Thinning is PIXEL-driven, not + // count-driven: real sessions carry hundreds/thousands of samples (~0.4px/sample), where + // any flat count step either mosaics the axis or drops to two naked numbers. Vertical + // (rotated) ticks reclaim the unused Y range; hold a constant ≥24px HORIZONTAL pitch. + // NO Math.max(barW,1) floor — that clamps sub-pixel bars UP to 1 and silently disables + // thinning exactly on the dense sessions this exists for. + function seqTickLines(lines, x, W, H, PL, PR) { + const barW = lines.length > 1 ? (W - PL - PR) / (lines.length - 1) : 1; + const tStep = Math.max(1, Math.ceil(24 / barW)); + const xtArr = []; + for (let i = lines.length - 1; i >= 0; i -= tStep) { + const l = lines[i]; + xtArr.push('' + l.seq + ""); + } + const xt = xtArr.join(""); + const xtTime = + (lines[0] && lines[0].at ? '' + fmtDT(lines[0].at) + "" : "") + + (lines.length > 1 && lines[lines.length - 1].at ? '' + fmtDT(lines[lines.length - 1].at) + "" : ""); + return xt + xtTime; + } + function trajectorySvg(lines, folds, win, baseIn, seamEvents) { + lines = (lines || []).filter((l) => Boolean(l)); + if (!lines.length) return ""; + const W = TRAJ_W, H = TRAJ_H, PL = TRAJ_PL, PR = TRAJ_PR, PT = TRAJ_PT, PB = TRAJ_PB; + const iw = W - PL - PR, ih = H - PT - PB; + let maxY = 0; + lines.forEach((l) => { if ((l.input || 0) > maxY) maxY = l.input; }); + if (win && win > maxY) maxY = win * 1.05; + if (maxY <= 0) maxY = 1; + const x = (i) => PL + (lines.length === 1 ? iw / 2 : (i / (lines.length - 1)) * iw); + const y = (v) => PT + ih - (Math.max(0, v) / maxY) * ih; + const dt = (ms) => fmtDT(ms); + let grid = "", ticks = ""; + for (let g = 0; g <= 4; g++) { + const v = (maxY / 4) * g; + const yy = y(v); + grid += ''; + ticks += '' + fmtW(v) + ""; + } + let area = "M" + x(0).toFixed(1) + "," + y(lines[0].input || 0).toFixed(1); + let stroke = ""; + lines.forEach((l, i) => { + area += " L" + x(i).toFixed(1) + "," + y(l.cached || 0).toFixed(1); + stroke += (i === 0 ? "M" : "L") + x(i).toFixed(1) + "," + y(l.input || 0).toFixed(1) + " "; + }); + area += " L" + x(lines.length - 1).toFixed(1) + "," + (PT + ih).toFixed(1) + " L" + x(0).toFixed(1) + "," + (PT + ih).toFixed(1) + " Z"; + // Cache-gap causes: color each sample's un-cached band (input − cached) + // by its most likely cause so gaps on the chart explain themselves. + // Classification lives in classifyLineCauses (#2929/#3484) — shared with + // the hit-rate line markers so both charts name the same buckets. + const causes = classifyLineCauses(lines, folds); + let bands = "", hovers = ""; + const swSeg = lines.length === 1 ? iw : iw / (lines.length - 1); + lines.forEach((l, i) => { + const c = causes[i]; + const yIn = y(l.input || 0), yCa = y(l.cached || 0); + const x0 = Math.max(PL, x(i) - swSeg / 2), x1 = Math.min(W - PR, x(i) + swSeg / 2); + if (c !== "new") { + bands += ''; + // Vertical spine: the miss band floats above the cache line, so drop + // a thin same-colour rule down to the baseline — the bar the band + // belongs to becomes self-evident instead of floating free. + bands += ''; + } + const hitPctLine = (l.input || 0) > 0 ? ((l.cached || 0) / l.input * 100).toFixed(1) + "%" : t("common.none"); + hovers += '' + + (l.seq != null ? "#" + l.seq + " · " : "") + dt(l.at) + + "\\nin " + fmtW(l.input || 0) + " · cached " + fmtW(l.cached || 0) + " · missed " + fmtW((l.input || 0) - (l.cached || 0)) + " · hit " + hitPctLine + + (c === "new" ? "" : "\\n" + t(CAUSE_KEY[c])) + ""; + }); + const foldMarks = foldMarkLines(folds, lines, x, PT, ih); + const seamMarks = seamMarkLines(seamEvents, lines, x, PT, ih); let ceiling = ""; if (win && win > 0) { const yy = y(win); @@ -1048,32 +1084,69 @@ export const WEB_CLIENT = `(function () { baseline = '' + '' + t(baseMeasured ? "det.legend_base" : "det.legend_base_est") + " " + fmtW(baseVal) + ""; } - // #2929: per-sample seq labels — every band must map to a visible - // index, not "somewhere between 5 and 10". Thinning is PIXEL-driven, - // not count-driven: real sessions carry hundreds/thousands of samples - // (~0.4px/sample), where any flat count step either mosaics the axis - // or drops to two naked numbers. Vertical (rotated) ticks reclaim the - // unused Y range; hold a constant ≥24px HORIZONTAL pitch. - // (#2929 cont.) NO Math.max(barW,1) here — that floor clamps - // sub-pixel bars UP to 1 and silently disables thinning exactly on - // the dense sessions this exists for. - const barW = lines.length > 1 ? (W - PL - PR) / (lines.length - 1) : 1; - const tStep = Math.max(1, Math.ceil(24 / barW)); - const xtArr = []; - for (let i = lines.length - 1; i >= 0; i -= tStep) { - const l = lines[i]; - xtArr.push('' + l.seq + ""); - } - const xt = xtArr.join(""); - const xtTime = - (lines[0] && lines[0].at ? '' + dt(lines[0].at) + "" : "") - + (lines.length > 1 && lines[lines.length - 1].at ? '' + dt(lines[lines.length - 1].at) + "" : ""); + const xt = seqTickLines(lines, x, W, H, PL, PR); return '' + grid + '' + bands + hovers + '' - + foldMarks + seamMarks + ceiling + baseline + ticks + xt + xtTime + ""; + + foldMarks + seamMarks + ceiling + baseline + ticks + xt + ""; + } + // #3484: per-request cache hit-rate line — the trend view the numeric cards lack + // (overview/list/card show one aggregate; this shows which rounds dipped and how far). + // Y axis is fixed 0–100% so drops read at a glance; non-"new" samples get a cause dot + // from the exact ledger-backed classification the trajectory bands paint, and the + // hover column names the cause. Same geometry and brush-zoom contract as trajectorySvg. + function hitRateSvg(lines, folds, seamEvents) { + lines = (lines || []).filter((l) => Boolean(l)); + if (!lines.length) return ""; + const W = TRAJ_W, H = TRAJ_H, PL = TRAJ_PL, PR = TRAJ_PR, PT = TRAJ_PT, PB = TRAJ_PB; + const iw = W - PL - PR, ih = H - PT - PB; + const x = (i) => PL + (lines.length === 1 ? iw / 2 : (i / (lines.length - 1)) * iw); + const y = (pct) => PT + ih - (Math.max(0, Math.min(100, pct)) / 100) * ih; + const dt = (ms) => fmtDT(ms); + // Ledger lines carry hitPct; older ledgers compute it from input/cached. + // Zero-input samples have no defined rate — break the line there. + const hp = (l) => l.hitPct != null ? l.hitPct : ((l.input || 0) > 0 ? ((l.cached || 0) / l.input) * 100 : null); + let grid = "", ticks = ""; + for (let g = 0; g <= 4; g++) { + const v = 25 * g; + const yy = y(v); + grid += ''; + ticks += '' + v + "%"; + } + const causes = classifyLineCauses(lines, folds); + let stroke = "", started = false; + lines.forEach((l, i) => { + const v = hp(l); + if (v == null) { started = false; return; } + stroke += (started ? "L" : "M") + x(i).toFixed(1) + "," + y(v).toFixed(1) + " "; + started = true; + }); + let dots = "", hovers = ""; + const swSeg = lines.length === 1 ? iw : iw / (lines.length - 1); + lines.forEach((l, i) => { + const c = causes[i]; + const v = hp(l); + const x0 = Math.max(PL, x(i) - swSeg / 2), x1 = Math.min(W - PR, x(i) + swSeg / 2); + if (v != null && c !== "new") dots += ''; + const hitTxt = v == null ? t("common.none") : v.toFixed(1) + "%"; + hovers += '' + + (l.seq != null ? "#" + l.seq + " · " : "") + dt(l.at) + + "\\nin " + fmtW(l.input || 0) + " · cached " + fmtW(l.cached || 0) + " · missed " + fmtW((l.input || 0) - (l.cached || 0)) + " · hit " + hitTxt + + (c === "new" ? "" : "\\n" + t(CAUSE_KEY[c])) + ""; + }); + // Accent placeholder dot only when the sample carries no cause dot of its own — + // a 1-line cold session must keep its cold color, not an accent dot on top. + const singleDot = lines.length === 1 && hp(lines[0]) != null && causes[0] === "new" + ? '' + : ""; + const foldMarks = foldMarkLines(folds, lines, x, PT, ih); + const seamMarks = seamMarkLines(seamEvents, lines, x, PT, ih); + const xt = seqTickLines(lines, x, W, H, PL, PR); + return '' + grid + + (stroke.trim() ? '' : "") + + dots + singleDot + hovers + foldMarks + seamMarks + ticks + xt + ""; } function legendItem(style, label, dashed) { if (dashed) return '' + label + ""; @@ -1098,142 +1171,157 @@ export const WEB_CLIENT = `(function () { function detailSeamActive(seam) { return !!(seam && (seam.suspects > 0 || seam.missed > 0 || seam.events.length > 0 || seam.providerSide.count > 0 || seam.rewinds.count > 0 || seam.client.count > 0 || seam.abortCorrelated > 0)); } - // #2489: zoom-to-selection over the context-trajectory chart. The data is already + // #2489/#3484: zoom-to-selection over the detail charts. The data is already // client-side, so zooming re-renders the SAME renderer over a filtered slice — no // server round-trip, and an un-zoomed view stays byte-identical to the full render. - let trajState = null; // { lines, folds, seams, win, baseIn } of the rendered detail - let trajRange = null; // absolute [i0, i1] into trajState.lines, or null = full view - let trajDrag = null; // in-flight brush gesture - function trajVisible() { - if (!trajState) return null; - const L = trajState.lines; - let a = 0, b = L.length - 1; - if (trajRange) { - a = Math.max(0, Math.min(L.length - 1, trajRange[0])); - b = Math.max(a, Math.min(L.length - 1, trajRange[1])); - } - const lines = L.slice(a, b + 1); - // Full view passes EVERY fold/seam through unfiltered: the renderer clamps - // out-of-sample-range marks to the nearest edge (the pre-#2489 behavior, which - // the byte-parity acceptance criterion pins). Time-filtering only applies to a - // ZOOMED window, where a foreign mark would land on the wrong sample. - if (!trajRange) return { lines, folds: trajState.folds || [], seams: trajState.seams || [], offset: a }; - const t0 = lines[0] ? (lines[0].at || 0) : 0; - const t1 = lines.length ? (lines[lines.length - 1].at || 0) : 0; - return { - lines, - folds: (trajState.folds || []).filter((f) => (f.at || 0) >= t0 && (f.at || 0) <= t1), - seams: (trajState.seams || []).filter((e) => e && e.at > 0 && e.at >= t0 && e.at <= t1), - offset: a, - }; - } - function trajRender() { - const wrap = $("traj-chart"); - const v = trajVisible(); - if (!wrap || !v) return; - wrap.innerHTML = v.lines.length ? trajectorySvg(v.lines, v.folds, trajState.win, trajState.baseIn, v.seams) : ""; - trajUpdateStatus(v); - } - function trajUpdateStatus(v) { - const st = $("traj-status"); - if (!st) return; - if (!trajRange || !v || !v.lines.length) { st.hidden = true; st.innerHTML = ""; return; } - const L = trajState.lines; - const a = v.offset, b = v.offset + v.lines.length - 1; - const sa = L[a].seq != null ? "#" + L[a].seq : "#" + (a + 1); - const sb = L[b].seq != null ? "#" + L[b].seq : "#" + (b + 1); - const times = v.lines.map((l) => l.at).filter(Boolean); - st.hidden = false; - st.innerHTML = '' + escapeHtml(t("det.traj_zoomed", { a: sa.slice(1), b: sb.slice(1), times: times.length ? fmtDT(times[0]) + " \u2192 " + fmtDT(times[times.length - 1]) : t("common.none") })) + "" - + '"; - const rb = $("traj-reset"); - if (rb) rb.addEventListener("click", () => trajSetRange(null)); - } - function trajSetRange(r) { - trajRange = r && r[1] > r[0] ? [r[0], r[1]] : null; - trajRender(); - } - function trajIdxFromX(x, n) { + // One gesture machinery serves both charts (context trajectory + cache hit rate): + // identical geometry and interaction; each instance supplies element ids, its + // state and its renderer. + function chartIdxFromX(x, n) { if (n <= 1) return 0; const iw = TRAJ_W - TRAJ_PL - TRAJ_PR; return Math.max(0, Math.min(n - 1, Math.round(((x - TRAJ_PL) / iw) * (n - 1)))); } - function trajLocalX(wrap, ev) { - const r = wrap.getBoundingClientRect ? wrap.getBoundingClientRect() : null; - if (!r || !(r.width > 0)) return null; - const x = (ev.clientX - r.left) * (TRAJ_W / r.width); - return Math.max(TRAJ_PL, Math.min(TRAJ_W - TRAJ_PR, x)); - } - function trajOverlayShow(wrap, xa, xb) { - if (!trajDrag || !trajDrag.overlay) return; - const r = wrap.getBoundingClientRect ? wrap.getBoundingClientRect() : null; - if (!r || !(r.width > 0)) return; - const o = trajDrag.overlay; - o.style.left = (Math.min(xa, xb) * (r.width / TRAJ_W)).toFixed(1) + "px"; - o.style.width = (Math.abs(xb - xa) * (r.width / TRAJ_W)).toFixed(1) + "px"; - o.style.top = (TRAJ_PT * (r.height / TRAJ_H)).toFixed(1) + "px"; - o.style.height = ((TRAJ_H - TRAJ_PT - TRAJ_PB) * (r.height / TRAJ_H)).toFixed(1) + "px"; - } - function trajOnDown(ev) { - if (!trajState || ev.button !== 0) return; - const wrap = $("traj-chart"); - const v = trajVisible(); - if (!wrap || !v || v.lines.length < TRAJ_MIN_SAMPLES) return; - ev.preventDefault(); - const x0 = trajLocalX(wrap, ev); - if (x0 == null) return; - const o = document.createElement("div"); - o.className = "chart-brush"; - wrap.appendChild(o); - trajDrag = { x0, cur: x0, n: v.lines.length, offset: v.offset, overlay: o }; - trajOverlayShow(wrap, x0, x0); - document.addEventListener("mousemove", trajOnMove); - document.addEventListener("mouseup", trajOnUp); - } - function trajOnMove(ev) { - if (!trajDrag) return; - const x = trajLocalX($("traj-chart"), ev); - if (x == null) return; - trajDrag.cur = x; - trajOverlayShow($("traj-chart"), trajDrag.x0, x); - } - function trajOnUp(ev) { - document.removeEventListener("mousemove", trajOnMove); - document.removeEventListener("mouseup", trajOnUp); - if (!trajDrag) return; - const d0 = trajDrag; - trajDrag = null; - if (d0.overlay) d0.overlay.remove(); - const x1 = trajLocalX($("traj-chart"), ev); - if (x1 == null) return; - const i0 = trajIdxFromX(Math.min(d0.x0, x1), d0.n); - const i1 = trajIdxFromX(Math.max(d0.x0, x1), d0.n); - if (i1 - i0 + 1 < TRAJ_MIN_SAMPLES) return; // too narrow — treat as a click - if (i1 - i0 + 1 >= d0.n) return; // full-width drag — nothing to gain - trajSetRange([d0.offset + i0, d0.offset + i1]); + const chartZooms = []; // live instances — Esc resets any zoomed chart (#2489 behavior) + function makeChartZoom(cfg) { + // cfg: { elId, statusId, resetId, render(lines, folds, seams) -> svg } + const z = { range: null, drag: null, state: null, cfg }; + z.visible = function visible() { + if (!z.state) return null; + const L = z.state.lines; + let a = 0, b = L.length - 1; + if (z.range) { + a = Math.max(0, Math.min(L.length - 1, z.range[0])); + b = Math.max(a, Math.min(L.length - 1, z.range[1])); + } + const lines = L.slice(a, b + 1); + // Full view passes EVERY fold/seam through unfiltered: the renderer clamps + // out-of-sample-range marks to the nearest edge (the pre-#2489 behavior, which + // the byte-parity acceptance criterion pins). Time-filtering only applies to a + // ZOOMED window, where a foreign mark would land on the wrong sample. + if (!z.range) return { lines, folds: z.state.folds || [], seams: z.state.seams || [], offset: a }; + const t0 = lines[0] ? (lines[0].at || 0) : 0; + const t1 = lines.length ? (lines[lines.length - 1].at || 0) : 0; + return { + lines, + folds: (z.state.folds || []).filter((f) => (f.at || 0) >= t0 && (f.at || 0) <= t1), + seams: (z.state.seams || []).filter((e) => e && e.at > 0 && e.at >= t0 && e.at <= t1), + offset: a, + }; + }; + function updateStatus(v) { + const st = $(cfg.statusId); + if (!st) return; + if (!z.range || !v || !v.lines.length) { st.hidden = true; st.innerHTML = ""; return; } + const L = z.state.lines; + const a = v.offset, b = v.offset + v.lines.length - 1; + const sa = L[a].seq != null ? "#" + L[a].seq : "#" + (a + 1); + const sb = L[b].seq != null ? "#" + L[b].seq : "#" + (b + 1); + const times = v.lines.map((l) => l.at).filter(Boolean); + st.hidden = false; + st.innerHTML = '' + escapeHtml(t("det.traj_zoomed", { a: sa.slice(1), b: sb.slice(1), times: times.length ? fmtDT(times[0]) + " \u2192 " + fmtDT(times[times.length - 1]) : t("common.none") })) + "" + + '"; + const rb = $(cfg.resetId); + if (rb) rb.addEventListener("click", () => z.setRange(null)); + } + z.render = function render() { + const wrap = $(cfg.elId); + const v = z.visible(); + if (!wrap || !v) return; + wrap.innerHTML = v.lines.length ? cfg.render(v.lines, v.folds, v.seams) : ""; + updateStatus(v); + }; + z.setRange = function setRange(r) { + z.range = r && r[1] > r[0] ? [r[0], r[1]] : null; + z.render(); + }; + function localX(wrap, ev) { + const r = wrap.getBoundingClientRect ? wrap.getBoundingClientRect() : null; + if (!r || !(r.width > 0)) return null; + const x = (ev.clientX - r.left) * (TRAJ_W / r.width); + return Math.max(TRAJ_PL, Math.min(TRAJ_W - TRAJ_PR, x)); + } + function overlayShow(wrap, xa, xb) { + if (!z.drag || !z.drag.overlay) return; + const r = wrap.getBoundingClientRect ? wrap.getBoundingClientRect() : null; + if (!r || !(r.width > 0)) return; + const o = z.drag.overlay; + o.style.left = (Math.min(xa, xb) * (r.width / TRAJ_W)).toFixed(1) + "px"; + o.style.width = (Math.abs(xb - xa) * (r.width / TRAJ_W)).toFixed(1) + "px"; + o.style.top = (TRAJ_PT * (r.height / TRAJ_H)).toFixed(1) + "px"; + o.style.height = ((TRAJ_H - TRAJ_PT - TRAJ_PB) * (r.height / TRAJ_H)).toFixed(1) + "px"; + } + function onDown(ev) { + if (!z.state || ev.button !== 0) return; + const wrap = $(cfg.elId); + const v = z.visible(); + if (!wrap || !v || v.lines.length < TRAJ_MIN_SAMPLES) return; + ev.preventDefault(); + const x0 = localX(wrap, ev); + if (x0 == null) return; + const o = document.createElement("div"); + o.className = "chart-brush"; + wrap.appendChild(o); + z.drag = { x0, cur: x0, n: v.lines.length, offset: v.offset, overlay: o }; + overlayShow(wrap, x0, x0); + document.addEventListener("mousemove", onMove); + document.addEventListener("mouseup", onUp); + } + function onMove(ev) { + if (!z.drag) return; + const x = localX($(cfg.elId), ev); + if (x == null) return; + z.drag.cur = x; + overlayShow($(cfg.elId), z.drag.x0, x); + } + function onUp(ev) { + document.removeEventListener("mousemove", onMove); + document.removeEventListener("mouseup", onUp); + if (!z.drag) return; + const d0 = z.drag; + z.drag = null; + if (d0.overlay) d0.overlay.remove(); + const x1 = localX($(cfg.elId), ev); + if (x1 == null) return; + const i0 = chartIdxFromX(Math.min(d0.x0, x1), d0.n); + const i1 = chartIdxFromX(Math.max(d0.x0, x1), d0.n); + if (i1 - i0 + 1 < TRAJ_MIN_SAMPLES) return; // too narrow — treat as a click + if (i1 - i0 + 1 >= d0.n) return; // full-width drag — nothing to gain + z.setRange([d0.offset + i0, d0.offset + i1]); + } + z.bind = function bind(state) { + z.state = state && state.lines.length ? state : null; + z.range = null; + const wrap = $(cfg.elId); + if (!wrap || !z.state) { z.render(); return; } + wrap.addEventListener("mousedown", onDown); + wrap.addEventListener("dblclick", () => z.setRange(null)); + z.render(); + }; + chartZooms.push(z); + return z; } + const trajAux = { win: 0, baseIn: 0 }; + const trajZoom = makeChartZoom({ elId: "traj-chart", statusId: "traj-status", resetId: "traj-reset", render: (lines, folds, seams) => trajectorySvg(lines, folds, trajAux.win, trajAux.baseIn, seams) }); + const hitZoom = makeChartZoom({ elId: "hit-chart", statusId: "hit-status", resetId: "hit-reset", render: (lines, folds, seams) => hitRateSvg(lines, folds, seams) }); function bindTrajectoryBrush(d) { - trajState = null; - trajRange = null; const ledger = d.ledger || {}; const lines = (ledger.lines || []).filter((l) => Boolean(l)); - if (!lines.length) return; const seam = detailSeam(ledger); - trajState = { - lines, - folds: ledger.folds || [], - seams: detailSeamActive(seam) && seam ? seam.events : [], - win: d.contextWindow || 0, - baseIn: d.systemPromptTokens || 0, - }; - const wrap = $("traj-chart"); - if (!wrap) return; - wrap.addEventListener("mousedown", trajOnDown); - wrap.addEventListener("dblclick", () => trajSetRange(null)); - trajRender(); + trajAux.win = d.contextWindow || 0; + trajAux.baseIn = d.systemPromptTokens || 0; + trajZoom.bind({ lines, folds: ledger.folds || [], seams: detailSeamActive(seam) && seam ? seam.events : [] }); + } + function bindHitRateChart(d) { + const ledger = d.ledger || {}; + const lines = (ledger.lines || []).filter((l) => Boolean(l)); + const seam = detailSeam(ledger); + hitZoom.bind({ lines, folds: ledger.folds || [], seams: detailSeamActive(seam) && seam ? seam.events : [] }); } window.bili_trajSvg = trajectorySvg; - window.bili_trajZoom = { minSamples: TRAJ_MIN_SAMPLES, idxFromX: trajIdxFromX, visible: () => trajVisible(), range: () => trajRange }; + window.bili_hitSvg = hitRateSvg; + window.bili_causes = classifyLineCauses; + window.bili_trajZoom = { minSamples: TRAJ_MIN_SAMPLES, idxFromX: chartIdxFromX, visible: () => trajZoom.visible(), range: () => trajZoom.range }; function blockTopic(b) { // #1426: untitled blocks fall back to the lead line of their summary if (b.topic && String(b.topic).trim()) return String(b.topic).trim(); @@ -1492,7 +1580,7 @@ export const WEB_CLIENT = `(function () { parts.push('
' + t("det.trajectory_empty") + "
"); } else { parts.push(''); - // #2489: the wrap starts empty — bindTrajectoryBrush() → trajRender() fills it, + // #2489: the wrap starts empty — bindTrajectoryBrush() fills it on bind, // so every chart state (full and zoomed) comes from the single render path. parts.push('
'); parts.push('
'); @@ -1528,6 +1616,29 @@ export const WEB_CLIENT = `(function () { if ((ledger.linesOmitted || 0) > 0) parts.push('
' + t("det.omitted", { n: ledger.linesOmitted }) + "
"); } parts.push("
"); + // #3484: hit-rate trend — same data as the trajectory chart above, plotted as + // per-request hit % so dips (and their causes) read at a glance. + parts.push('
' + t("det.hitrate") + '' + t("det.hitrate_sub") + '
'); + if (!lines.length) { + parts.push('
' + t("det.hitrate_empty") + "
"); + } else { + parts.push(''); + parts.push('
'); + const hrCauses = classifyLineCauses(lines, ledger.folds || []); + const present = {}; + hrCauses.forEach((c) => { if (c !== "new") present[c] = true; }); + parts.push('
'); + parts.push(legendItem("background:var(--accent)", t("det.legend_hitline"))); + ["comp", "cold", "seam", "pt", "ps", "rw", "ci", "rest"].forEach((c) => { + if (present[c]) parts.push(legendItem("background:" + CAUSE_COLOR[c], t(CAUSE_KEY[c]))); + }); + if ((ledger.folds || []).length > 0) parts.push(legendItem("#cf222e", t("det.legend_fold"), true)); + if (seamActive && seam.events.length > 0) parts.push(legendItem("#cf222e", t("det.legend_seam"))); + parts.push("
"); + parts.push('
' + t("det.traj_zoom_hint") + "
"); + if ((ledger.linesOmitted || 0) > 0) parts.push('
' + t("det.omitted", { n: ledger.linesOmitted }) + "
"); + } + parts.push("
"); if (seamActive && seam.events.length > 0) { const evHead = '#' + t("det.fold_time") + '' + t("det.seam_col_hit") + '' + t("det.seam_col_input") + '' + t("det.seam_col_div") + ""; parts.push('
' + t("det.seam_events", { n: seam.events.length }) + "" @@ -1729,6 +1840,7 @@ export const WEB_CLIENT = `(function () { bindCacheReportActions(d); bindSessionReportActions(d); bindTrajectoryBrush(d); + bindHitRateChart(d); const cc = $("session-conflicts-clear"); if (cc) { cc.addEventListener("click", async () => { @@ -2704,7 +2816,7 @@ export const WEB_CLIENT = `(function () { } window.addEventListener("hashchange", route); // #2489: Esc resets a zoomed trajectory view from anywhere on the page. - document.addEventListener("keydown", (ev) => { if (ev.key === "Escape" && trajRange) trajSetRange(null); }); + document.addEventListener("keydown", (ev) => { if (ev.key === "Escape") chartZooms.forEach((z) => { if (z.range) z.setRange(null); }); }); function initStaticHandlers() { const tog = $("language-toggle"); diff --git a/src/web/i18n.ts b/src/web/i18n.ts index dee2ee9f16..e6d0e92e4a 100644 --- a/src/web/i18n.ts +++ b/src/web/i18n.ts @@ -240,6 +240,10 @@ export const MESSAGES: Record> = { "det.trajectory": "上下文轨迹", "det.trajectory_sub": "每次请求的输入 token 与缓存命中;红色竖线为压缩折叠点", "det.trajectory_empty": "该会话还没有用量采样", + "det.hitrate": "缓存命中率走势", + "det.hitrate_sub": "逐请求命中率;掉点按账本归因着色(与轨迹图同一套口径)", + "det.hitrate_empty": "该会话还没有缓存采样", + "det.legend_hitline": "命中率", "det.legend_input": "输入", "det.legend_cached": "其中缓存命中", "det.legend_fold": "压缩折叠点", @@ -716,6 +720,10 @@ export const MESSAGES: Record> = { "det.trajectory": "Context trajectory", "det.trajectory_sub": "Per-request input tokens and cache hits; red marks are compression folds", "det.trajectory_empty": "No usage samples for this session yet", + "det.hitrate": "Cache hit rate", + "det.hitrate_sub": "Per-request hit %; dips colored by ledger attribution (same buckets as the trajectory chart)", + "det.hitrate_empty": "No cache samples for this session yet", + "det.legend_hitline": "hit %", "det.legend_input": "input", "det.legend_cached": "of which cached", "det.legend_fold": "compression fold", diff --git a/tests/golden/web-hitrate/small-full.svg b/tests/golden/web-hitrate/small-full.svg new file mode 100644 index 0000000000..3df7495b05 --- /dev/null +++ b/tests/golden/web-hitrate/small-full.svg @@ -0,0 +1,36 @@ +#1 · 10-01 00:00 +in 50K · cached 0 · missed 50K · hit 0.0% +cold start (no prior cache)#2 · 10-01 00:01 +in 51K · cached 46K · missed 5.1K · hit 90.0%#3 · 10-01 00:02 +in 52K · cached 47K · missed 5.2K · hit 90.0%#4 · 10-01 00:03 +in 53K · cached 48K · missed 5.3K · hit 90.0%#5 · 10-01 00:04 +in 54K · cached 49K · missed 5.4K · hit 90.0%#6 · 10-01 00:05 +in 55K · cached 50K · missed 5.5K · hit 90.0%#7 · 10-01 00:06 +in 56K · cached 50K · missed 5.6K · hit 90.0%#8 · 10-01 00:07 +in 57K · cached 51K · missed 5.7K · hit 90.0%#9 · 10-01 00:08 +in 58K · cached 52K · missed 5.8K · hit 90.0%#10 · 10-01 00:09 +in 59K · cached 53K · missed 5.9K · hit 90.0%#11 · 10-01 00:10 +in 60K · cached 54K · missed 6.0K · hit 90.0% +post-fold rebuild#12 · 10-01 00:11 +in 61K · cached 55K · missed 6.1K · hit 90.0% +post-fold rebuild#13 · 10-01 00:12 +in 62K · cached 56K · missed 6.2K · hit 90.0% +post-fold rebuild#14 · 10-01 00:13 +in 63K · cached 57K · missed 6.3K · hit 90.0% +post-fold rebuild#15 · 10-01 00:14 +in 64K · cached 58K · missed 6.4K · hit 90.0% +post-fold rebuild#16 · 10-01 00:15 +in 65K · cached 59K · missed 6.5K · hit 90.0%#17 · 10-01 00:16 +in 66K · cached 59K · missed 6.6K · hit 90.0%#18 · 10-01 00:17 +in 67K · cached 60K · missed 6.7K · hit 90.0%#19 · 10-01 00:18 +in 68K · cached 61K · missed 6.8K · hit 90.0% +post-fold rebuild#20 · 10-01 00:19 +in 69K · cached 62K · missed 6.9K · hit 90.0% +post-fold rebuild#21 · 10-01 00:20 +in 70K · cached 63K · missed 7.0K · hit 90.0% +post-fold rebuild#22 · 10-01 00:21 +in 71K · cached 64K · missed 7.1K · hit 90.0% +post-fold rebuild#23 · 10-01 00:22 +in 72K · cached 65K · missed 7.2K · hit 90.0% +post-fold rebuild#24 · 10-01 00:23 +in 73K · cached 66K · missed 7.3K · hit 90.0%fold ×2 #11·#12 · 10-01 00:10 · 8.0Kfold #19 · 10-01 00:18 · 8.0K⚠ CACHE SEAM #8 · 10-01 00:07 · hit 42.5% · first divergence ≥8.8 KB bytes @ message[12] (30→31 msgs)⚠ CACHE SEAM #21 · 10-01 00:20 · hit 38.2% · first divergence ≥7.3 KB bytes @ message[8] (21→22 msgs)0%25%50%75%100%24232221201918171615141312111098765432110-01 00:0010-01 00:23 \ No newline at end of file diff --git a/tests/web-hitrate-chart.test.ts b/tests/web-hitrate-chart.test.ts new file mode 100644 index 0000000000..faef8aee54 --- /dev/null +++ b/tests/web-hitrate-chart.test.ts @@ -0,0 +1,120 @@ +// #3484: per-request cache hit-rate line chart — golden byte-stability, cause-dot +// parity with the trajectory bands, and the brush-zoom contract (shared machinery). +process.env.TZ = "UTC"; +import test from "node:test"; +import assert from "node:assert/strict"; +import { readFileSync } from "node:fs"; +import { join } from "node:path"; +import { bigFixture, bigDetailPayload, seamEventsOf, smallFixture } from "./web-trajectory-fixture.ts"; +import { runWebClient, waitFor } from "./web-trajectory-harness.ts"; + +type HitSvgFn = (lines: unknown[], folds: unknown[], seams: unknown[]) => string; +type TrajSvgFn = (lines: unknown[], folds: unknown[], win: number, baseIn: number, seams: unknown[]) => string; +type CausesFn = (lines: unknown[], folds: unknown[]) => string[]; + +// Full-view sample x in viewBox units (PL + i/(n-1)*iw with n=1200). +const X_FULL = (i: number) => 56 + (i * 888) / 1199; +const hoverCount = (svg: string) => (svg.match(/fill="transparent"/g) || []).length; +const dotCount = (svg: string) => (svg.match(/r="2\.5"/g) || []).length; +const bandCount = (svg: string) => (svg.match(/opacity="0\.35"/g) || []).length; + +const detailFetch = (payload: unknown) => async (url: string) => { + if (String(url).includes("/__bili/sessions/big-1/detail")) return { ok: true, status: 200, json: async () => payload }; + return { ok: false, status: 503, json: async () => ({ error: "stub" }) }; +}; +const rejectFetch = async () => ({ ok: false, status: 503, json: async () => ({ error: "stub" }) }); + +test("#3484: golden — unzoomed hit-rate SVG is byte-stable", () => { + const h = runWebClient({ hash: "#/", fetchImpl: rejectFetch }); + const fn = h.window.bili_hitSvg; + assert.equal(typeof fn, "function", "window.bili_hitSvg test seam missing"); + const fx = smallFixture(); + const svg = (fn as HitSvgFn)(fx.lines, fx.folds, seamEventsOf(fx.seam)); + const golden = readFileSync(join(import.meta.dirname, "golden", "web-hitrate", "small-full.svg"), "utf8"); + assert.equal(svg, golden, "renderer output drifted from the golden — regenerate via scripts/update-web-hitrate-golden.ts and justify the change in the PR"); +}); + +test("#3484: hit-rate cause dots match the ledger classification and the trajectory bands", () => { + const h = runWebClient({ hash: "#/", fetchImpl: rejectFetch }); + const hitSvg = h.window.bili_hitSvg as HitSvgFn; + const trajSvg = h.window.bili_trajSvg as TrajSvgFn; + const causes = h.window.bili_causes as CausesFn; + assert.equal(typeof causes, "function", "window.bili_causes test seam missing"); + const fx = bigFixture(); + const seams = seamEventsOf(fx.seam); + const list = causes(fx.lines, fx.folds); + assert.equal(list.length, fx.lines.length); + // Each fixture fold lands exactly on a sample boundary, so BOTH flanking + // lines fire the opener heuristic (re-arming the 3-round tail counter): + // 5 comp claims per fold × 4 folds. No cold (line 0 carries cache here), + // no warm resets (fixture lines have no hitPct field). + const nonNew = list.filter((c) => c !== "new"); + assert.deepEqual(nonNew, Array(20).fill("comp")); + assert.equal(list[100], "comp"); + assert.equal(list[105], "new", "tail counter retired after its window"); + const hv = hitSvg(fx.lines, fx.folds, seams); + const tv = trajSvg(fx.lines, fx.folds, 0, fx.systemPromptTokens, seams); + assert.equal(dotCount(hv), nonNew.length, "one dot per classified sample"); + assert.equal(bandCount(tv), nonNew.length, "trajectory bands stay in lockstep with the same classification"); + // Hover columns carry the same per-sample numbers in both charts. + assert.ok(hv.includes("hit 97.0%"), "steady-state samples read their rate"); +}); + +test("#3484: hit-rate chart binds, zooms, and resets like the trajectory chart", async () => { + const fx = bigFixture(); + const h = runWebClient({ hash: "#/session/big-1", fetchImpl: detailFetch(bigDetailPayload(fx)) }); + await waitFor(() => { + const c = h.els.get("hit-chart"); + return c !== undefined && c.innerHTML.includes(" 0, "overlay spans the selection"); + h.document.dispatch("mouseup", { clientX: X_FULL(520), clientY: 100 }); + let svg = chart.innerHTML; + assert.notEqual(svg, fullSvg, "zoom re-rendered the chart"); + assert.equal(hoverCount(svg), 121, "only the selected samples remain"); + assert.ok(!status.hidden); + assert.ok(status.innerHTML.includes("View #401-#521"), status.innerHTML); + assert.ok(status.innerHTML.includes('id="hit-reset"')); + + // Reset — button. + const resetBtn = h.els.get("hit-reset"); + assert.ok(resetBtn, "reset button rendered in the status row"); + resetBtn.dispatch("click"); + assert.equal(chart.innerHTML, fullSvg); + assert.ok(status.hidden); + + // Reset — double-click. + chart.dispatch("mousedown", { clientX: X_FULL(400), clientY: 100, button: 0 }); + h.document.dispatch("mouseup", { clientX: X_FULL(520), clientY: 100 }); + chart.dispatch("dblclick"); + assert.equal(chart.innerHTML, fullSvg); + + // Reset — Esc. + chart.dispatch("mousedown", { clientX: X_FULL(400), clientY: 100, button: 0 }); + h.document.dispatch("mouseup", { clientX: X_FULL(520), clientY: 100 }); + h.document.dispatch("keydown", { key: "Escape" }); + assert.equal(chart.innerHTML, fullSvg); + + // Too-narrow selection (<5 samples) is ignored. + chart.dispatch("mousedown", { clientX: X_FULL(500), clientY: 100, button: 0 }); + h.document.dispatch("mouseup", { clientX: X_FULL(502), clientY: 100 }); + assert.equal(chart.innerHTML, fullSvg); + + // Full-width drag is ignored (nothing to gain). + chart.dispatch("mousedown", { clientX: X_FULL(0), clientY: 100, button: 0 }); + h.document.dispatch("mouseup", { clientX: X_FULL(1199), clientY: 100 }); + assert.equal(chart.innerHTML, fullSvg); +}); diff --git a/tests/web-trajectory-harness.ts b/tests/web-trajectory-harness.ts index 5a5f1ac366..a093d8388f 100644 --- a/tests/web-trajectory-harness.ts +++ b/tests/web-trajectory-harness.ts @@ -77,7 +77,7 @@ function makeEl(tag: string, chartRect: Rect): El { closest() { return null; }, select() {}, click() { el.dispatch("click"); }, - getBoundingClientRect() { return el.id === "traj-chart" ? chartRect : { left: 0, top: 0, width: 100, height: 20 }; }, + getBoundingClientRect() { return el.id === "traj-chart" || el.id === "hit-chart" ? chartRect : { left: 0, top: 0, width: 100, height: 20 }; }, }; return el; }