Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
84 changes: 83 additions & 1 deletion src/server/admin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 { buildOverview, buildSessionDetail, buildSessionList, buildSessionPage, buildBlockContent, buildRefLookup, handleConfigGet, handleConfigPut, hiddenEmptyCount, renderUI } from "../web/index.js";
import { buildSessionReportMd, buildSessionReportSvg } from "../web/report.js";
import { queryLogLines } from "../web/logs-query.js";
import { buildDiagnostics } from "../web/diagnostics.js";
Expand Down Expand Up @@ -215,6 +215,8 @@ 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);
if (req.method === "GET" && req.url?.startsWith("/__bili/sessions/") && req.url.split("?")[0].endsWith("/block-content")) return sendWebBlockContent(res, req.url);
if (req.method === "GET" && req.url?.startsWith("/__bili/sessions/") && req.url.split("?")[0].endsWith("/block-ref")) return sendWebBlockRef(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
Expand Down Expand Up @@ -1202,6 +1204,86 @@ async function sendWebSessionDetail(res: http.ServerResponse, url: string): Prom
res.end(JSON.stringify(detail, null, 2));
}

function parseBlockUrl(url: string): { id: string; params: URLSearchParams } | null {
let u: URL;
try {
u = new URL(url, "http://localhost");
} catch {
return null;
}
const m = /^\/__bili\/sessions\/([^/]+)\/(?:block-content|block-ref)$/.exec(u.pathname);
if (!m) return null;
let id = "";
try {
id = decodeURIComponent(m[1]);
} catch {
// malformed percent-encoding → treat as unknown session (404 below)
}
return { id, params: u.searchParams };
}

async function sendWebBlockContent(res: http.ServerResponse, url: string): Promise<void> {
const parsed = parseBlockUrl(url);
if (!parsed) {
res.writeHead(404, { "content-type": "application/json" });
res.end(JSON.stringify({ error: "not found" }));
return;
}
const blockId = parsed.params.get("block");
const mode = parsed.params.get("mode");
if (!blockId || !mode) {
res.writeHead(400, { "content-type": "application/json" });
res.end(JSON.stringify({ error: "missing block or mode query parameter" }));
return;
}
const r = await buildBlockContent(parsed.id, blockId, mode);
if (r.status === "unknown-session") {
res.writeHead(404, { "content-type": "application/json" });
res.end(JSON.stringify({ error: `unknown session: ${parsed.id}` }));
return;
}
if (r.status === "unknown-block") {
res.writeHead(404, { "content-type": "application/json" });
res.end(JSON.stringify({ error: `unknown block: ${r.blockId}` }));
return;
}
if (r.status === "bad-mode") {
res.writeHead(400, { "content-type": "application/json" });
res.end(JSON.stringify({ error: `invalid mode: ${r.mode} (expected one|full)` }));
return;
}
res.writeHead(200, { "content-type": "application/json" });
res.end(JSON.stringify(r.content, null, 2));
}

async function sendWebBlockRef(res: http.ServerResponse, url: string): Promise<void> {
const parsed = parseBlockUrl(url);
if (!parsed) {
res.writeHead(404, { "content-type": "application/json" });
res.end(JSON.stringify({ error: "not found" }));
return;
}
const q = parsed.params.get("q");
if (!q || !q.trim()) {
res.writeHead(400, { "content-type": "application/json" });
res.end(JSON.stringify({ error: "missing q query parameter" }));
return;
}
const r = await buildRefLookup(parsed.id, q);
if (r.status === "unknown-session") {
res.writeHead(404, { "content-type": "application/json" });
res.end(JSON.stringify({ error: `unknown session: ${parsed.id}` }));
return;
}
if (r.status === "bad-query") {
res.writeHead(400, { "content-type": "application/json" });
res.end(JSON.stringify({ error: "empty q query parameter" }));
return;
}
res.writeHead(200, { "content-type": "application/json" });
res.end(JSON.stringify(r, null, 2));
}

async function sendSessionReport(res: http.ServerResponse, url: string): Promise<void> {
const q = new URL(url, "http://localhost").searchParams;
const id = q.get("session");
Expand Down
133 changes: 133 additions & 0 deletions src/web/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1929,6 +1929,17 @@ export const WEB_CLIENT = `(function () {
});
}
parts.push("</div></div>");
// #3917: compression structure — tier tree over directBlockIds, lazy
// originals (one/full), mNNNNN locate, JSON export of the current view.
parts.push('<div class="card" style="margin-top:16px"><div class="card-h"><span>' + t("det.cstruct_title") + '</span><span class="hint">' + t("det.cstruct_hint") + '</span></div><div class="card-b">');
if (!blocks.length) {
parts.push('<div class="dim small" style="padding:8px 0">' + t("det.blocks_empty") + "</div>");
} else {
parts.push('<div style="display:flex;gap:8px;margin-bottom:10px;flex-wrap:wrap;align-items:center"><input id="cstruct-q" type="search" class="search" placeholder="' + escapeHtml(t("det.cstruct_search_ph")) + '" spellcheck="false" style="min-width:220px"><button id="cstruct-find" class="btn sm">' + t("det.cstruct_search_btn") + '</button><button id="cstruct-export" class="btn sm">' + t("det.cstruct_export") + "</button></div>");
parts.push('<div id="cstruct-status" class="dim small" style="margin-bottom:8px"></div>');
parts.push(buildCstructTree(blocks));
}
parts.push("</div></div>");
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.
Expand Down Expand Up @@ -1969,6 +1980,7 @@ export const WEB_CLIENT = `(function () {
host.innerHTML = buildDetailHtml(d);
bindHandoffActions(d);
bindBlocksActions(d);
bindCstructActions(d);
bindCacheReportActions(d);
bindSessionReportActions(d);
bindTrajectoryBrush(d);
Expand Down Expand Up @@ -2080,6 +2092,35 @@ export const WEB_CLIENT = `(function () {
d.blockDetails.forEach((b) => { L.push(""); L.push(buildBlockMd(b)); });
return L.join("\\n");
}
// #3917: tier tree over directBlockIds. Roots = blocks no other block lists
// as a child (orphans whose parent was pruned surface as roots too).
function buildCstructTree(blocks) {
const byId = {};
blocks.forEach((b) => { byId[b.blockId] = b; });
const hasParent = new Set();
blocks.forEach((b) => (Array.isArray(b.children) ? b.children : []).forEach((c) => hasParent.add(c)));
const roots = blocks.filter((b) => !hasParent.has(b.blockId));
const node = (b, depth) => {
const refRange = refRangeOf(b);
const badge = b.active
? '<span class="badge ok">' + t("det.block_active") + "</span>"
: '<span class="badge disk">' + t("det.block_inactive") + "</span>";
const extBadge = b.external ? '<span class="badge ext">' + t("det.block_external") + "</span>" : "";
// Same row shape as the flat 压缩块 list (class block-item) so the
// shared typography applies; cstruct-node adds tree behavior.
let html = '<details class="block-item cstruct-node" data-block="' + escapeHtml(b.blockId) + '" style="margin-left:' + depth * 16 + 'px"><summary><span class="bid">' + escapeHtml(b.blockId) + '</span>' + badge + extBadge + '<span class="topic">' + escapeHtml(blockTopic(b)) + '</span><span class="meta">T' + String(b.tier) + " · " + fmtW(b.compressedTokens) + " · " + timeAgo(b.createdAt) + (refRange ? " · " + escapeHtml(refRange) : "") + '</span></summary><div class="body md">';
html += renderBlockMd(b.summary || "");
html += '<div class="cstruct-orig" data-orig="' + escapeHtml(b.blockId) + '" style="margin-top:8px"><button class="btn sm cstruct-load" data-block="' + escapeHtml(b.blockId) + '" data-mode="one">' + t("det.cstruct_load_one") + '</button> <button class="btn sm cstruct-load" data-block="' + escapeHtml(b.blockId) + '" data-mode="full">' + t("det.cstruct_load_full") + '</button><div class="cstruct-orig-body"></div></div>';
html += "</div>";
(Array.isArray(b.children) ? b.children : []).forEach((cid) => {
const cb = byId[cid];
if (cb) html += node(cb, depth + 1);
});
html += "</details>";
return html;
};
return roots.map((r) => node(r, 0)).join("");
}
// #3057 report export: MD/SVG render server-side (/__bili/session-report); the browser downloads MD and rasterizes the closed-vector SVG to PNG.
function downloadUrl(url, name) {
var a = document.createElement("a");
Expand Down Expand Up @@ -2156,6 +2197,98 @@ export const WEB_CLIENT = `(function () {
btn.addEventListener("click", (ev) => { ev.preventDefault(); ev.stopPropagation(); copyText(buildBlockMd(b), btn); });
});
}
// #3917: structure-tab actions — mNNNNN locate (exact id-set membership on
// the server), lazy originals per node, JSON export of the current view
// (blockDetails + whatever originals were loaded during this page visit).
function bindCstructActions(d) {
const findBtn = $("cstruct-find");
if (!findBtn) return;
const qEl = $("cstruct-q");
const status = $("cstruct-status");
const originals = {};
const nodeOf = (blockId) => document.querySelector('.cstruct-node[data-block="' + blockId + '"]');
const parentIdOf = (blockId) => {
for (const b of d.blockDetails || []) {
if ((Array.isArray(b.children) ? b.children : []).includes(blockId)) return b.blockId;
}
return null;
};
const clearHits = () => document.querySelectorAll(".cstruct-node.hit").forEach((n) => n.classList.remove("hit"));
const locate = async () => {
const q = String(qEl.value || "").trim();
if (!q) return;
clearHits();
status.textContent = "";
busy(findBtn, true);
try {
const r = await json(API_ROOT + "/sessions/" + encodeURIComponent(d.id) + "/block-ref?q=" + encodeURIComponent(q));
const matches = Array.isArray(r.matches) ? r.matches : [];
if (!matches.length) {
status.textContent = q + " — " + t("det.cstruct_search_notfound");
return;
}
matches.forEach((m) => {
const n = nodeOf(m.blockId);
if (n) n.classList.add("hit");
});
const owner = r.owner ? r.owner.blockId : matches[matches.length - 1].blockId;
for (let p = owner; p; p = parentIdOf(p)) {
const n = nodeOf(p);
if (n) n.open = true; else break;
}
status.textContent = q + " — " + t("det.cstruct_search_found", { n: matches.length, owner: owner });
const target = nodeOf(owner);
if (target && target.scrollIntoView) target.scrollIntoView({ block: "center", behavior: "smooth" });
} catch (e) {
toast(friendlyMsg(e), "err");
} finally {
busy(findBtn, false);
}
};
findBtn.addEventListener("click", locate);
qEl.addEventListener("keydown", (ev) => { if (ev.key === "Enter") locate(); });
document.querySelectorAll(".cstruct-load").forEach((btn) => {
btn.addEventListener("click", async () => {
const blockId = btn.getAttribute("data-block");
const mode = btn.getAttribute("data-mode");
const host = document.querySelector('.cstruct-orig[data-orig="' + blockId + '"] .cstruct-orig-body');
if (!host) return;
busy(btn, true);
try {
const key = blockId + ":" + mode;
let c = originals[key];
if (!c) {
c = await json(API_ROOT + "/sessions/" + encodeURIComponent(d.id) + "/block-content?block=" + encodeURIComponent(blockId) + "&mode=" + mode);
originals[key] = c;
}
if (c.missing) {
host.innerHTML = '<div class="dim small">' + t("det.cstruct_no_content") + "</div>";
return;
}
let note = "";
if (c.identicalToFull) note += '<div class="dim small" style="margin-top:4px">(' + t("det.cstruct_same_as_full") + ")</div>";
if (c.truncated) note += '<div class="dim small" style="margin-top:4px;color:#d4a72c">' + t("det.cstruct_truncated") + "</div>";
host.innerHTML = note + '<div class="md" style="margin-top:6px">' + renderBlockMd(String(c.text || "")) + "</div>";
} catch (e) {
toast(friendlyMsg(e), "err");
} finally {
busy(btn, false);
}
});
});
const exBtn = $("cstruct-export");
if (exBtn) exBtn.addEventListener("click", () => {
const payload = {
session: d.id,
...(d.title ? { title: d.title } : {}),
generatedAt: new Date().toISOString(),
blocks: d.blockDetails || [],
originals: Object.keys(originals).map((k) => ({ blockId: k.split(":")[0], mode: k.split(":")[1], content: originals[k] })),
};
const url = URL.createObjectURL(new Blob([JSON.stringify(payload, null, 2)], { type: "application/json;charset=utf-8" }));
downloadUrl(url, "billion-context-cstruct-" + String(d.id).replace(/[^A-Za-z0-9._-]/g, "_") + ".json");
});
}
function bindCacheReportActions(d) {
const copyB = $("cacherpt-copy");
const dlB = $("cacherpt-dl");
Expand Down
24 changes: 24 additions & 0 deletions src/web/i18n.ts
Original file line number Diff line number Diff line change
Expand Up @@ -356,6 +356,18 @@ export const MESSAGES: Record<Locale, Record<string, string>> = {
"det.rpt_missed": "未命中",
"det.rpt_hit": "命中率",
"det.blocks_copy_md": "复制 Markdown",
"det.cstruct_title": "压缩结构",
"det.cstruct_hint": "层级视图:点开看摘要,按需加载原文,可定位 mNNNNN 并导出当前视图",
"det.cstruct_search_ph": "定位 mNNNNN 或原始消息 ID",
"det.cstruct_search_btn": "定位",
"det.cstruct_search_found": "{n} 个块包含该消息,所属块 {owner}",
"det.cstruct_search_notfound": "该消息不在任何压缩块中(可能仍在活动上下文里)",
"det.cstruct_load_one": "加载一级原文",
"det.cstruct_load_full": "加载完整原文",
"det.cstruct_truncated": "⚠️ 超过 2 MiB 已截断",
"det.cstruct_same_as_full": "与完整原文相同",
"det.cstruct_no_content": "该块没有持久化原文",
"det.cstruct_export": "导出当前视图 (.json)",
"det.handoff": "会话交接文档",
"det.handoff_hint": "与 bili export 相同的内容 —— 复制粘贴到新会话即可继续",
"det.thinking": "思考",
Expand Down Expand Up @@ -851,6 +863,18 @@ export const MESSAGES: Record<Locale, Record<string, string>> = {
"det.rpt_missed": "missed",
"det.rpt_hit": "hit %",
"det.blocks_copy_md": "copy Markdown",
"det.cstruct_title": "Compression structure",
"det.cstruct_hint": "Tier tree: open a node for its summary, load originals on demand, locate mNNNNN refs, export the current view",
"det.cstruct_search_ph": "Locate mNNNNN or raw message id",
"det.cstruct_search_btn": "Locate",
"det.cstruct_search_found": "{n} block(s) contain it; owning block {owner}",
"det.cstruct_search_notfound": "not inside any compressed block (it may still be live context)",
"det.cstruct_load_one": "Load one-level originals",
"det.cstruct_load_full": "Load full originals",
"det.cstruct_truncated": "⚠️ truncated beyond 2 MiB",
"det.cstruct_same_as_full": "identical to full",
"det.cstruct_no_content": "this block has no persisted originals",
"det.cstruct_export": "Export current view (.json)",
"det.handoff": "Handoff document",
"det.handoff_hint": "Same content as bili export — paste into a new session to continue",
"det.thinking": "thinking",
Expand Down
2 changes: 1 addition & 1 deletion src/web/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ export {
readUpstreamSettings,
} from "./api.js";

export { buildOverview, buildSessionList, buildSessionPage, buildSessionDetail, hiddenEmptyCount } from "./sessions-data.js";
export { buildOverview, buildSessionList, buildSessionPage, buildSessionDetail, buildBlockContent, buildRefLookup, hiddenEmptyCount } 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
Expand Down
Loading
Loading