From d620ad9b5b5ae7e1407bb520b8b187c3e78b7f1c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=96=B0=E5=B9=B4=E5=BF=AB=E4=B9=90?= <12038858+ahhh1432@user.noreply.gitee.com> Date: Tue, 20 Oct 2026 13:25:33 +0800 Subject: [PATCH 1/2] feat(web): compression-structure tab with tier tree, graph view and lazy leaves Session detail gains a Structure sub-tab next to Overview/Handoff. It reads the kernel's own accounting: blocks nest by parentBlockId (who folded whom), each node shows tier, compressed->summary tokens with ratio, summary bytes, the mNNNNN span, message counts and age, plus the summary markdown and one leaf per folded message. Two readings of the same data switch in place: the list (inspect concrete messages) and a layered tree map (overall shape, click a node to jump back to its row). Originals load on demand through two admin-gated endpoints (/block-content and /message, 2 MiB cap with honest truncation, unknown / pruned / no-snapshot answers instead of guesses). --- reference/architecture.md | 2 +- src/server/admin.ts | 78 +++++++- src/web/client.ts | 354 +++++++++++++++++++++++++++++++--- src/web/i18n.ts | 40 ++++ src/web/index.ts | 3 +- src/web/sessions-data.ts | 284 ++++++++++++++++++++++++--- src/web/styles.ts | 53 +++++ tests/web-blocks-tree.test.ts | 215 +++++++++++++++++++++ 8 files changed, 978 insertions(+), 51 deletions(-) create mode 100644 tests/web-blocks-tree.test.ts diff --git a/reference/architecture.md b/reference/architecture.md index f929892475..57d6f146b2 100644 --- a/reference/architecture.md +++ b/reference/architecture.md @@ -176,7 +176,7 @@ billion-context/ │ │ └── native.ts # Routing scope/exemptions policy (#1622) │ └── web/ # Web UI (config editor, sessions, logs) │ ├── api.ts # REST handlers (config get/put with parse-state guard) -│ ├── sessions-data.ts # Read-only session browsing (live pool + on-disk, #1420) +│ ├── sessions-data.ts # Read-only session browsing (live pool + on-disk, #1420); tier tree + lazy block content (#3936) │ ├── logs-query.ts # GET /__bili/logs selection engine │ ├── markdown.ts # Escape-safe Markdown → HTML (#1420) │ ├── page.ts # Server-rendered HTML page shell (CA cert hint, i18n) diff --git a/src/server/admin.ts b/src/server/admin.ts index bdbbcc0340..d9359b4271 100644 --- a/src/server/admin.ts +++ b/src/server/admin.ts @@ -30,7 +30,7 @@ import { formatUpstreamError, getUpstreamConnectionStatus, proxyDispatcher, reco import { detectStaleInstall, getLastInstall } from "../update.js"; import { getPlannedUpgrade, getUpdatePolicyState } from "../update-policy.js"; import { PACKAGE_NAME, VERSION, BUILD_COMMIT } from "../version.js"; -import { buildOverview, buildSessionDetail, buildSessionList, buildSessionPage, handleConfigGet, handleConfigPut, hiddenEmptyCount, renderUI } from "../web/index.js"; +import { buildBlockContent, buildMessageContent, buildOverview, buildSessionDetail, buildSessionList, buildSessionPage, handleConfigGet, handleConfigPut, hiddenEmptyCount, renderUI, type BlockContentView } from "../web/index.js"; import { buildSessionReportMd, buildSessionReportSvg } from "../web/report.js"; import { queryLogLines } from "../web/logs-query.js"; import { buildDiagnostics } from "../web/diagnostics.js"; @@ -215,6 +215,12 @@ export async function handleAdminRoute(req: http.IncomingMessage, res: http.Serv if (req.method === "GET" && req.url?.startsWith("/__bili/logs")) return sendWebLogs(res, req); if (req.method === "GET" && req.url?.startsWith("/__bili/diagnostics")) return sendDiagnostics(res, req.url); if (req.method === "GET" && req.url?.startsWith("/__bili/sessions/") && req.url.endsWith("/detail")) return sendWebSessionDetail(res, req.url); + // #3917: one block's original text for the 压缩结构 tree — lazy per click, so + // the detail payload never carries whole originals. + if (req.method === "GET" && req.url !== undefined && isBlockContentPath(req.url)) return sendWebBlockContent(res, req.url); + // #3917: one folded message's text, addressed by its mNNNNN ref — the leaf + // rows of the tier tree fetch their bytes one click at a time. + if (req.method === "GET" && req.url !== undefined && isSessionMessagePath(req.url)) return sendWebSessionMessage(res, req.url); if (req.method === "GET" && req.url === "/") { // Browser visits root → redirect to the web UI. curl / health probes // (Accept: */* or no Accept) still get the JSON health check so @@ -1141,6 +1147,76 @@ async function sendWebSessionDetail(res: http.ServerResponse, url: string): Prom res.end(JSON.stringify(detail, null, 2)); } +// #3917: `/__bili/sessions//block-content?blockId=bN&view=one|full`. +const BLOCK_CONTENT_PATH = "/block-content"; + +function isBlockContentPath(url: string): boolean { + const q = url.indexOf("?"); + const path = q === -1 ? url : url.slice(0, q); + return path.startsWith("/__bili/sessions/") && path.endsWith(BLOCK_CONTENT_PATH); +} + +async function sendWebBlockContent(res: http.ServerResponse, url: string): Promise { + const u = new URL(url, "http://localhost"); + const pathname = u.pathname; + const prefix = "/__bili/sessions/"; + let id = ""; + try { + id = decodeURIComponent(pathname.slice(prefix.length, -BLOCK_CONTENT_PATH.length)); + } catch { + // malformed percent-encoding → unknown session below + } + const blockId = u.searchParams.get("blockId") ?? ""; + const view: BlockContentView = u.searchParams.get("view") === "full" ? "full" : "one"; + if (!id || !blockId) { + res.writeHead(400, { "content-type": "application/json" }); + res.end(JSON.stringify({ error: "missing session id or blockId" })); + return; + } + const result = await buildBlockContent(id, blockId, view); + if (!result.ok) { + res.writeHead(404, { "content-type": "application/json" }); + res.end(JSON.stringify({ error: result.reason, reason: result.reason, session: id, blockId })); + return; + } + res.writeHead(200, { "content-type": "application/json" }); + res.end(JSON.stringify(result)); +} + +// #3917: `/__bili/sessions//message?ref=mNNNNN` — one folded message's text. +const SESSION_MESSAGE_PATH = "/message"; + +function isSessionMessagePath(url: string): boolean { + const q = url.indexOf("?"); + const path = q === -1 ? url : url.slice(0, q); + return path.startsWith("/__bili/sessions/") && path.endsWith(SESSION_MESSAGE_PATH); +} + +async function sendWebSessionMessage(res: http.ServerResponse, url: string): Promise { + const u = new URL(url, "http://localhost"); + const prefix = "/__bili/sessions/"; + let id = ""; + try { + id = decodeURIComponent(u.pathname.slice(prefix.length, -SESSION_MESSAGE_PATH.length)); + } catch { + // malformed percent-encoding → unknown session below + } + const ref = u.searchParams.get("ref") ?? ""; + if (!id || !ref) { + res.writeHead(400, { "content-type": "application/json" }); + res.end(JSON.stringify({ error: "missing session id or ref" })); + return; + } + const result = await buildMessageContent(id, ref); + if (!result.ok) { + res.writeHead(404, { "content-type": "application/json" }); + res.end(JSON.stringify({ error: result.reason, reason: result.reason, session: id, ref })); + return; + } + res.writeHead(200, { "content-type": "application/json" }); + res.end(JSON.stringify(result)); +} + async function sendSessionReport(res: http.ServerResponse, url: string): Promise { const q = new URL(url, "http://localhost").searchParams; const id = q.get("session"); diff --git a/src/web/client.ts b/src/web/client.ts index 3de7709226..d28ea59b06 100644 --- a/src/web/client.ts +++ b/src/web/client.ts @@ -1471,7 +1471,8 @@ export const WEB_CLIENT = `(function () { // #1426: untitled blocks fall back to the lead line of their summary if (b.topic && String(b.topic).trim()) return String(b.topic).trim(); const lead = String(b.summary || "").split("\\n").map((s) => s.trim()).find(Boolean) || ""; - return lead.length > 48 ? lead.slice(0, 48) + "…" : lead || b.blockId; + const plain = lead.replace(/^#{1,6}\\s*/, "").replace(/^[*>-]+\\s*/, ""); + return plain.length > 48 ? plain.slice(0, 48) + "…" : plain || b.blockId; } function detailBadges(d) { const live = d.live && !d.restored; @@ -1621,11 +1622,218 @@ export const WEB_CLIENT = `(function () { return html.join(""); } window.bili_renderHandoffMd = renderHandoffMd; + // #3917: compression-structure tree — nested by parentBlockId (an active + // block's children are the blocks it folded); roots are blocks whose parent + // is no longer folded. Nodes carry the kernel's own accounting: + // compressedTokens (what the block absorbed), summaryTokens (what replaced + // it), summaryBytes (the rendered artifact) and the mNNNNN span it covers. + function blockTreeStats(blocks) { + const tiers = {}; + let active = 0; + let coverTokens = 0; + let summaryTokens = 0; + blocks.forEach(function (b) { + const tier = Number(b.tier) || 1; + tiers[tier] = (tiers[tier] || 0) + 1; + if (b.active) active += 1; + coverTokens += Number(b.compressedTokens) || 0; + summaryTokens += Number(b.summaryTokens) || 0; + }); + return { tiers: tiers, active: active, coverTokens: coverTokens, summaryTokens: summaryTokens }; + } + function blockTreeShape(blocks) { + const byId = {}; + blocks.forEach(function (b) { byId[b.blockId] = b; }); + const children = {}; + const roots = []; + blocks.forEach(function (b) { + const pid = b.parentBlockId; + if (pid && byId[pid] && pid !== b.blockId) (children[pid] = children[pid] || []).push(b); + else roots.push(b); + }); + return { children: children, roots: roots }; + } + // #3917: at-a-glance view of the same folds. Layered top-down (roots on top, + // each fold one level below the block that absorbed it), edges drawn as + // beziers — a knowledge-graph-ish shape for reading structure, while the + // list view stays the place to read concrete messages. A wide tree is scaled + // to fit the card rather than hiding nodes behind a horizontal scroll. + const GRAPH_NODE_W = 118; + const GRAPH_NODE_H = 36; + const GRAPH_GAP_X = 16; + const GRAPH_LEVEL_H = 84; + const GRAPH_FIT_W = 1120; + function blockGraphLayout(blocks) { + const shape = blockTreeShape(blocks); + const nodes = []; + const links = []; + let cursor = 0; + let maxDepth = 0; + const place = function (b, depth) { + if (depth > 40) return null; + const kids = shape.children[b.blockId] || []; + const childNodes = []; + kids.forEach(function (k) { + const kid = place(k, depth + 1); + if (kid) childNodes.push(kid); + }); + let x; + if (!childNodes.length) { + x = cursor; + cursor += GRAPH_NODE_W + GRAPH_GAP_X; + } else { + x = (childNodes[0].x + childNodes[childNodes.length - 1].x) / 2; + } + const node = { b: b, x: x, y: depth * GRAPH_LEVEL_H }; + nodes.push(node); + if (depth > maxDepth) maxDepth = depth; + childNodes.forEach(function (c) { links.push([node, c]); }); + return node; + }; + const roots = shape.roots.length ? shape.roots : blocks; + roots.forEach(function (r) { place(r, 0); }); + if (!nodes.length) return { nodes: [], links: [], width: 0, height: 0 }; + return { nodes: nodes, links: links, width: cursor - GRAPH_GAP_X, height: maxDepth * GRAPH_LEVEL_H + GRAPH_NODE_H }; + } + function buildGraphSvg(blocks) { + const layout = blockGraphLayout(blocks); + if (!layout.nodes.length) return ""; + const pad = 14; + const half = GRAPH_NODE_W / 2; + const W = Math.ceil(layout.width + pad * 2); + const H = Math.ceil(layout.height + pad * 2); + const fit = W > GRAPH_FIT_W ? GRAPH_FIT_W / W : 1; + const parts = []; + parts.push(''); + layout.links.forEach(function (l) { + const x1 = l[0].x + pad + half; + const y1 = l[0].y + pad + GRAPH_NODE_H; + const x2 = l[1].x + pad + half; + const y2 = l[1].y + pad; + const my = (y1 + y2) / 2; + parts.push(''); + }); + layout.nodes.forEach(function (n) { + const b = n.b; + const tierNum = Number(b.tier) || 1; + const cls = "g-node tier-" + (tierNum > 3 ? "n" : String(tierNum)) + (b.active ? "" : " inactive"); + const ratio = b.compressedTokens > 0 && b.summaryTokens > 0 ? (100 * b.summaryTokens / b.compressedTokens).toFixed(1) + "%" : ""; + const meta = fmtW(b.compressedTokens) + " → " + fmtW(b.summaryTokens) + (ratio ? " " + ratio : ""); + parts.push('' + + "" + escapeHtml(b.blockId + " · T" + tierNum + " · " + blockTopic(b)) + "" + + '' + + '' + escapeHtml(b.blockId + " · T" + tierNum) + "" + + '' + escapeHtml(meta) + "" + + ""); + }); + parts.push(""); + return parts.join(""); + } + function refRangeOf(b) { + if (!b.startRef) return ""; + return b.endRef && b.endRef !== b.startRef ? b.startRef + "–" + b.endRef : String(b.startRef); + } + function blockNodeHtml(b, shape, idx, depth) { + const kids = shape.children[b.blockId] || []; + const tierNum = Number(b.tier) || 1; + const openAttr = depth < 2 || (b.active && depth < 3) ? " open" : ""; + const badge = b.active + ? '' + t("det.block_active") + "" + : '' + t("det.block_inactive") + ""; + const extBadge = b.external ? '' + t("det.block_external") + "" : ""; + const refRange = refRangeOf(b); + const meta = ["T" + tierNum, fmtW(b.compressedTokens) + " → " + fmtW(b.summaryTokens)]; + if (b.compressedTokens > 0 && b.summaryTokens > 0) meta.push((100 * b.summaryTokens / b.compressedTokens).toFixed(1) + "%"); + meta.push(fmtB(b.summaryBytes)); + if (b.effectiveMessageCount) meta.push(t("det.tree_msgs", { n: b.effectiveMessageCount })); + if (refRange) meta.push(refRange); + meta.push(timeAgo(b.createdAt)); + const bid = escapeHtml(b.blockId); + let html = '
" + + '' + bid + "" + badge + extBadge + + '' + escapeHtml(blockTopic(b)) + "" + + '' + escapeHtml(meta.join(" · ")) + "" + + '" + + "" + + '
' + renderBlockMd(b.summary || "") + "
" + + '
' + + '" + + '" + + '' + escapeHtml(t("det.tree_direct", { n: Number(b.directMessageCount) || 0 })) + "" + + "
" + + ''; + // #3917: the messages this block folded, one leaf per mNNNNN ref. The + // preview is all the tree needs; the bytes arrive on the first click + // (the lazy endpoint), so a wide session never ships its transcript. + const msgs = b.directMessages || []; + if (msgs.length) { + html += '
    '; + msgs.forEach(function (m) { + if (m.missing) { + html += '
  • ' + escapeHtml(m.ref) + '' + t("det.tree_msg_gone") + "
  • "; + return; + } + const tags = m.toolName ? '' + escapeHtml(m.toolName) + "" : ""; + html += '
  • " + + '
  • '; + }); + html += "
"; + } else if (Number(b.directMessageCount) > 0) { + html += '
' + t("det.tree_msgs_unavailable") + "
"; + } + if (depth < 32) kids.forEach(function (k) { html += blockNodeHtml(k, shape, idx, depth + 1); }); + return html + "
"; + } + function buildTreePane(blocks) { + const parts = []; + parts.push('
' + t("det.blocks_title") + '' + t("det.blocks_count", { total: blocks.length, active: blocks.filter(function (b) { return b.active; }).length }) + '
'); + if (!blocks.length) { + parts.push('
' + t("det.blocks_empty") + "
"); + return parts.join(""); + } + const stats = blockTreeStats(blocks); + const tierBits = Object.keys(stats.tiers).sort(function (a, b) { return Number(a) - Number(b); }).map(function (k) { return "T" + k + " ×" + stats.tiers[k]; }); + parts.push('
' + + "" + escapeHtml(t("det.tree_total", { n: blocks.length })) + "" + + "" + escapeHtml(t("det.tree_active", { n: stats.active })) + "" + + "" + escapeHtml(t("det.tree_split", { x: fmtW(stats.coverTokens), y: fmtW(stats.summaryTokens), p: stats.coverTokens > 0 ? (100 * stats.summaryTokens / stats.coverTokens).toFixed(1) + "%" : t("common.none") })) + "" + + (tierBits.length ? "" + escapeHtml(tierBits.join(" · ")) + "" : "") + + "
"); + parts.push('
"); + const shape = blockTreeShape(blocks); + const idxOf = {}; + blocks.forEach(function (b, i) { if (idxOf[b.blockId] === undefined) idxOf[b.blockId] = i; }); + parts.push('
"); + parts.push('
'); + parts.push('
'); + const rootBlocks = shape.roots.length ? shape.roots : blocks; + rootBlocks.forEach(function (b) { parts.push(blockNodeHtml(b, shape, idxOf[b.blockId] || 0, 0)); }); + parts.push("
"); + parts.push('
' + t("det.tree_hint") + "
"); + parts.push("
"); + parts.push('"); + parts.push(""); + return parts.join(""); + } function buildDetailHtml(d) { 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") + '
'); + // #3917: the detail page splits into panes — overview (identity, usage, + // cache economics), the compression tree, and the handoff document. The + // blocks card moved out of the overview into its own tier-tree pane. + const blocks = d.blockDetails || []; + parts.push('
' + + '" + + '" + + '" + + "
"); + parts.push('
'); 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") + "") + "
"); @@ -1895,30 +2103,9 @@ export const WEB_CLIENT = `(function () { parts.push("
"); } parts.push("
"); - const blocks = d.blockDetails || []; // #2904: no-ceiling output-budget pin — surface at the top of the detail // so GUI users see WHY long turns truncate (the /acp twin). if (d.outputBudgetDegraded) parts.push('"); - const activeBlocks = blocks.filter((b) => b.active).length; - parts.push('
' + t("det.blocks_title") + '' + t("det.blocks_count", { total: blocks.length, active: activeBlocks }) + '
'); - if (!blocks.length) { - parts.push('
' + t("det.blocks_empty") + "
"); - } else { - // #1426: copy-all / download blocks-markdown actions - parts.push('
"); - blocks.forEach((b, i) => { - // #1426: expose the compressed conversation span (mNNNNN refs) when the kernel tagged it - const refRange = b.startRef ? (b.endRef && b.endRef !== b.startRef ? b.startRef + "–" + b.endRef : b.startRef) : null; - // Active = still inside the current context window; inactive = archived history. - const badge = b.active - ? '' + t("det.block_active") + "" - : '' + t("det.block_inactive") + ""; - // External summary chain wrote the summary — mirrors /acp's "⚡ext" marker. - const extBadge = b.external ? '' + t("det.block_external") + "" : ""; - parts.push('
' + escapeHtml(b.blockId) + '' + badge + extBadge + '' + escapeHtml(blockTopic(b)) + 'T' + String(b.tier) + " · " + fmtW(b.compressedTokens) + " · " + timeAgo(b.createdAt) + (refRange ? " · " + escapeHtml(refRange) : "") + '
' + renderBlockMd(b.summary || "") + "
"); - }); - } - parts.push("
"); if (Array.isArray(d.conflicts) && d.conflicts.length > 0) { // #2102: per-session evidence rows — the banner aggregates across sessions, // so this page is where its detail pointer lands. @@ -1933,7 +2120,10 @@ export const WEB_CLIENT = `(function () { parts.push('
"); parts.push(""); } - parts.push('
' + t("det.handoff") + '' + t("det.handoff_hint") + '
'); + parts.push("
"); + parts.push('"); + parts.push('"); return parts.join(""); } async function loadDetail(id) { @@ -1959,6 +2150,9 @@ export const WEB_CLIENT = `(function () { host.innerHTML = buildDetailHtml(d); bindHandoffActions(d); bindBlocksActions(d); + bindBlockContentActions(d); + bindTreeModeActions(); + bindDetTabs(); bindCacheReportActions(d); bindSessionReportActions(d); bindTrajectoryBrush(d); @@ -2146,6 +2340,120 @@ export const WEB_CLIENT = `(function () { btn.addEventListener("click", (ev) => { ev.preventDefault(); ev.stopPropagation(); copyText(buildBlockMd(b), btn); }); }); } + // #3917: pane switcher for the detail page — the last-used pane survives a + // reload so a user who lives on the tree does not re-click every visit. + function bindDetTabs() { + const tabs = $("det-tabs"); + if (!tabs) return; + const panes = document.querySelectorAll("#session-detail-view .det-pane"); + const show = (want) => { + tabs.querySelectorAll(".det-tab").forEach((b) => b.classList.toggle("active", b.getAttribute("data-pane") === want)); + panes.forEach((p) => { p.hidden = p.getAttribute("data-pane") !== want; }); + }; + tabs.querySelectorAll(".det-tab").forEach((btn) => { + btn.addEventListener("click", () => { + const want = btn.getAttribute("data-pane") || "overview"; + show(want); + try { sessionStorage.setItem("bili-det-pane", want); } catch (e) {} + }); + }); + let saved = "overview"; + try { saved = sessionStorage.getItem("bili-det-pane") || "overview"; } catch (e) {} + show(saved === "blocks" || saved === "handoff" ? saved : "overview"); + } + // #3917: lazy raw-content loader per block — the tree ships summary + numbers + // only; the conversation bytes behind a block come on demand. "one" is what + // decompress(block) hands back, "full" is the whole covered span. + function bindBlockContentActions(d) { + document.querySelectorAll(".blk-content-btn").forEach((btn) => { + btn.addEventListener("click", async (ev) => { + ev.preventDefault(); + ev.stopPropagation(); + const bid = btn.getAttribute("data-bid") || ""; + const view = btn.getAttribute("data-view") === "full" ? "full" : "one"; + const box = $("blk-content-" + bid); + if (!box) return; + if (box.getAttribute("data-state") === "ok" && box.getAttribute("data-view") === view) { box.hidden = false; return; } + box.hidden = false; + box.setAttribute("data-state", "loading"); + box.innerHTML = '
' + t("common.loading") + "
"; + busy(btn, true); + try { + const r = await json(API_ROOT + "/sessions/" + encodeURIComponent(d.id) + "/block-content?blockId=" + encodeURIComponent(bid) + "&view=" + view); + box.setAttribute("data-state", "ok"); + box.setAttribute("data-view", view); + const head = '"; + box.innerHTML = head + '
' + escapeHtml(r.text) + "
"; + } catch (e) { + box.setAttribute("data-state", "err"); + const msg = String(e && e.message ? e.message : e); + box.innerHTML = '
' + escapeHtml(msg.indexOf("no-content-snapshot") >= 0 ? t("det.tree_orig_missing") : msg) + "
"; + } finally { + busy(btn, false); + } + }); + }); + // #3917: message leaves — first click fetches that one message's text. + document.querySelectorAll(".msg-row").forEach((btn) => { + btn.addEventListener("click", async (ev) => { + ev.preventDefault(); + ev.stopPropagation(); + const row = btn.closest("li"); + const box = row ? row.querySelector(".msg-body") : null; + if (!box) return; + if (!box.hidden) { box.hidden = true; return; } + if (box.getAttribute("data-state") === "ok") { box.hidden = false; return; } + box.hidden = false; + box.setAttribute("data-state", "loading"); + box.innerHTML = '
' + t("common.loading") + "
"; + try { + const ref = btn.getAttribute("data-ref") || ""; + const r = await json(API_ROOT + "/sessions/" + encodeURIComponent(d.id) + "/message?ref=" + encodeURIComponent(ref)); + box.setAttribute("data-state", "ok"); + const meta = '"; + box.innerHTML = meta + '
' + escapeHtml(r.text) + "
"; + } catch (e) { + box.setAttribute("data-state", "err"); + const msg = String(e && e.message ? e.message : e); + box.innerHTML = '
' + escapeHtml(msg.indexOf("unknown-message") >= 0 ? t("det.tree_msg_gone") : msg) + "
"; + } + }); + }); + } + // #3917: the compression pane carries two readings of the same data — the + // list (read concrete messages) and the graph (read the overall shape). + // Clicking a graph node jumps back to that block's expanded row in the list. + function bindTreeModeActions() { + const list = $("tree-list"); + const graph = $("tree-graph"); + if (!list || !graph) return; + const btns = Array.prototype.slice.call(document.querySelectorAll(".tree-mode")); + const setMode = function (mode) { + const g = mode === "graph"; + list.hidden = g; + graph.hidden = !g; + btns.forEach(function (b) { b.classList.toggle("active", b.getAttribute("data-mode") === mode); }); + }; + btns.forEach(function (b) { + b.addEventListener("click", function (ev) { + ev.preventDefault(); + setMode(b.getAttribute("data-mode") === "graph" ? "graph" : "list"); + }); + }); + graph.querySelectorAll(".g-node").forEach(function (n) { + n.addEventListener("click", function () { + const bid = n.getAttribute("data-bid"); + if (!bid) return; + setMode("list"); + const row = document.querySelector('.block-node[data-bid="' + bid + '"]'); + if (!row) return; + row.open = true; + row.classList.add("flash"); + row.scrollIntoView({ block: "center", behavior: "smooth" }); + setTimeout(function () { row.classList.remove("flash"); }, 1600); + }); + }); + } function bindCacheReportActions(d) { const copyB = $("cacherpt-copy"); const dlB = $("cacherpt-dl"); diff --git a/src/web/i18n.ts b/src/web/i18n.ts index 4bbcb7c5ba..1aa5b301ea 100644 --- a/src/web/i18n.ts +++ b/src/web/i18n.ts @@ -354,6 +354,26 @@ export const MESSAGES: Record> = { "det.rpt_missed": "未命中", "det.rpt_hit": "命中率", "det.blocks_copy_md": "复制 Markdown", + "det.tab_overview": "概览", + "det.tab_blocks": "压缩结构", + "det.tab_handoff": "交接文档", + "det.tree_total": "共 {n} 块", + "det.tree_active": "活跃 {n}", + "det.tree_split": "覆盖 {x} → 摘要 {y}({p})", + "det.tree_msgs": "{n} 条消息", + "det.tree_direct": "直属 {n} 条", + "det.tree_orig_one": "原文(本层)", + "det.tree_orig_full": "原文(全部)", + "det.tree_orig_meta": "{n} 条消息 · {b}", + "det.tree_orig_truncated": "已截断至 {b}", + "det.tree_orig_missing": "该块未保存原文快照(压缩时未保留,或已被清理)", + "det.tree_msgs_unavailable": "该块的直属消息已不在会话里(可能被原生压缩清理),无法列出 m 编号", + "det.tree_msg_gone": "该消息已不在会话里(可能被原生压缩清理)", + "det.tree_hint": "按压缩的父子关系嵌套:T1 收原始消息,T2 收 T1 的块,以此类推。点「原文」按需加载内容。", + "det.tree_view_list": "列表", + "det.tree_view_graph": "树图", + "det.tree_graph_hint": "整体形状:每个方块是一个压缩块,从上到下是「谁压缩了谁」。点方块跳到列表里对应的一行。", + "det.tree_graph_legend": "实线框=活跃,虚线框=已归档", "det.handoff": "会话交接文档", "det.handoff_hint": "与 bili export 相同的内容 —— 复制粘贴到新会话即可继续", "det.thinking": "思考", @@ -847,6 +867,26 @@ export const MESSAGES: Record> = { "det.rpt_missed": "missed", "det.rpt_hit": "hit %", "det.blocks_copy_md": "copy Markdown", + "det.tab_overview": "Overview", + "det.tab_blocks": "Structure", + "det.tab_handoff": "Handoff", + "det.tree_total": "{n} blocks", + "det.tree_active": "{n} active", + "det.tree_split": "covered {x} → summary {y} ({p})", + "det.tree_msgs": "{n} msgs", + "det.tree_direct": "{n} direct", + "det.tree_orig_one": "Original (this level)", + "det.tree_orig_full": "Original (full)", + "det.tree_orig_meta": "{n} messages · {b}", + "det.tree_orig_truncated": "truncated at {b}", + "det.tree_orig_missing": "No content snapshot for this block (not kept at fold time, or already pruned)", + "det.tree_msgs_unavailable": "This block's direct messages are no longer in the session (pruned by native compaction) — their m-refs cannot be listed", + "det.tree_msg_gone": "This message is no longer in the session (pruned by native compaction)", + "det.tree_hint": "Nested by fold parent: T1 folds raw messages, T2 folds T1 blocks, and so on. Original loads the covered bytes on demand.", + "det.tree_view_list": "List", + "det.tree_view_graph": "Tree map", + "det.tree_graph_hint": "Overall shape: each box is one block, top-down is which block folded which. Click a box to jump to that row in the list.", + "det.tree_graph_legend": "solid border = active, dashed = archived", "det.handoff": "Handoff document", "det.handoff_hint": "Same content as bili export — paste into a new session to continue", "det.thinking": "thinking", diff --git a/src/web/index.ts b/src/web/index.ts index 708dd5475b..0878a71528 100644 --- a/src/web/index.ts +++ b/src/web/index.ts @@ -9,7 +9,8 @@ export { readUpstreamSettings, } from "./api.js"; -export { buildOverview, buildSessionList, buildSessionPage, buildSessionDetail, hiddenEmptyCount } from "./sessions-data.js"; +export { buildOverview, buildSessionList, buildSessionPage, buildSessionDetail, buildBlockContent, buildMessageContent, hiddenEmptyCount } from "./sessions-data.js"; +export type { BlockContentLookup, BlockContentView, MessageContentLookup } from "./sessions-data.js"; export function renderUI(origin: string, opts?: { embed?: boolean; theme?: "light" | "dark" }): string { // #1426 fix: reuse the bundle-safe VERSION from src/version.ts — resolving diff --git a/src/web/sessions-data.ts b/src/web/sessions-data.ts index 237ce9c60d..36d27a34f5 100644 --- a/src/web/sessions-data.ts +++ b/src/web/sessions-data.ts @@ -1,5 +1,5 @@ -import { orderedRefPair } from "acp-kernel"; -import { listSessions, displayContextBest, type ContextBest, type Session } from "../session.js"; +import { defaultCountTokens, orderedRefPair } from "acp-kernel"; +import { listSessions, displayContextBest, type ContextBest, type Session, type BlockContent } from "../session.js"; import { conflictClientOf, conflictEventsOf } from "../conflict-watch.js"; import { isDisplayOnlyConflictDetail, isSiblingConflictDetail } from "../thirdparty-scan.js"; import { SessionStore, fileNameMatchesId, isValidRecord, relPathFor } from "../persist.js"; @@ -211,6 +211,29 @@ interface WebSessionDetail extends WebSessionSummary { /** Present when the block's summary was written by the external * summary chain — the web block badge mirrors /acp's "⚡ext". */ external?: true; + /** #3917: blockId of the tier-above block that folded THIS one in + * (`CompressionBlock.directBlockIds` inverted). Absent = tree root. + * The 压缩结构 tab rebuilds the tier tree from these edges. */ + parentBlockId?: string; + /** #3917: blocks this one absorbed when it was created (T2 covers T1s, + * T3 covers T2s …); kept verbatim so the tree never has to infer. */ + directBlockIds: string[]; + /** #3917: Σ messages covered by this block AND its children — the + * "N 条消息" the tree line shows. */ + effectiveMessageCount: number; + /** #3917: messages this block folded directly (not through children). */ + directMessageCount: number; + /** #3917: direct messages resolved to their mNNNNN refs (unresolvable + * raw ids are omitted; `directMessageCount` still counts them). */ + directMessageRefs: string[]; + /** #3917: the block's direct messages as tree leaves — ref, role and a + * short preview only; the full text stays behind the lazy endpoint. + * `missing` marks a ref whose bytes are no longer stored (host prune). */ + directMessages: Array<{ ref: string; role?: string; toolName?: string; preview?: string; missing?: boolean }>; + /** #3917: summary size on the wire — tokens (same estimator the kernel + * status uses) and UTF-8 bytes, so the tree can show size + ratio. */ + summaryTokens: number; + summaryBytes: number; }>; } @@ -924,35 +947,37 @@ export async function buildOverview(): Promise { const detailInFlight = new Map>(); +/** #2960 R2.2: unified-first — loadSync resolves the index row even when the + * legacy file is gone; otherwise fall through to the decoded disk-index file. + * Returns null when the id is unknown. Never creates sessions — lookups go + * through listSessions() + ONE decoded disk file (#1937: the old path scanned + * the entire directory for a single id). */ +async function loadSessionById(id: string): Promise<{ session: Session; live: boolean } | null> { + const live = listSessions().find((s) => s.id === id); + if (live) return { session: live, live: true }; + const synced = getDiskStore().loadSync(id); + if (synced) return { session: synced, live: false }; + const files = await ensureIndex(); + const abs = byId?.get(id); + if (abs && files.has(abs)) { + detailDecodes++; + const decoded = await getDiskStore().loadSessionFromFile(abs, id); + if (decoded) return { session: decoded, live: false }; + } + return null; +} + /** Full detail for one session: stats + compression blocks + the per-request * cache ledger (trajectory-chart source) + rendered handoff document. - * Returns null when the id is unknown (→ 404). Never creates sessions — - * lookups go through listSessions() + ONE decoded disk file (#1937: the old - * path scanned the entire directory for a single id). Concurrent requests - * for the same id share one decode. */ + * Returns null when the id is unknown (→ 404). Concurrent requests for the + * same id share one decode. */ export function buildSessionDetail(id: string): Promise { const existing = detailInFlight.get(id); if (existing) return existing; const run = (async (): Promise => { - const live = listSessions().find((s) => s.id === id); - let session: Session | undefined = live; - if (!session) { - // #2960 R2.2: unified-first — in full mode loadSync resolves the - // index row even when the legacy file is gone; in legacy/shadow it - // composes an origin-less path and misses, falling through to the - // disk-index file below. - session = getDiskStore().loadSync(id) ?? undefined; - } - if (!session) { - const files = await ensureIndex(); - const abs = byId?.get(id); - if (abs && files.has(abs)) { - detailDecodes++; - session = (await getDiskStore().loadSessionFromFile(abs, id)) ?? undefined; - } - } - if (!session) return null; - return renderDetail(session, !!live); + const found = await loadSessionById(id); + if (!found) return null; + return renderDetail(found.session, found.live); })(); const done = run.finally(() => detailInFlight.delete(id)); detailInFlight.set(id, done); @@ -988,6 +1013,54 @@ function renderDetail(session: Session, live: boolean): WebSessionDetail { const conflicts = conflictEventsOf(session).filter((e) => !(e.kind === "third-party-plugin" && (isSiblingConflictDetail(e.detail) || isDisplayOnlyConflictDetail(e.detail)))); const conflictClient = conflicts.length > 0 ? conflictClientOf(session) : undefined; + // #3917: tier-tree edges. `directBlockIds` is the child list; the tree needs + // the inverse to know which blocks are roots. First parent wins (the kernel + // never lets two blocks fold the same child). + const parentBlockIdOf = new Map(); + for (const b of session.state.blocks) { + for (const childId of b.directBlockIds || []) { + if (!parentBlockIdOf.has(childId)) parentBlockIdOf.set(childId, b.blockId); + } + } + const byRaw = session.state.messageRefs.byRaw; + const refsOf = (rawIds: string[]): string[] => { + const out: string[] = []; + for (const raw of rawIds) { + const ref = byRaw[raw]; + if (typeof ref === "string" && ref.length > 0) out.push(ref); + } + return out; + }; + // #3917: message leaves. `lastMessages` is the newest full request the + // client sent (folded messages included — a client never drops them because + // of OUR folding), so the tree can name every message a block folded — ref, + // role, preview — without shipping a byte of full text. A raw id with no + // resident message (host-pruned / archived-only session) simply has no leaf; + // `directMessageCount` still tells the UI how many were folded. + const messageById = new Map((session.lastMessages || []).map((m) => [m.id, m])); + const messageLeaves = (rawIds: string[]): Array<{ ref: string; role?: string; toolName?: string; preview?: string; missing?: boolean }> => { + const out: Array<{ ref: string; role?: string; toolName?: string; preview?: string; missing?: boolean }> = []; + for (const raw of rawIds) { + const ref = byRaw[raw]; + if (typeof ref !== "string" || ref.length === 0) continue; + const msg = messageById.get(raw); + // #3917: a folded message whose bytes are gone from the store still + // gets a row — the ref is the identity the user asked for — but it + // carries no preview and the UI says so instead of inventing text. + if (!msg) { + out.push({ ref, missing: true }); + continue; + } + out.push({ + ref, + role: msg.role, + ...(msg.toolName !== undefined ? { toolName: msg.toolName } : {}), + preview: messagePreview(msg.text ?? ""), + }); + } + return out; + }; + return { ...summaryOf(session, live), lastInputTokens: session.stats.lastInputTokens, @@ -1056,7 +1129,168 @@ function renderDetail(session: Session, live: boolean): WebSessionDetail { ...(span === null && b.endRef !== undefined ? { endRef: b.endRef } : {}), active: b.active, ...(isExternalSummaryBlock(b) ? { external: true } : {}), + ...(parentBlockIdOf.get(b.blockId) !== undefined ? { parentBlockId: parentBlockIdOf.get(b.blockId) } : {}), + directBlockIds: (b.directBlockIds || []).slice(), + effectiveMessageCount: (b.effectiveMessageIds || []).length, + directMessageCount: (b.directMessageIds || []).length, + directMessageRefs: refsOf(b.directMessageIds || []), + directMessages: messageLeaves(b.directMessageIds || []), + summaryTokens: defaultCountTokens(b.summary), + summaryBytes: utf8Bytes(b.summary), }; }), }; } + +// --------------------------------------------------------------------------- +// #3917 lazy block content — the 压缩结构 tree fetches ONE block at a time +// --------------------------------------------------------------------------- + +export type BlockContentView = "one" | "full"; + +export type BlockContentLookup = + | { ok: true; blockId: string; view: BlockContentView; count: number; bytes: number; totalBytes: number; truncated: boolean; text: string } + | { ok: false; reason: "unknown-session" | "unknown-block" | "no-content-snapshot" }; + +/** Cap on a single block's returned text: the tree renders original messages in + * a
, and a huge block would freeze the browser + bloat the response. The
+ *  full size is always reported via `totalBytes` so the UI can say "truncated". */
+const BLOCK_CONTENT_MAX_BYTES = 2 * 1024 * 1024;
+
+/** #3917: one-line preview for a message leaf — whitespace collapsed so a
+ *  multi-line tool output still fits the tree row. */
+const MESSAGE_PREVIEW_CHARS = 110;
+
+function messagePreview(text: string): string {
+    const flat = text.replace(/\s+/g, " ").trim();
+    const chars = Array.from(flat);
+    return chars.length > MESSAGE_PREVIEW_CHARS ? chars.slice(0, MESSAGE_PREVIEW_CHARS).join("") + "…" : flat;
+}
+
+function utf8Bytes(s: string): number {
+    return Buffer.byteLength(s, "utf8");
+}
+
+/** Largest prefix of `s` whose UTF-8 encoding fits in `maxBytes`, never cutting
+ *  a surrogate pair in half (a lone surrogate would surface as U+FFFD). */
+function sliceUtf8(s: string, maxBytes: number): string {
+    let lo = 0;
+    let hi = s.length;
+    while (lo < hi) {
+        const mid = Math.ceil((lo + hi) / 2);
+        if (utf8Bytes(s.slice(0, mid)) > maxBytes) hi = mid - 1;
+        else lo = mid;
+    }
+    let end = lo;
+    if (end > 0 && end < s.length) {
+        const code = s.charCodeAt(end - 1);
+        if (code >= 0xd800 && code <= 0xdbff) end -= 1;
+    }
+    return s.slice(0, end);
+}
+
+/** #3917: short-lived decode cache — the tree issues one request per block the
+ *  user opens, and every request would otherwise re-decode the whole session
+ *  file AND re-materialize its block contents (the expensive part). Keyed by
+ *  session id with a small TTL: the panel is read-only diagnostics, so a
+ *  sub-minute stale snapshot is acceptable, and the entry disappears on its
+ *  own. Bounded at 2 entries so resident memory stays flat. */
+const contentCache = new Map();
+const CONTENT_CACHE_MS = 60_000;
+const CONTENT_CACHE_MAX = 2;
+
+async function sessionForContent(id: string): Promise {
+    const hit = contentCache.get(id);
+    if (hit && Date.now() - hit.at <= CONTENT_CACHE_MS) return hit.session;
+    const loaded = await loadSessionById(id);
+    if (!loaded) return null;
+    cachedSession(id, loaded.session);
+    return loaded.session;
+}
+
+function cachedSession(id: string, session: Session): void {
+    const now = Date.now();
+    for (const [key, entry] of contentCache) {
+        if (now - entry.at > CONTENT_CACHE_MS) contentCache.delete(key);
+    }
+    while (contentCache.size >= CONTENT_CACHE_MAX) {
+        const oldest = contentCache.keys().next();
+        if (oldest.done) break;
+        contentCache.delete(oldest.value);
+    }
+    contentCache.set(id, { at: now, session });
+}
+
+/** #3917: one block's frozen original text, exactly as the compressor saw it.
+ *  `one` = the block's direct messages in full plus its children's summaries
+ *  (the one-tier-up view `collectBlockContent` builds); `full` = EVERY message
+ *  the block covers, children included. Both come from the snapshot cached on
+ *  the session at compression time (#401), so they survive later pruning of the
+ *  live message list. Missing snapshot → `no-content-snapshot` (the UI says so;
+ *  it never fabricates a view from whatever messages happen to remain). */
+export async function buildBlockContent(id: string, blockId: string, view: BlockContentView): Promise {
+    const session = await sessionForContent(id);
+    if (!session) return { ok: false, reason: "unknown-session" };
+    const block = session.state.blocks.find((b) => b.blockId === blockId);
+    if (!block) return { ok: false, reason: "unknown-block" };
+    let content: BlockContent | undefined;
+    try {
+        content = session.blockContents.get(blockId);
+    } catch (error) {
+        // #3917: a corrupt/unreadable content store must not 500 the panel —
+        // report it as "no snapshot" and let the UI explain.
+        log("warn", `[acp-web] block content read failed for ${id}/${blockId}: ${String(error)}`);
+        content = undefined;
+    }
+    const picked = content ? (view === "one" ? (content.one ?? content.full) : content.full) : null;
+    if (!picked) return { ok: false, reason: "no-content-snapshot" };
+    const totalBytes = utf8Bytes(picked.text);
+    const truncated = totalBytes > BLOCK_CONTENT_MAX_BYTES;
+    return {
+        ok: true,
+        blockId,
+        view,
+        count: picked.count,
+        bytes: truncated ? BLOCK_CONTENT_MAX_BYTES : totalBytes,
+        totalBytes,
+        truncated,
+        text: truncated ? sliceUtf8(picked.text, BLOCK_CONTENT_MAX_BYTES) : picked.text,
+    };
+}
+
+// ---------------------------------------------------------------------------
+// #3917 single-message leaves — the tier tree lists the mNNNNN messages a block
+// folded; their bytes load one click at a time, so a 3000-message session never
+// ships its transcript to the browser just to draw the tree.
+// ---------------------------------------------------------------------------
+
+export type MessageContentLookup =
+    | { ok: true; ref: string; role: string; toolName?: string; bytes: number; totalBytes: number; truncated: boolean; text: string }
+    | { ok: false; reason: "unknown-session" | "unknown-message" };
+
+/** #3917: ONE message's text, addressed by its ref. Resolves the ref to its raw
+ *  id and reads the message out of the newest request snapshot (`lastMessages`),
+ *  which still carries the messages this proxy folded — folding only changes the
+ *  OUTBOUND projection, never what the client keeps sending. A ref whose message
+ *  is gone (host-side native compaction pruning) reports `unknown-message`
+ *  instead of guessing. */
+export async function buildMessageContent(id: string, ref: string): Promise {
+    const session = await sessionForContent(id);
+    if (!session) return { ok: false, reason: "unknown-session" };
+    const raw = session.state.messageRefs.byRef[ref];
+    const msg = typeof raw === "string" ? (session.lastMessages || []).find((m) => m.id === raw) : undefined;
+    if (!msg) return { ok: false, reason: "unknown-message" };
+    const text = msg.text ?? "";
+    const totalBytes = utf8Bytes(text);
+    const truncated = totalBytes > BLOCK_CONTENT_MAX_BYTES;
+    return {
+        ok: true,
+        ref,
+        role: msg.role,
+        ...(msg.toolName !== undefined ? { toolName: msg.toolName } : {}),
+        bytes: truncated ? BLOCK_CONTENT_MAX_BYTES : totalBytes,
+        totalBytes,
+        truncated,
+        text: truncated ? sliceUtf8(text, BLOCK_CONTENT_MAX_BYTES) : text,
+    };
+}
diff --git a/src/web/styles.ts b/src/web/styles.ts
index 41675a28b0..241b4b85d8 100644
--- a/src/web/styles.ts
+++ b/src/web/styles.ts
@@ -249,6 +249,59 @@ td.num, th.num { text-align: right; font-variant-numeric: tabular-nums; font-fam
 .block-item .body.md hr { border: none; border-top: 1px solid var(--border); margin: 10px 0; }
 .block-item .body.md strong { color: var(--text); }
 
+/* #3917: detail-page panes + compression tree */
+.det-tabs { display: flex; gap: 4px; margin: 16px 0 0; border-bottom: 1px solid var(--border); }
+.det-tab { background: none; border: none; border-bottom: 2px solid transparent; padding: 8px 14px; font-size: 13px; font-weight: 600; color: var(--text-muted); cursor: pointer; }
+.det-tab:hover { color: var(--text); }
+.det-tab.active { color: var(--accent); border-bottom-color: var(--accent); }
+.det-tab .hint { font-weight: 400; }
+.det-pane { margin-top: 16px; }
+.tree-stats { display: flex; gap: 16px; flex-wrap: wrap; padding: 2px 0 10px; color: var(--text-muted); }
+.tree-actions { display: flex; gap: 8px; margin: 0 0 10px; flex-wrap: wrap; }
+.block-tree { max-height: 70vh; overflow-y: auto; border-top: 1px solid var(--border-soft); }
+/* #3917: list ⇄ graph switch for the compression pane, plus the graph itself
+   (layered block boxes on a light canvas, tier-tinted borders). */
+.tree-modes { display: flex; gap: 6px; margin: 0 0 10px; }
+.tree-mode { color: var(--text-muted); }
+.tree-mode.active { color: var(--accent); border-color: var(--accent); background: var(--bg-muted); }
+.tree-graph { max-height: 70vh; overflow: auto; border-top: 1px solid var(--border-soft); padding: 12px 8px 8px; background: var(--bg-muted); border-radius: 0 0 10px 10px; }
+.g-svg { display: block; max-width: 100%; height: auto; }
+.g-edge { stroke: var(--accent); stroke-width: 1.6; opacity: .5; }
+.g-node { cursor: pointer; }
+.g-node rect { fill: #fff; stroke: var(--border-soft); stroke-width: 1.4; }
+.g-node.tier-1 rect { stroke: var(--accent); fill: #f2f7ff; }
+.g-node.tier-2 rect { stroke: #7a5af8; fill: #f6f3ff; }
+.g-node.tier-3 rect { stroke: #bf8700; fill: #fffaf0; }
+.g-node.tier-n rect { stroke: #8a8f99; fill: #f7f8fa; }
+.g-node.inactive rect { stroke-dasharray: 4 3; opacity: .75; }
+.g-node:hover rect { stroke-width: 2.4; }
+.g-id { font: 600 11px ui-monospace, SFMono-Regular, Menlo, monospace; fill: var(--text); }
+.g-meta { font: 10px ui-monospace, SFMono-Regular, Menlo, monospace; fill: var(--text-muted); }
+.block-node.flash { outline: 2px solid var(--accent); outline-offset: 2px; border-radius: 8px; }
+.block-node .block-node { margin-left: 18px; border-left: 2px solid var(--border-soft); }
+.block-node summary { align-items: center; flex-wrap: wrap; row-gap: 4px; }
+.block-node summary .blk-copy { margin-left: auto; flex: none; }
+.block-node summary .meta { overflow: hidden; text-overflow: ellipsis; min-width: 0; flex: 0 1 auto; }
+.block-node .topic { flex: 1 1 140px; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+.block-node .body { padding: 0 16px 10px 70px; }
+.block-node .blk-content-bar { display: flex; gap: 8px; align-items: center; flex-wrap: wrap; padding: 0 16px 8px 70px; }
+.block-node .blk-content { margin: 0 16px 12px 70px; }
+.blk-content-meta { color: var(--text-muted); margin-bottom: 6px; }
+.blk-msgs { list-style: none; margin: 0 16px 10px 70px; padding: 0; border-left: 1px dashed var(--border-soft); }
+.blk-msgs li { margin: 0; }
+.msg-row { display: flex; align-items: center; gap: 8px; width: 100%; text-align: left; background: none; border: 0; border-radius: 6px; padding: 4px 6px; cursor: pointer; color: var(--text-muted); font: inherit; }
+.msg-row:hover { background: var(--bg-muted); color: var(--text); }
+.msg-row.missing { cursor: default; opacity: .65; }
+.msg-row.missing:hover { background: none; color: var(--text-muted); }
+.msg-row .mref { color: var(--text); font-size: 12px; flex: none; }
+.msg-row .mprev { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; min-width: 0; font-size: 12px; }
+.msg-row .badge { flex: none; }
+.blk-msgs .msg-body { margin: 0 6px 8px 8px; }
+.blk-msgs .msg-body .blk-content-pre { max-height: 320px; }
+.blk-content-pre { background: var(--bg-muted); border: 1px solid var(--border-soft); border-radius: 8px; padding: 10px 12px; overflow: auto; max-height: 420px; white-space: pre-wrap; word-break: break-word; }
+.tier-1 summary .bid { color: var(--accent); }
+.warn-text { color: #bf8700; }
+
 .handoff { font-size: 13.5px; line-height: 1.65; }
 .handoff h1, .handoff h2, .handoff h3, .handoff h4 { margin: 18px 0 8px; line-height: 1.3; }
 .handoff h1 { font-size: 17px; } .handoff h2 { font-size: 15.5px; } .handoff h3 { font-size: 14px; }
diff --git a/tests/web-blocks-tree.test.ts b/tests/web-blocks-tree.test.ts
new file mode 100644
index 0000000000..5257669e45
--- /dev/null
+++ b/tests/web-blocks-tree.test.ts
@@ -0,0 +1,215 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+import { mkdtempSync } from "node:fs";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import vm from "node:vm";
+import { createInitialState, defaultCountTokens } from "acp-kernel";
+import type { CompressionBlock } from "acp-kernel";
+import { LazyBlockContents, _resetSessionsForTest, getSession } from "../src/session.ts";
+import { SessionStore, _setStoreForTest } from "../src/persist.ts";
+import { _resetDiskCacheForTest, buildBlockContent, buildMessageContent, buildSessionDetail } from "../src/web/sessions-data.ts";
+import { MESSAGES } from "../src/web/i18n.ts";
+import { WEB_CLIENT } from "../src/web/client.ts";
+
+process.env.BILI_PERSIST_ZSTD = "0";
+process.env.BILI_STORAGE_UNIFIED = "legacy";
+process.env.BILI_SESSIONS_DIR = mkdtempSync(path.join(tmpdir(), "bili-blocks-tree-sess-"));
+process.env.BILI_CONFIG_FILE = path.join(mkdtempSync(path.join(tmpdir(), "bili-blocks-tree-")), "no-config.json");
+
+// #3917: the compression-tree lane is read-only web diagnostics — no store, no
+// disk, every fixture is an in-memory live session.
+_setStoreForTest(new SessionStore({ enabled: false }));
+
+function mkBlock(
+    blockId: string,
+    tier: number,
+    summary: string,
+    direct: string[],
+    effective: string[],
+    kids: string[] = [],
+    span?: [string, string],
+): CompressionBlock {
+    return {
+        blockId,
+        runId: "run-1",
+        tier: tier as CompressionBlock["tier"],
+        summary,
+        directMessageIds: direct,
+        effectiveMessageIds: effective,
+        directBlockIds: kids,
+        compressedTokens: 1000 * tier,
+        createdAt: 1_700_000_000_000 - 1000 * tier,
+        survivedCount: 0,
+        generation: "young",
+        active: true,
+        ...(span ? { startRef: span[0], endRef: span[1] } : {}),
+    };
+}
+
+function seedSession(id: string, blocks: CompressionBlock[]): ReturnType {
+    _resetSessionsForTest();
+    const s = getSession(id, { protocol: "openai" });
+    s.state = createInitialState();
+    s.state.blocks = blocks;
+    s.blockContents = new LazyBlockContents(id, {}, () => null);
+    return s;
+}
+
+test("#3917: detail carries fold-parent links and summary accounting for the tree", async () => {
+    const t1 = mkBlock("b1", 1, "## T1 summary\n- point one", ["rm1", "rm2"], ["rm1", "rm2"], [], ["m00001", "m00002"]);
+    const t2 = mkBlock("b2", 2, "T2 summary", ["rm3"], ["rm1", "rm2", "rm3"], ["b1"], ["m00001", "m00003"]);
+    seedSession("tree-1", [t1, t2]);
+    _resetDiskCacheForTest();
+    const d = await buildSessionDetail("tree-1");
+    assert.ok(d, "live session resolves");
+    const byId = new Map(d.blockDetails.map((b) => [b.blockId, b]));
+    const b1 = byId.get("b1")!;
+    const b2 = byId.get("b2")!;
+    assert.equal(b1.parentBlockId, "b2", "the folded child points at the block that absorbed it");
+    assert.equal(b2.parentBlockId, undefined, "a root has no fold parent");
+    assert.deepEqual(b2.directBlockIds, ["b1"], "children survive in the payload so the tree can nest");
+    assert.equal(b1.effectiveMessageCount, 2);
+    assert.equal(b1.directMessageCount, 2);
+    assert.equal(b1.summaryTokens, defaultCountTokens(t1.summary), "summary tokens are the kernel's own count");
+    assert.equal(b1.summaryBytes, Buffer.byteLength(t1.summary));
+    assert.equal(b2.startRef, "m00001");
+    assert.equal(b2.endRef, "m00003");
+    assert.equal(b1.active, true);
+});
+
+test("#3917: buildBlockContent serves one/full views and reports honest misses", async () => {
+    const s = seedSession("tree-content", [mkBlock("b1", 1, "s", ["m1"], ["m1"])]);
+    s.blockContents.set("b1", { one: { text: "one-body", count: 1 }, full: { text: "full-body-longer", count: 3 } });
+
+    const one = await buildBlockContent("tree-content", "b1", "one");
+    assert.ok(one.ok);
+    assert.equal(one.text, "one-body");
+    assert.equal(one.count, 1);
+    assert.equal(one.view, "one");
+    assert.equal(one.bytes, Buffer.byteLength("one-body"));
+    assert.equal(one.totalBytes, one.bytes);
+    assert.equal(one.truncated, false);
+
+    const full = await buildBlockContent("tree-content", "b1", "full");
+    assert.ok(full.ok);
+    assert.equal(full.text, "full-body-longer");
+    assert.equal(full.count, 3);
+
+    assert.deepEqual(await buildBlockContent("tree-content", "missing", "one"), { ok: false, reason: "unknown-block" });
+    assert.deepEqual(await buildBlockContent("no-such-session", "b1", "one"), { ok: false, reason: "unknown-session" });
+
+    s.state.blocks.push(mkBlock("b2", 1, "no snapshot", [], []));
+    assert.deepEqual(await buildBlockContent("tree-content", "b2", "one"), { ok: false, reason: "no-content-snapshot" });
+});
+
+test("#3917: an oversized block truncates at the byte cap and still reports the full size", async () => {
+    const s = seedSession("tree-big", [mkBlock("b1", 1, "s", ["m1"], ["m1"])]);
+    const huge = "x".repeat(2 * 1024 * 1024 + 64);
+    s.blockContents.set("b1", { one: { text: huge, count: 9 }, full: { text: huge, count: 9 } });
+    const r = await buildBlockContent("tree-big", "b1", "full");
+    assert.ok(r.ok);
+    assert.equal(r.truncated, true);
+    assert.equal(r.bytes, 2 * 1024 * 1024);
+    assert.equal(r.totalBytes, huge.length);
+    assert.equal(r.text.length, 2 * 1024 * 1024);
+});
+
+test("#3917: a block stored before directBlockIds existed neither throws nor nests", async () => {
+    const legacy = mkBlock("b1", 1, "s", ["m1"], ["m1"]);
+    delete (legacy as { directBlockIds?: string[] }).directBlockIds;
+    delete (legacy as { effectiveMessageIds?: string[] }).effectiveMessageIds;
+    delete (legacy as { directMessageIds?: string[] }).directMessageIds;
+    seedSession("tree-legacy", [legacy]);
+    _resetDiskCacheForTest();
+    const d = await buildSessionDetail("tree-legacy");
+    assert.ok(d, "a partial legacy block still renders");
+    const b1 = d.blockDetails[0];
+    assert.deepEqual(b1.directBlockIds, []);
+    assert.equal(b1.effectiveMessageCount, 0);
+    assert.equal(b1.directMessageCount, 0);
+    assert.deepEqual(b1.directMessageRefs, []);
+    assert.equal(b1.parentBlockId, undefined);
+});
+
+test("#3917: message leaves name each folded message and serve its text lazily", async () => {
+    const s = seedSession("tree-msgs", [mkBlock("b1", 1, "s", ["rm1", "rm2"], ["rm1", "rm2"])]);
+    s.state.messageRefs = { byRaw: { rm1: "m00001", rm2: "m00002" }, byRef: { m00001: "rm1", m00002: "rm2" } };
+    s.lastMessages = [
+        { id: "rm1", role: "user", contentType: "text", text: "hello   there\nworld" },
+        { id: "rm2", role: "assistant", contentType: "text", text: "hi" },
+    ];
+    _resetDiskCacheForTest();
+    const d = await buildSessionDetail("tree-msgs");
+    assert.ok(d);
+    assert.deepEqual(d.blockDetails[0].directMessages, [
+        { ref: "m00001", role: "user", preview: "hello there world" },
+        { ref: "m00002", role: "assistant", preview: "hi" },
+    ]);
+    const one = await buildMessageContent("tree-msgs", "m00001");
+    assert.ok(one.ok);
+    assert.equal(one.role, "user");
+    assert.equal(one.text, "hello   there\nworld", "the leaf serves the message verbatim, whitespace intact");
+    assert.equal(one.totalBytes, Buffer.byteLength("hello   there\nworld"));
+    assert.deepEqual(await buildMessageContent("tree-msgs", "m99999"), { ok: false, reason: "unknown-message" });
+    assert.deepEqual(await buildMessageContent("no-such-session", "m00001"), { ok: false, reason: "unknown-session" });
+});
+
+test("#3917: a folded message the host pruned reports a miss instead of a guess", async () => {
+    const s = seedSession("tree-pruned", [mkBlock("b1", 1, "s", ["rm1"], ["rm1"])]);
+    s.state.messageRefs = { byRaw: { rm1: "m00001" }, byRef: { m00001: "rm1" } };
+    s.lastMessages = [];
+    _resetDiskCacheForTest();
+    const d = await buildSessionDetail("tree-pruned");
+    assert.ok(d);
+    assert.deepEqual(d.blockDetails[0].directMessages, [{ ref: "m00001", missing: true }], "the ref survives even when its bytes are gone");
+    assert.equal(d.blockDetails[0].directMessageCount, 1, "but the count still says one message was folded");
+    assert.equal(d.blockDetails[0].directMessageRefs.length, 1, "and its ref is still named");
+    assert.deepEqual(await buildMessageContent("tree-pruned", "m00001"), { ok: false, reason: "unknown-message" });
+});
+
+test("#3917: the tree's strings exist in both locales with identical placeholders", () => {
+    const keys = [
+        "det.tab_overview",
+        "det.tab_blocks",
+        "det.tab_handoff",
+        "det.tree_total",
+        "det.tree_active",
+        "det.tree_split",
+        "det.tree_msgs",
+        "det.tree_direct",
+        "det.tree_orig_one",
+        "det.tree_orig_full",
+        "det.tree_orig_meta",
+        "det.tree_orig_truncated",
+        "det.tree_orig_missing",
+        "det.tree_msgs_unavailable",
+        "det.tree_msg_gone",
+        "det.tree_hint",
+        "det.tree_view_list",
+        "det.tree_view_graph",
+        "det.tree_graph_hint",
+        "det.tree_graph_legend",
+    ];
+    const placeholders = (s: string) => (s.match(/\{[a-z]+\}/g) ?? []).sort().join(",");
+    for (const key of keys) {
+        const zh = MESSAGES["zh-CN"][key];
+        const en = MESSAGES.en[key];
+        assert.ok(zh, `zh-CN missing ${key}`);
+        assert.ok(en, `en missing ${key}`);
+        assert.equal(placeholders(zh), placeholders(en), `${key} placeholder drift`);
+    }
+});
+
+test("#3917: the web client bundle stays parseable JS after the tree additions", () => {
+    assert.doesNotThrow(() => new vm.Script(WEB_CLIENT), "WEB_CLIENT must compile as a standalone script");
+    assert.match(WEB_CLIENT, /function buildTreePane\(blocks\)/);
+    assert.match(WEB_CLIENT, /\/block-content\?blockId=/);
+    // the graph reading of the same folds: layered boxes + list⇄graph switch
+    assert.match(WEB_CLIENT, /function buildGraphSvg\(blocks\)/);
+    assert.match(WEB_CLIENT, /function blockGraphLayout\(blocks\)/);
+    assert.match(WEB_CLIENT, /"g-node tier-" \+/);
+    assert.match(WEB_CLIENT, /data-mode="graph"/);
+    assert.match(WEB_CLIENT, /id="tree-graph"/);
+    assert.match(WEB_CLIENT, /\.block-node\[data-bid=/);
+});

From 49019ea1ed6b2d65bb1e183ad523c572487ebbcc Mon Sep 17 00:00:00 2001
From: awork 
Date: Tue, 20 Oct 2026 15:57:42 +0800
Subject: [PATCH 2/2] docs: correct stale issue ref in architecture.md (#3936
 -> #3917)

---
 reference/architecture.md | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/reference/architecture.md b/reference/architecture.md
index 57d6f146b2..1275d438c9 100644
--- a/reference/architecture.md
+++ b/reference/architecture.md
@@ -176,7 +176,7 @@ billion-context/
 │   │   └── native.ts             #   Routing scope/exemptions policy (#1622)
 │   └── web/                      # Web UI (config editor, sessions, logs)
 │       ├── api.ts                #   REST handlers (config get/put with parse-state guard)
-│       ├── sessions-data.ts      #   Read-only session browsing (live pool + on-disk, #1420); tier tree + lazy block content (#3936)
+│       ├── sessions-data.ts      #   Read-only session browsing (live pool + on-disk, #1420); tier tree + lazy block content (#3917)
 │       ├── logs-query.ts         #   GET /__bili/logs selection engine
 │       ├── markdown.ts           #   Escape-safe Markdown → HTML (#1420)
 │       ├── page.ts               #   Server-rendered HTML page shell (CA cert hint, i18n)