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
6 changes: 4 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -358,8 +358,10 @@ report above.

**Can I query sessions and config over the web?** Yes — open
[http://localhost:8787](http://localhost:8787): an overview dashboard, session
list with per-session detail, live logs, a config editor, and an upstream
connectivity test. Everything is also plain JSON for scripting
list with per-session detail, live logs, a config editor, an upstream
connectivity test, and a feedback button that opens a prefilled GitHub issue
(environment diagnostics plus your own problem description). Everything is
also plain JSON for scripting
(`/__bili/stats`, `/__bili/sessions`, `/__bili/config`, …).

**When does compression happen?** It is model-driven: the injected context
Expand Down
2 changes: 1 addition & 1 deletion README.zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -268,7 +268,7 @@ curl -s http://localhost:8787/__bili/stats

**`/acp` 显示什么?** 带原生插件的客户端(opencode、dsh)里,`/acp` 直接从代理取当前会话的 ACP 状态面板(会话、块、可压缩区间、用量);首个模型请求到来前显示空闲提示。`/acp-cache [full]` 打印上面的缓存报告。

**能用网页查会话和配置吗?** 能 —— 打开 [http://localhost:8787](http://localhost:8787):总览仪表盘、会话列表(含逐会话详情)、实时日志、配置编辑器、上游连通性测试。全部功能同样以纯 JSON 提供(`/__bili/stats`、`/__bili/sessions`、`/__bili/config`、…),方便脚本化。
**能用网页查会话和配置吗?** 能 —— 打开 [http://localhost:8787](http://localhost:8787):总览仪表盘、会话列表(含逐会话详情)、实时日志、配置编辑器、上游连通性测试,以及一个反馈入口(一键打开预填了环境诊断和你自己的问题描述的 GitHub issue)。全部功能同样以纯 JSON 提供(`/__bili/stats`、`/__bili/sessions`、`/__bili/config`、…),方便脚本化。

**压缩什么时候发生?** 由模型驱动:注入的上下文工具由模型在上下文增长时自行调用,温和的增长 nudge(按设计固定约 50K token 步长,可用 `compress.nudgeGrowthTokens` 调整)沿途提醒它,仅输入就超窗时预检作为硬兜底触发(#470)。用 `/acp` 或网页界面实时观察。

Expand Down
15 changes: 11 additions & 4 deletions src/server/admin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -915,17 +915,24 @@ async function sendOverview(res: http.ServerResponse, opts: ProxyOptions): Promi
}, null, 2));
}

/** #3040: generic diagnostics report — copyable blob + prefilled GitHub issue
* link. Loopback-gated like every other /__bili/* route; never throws. */
/** #3040 (+#3299): generic diagnostics report — copyable blob + prefilled
* GitHub issue link. Loopback-gated like every other /__bili/* route; never
* throws. #3299 adds ?desc=<user description> and ?errors=0 (opt out of the
* [error] log tail on topic=general). */
function sendDiagnostics(res: http.ServerResponse, url: string | null): void {
let topic: string | undefined;
let desc: string | undefined;
let includeErrors = true;
try {
topic = new URL(url ?? "/__bili/diagnostics", "http://localhost").searchParams.get("topic") ?? undefined;
const p = new URL(url ?? "/__bili/diagnostics", "http://localhost").searchParams;
topic = p.get("topic") ?? undefined;
desc = p.get("desc") ?? undefined;
if (p.get("errors") === "0") includeErrors = false;
} catch {
topic = undefined;
}
res.writeHead(200, { "content-type": "application/json" });
res.end(JSON.stringify(buildDiagnostics(topic), null, 2));
res.end(JSON.stringify(buildDiagnostics(topic, { desc, includeErrors }), null, 2));
}

/** #1937: optional ?q= / ?page= / ?pageSize= (≤200) switch the endpoint to
Expand Down
85 changes: 84 additions & 1 deletion src/web/client.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
import { MESSAGES } from "./i18n.js";
import { safeSuffix } from "../text-safe.js";

export const WEB_CLIENT = `(function () {
"use strict";
const MESSAGES=${JSON.stringify(MESSAGES)};
// #816 family: id tails must not cut surrogate pairs — inline the shared clamp (IIFE has no module access).
const safeSuffix=${safeSuffix.toString()};
let locale = "zh-CN";
try {
// #2321: an embedding host may pin the locale explicitly (?lang=zh|en) —
Expand Down Expand Up @@ -1380,7 +1383,7 @@ export const WEB_CLIENT = `(function () {
const parts = [];
parts.push('<a class="btn sm" href="#/sessions">' + t("common.back") + "</a>");
parts.push('<div class="page-head"><div><h1 title="' + escapeHtml(d.title || d.label || d.id) + '">' + escapeHtml(d.title || d.label || d.id.slice(0, 16)) + '</h1><div class="sub mono">' + escapeHtml(d.id) + "</div></div><div>" + detailBadges(d) + "</div></div>");
parts.push('<div style="display:flex;align-items:center;gap:8px;margin-top:12px;flex-wrap:wrap"><span class="dim small">' + t("det.report_note") + '</span><button id="sessrpt-md" class="btn sm">' + t("det.report_md") + '</button><button id="sessrpt-png" class="btn sm">' + t("det.report_png") + '</button></div>');
parts.push('<div style="display:flex;align-items:center;gap:8px;margin-top:12px;flex-wrap:wrap"><span class="dim small">' + t("det.report_note") + '</span><button id="sessrpt-md" class="btn sm">' + t("det.report_md") + '</button><button id="sessrpt-png" class="btn sm">' + t("det.report_png") + '</button><button id="sessrpt-issue" class="btn sm">' + t("det.report_issue_session") + "</button></div>");
parts.push('<div class="card"><div class="card-h"><span>' + t("det.identity") + '</span></div><div class="card-b"><dl class="kv">');
// Full title wraps in place, is hoverable (title attr) and carries a copy button.
parts.push('<div class="k">' + t("common.title") + '</div><div class="v" title="' + escapeHtml(d.title || "") + '">' + (d.title ? escapeHtml(d.title) + ' <button id="title-copy" class="btn sm">' + t("common.copy") + "</button>" : '<span class="faint">' + t("common.none") + "</span>") + "</div>");
Expand Down Expand Up @@ -1802,6 +1805,67 @@ export const WEB_CLIENT = `(function () {
busy(copyBtn, false);
}
}

// #3299: global feedback modal — the report channel for problems that never
// raised a warning banner. Unlike the banner wiring there is NO cache here:
// every action re-fetches because the description is live user input.
async function fetchReportDiagnostics() {
const ta = $("report-desc");
const cb = $("report-incl-errors");
const p = new URLSearchParams();
p.set("topic", "general");
if (ta && ta.value.trim()) p.set("desc", ta.value.trim());
if (cb && !cb.checked) p.set("errors", "0");
const d = await json("/__bili/diagnostics?" + p.toString());
if (!d || typeof d.blob !== "string" || typeof d.url !== "string") throw new Error("bad diagnostics payload");
return d;
}
function openReportModal(prefill) {
const m = $("report-modal");
if (!m) return;
const ta = $("report-desc");
if (ta && prefill) ta.value = prefill;
m.hidden = false;
const gh = $("report-github");
if (gh) gh.removeAttribute("href");
if (ta) ta.focus();
}
function closeReportModal() {
const m = $("report-modal");
if (!m) return;
m.hidden = true;
const ta = $("report-desc");
if (ta) ta.value = "";
}
function bindReportModalActions() {
const m = $("report-modal");
if (!m) return;
const close = () => closeReportModal();
for (const id of ["report-close", "report-cancel"]) {
const b = $(id);
if (b) b.addEventListener("click", close);
}
m.addEventListener("click", (ev) => { if (ev.target === m) close(); });
document.addEventListener("keydown", (ev) => { if (ev.key === "Escape" && !m.hidden) close(); });
const copyBtn = $("report-copy");
if (copyBtn) copyBtn.addEventListener("click", async () => {
busy(copyBtn, true);
try { copyText((await fetchReportDiagnostics()).blob, copyBtn); }
catch (e) { toast(t("toast.failed", { msg: e.message }), "err"); }
finally { busy(copyBtn, false); }
});
const gh = $("report-github");
if (gh) gh.addEventListener("click", async (ev) => {
ev.preventDefault();
if (gh.classList.contains("busy")) return;
busy(gh, true);
try {
const url = (await fetchReportDiagnostics()).url;
window.open(url, "_blank", "noopener,noreferrer");
} catch (e) { toast(t("toast.failed", { msg: e.message }), "err"); }
finally { busy(gh, false); }
});
}
function refRangeOf(b) {
return b.startRef ? (b.endRef && b.endRef !== b.startRef ? b.startRef + "–" + b.endRef : b.startRef) : null;
}
Expand Down Expand Up @@ -1877,6 +1941,22 @@ export const WEB_CLIENT = `(function () {
downloadUrl(URL.createObjectURL(blob), base + ".png");
} catch (e) { toast(t("toast.failed", { msg: e.message }), "err"); } finally { busy(pngBtn, false); }
});
// #3299: session-scoped reports reuse the same modal, prefilled with a
// compact fingerprint — the full MD report stays a download (too big for
// a GitHub issues/new URL).
var issueBtn = $("sessrpt-issue");
if (issueBtn) issueBtn.addEventListener("click", function () {
var host = "";
try { host = d.upstreamOrigin ? new URL(d.upstreamOrigin).host : ""; } catch (e) { host = String(d.upstreamOrigin || ""); }
const hit = d.inputTokens ? Math.round((d.cachedTokens || 0) * 100 / d.inputTokens) + "%" : "?";
openReportModal(t("rpt.session_prefill", {
id: safeSuffix(String(d.id), 12),
protocol: d.protocol || "?",
host: host || "?",
reqs: d.requests != null ? String(d.requests) : "?",
hit: hit,
}));
});
}
function bindBlocksActions(d) {
if (!d.blockDetails || !d.blockDetails.length) return;
Expand Down Expand Up @@ -2708,6 +2788,9 @@ export const WEB_CLIENT = `(function () {
location.reload();
}
});
const reportOpen = $("report-open");
if (reportOpen) reportOpen.addEventListener("click", () => openReportModal());
bindReportModalActions();
// #1937: search is server-side (?q=) — debounced re-query, not a local filter.
const search = $("ses-search");
if (search) {
Expand Down
77 changes: 70 additions & 7 deletions src/web/diagnostics.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,15 @@
/**
* Generic diagnostics report builder (#3040).
*
* One reusable facility behind every web warning: assemble a ready-to-paste
* diagnostic blob (environment facts + one topic-specific section) plus a
* prefilled GitHub issue link, so any future warning can offer "copy
* diagnostics / report on GitHub" without inventing its own plumbing. The
* first consumer is the SQLite legacy-only degradation banner
* (topic `storage-legacy-only`).
* One reusable facility behind every web warning AND the permanent feedback
* entry (#3299): assemble a ready-to-paste diagnostic blob (environment
* facts + one topic-specific section, plus an optional user description)
* plus a prefilled GitHub issue link, so any warning — or a user who hit a
* problem that never raised one — can get "copy diagnostics / report on
* GitHub" without inventing its own plumbing. Consumers: the SQLite
* legacy-only degradation banner (topic `storage-legacy-only`), the
* compression-conflict banner (`conflict-banner`, #3235) and the always-on
* topbar feedback modal (`general`, #3299).
*
* Contract: NEVER throws — every fs/listSessions access is guarded so a
* broken log file or an unbuilt store degrades the blob, not the endpoint.
Expand All @@ -25,6 +28,11 @@ import { BUILD_COMMIT, PACKAGE_NAME, VERSION } from "../version.js";

const GITHUB_NEW_ISSUE_URL = "https://github.com/ranxianglei/billion-context/issues/new";
const STORAGE_LOG_TAIL_LINES = 12;
// #3299: the always-on feedback modal carries the recent [error]-level tail so a
// report that never raised a warning banner still ships real evidence.
const ERROR_LOG_TAIL_LINES = 15;
// Cap the user description so a pasted wall of text cannot bloat the issue body.
const DESC_MAX_CHARS = 4000;

function humanUptime(seconds: number): string {
const h = Math.floor(seconds / 3600);
Expand Down Expand Up @@ -67,6 +75,26 @@ function storageLogTail(): string[] {
}
}

/** Last N `[error]` lines across the rotated pair (same candidate recipe as
* storageLogTail); empty on any fs failure. */
function errorLogTail(): string[] {
try {
const logFile = getLogPath() ?? defaultLogFile();
const dir = logFile ? path.dirname(logFile) + path.sep : "";
const candidates = [dir + "bili.log.old", dir + "bili.log"];
let lines: string[] = [];
for (const f of candidates) {
try { if (!statSync(f).isFile()) continue; } catch { continue; }
try {
lines = lines.concat(readFileSync(f, "utf8").split("\n").filter((l) => l.length > 0 && l.includes("[error]")));
} catch { continue; }
}
return lines.slice(-ERROR_LOG_TAIL_LINES);
} catch {
return [];
}
}

function safeSessionCount(): number {
try { return listSessions().length; } catch { return -1; }
}
Expand Down Expand Up @@ -105,10 +133,26 @@ function conflictDiagnosticsLines(summary: ReturnType<typeof summarizeConflicts>
return lines;
}

/** #3299: the always-on feedback modal's section — no banner evidence exists by
* definition, so the blob carries what every report benefits from: how many
* sessions are on disk plus the recent [error]-level log tail (the logger already
* masks secret values; conversation content never reaches this file). */
function generalDiagnosticsLines(ctx: TopicContext): string[] {
const lines: string[] = ["--- reported problem ---", `sessions on disk: ${ctx.sessions}`];
if (ctx.errorLines.length > 0) {
lines.push(`recent [error] log lines (last ${ctx.errorLines.length}):`);
lines.push(...ctx.errorLines);
} else {
lines.push("(no recent [error] log lines)");
}
return lines;
}

interface TopicContext {
sessions: number;
storageLogLines: string[];
conflicts: ReturnType<typeof summarizeConflicts> | null;
errorLines: string[];
}

interface TopicDef {
Expand All @@ -127,6 +171,12 @@ const TOPICS: Record<string, TopicDef> = {
title: () => `Compression conflict banner (bili v${VERSION}, node ${process.version}, ${process.platform}-${process.arch})`,
section: (ctx) => conflictDiagnosticsLines(ctx.conflicts),
},
// #3299: the permanent topbar feedback entry — usable for ANY problem, with or
// without a banner; opts.desc carries the user's own description.
"general": {
title: () => `User report via web UI (bili v${VERSION}, node ${process.version}, ${process.platform}-${process.arch})`,
section: (ctx) => generalDiagnosticsLines(ctx),
},
};

interface DiagnosticsReport {
Expand All @@ -135,15 +185,28 @@ interface DiagnosticsReport {
url: string;
}

export function buildDiagnostics(topic?: string): DiagnosticsReport {
interface DiagnosticsOptions {
/** #3299: the user's own problem description from the feedback modal. */
desc?: string;
/** Include the [error] log tail in the `general` topic (default true). */
includeErrors?: boolean;
}

export function buildDiagnostics(topic?: string, opts?: DiagnosticsOptions): DiagnosticsReport {
const t = topic?.trim().slice(0, 64) ?? "";
const def = t ? TOPICS[t] : undefined;
const ctx: TopicContext = {
sessions: safeSessionCount(),
storageLogLines: def ? storageLogTail() : [],
conflicts: def ? safeConflictSummary() : null,
errorLines: def && t === "general" && opts?.includeErrors !== false ? errorLogTail() : [],
};
const lines = baseLines();
const desc = opts?.desc?.trim().slice(0, DESC_MAX_CHARS) ?? "";
if (desc) {
lines.push("--- user description ---");
lines.push(desc);
}
if (t && !def) lines.push(`topic: ${t} (no topic-specific section registered)`);
if (def) lines.push(...def.section(ctx));
const blob = lines.join("\n");
Expand Down
18 changes: 18 additions & 0 deletions src/web/i18n.ts
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,15 @@ export const MESSAGES: Record<Locale, Record<string, string>> = {
"sys.storage_degraded": "未来几个版本将默认开启 SQLite 统一存储,但你的系统因 {reason} 暂不支持(已自动回退 JSON 存储,当前不受影响)。请点击下方按钮反馈,帮助我们在默认开启前覆盖你的环境。",
"sys.report_copy": "复制诊断信息",
"sys.report_issue": "在 GitHub 反馈",
// #3299: permanent feedback entry (topbar button → modal).
"nav.report": "反馈",
"rpt.title": "反馈问题",
"rpt.note": "描述你遇到的问题。诊断信息(版本、环境、最近的错误日志)会预填进 GitHub issue;API key 与会话内容不会包含在内,但日志行可能包含本地文件路径——提交前请检查。",
"rpt.desc_ph": "问题现象、操作步骤、期望行为(可选,但越具体越好)",
"rpt.incl_errors": "附带最近的错误日志",
"rpt.cancel": "取消",
"rpt.session_prefill": "会话 …{id}({protocol},upstream {host},请求 {reqs} 次,缓存命中 {hit}):",
"det.report_issue_session": "报告此会话",
"conflict.on": "检测到压缩冲突",
// #2102: the sentence is composed per kind family present — a ledger full of
// client-native rewrites must not read as "third-party plugin" evidence.
Expand Down Expand Up @@ -592,6 +601,15 @@ export const MESSAGES: Record<Locale, Record<string, string>> = {
"sys.storage_degraded": "Unified SQLite storage becomes the default in an upcoming release, but this system cannot run it ({reason}). You have been automatically rolled back to JSON storage — nothing is affected today. Please report this so your environment is covered before the flip.",
"sys.report_copy": "Copy diagnostics",
"sys.report_issue": "Report on GitHub",
// #3299: permanent feedback entry (topbar button → modal).
"nav.report": "Report an issue",
"rpt.title": "Report an issue",
"rpt.note": "Describe the problem you ran into. Diagnostics (version, environment, recent error log lines) are prefilled into the GitHub issue; API keys and conversation content are never included, but log lines may contain local file paths — review before submitting.",
"rpt.desc_ph": "Symptoms, steps to reproduce, expected behavior (optional, but more detail helps)",
"rpt.incl_errors": "Include recent error log lines",
"rpt.cancel": "Cancel",
"rpt.session_prefill": "Session …{id} ({protocol}, upstream {host}, {reqs} requests, {hit} cache hit): ",
"det.report_issue_session": "Report this session",
"conflict.on": "Compression conflict detected",
// #2102: composed per kind family present — see the zh entry above.
"conflict.found": ": traces of ",
Expand Down
Loading
Loading