From 9578c8432e67cd94177a4c13ac1e0f057b91df33 Mon Sep 17 00:00:00 2001 From: awork Date: Fri, 16 Oct 2026 00:00:00 +0800 Subject: [PATCH 1/3] feat: permanent feedback channel in the web UI (#3299) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Complete the #3040 diagnostics facility into an always-reachable report path for users who hit problems that never raise a warning banner: - diagnostics: new topic=general (env facts + sessions-on-disk count + last 15 [error] log lines), ?desc= carries the user's own description into blob and prefilled issues/new URL body, ?errors=0 opts out of the log tail - page/styles: topbar '反馈/Report' button + modal (description textarea, include-errors checkbox default on with public-visibility note, copy diagnostics / open prefilled GitHub issue / cancel, Esc/backdrop close) - client: modal wired to /__bili/diagnostics?topic=general (fresh fetch per action, no cache); session-detail export row gains 'report this session' with a compact localized fingerprint prefill - i18n: symmetric zh/en keys (nav.report, rpt.*, det.report_issue_session), parity covered by web-i18n.test - tests: tests/web-report-channel.test.ts pins endpoint params, error-tail filtering, url round-trip, modal skeleton, client wiring - docs: README en+zh FAQ mention of the feedback entry No new config keys/env vars/CLI flags; no wire or request-pipeline changes. --- README.md | 6 +- README.zh-CN.md | 2 +- src/server/admin.ts | 15 ++- src/web/client.ts | 81 ++++++++++++++- src/web/diagnostics.ts | 77 ++++++++++++-- src/web/i18n.ts | 18 ++++ src/web/page.ts | 12 ++- src/web/styles.ts | 6 ++ tests/web-report-channel.test.ts | 172 +++++++++++++++++++++++++++++++ 9 files changed, 373 insertions(+), 16 deletions(-) create mode 100644 tests/web-report-channel.test.ts diff --git a/README.md b/README.md index d0aef5889b..662b72e953 100644 --- a/README.md +++ b/README.md @@ -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 diff --git a/README.zh-CN.md b/README.zh-CN.md index 16f524a089..b7d9bb4b95 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -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` 或网页界面实时观察。 diff --git a/src/server/admin.ts b/src/server/admin.ts index 434b8982f0..d4c0261a4f 100644 --- a/src/server/admin.ts +++ b/src/server/admin.ts @@ -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= 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 diff --git a/src/web/client.ts b/src/web/client.ts index b53b91b19a..0fd611bc9b 100644 --- a/src/web/client.ts +++ b/src/web/client.ts @@ -1380,7 +1380,7 @@ export const WEB_CLIENT = `(function () { const parts = []; parts.push('' + t("common.back") + ""); parts.push('

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

' + escapeHtml(d.id) + "
" + detailBadges(d) + "
"); - parts.push('
' + t("det.report_note") + '
'); + parts.push('
' + t("det.report_note") + '
"); parts.push('
' + t("det.identity") + '
'); // Full title wraps in place, is hoverable (title attr) and carries a copy button. parts.push('
' + t("common.title") + '
' + (d.title ? escapeHtml(d.title) + ' " : '' + t("common.none") + "") + "
"); @@ -1802,6 +1802,66 @@ 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(); + 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; } @@ -1877,6 +1937,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: String(d.id).slice(-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; @@ -2708,6 +2784,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) { diff --git a/src/web/diagnostics.ts b/src/web/diagnostics.ts index ab54759ed1..218e0c2e11 100644 --- a/src/web/diagnostics.ts +++ b/src/web/diagnostics.ts @@ -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. @@ -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); @@ -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; } } @@ -105,10 +133,26 @@ function conflictDiagnosticsLines(summary: ReturnType 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 | null; + errorLines: string[]; } interface TopicDef { @@ -127,6 +171,12 @@ const TOPICS: Record = { 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 { @@ -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"); diff --git a/src/web/i18n.ts b/src/web/i18n.ts index 9483f54eba..b02fa07bde 100644 --- a/src/web/i18n.ts +++ b/src/web/i18n.ts @@ -113,6 +113,15 @@ export const MESSAGES: Record> = { "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. @@ -592,6 +601,15 @@ export const MESSAGES: Record> = { "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 ", diff --git a/src/web/page.ts b/src/web/page.ts index aa75a8dbb7..71e0341171 100644 --- a/src/web/page.ts +++ b/src/web/page.ts @@ -19,7 +19,7 @@ export function renderPage(origin: string, version: string, embed = false, theme const caPathEsc = escapeHtml(caPath); const caReady = existsSync(caPath); return `billion-context -
billion-contextv${version}
+
billion-contextv${version}
${zh("fork.label")}
@@ -193,6 +193,16 @@ export function renderPage(origin: string, version: string, embed = false, theme
+ +
`; diff --git a/src/web/styles.ts b/src/web/styles.ts index 41675a28b0..00fddf32cd 100644 --- a/src/web/styles.ts +++ b/src/web/styles.ts @@ -425,4 +425,10 @@ pre.tool-args, pre.tool-out { margin: 6px 0 0; padding: 8px; background: var(--b embed face a little breathing room instead of zero gutter. */ .embed main { max-width: none; padding: 8px 10px 16px; } .embed .banner { margin: 8px 0 0; } +/* #3299: global feedback modal — above the page content and qtips (z 60), + below the toast host (z 100) so action feedback stays visible on top. */ +.modal-backdrop { position: fixed; inset: 0; z-index: 90; background: rgba(31, 35, 40, 0.45); display: flex; align-items: center; justify-content: center; padding: 16px; } +.modal-backdrop[hidden] { display: none; } +.modal-card { width: min(680px, 100%); max-height: calc(100vh - 48px); overflow: auto; } +#report-desc { width: 100%; box-sizing: border-box; margin-top: 10px; resize: vertical; min-height: 90px; } `; diff --git a/tests/web-report-channel.test.ts b/tests/web-report-channel.test.ts new file mode 100644 index 0000000000..6f6ad6e621 --- /dev/null +++ b/tests/web-report-channel.test.ts @@ -0,0 +1,172 @@ +// #3299 permanent feedback channel: problems that never raised a warning banner +// had no web-side report path — users had to find a human. These tests pin the +// completed #3040 facility: +// 1. topic=general serves env facts + session count + the recent [error] log +// tail; ?desc= carries the user's own description into the blob AND the +// prefilled issues/new URL body (body decodes back to the exact blob). +// 2. ?errors=0 opts out of the log tail (honest "(no recent …)" line); +// unknown topics still degrade to the base blob. +// 3. the page ships the always-on entry (#report-open) + modal skeleton with +// localized copy; the client wires both actions to the endpoint and the +// session-detail row offers a prefilled "report this session" path. +import test from "node:test"; +import assert from "node:assert/strict"; +import http from "node:http"; +import { once } from "node:events"; +import { mkdtempSync, mkdirSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { defaultConfig } from "acp-kernel"; +import { startServer } from "../src/server.ts"; +import type { ProxyOptions } from "../src/config.ts"; +import { SessionStore, _setStoreForTest } from "../src/persist.ts"; +import { defaultLogFile } from "../src/paths.ts"; +import { renderPage } from "../src/web/page.ts"; +import { WEB_CLIENT } from "../src/web/client.ts"; +import { VERSION } from "../src/version.ts"; +import { rmrf } from "./tmp-rm.ts"; + +process.env.BILI_PERSIST_ZSTD = "0"; + +const ENV_KEYS = ["BILI_SESSIONS_DIR", "BILI_CONFIG_FILE", "XDG_CACHE_HOME", "XDG_STATE_HOME", "BILI_STORAGE_UNIFIED", "BILI_ENCRYPTION_KEY"] as const; +type EnvSnap = Partial>; + +function saveEnv(): EnvSnap { + const snap: EnvSnap = {}; + for (const k of ENV_KEYS) snap[k] = process.env[k]; + return snap; +} + +function restoreEnv(snap: EnvSnap): void { + for (const k of ENV_KEYS) { + if (snap[k] === undefined) delete process.env[k]; + else process.env[k] = snap[k]; + } +} + +function isolate(base: string): void { + mkdirSync(path.join(base, "sessions"), { recursive: true }); + process.env.BILI_SESSIONS_DIR = path.join(base, "sessions"); + process.env.BILI_CONFIG_FILE = path.join(base, "absent-config.json"); + process.env.XDG_CACHE_HOME = path.join(base, "cache"); + process.env.XDG_STATE_HOME = path.join(base, "state"); +} + +function close(server: http.Server): Promise { + return new Promise((resolve, reject) => server.close((error) => (error ? reject(error) : resolve()))); +} + +async function freePort(): Promise { + const server = http.createServer(); + server.listen(0, "127.0.0.1"); + await once(server, "listening"); + const port = (server.address() as { port: number }).port; + await close(server); + return port; +} + +interface DiagnosticsWire { + blob: string; + title: string; + url: string; +} + +async function fetchJson(port: number, p: string): Promise { + const res = await fetch(`http://127.0.0.1:${port}${p}`); + assert.equal(res.status, 200, `${p} answers 200`); + return (await res.json()) as T; +} + +function makeOpts(upstreamPort: number): ProxyOptions { + return { + port: 0, + host: "127.0.0.1", + upstream: `http://127.0.0.1:${upstreamPort}`, + routes: {}, + modelContextLimit: 400_000, + kernelConfig: defaultConfig(400_000), + compress: { injectTool: false, injectNudge: false }, + promptCache: { routing: "auto" }, + sessionHeader: "x-acp-session", + log: false, + debug: false, + passthrough: false, + autoUpdate: false, + compat: { roles: {} }, + streamErrorShape: "protocol", + passthroughSource: null, + autoRestartOnUpdate: false, + updateTag: "latest", + advisoryCheck: false, + releaseNotesCheck: false, + mitm: { enabled: false, domains: [] }, + }; +} + +test("#3299 topic=general: user description + [error] tail in blob and prefilled issue url", async () => { + const snap = saveEnv(); + const base = mkdtempSync(path.join(tmpdir(), "bili-report-channel-")); + let store: SessionStore | null = null; + try { + isolate(base); + delete process.env.BILI_STORAGE_UNIFIED; + delete process.env.BILI_ENCRYPTION_KEY; + store = new SessionStore({ dir: process.env.BILI_SESSIONS_DIR, enabled: true }); + _setStoreForTest(store); + // The harness never configures the logger (log:false), so the tail reader + // falls back to defaultLogFile() under the sandboxed state dir. + const logFile = defaultLogFile(); + mkdirSync(path.dirname(logFile), { recursive: true }); + writeFileSync(logFile, [ + "2026-10-15T00:00:00.000Z [info] [v=test] startup ok", + "2026-10-15T00:00:01.000Z [error] [v=test] upstream reset by peer (session abc123def456)", + "2026-10-15T00:00:02.000Z [warn] [v=test] slow response 5000ms", + ].join("\n") + "\n"); + const upstreamPort = await freePort(); + const proxy = await startServer(makeOpts(upstreamPort)); + await once(proxy, "listening"); + const port = (proxy.address() as { port: number }).port; + try { + const d = await fetchJson(port, "/__bili/diagnostics?topic=general&desc=" + encodeURIComponent("压缩之后上下文丢失了,复现步骤:…")); + assert.ok(d.blob.includes("--- user description ---"), "blob carries the user description section"); + assert.ok(d.blob.includes("压缩之后上下文丢失了"), "description text survives the round-trip"); + assert.ok(d.blob.includes("--- reported problem ---"), "blob carries the general section"); + assert.ok(d.blob.includes("sessions on disk:"), "blob carries the session count"); + assert.ok(d.blob.includes("upstream reset by peer"), "blob carries the [error] log line"); + assert.ok(!d.blob.includes("startup ok"), "[info] lines are excluded"); + assert.ok(!d.blob.includes("slow response"), "[warn] lines are excluded"); + assert.ok(d.title.startsWith("User report via web UI"), "title names the channel"); + assert.ok(d.url.startsWith("https://github.com/ranxianglei/billion-context/issues/new?title="), "url targets issues/new"); + const u = new URL(d.url); + assert.equal(u.searchParams.get("body"), d.blob, "issue body decodes back to the exact blob"); + + const d2 = await fetchJson(port, "/__bili/diagnostics?topic=general&errors=0"); + assert.ok(d2.blob.includes("(no recent [error] log lines)"), "errors=0 drops the tail and says so honestly"); + assert.ok(!d2.blob.includes("upstream reset by peer"), "errors=0 omits the log lines"); + + const d3 = await fetchJson(port, "/__bili/diagnostics?topic=some-future-topic"); + assert.ok(d3.blob.includes("some-future-topic (no topic-specific section registered)"), "unknown topics still degrade to the base blob"); + + const html = renderPage(`http://127.0.0.1:${port}`, VERSION); + assert.ok(html.includes('id="report-open"'), "page carries the always-on feedback button"); + assert.ok(html.includes('data-i18n="nav.report"'), "button label is localized"); + assert.ok(html.includes('id="report-modal"'), "page carries the modal skeleton"); + for (const id of ["report-desc", "report-incl-errors", "report-copy", "report-github", "report-cancel", "report-close"]) { + assert.ok(html.includes(`id="${id}"`), `modal carries #${id}`); + } + assert.ok(html.includes('data-i18n-ph="rpt.desc_ph"'), "placeholder is localized"); + assert.ok(WEB_CLIENT.includes('p.set("topic", "general")'), "client targets the general topic"); + assert.ok(WEB_CLIENT.includes('p.set("errors", "0")'), "client can opt out of the error tail"); + assert.ok(WEB_CLIENT.includes("openReportModal()"), "topbar button opens the modal"); + assert.ok(WEB_CLIENT.includes('id="sessrpt-issue"'), "session detail offers report-this-session"); + assert.ok(WEB_CLIENT.includes('t("rpt.session_prefill"'), "prefill uses the localized fingerprint template"); + assert.ok(WEB_CLIENT.includes('t("det.report_issue_session")'), "session button label is localized"); + } finally { + await close(proxy); + } + } finally { + store?.closeQuietly(); + rmrf(base); + restoreEnv(snap); + } +}); From 3a941516df0469113d8655a98f000dc637ad6b6d Mon Sep 17 00:00:00 2001 From: awork Date: Fri, 16 Oct 2026 00:22:12 +0800 Subject: [PATCH 2/3] fix: ignore repeat clicks on the feedback modal GitHub link while fetching (#3299) busy() sets .disabled which has no effect on elements; a double-click during the diagnostics fetch could open two prefilled issue tabs. Guard on the busy class instead. --- src/web/client.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/src/web/client.ts b/src/web/client.ts index 0fd611bc9b..3417e16513 100644 --- a/src/web/client.ts +++ b/src/web/client.ts @@ -1854,6 +1854,7 @@ export const WEB_CLIENT = `(function () { 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; From a63e0cd051a5ebeb86b75efbff7530be7e41e3ac Mon Sep 17 00:00:00 2001 From: awork Date: Fri, 16 Oct 2026 01:34:07 +0800 Subject: [PATCH 3/3] fix: route feedback-prefill id tail through safeSuffix (#816 family gate) CI text-safe family gate flagged String(d.id).slice(-12) in the new session prefill (raw negative slice on a string). Inline the shared clamp into the self-contained WEB_CLIENT IIFE via function-source interpolation (the IIFE has no module access), so the tail can never cut a surrogate pair. Verified: text-safe gate green, targeted web suites 63/63, typecheck clean, built dist WEB_CLIENT evaluates to valid JS with the clamp embedded. --- src/web/client.ts | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/web/client.ts b/src/web/client.ts index 3417e16513..39e4e05d46 100644 --- a/src/web/client.ts +++ b/src/web/client.ts @@ -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) — @@ -1947,7 +1950,7 @@ export const WEB_CLIENT = `(function () { 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: String(d.id).slice(-12), + id: safeSuffix(String(d.id), 12), protocol: d.protocol || "?", host: host || "?", reqs: d.requests != null ? String(d.requests) : "?",