From a14be7c663db9a422200080c005527608a5562db Mon Sep 17 00:00:00 2001 From: awork Date: Tue, 20 Oct 2026 05:01:47 +0800 Subject: [PATCH 1/6] feat: dsh client Context tab + structured contextView in plugin/status (#3862) Host-side meters (dsh-context and kin) anchor on dsh's local event stream, which never sees bili's folds, so their bars stay on the pre-compression caliber forever (dsh-context#173). bili knows the exact post-fold sent bytes, so it publishes them two ways: - GET /__bili/plugin/status gains an additive contextView field: the machine-readable twin of the /acp panel breakdown (sentTotal vs limit, category segments mirroring buildStatusPanel math exactly, the usage-grade anchor from displayContextBest on its own labeled scale, fold/switch trails mapped from the cache ledger). The route echoes access-control-allow-origin for origins the existing trusted-origin gate already admitted, so a cross-origin browser reader can consume it; the gate itself is untouched, no access widening. - The dsh native plugin registers a session-scoped Context tab (conversation.view slot, id bili-context) rendering that view with plain React from dsh's own runtime (no iframe, no new dependencies): stacked bar, legend, events list, 10s poll, honest degraded/stale/waiting states, open-Web-UI escape hatch. --- CLIENTS.md | 14 +- src/agent/dsh-native-client.ts | 381 +++++++++++++++++++++++++-- src/cache-ledger.ts | 4 +- src/context-view.ts | 148 +++++++++++ src/plugin.ts | 35 ++- src/server/admin.ts | 6 +- tests/dsh-settings-ui.test.ts | 214 ++++++++++++++- tests/issue3862-context-view.test.ts | 315 ++++++++++++++++++++++ 8 files changed, 1080 insertions(+), 37 deletions(-) create mode 100644 src/context-view.ts create mode 100644 tests/issue3862-context-view.test.ts diff --git a/CLIENTS.md b/CLIENTS.md index 585e72072a..c12ee82473 100644 --- a/CLIENTS.md +++ b/CLIENTS.md @@ -154,7 +154,19 @@ is expected, not a stuck compressor. The effective size is the proxy's: read `/acp` (or `GET /__bili/plugin/status` → `contextTokens`, provenance in `contextTokensSource`) instead of re-deriving it locally. -## Kimi Code (Moonshot) +**The dsh client ships a Context tab for this (#3862):** the native plugin +registers a session-scoped `Context` tab in dsh's conversation view (right of +Chat/Trajectory). It reads `GET /__bili/plugin/status` cross-origin from the +dsh web app and renders the same breakdown the `/acp` panel computes live: +the post-compression sent total against the window limit, category segments +(system+tools / tools / text / code / summaries), the usage-grade billed +anchor on its own labeled scale, and recent fold/switch events with reclaimed +tokens. It refreshes every 10 s; when the running proxy predates this build +the tab degrades to a restart notice plus an open-Web-UI button instead of +guessing. Plain React from dsh's own runtime — no iframe, no added +dependencies. + + ## Kimi Code (Moonshot) Three aligned modes: `bili kimi` (launcher, cert-MITM — README Quickstart Option 2), `/bili/` diff --git a/src/agent/dsh-native-client.ts b/src/agent/dsh-native-client.ts index 340a1be443..77393d41e3 100644 --- a/src/agent/dsh-native-client.ts +++ b/src/agent/dsh-native-client.ts @@ -36,7 +36,15 @@ // (always present — the launcher posture has no bundle page) and // plugins.bundle.config (keyed by package name; the plugin detail page renders // it only when this package is installed as a profile bundle and draws the -// title itself, so that registration drops the h3). +// title itself, so that registration drops the h3). #3862: a THIRD face — a +// per-session Context tab in the official dsh client (conversation.view slot). +// dsh exposes no API to edit the context stream, so host-side stat plugins +// anchored on the event log can never observe bili's folds (their bar freezes +// at the pre-compression caliber, dsh-context#173); the tab instead renders +// the proxy's OWN live view (GET /__bili/plugin/status `contextView`: the +// post-fold sent composition recomputed by the kernel + fold/switch trails +// from the cache ledger). It is native DOM in this bundle, NOT an iframe +// (owner directive): react stays the single external, no second document. import { createElement, useEffect, useState } from "react"; @@ -110,6 +118,150 @@ const ACTION_BTN_STYLE = { whiteSpace: "nowrap", }; +// #3862: Context tab data source + cadence. The status URL is the SAME +// canonical form the dsh lane uses server-side (/acp command), so the tab and +// the slash command can never read two different sessions. Polling is slow by +// design: the view only changes on model requests, 10s is imperceptible lag +// at zero cost. +const CTX_STATUS_PATH = "/__bili/plugin/status?conversationId=dsh&fallback=latest"; +const CTX_POLL_MS = 10000; +const CTX_EVENT_ROWS = 12; + +// Segment palette: GitHub-dark category colors, readable on both host themes +// (segments sit on a neutral track, not on the page ground). +const CATEGORY_COLOR: Record = { + sysprompt: "#6e7781", + tool: "#d29922", + text: "#58a6ff", + code: "#bc8cff", + summaries: "#3fb950", + system: "#8b949e", +}; +const CATEGORY_LABEL_KEYS: Record = { + sysprompt: "cat_sysprompt", + tool: "cat_tool", + text: "cat_text", + code: "cat_code", + summaries: "cat_summaries", + system: "cat_system", +}; +const ANCHOR_KIND_KEYS: Record = { + usage: "ctx_anchor_kind_usage", + estimate: "ctx_anchor_kind_estimate", + upper: "ctx_anchor_kind_upper", +}; +const SWITCH_KEYS: Record = { + model: "ctx_switch_model", + key: "ctx_switch_key", + prompt: "ctx_switch_prompt", + restart: "ctx_switch_restart", +}; + +function categoryColor(key: string): string { + return CATEGORY_COLOR[key] ?? "#8b949e"; +} + +function categoryLabel(key: string, t: (k: string) => string): string { + const k = CATEGORY_LABEL_KEYS[key]; + return k !== undefined ? t(k) : key; +} + +function num(v: unknown): number { + return typeof v === "number" && Number.isFinite(v) ? v : 0; +} + +function numOrNull(v: unknown): number | null { + return typeof v === "number" && Number.isFinite(v) && v > 0 ? v : null; +} + +function arr(v: unknown): unknown[] { + return Array.isArray(v) ? v : []; +} + +function rec(v: unknown): Record | null { + return typeof v === "object" && v !== null ? (v as Record) : null; +} + +function fmtTok(n: number): string { + if (!Number.isFinite(n)) return "?"; + if (n < 1000) return String(Math.round(n)); + if (n < 1_000_000) return `${(n / 1000).toFixed(1).replace(/\.0$/, "")}k`; + return `${(n / 1_000_000).toFixed(2).replace(/\.?0+$/, "")}M`; +} + +function fmtTime(at: number, lang: "zh" | "en"): string { + try { + return new Date(at).toLocaleTimeString(lang === "zh" ? "zh-CN" : "en-US", { hour: "2-digit", minute: "2-digit" }); + } catch { + return ""; + } +} + +type CtxCategory = { key: string; tokens: number; pct: number }; +type CtxFoldEvent = { seq: number; at: number; s: number; sigma: number; reclaimed: number; savedSoFar: number }; +type CtxSwitchEvent = { dim: string; at: number; from: string | null; to: string; attributed: number }; +type CtxAnchor = { tokens: number; kind: string; at: number | null }; +type CtxView = { limit: number | null; sentTotal: number; growth: number; categories: CtxCategory[]; anchor: CtxAnchor | null; folds: CtxFoldEvent[]; switches: CtxSwitchEvent[] }; +type CtxStatus = { ok: boolean; phase?: string; panelPresent: boolean; contextView: CtxView | null }; + +/** Parse the /__bili/plugin/status body into the tab's render shape. Every + * field is guard-wrapped: an older or foreign build answering the URL must + * yield `undefined` (→ degraded states), never a crash mid-render. */ +function parseCtxStatus(raw: unknown): CtxStatus | undefined { + const o = rec(raw); + if (o === null || typeof o.ok !== "boolean") return undefined; + let view: CtxView | null = null; + const v = rec(o.contextView); + if (v !== null) { + const a = rec(v.anchor); + view = { + limit: numOrNull(v.limit), + sentTotal: num(v.sentTotal), + growth: num(v.growth), + categories: arr(v.categories) + .map((c) => { + const r = rec(c); + return r === null || typeof r.key !== "string" || r.key.length === 0 ? undefined : { key: r.key, tokens: num(r.tokens), pct: num(r.pct) }; + }) + .filter((c): c is CtxCategory => c !== undefined), + anchor: a === null ? null : { tokens: num(a.tokens), kind: typeof a.kind === "string" ? a.kind : "estimate", at: typeof a.at === "number" ? a.at : null }, + folds: arr(v.folds) + .map((f) => { + const r = rec(f); + return r === null ? undefined : { seq: num(r.seq), at: num(r.at), s: num(r.s), sigma: num(r.sigma), reclaimed: num(r.reclaimed), savedSoFar: num(r.savedSoFar) }; + }) + .filter((f): f is CtxFoldEvent => f !== undefined), + switches: arr(v.switches) + .map((s) => { + const r = rec(s); + return r === null || typeof r.dim !== "string" || r.dim.length === 0 + ? undefined + : { dim: r.dim, at: num(r.at), from: typeof r.from === "string" ? r.from : null, to: typeof r.to === "string" ? r.to : "?", attributed: num(r.attributed) }; + }) + .filter((s): s is CtxSwitchEvent => s !== undefined), + }; + } + return { ok: o.ok, phase: typeof o.phase === "string" ? o.phase : undefined, panelPresent: o.panel !== undefined, contextView: view }; +} + +/** Shared open-in-browser action — one builder for the settings-panel footer, + * the embedded tab row and the Context tab so the placements cannot drift + * (label, tooltip, target). Returns null while the origin is unknown. */ +function openWebButton(origin: string | undefined, t: (key: string) => string, style?: Record): ReturnType { + return origin === undefined + ? null + : createElement( + "button", + { + type: "button", + title: origin, + onClick: () => openExternal(`${origin}/__bili/`), + style: { ...ACTION_BTN_STYLE, ...style }, + }, + t("open"), + ); +} + // #3100: pre-flight for the framed face. Auto-update refreshes the profile // bundle on DISK while the long-running proxy child keeps serving the code it // booted with — and this browser half always runs the freshest disk code — so @@ -239,6 +391,33 @@ const zh: Dict = { "tab_sessions": "会话", "tab_config": "配置", "tab_logs": "日志", + "tab_ctx": "上下文", + "ctx_sent": "发送到模型(压缩后,估算)", + "ctx_anchor": "计费口径", + "ctx_anchor_kind_usage": "usage 实测", + "ctx_anchor_kind_estimate": "估算(锚定 usage)", + "ctx_anchor_kind_upper": "上界估算", + "cat_sysprompt": "系统提示与工具定义", + "cat_tool": "工具调用与结果", + "cat_text": "对话文本", + "cat_code": "代码", + "cat_summaries": "压缩摘要", + "cat_system": "历史系统消息", + "ctx_events": "事件", + "ctx_fold": "压缩", + "ctx_reclaimed": "回收", + "ctx_saved": "累计节省", + "ctx_switch_model": "模型切换", + "ctx_switch_key": "密钥切换", + "ctx_switch_prompt": "提示词变化", + "ctx_switch_restart": "代理重启", + "ctx_empty_events": "本会话暂无压缩或切换事件。", + "ctx_waiting": "等待首个模型请求…", + "ctx_nodata": "暂无上下文数据——完成一次模型请求后自动刷新。", + "ctx_stale": "运行中的 bili 代理比已安装的配置文件旧:本页面已加载新版界面,但代理进程尚未提供结构化上下文数据(重启后即可)。恢复前可点下方按钮打开 Web UI。", + "ctx_stale_data": "数据可能不是最新。", + "ctx_refresh": "刷新", + "ctx_hint": "柱状图为 bili 代理实时重算的估算口径;计费行来自 provider 实测 usage——两者口径不同,不可直接相减。", }; const en: Dict = { @@ -255,6 +434,33 @@ const en: Dict = { "tab_sessions": "Sessions", "tab_config": "Config", "tab_logs": "Logs", + "tab_ctx": "Context", + "ctx_sent": "Sent to model (post-compression, est.)", + "ctx_anchor": "Billed reading", + "ctx_anchor_kind_usage": "provider-measured usage", + "ctx_anchor_kind_estimate": "estimate anchored on usage", + "ctx_anchor_kind_upper": "upper-bound estimate", + "cat_sysprompt": "System prompt & tool defs", + "cat_tool": "Tool calls & results", + "cat_text": "Conversation text", + "cat_code": "Code", + "cat_summaries": "Compression summaries", + "cat_system": "Historic system messages", + "ctx_events": "Events", + "ctx_fold": "Fold", + "ctx_reclaimed": "reclaimed", + "ctx_saved": "saved so far", + "ctx_switch_model": "Model switch", + "ctx_switch_key": "Key switch", + "ctx_switch_prompt": "Prompt change", + "ctx_switch_restart": "Proxy restart", + "ctx_empty_events": "No compression or switch events yet.", + "ctx_waiting": "Waiting for the first model request…", + "ctx_nodata": "No context data yet — refreshes automatically after the first model request.", + "ctx_stale": "The running bili proxy is older than the installed profile: this page already runs the new face, but the proxy process does not serve structured context data yet (a restart fixes it). Until then, use the button below to open the Web UI directly.", + "ctx_stale_data": "Data may be stale.", + "ctx_refresh": "Refresh", + "ctx_hint": "The bar is the proxy's live recompute on the estimate scale; the billed line uses provider-measured usage — different scales, never subtract them.", }; function readOrigin(): string | undefined { @@ -403,6 +609,150 @@ export function apply(ctx: ClientContext): void { "bili: dictionaries", ); const t = ctx.locale.bind(NS); + // #3862: per-session Context tab (conversation.view slot). Native DOM card + // fed by the proxy's live contextView — see parseCtxStatus for the wire + // contract and src/context-view.ts for the scale discipline. + const contextPanel = (): ((props: Record) => unknown) => () => { + const [origin, setOrigin] = useState(readOrigin()); + const [status, setStatus] = useState(undefined); + const [fetchFailed, setFetchFailed] = useState(false); + const [reloadTick, setReloadTick] = useState(0); + useEffect(() => probeOrigin(setOrigin), []); + useEffect(() => { + if (origin === undefined) return; + let cancelled = false; + const load = (): void => { + void fetch(`${origin}${CTX_STATUS_PATH}`) + .then((res) => res.json() as Promise) + .then((raw) => { + if (cancelled) return; + const parsed = parseCtxStatus(raw); + setStatus(parsed); + setFetchFailed(parsed === undefined); + }) + .catch(() => { + if (!cancelled) setFetchFailed(true); + }); + }; + load(); + const timer: ReturnType = setInterval(load, CTX_POLL_MS); + return () => { + cancelled = true; + clearInterval(timer); + }; + }, [origin, reloadTick]); + const lang = t("nav") === zhDict.nav ? "zh" : "en"; + const hintP = (key: string): unknown => createElement("p", { style: { margin: 0, opacity: 0.7, lineHeight: 1.6 } }, t(key)); + const renderCard = (view: CtxView): unknown => { + const pctOfLimit = view.limit !== null && view.limit > 0 ? Math.round((view.sentTotal / view.limit) * 100) : null; + const anchorKindKey = view.anchor !== null ? ANCHOR_KIND_KEYS[view.anchor.kind] : undefined; + const events: Array<{ at: number; head: string; detail: string }> = []; + for (const f of view.folds) { + const saved = f.savedSoFar > 0 ? ` · ${t("ctx_saved")} ${fmtTok(f.savedSoFar)}` : ""; + events.push({ at: f.at, head: `${t("ctx_fold")} #${f.seq}`, detail: `−${fmtTok(f.s)} → σ ${fmtTok(f.sigma)} · ${t("ctx_reclaimed")} ${fmtTok(f.reclaimed)}${saved}` }); + } + for (const s of view.switches) { + const key = SWITCH_KEYS[s.dim]; + if (key === undefined) continue; + const attr = s.attributed > 0 ? ` · ~${fmtTok(s.attributed)}` : ""; + events.push({ at: s.at, head: t(key), detail: `${s.from ?? "?"} → ${s.to}${attr}` }); + } + events.sort((a, b) => b.at - a.at); + return createElement( + "div", + { style: { display: "flex", flexDirection: "column", gap: 10 } }, + fetchFailed ? createElement("p", { style: { margin: 0, opacity: 0.6, fontSize: 12 } }, t("ctx_stale_data")) : null, + createElement( + "div", + { style: { display: "flex", alignItems: "baseline", justifyContent: "space-between", gap: 12, flexWrap: "wrap" } }, + createElement( + "div", + null, + createElement("div", { style: { fontSize: 18, fontWeight: 600 } }, `${fmtTok(view.sentTotal)} / ${view.limit !== null ? fmtTok(view.limit) : "—"}${pctOfLimit !== null ? ` (${pctOfLimit}%)` : ""}`), + createElement("p", { style: { margin: 0, opacity: 0.7, fontSize: 12 } }, t("ctx_sent")), + ), + view.anchor !== null + ? createElement("span", { style: { opacity: 0.85, fontSize: 13 } }, `${t("ctx_anchor")} ${fmtTok(view.anchor.tokens)} · ${anchorKindKey !== undefined ? t(anchorKindKey) : view.anchor.kind}`) + : null, + ), + createElement( + "div", + { style: { display: "flex", height: 10, borderRadius: 5, overflow: "hidden", background: "rgba(127,127,127,0.18)" } }, + view.categories.map((c) => + createElement("div", { + key: c.key, + title: `${categoryLabel(c.key, t)}: ${fmtTok(c.tokens)} (${c.pct}%)`, + style: { width: `${c.tokens > 0 ? Math.max(c.pct, 1.5) : 0}%`, height: "100%", background: categoryColor(c.key) }, + }), + ), + ), + createElement( + "div", + { style: { display: "flex", flexDirection: "column", gap: 4 } }, + view.categories.map((c) => + createElement( + "div", + { key: c.key, style: { display: "flex", alignItems: "center", gap: 8, fontSize: 13 } }, + createElement("span", { style: { width: 10, height: 10, borderRadius: 2, background: categoryColor(c.key), flexShrink: 0 } }), + createElement("span", { style: { flex: 1 } }, categoryLabel(c.key, t)), + createElement("span", { style: { opacity: 0.85 } }, `${fmtTok(c.tokens)} (${c.pct}%)`), + ), + ), + ), + createElement( + "div", + { style: { display: "flex", flexDirection: "column", gap: 6 } }, + createElement("div", { style: { fontSize: 13, fontWeight: 600, opacity: 0.85 } }, t("ctx_events")), + events.length === 0 + ? createElement("p", { style: { margin: 0, opacity: 0.6, fontSize: 13 } }, t("ctx_empty_events")) + : events.slice(0, CTX_EVENT_ROWS).map((e, i) => + createElement( + "div", + { key: i, style: { display: "flex", justifyContent: "space-between", gap: 12, fontSize: 12, alignItems: "baseline" } }, + createElement("span", { style: { opacity: 0.7 } }, `${fmtTime(e.at, lang)} ${e.head}`), + createElement("span", { style: { opacity: 0.85 } }, e.detail), + ), + ), + ), + createElement("p", { style: { margin: 0, opacity: 0.55, fontSize: 12, lineHeight: 1.6 } }, t("ctx_hint")), + ); + }; + let middle: unknown; + if (origin === undefined) { + middle = hintP("degraded"); + } else if (status?.ok === true && status.phase === "pre-first-request") { + middle = hintP("ctx_waiting"); + } else if (status?.ok === true && status.contextView === null) { + middle = hintP(status.panelPresent ? "ctx_stale" : "ctx_nodata"); + } else if (status === undefined) { + middle = hintP(fetchFailed ? "degraded" : "connecting"); + } else if (!status.ok) { + middle = hintP("ctx_nodata"); + } else { + middle = renderCard(status.contextView!); + } + return createElement( + "div", + { style: { display: "flex", flexDirection: "column", gap: 12, padding: "20px 8px" } }, + middle, + createElement( + "div", + { style: { display: "flex", alignItems: "center", gap: 10, flexWrap: "wrap" } }, + origin !== undefined + ? createElement( + "button", + { + type: "button", + onClick: () => setReloadTick((x) => x + 1), + style: { cursor: "pointer", borderRadius: 8, border: "1px solid rgba(127,127,127,0.4)", background: "transparent", color: "inherit", fontFamily: "inherit", fontSize: 13, lineHeight: "20px", padding: "4px 14px" }, + }, + t("ctx_refresh"), + ) + : null, + openWebButton(origin, t, { fontSize: "13", lineHeight: "20px", padding: "4px 14px" }), + ), + ); + }; const panel = (titled: boolean): ((props: Record) => unknown) => () => { const [origin, setOrigin] = useState(readOrigin()); const [page, setPage] = useState("overview"); @@ -448,23 +798,6 @@ export function apply(ctx: ClientContext): void { // notice of a reachable-but-frozen proxy. const remoteBlocked = remoteMismatch(origin) && liveEmbed === undefined; const lang = t("nav") === zhDict.nav ? "zh" : "en"; - // The open-in-browser action button. One shared builder so the two - // placements (embedded-tab row, degraded/stale footer) cannot drift: - // same label, same tooltip, same jump target. Returns null while the - // origin is unknown — there is nothing to open yet. - const openWebButton = (style?: Record): ReturnType => - origin === undefined - ? null - : createElement( - "button", - { - type: "button", - title: origin, - onClick: () => openExternal(`${origin}/__bili/`), - style: { ...ACTION_BTN_STYLE, ...style }, - }, - t("open"), - ); let middle: unknown; if (origin === undefined) { middle = createElement("p", { style: { margin: 0, opacity: 0.7, lineHeight: 1.6 } }, t("degraded")); @@ -535,7 +868,7 @@ export function apply(ctx: ClientContext): void { // The open-in-browser action rides the TAB row — right // after the logs tab, pushed to the row's far end — // instead of sitting in the footer below the iframe. - openWebButton({ marginLeft: "auto", fontSize: "13", lineHeight: "20px", padding: "4px 14px" }), + openWebButton(origin, t, { marginLeft: "auto", fontSize: "13", lineHeight: "20px", padding: "4px 14px" }), ), createElement("iframe", { src: `${origin}/__bili/?embed=1&lang=${lang}${theme ? `&theme=${theme}` : ""}#/${page}`, @@ -565,7 +898,7 @@ export function apply(ctx: ClientContext): void { // ok 状态:按钮在上方页签行(日志页签后面);degraded/stale // 仍留在页脚作后备入口(#2448 同一按钮)。#3816: remoteBlocked // 时按钮指向的正是那个够不到的回环地址——死链,一并隐藏。 - liveEmbed === "ok" || remoteBlocked ? null : openWebButton(), + liveEmbed === "ok" || remoteBlocked ? null : openWebButton(origin, t), ), ); }; @@ -577,4 +910,12 @@ export function apply(ctx: ClientContext): void { "plugins.bundle.config", () => ctx.slots.register({ name: "plugins.bundle.config", key: "billion-context", locale: NS }, panel(false)), ); + // #3862: session Context tab. order 30 sits right of the built-in chat (0) + // and trajectory (10) tabs and right of dsh-context's Context tab (20) + // when both are installed. Deferred injection is fail-open on hosts whose + // build lacks the slot. + ctx.slots.inject( + "conversation.view", + () => ctx.slots.register({ name: "conversation.view", id: "bili-context", order: 30, label: () => t("tab_ctx"), locale: NS }, contextPanel()), + ); } diff --git a/src/cache-ledger.ts b/src/cache-ledger.ts index a2907e5d83..a087ab4505 100644 --- a/src/cache-ledger.ts +++ b/src/cache-ledger.ts @@ -1635,7 +1635,7 @@ function stampedPriceProfile(session: Session): PriceProfile | undefined { return Object.keys(out).length > 0 ? out : undefined; } -interface ModelSwitchEvent { +export interface ModelSwitchEvent { seq: number; at: number; from: string | null; @@ -1647,7 +1647,7 @@ interface ModelSwitchEvent { attributed: number; } -interface ModelSwitchStats { +export interface ModelSwitchStats { count: number; missedTokens: number; events: ModelSwitchEvent[]; diff --git a/src/context-view.ts b/src/context-view.ts new file mode 100644 index 0000000000..121d983880 --- /dev/null +++ b/src/context-view.ts @@ -0,0 +1,148 @@ +// #3862: structured context view for programmatic consumers (the dsh client +// Context tab). bili folds happen OUTSIDE the dsh event stream, so host-side +// stat plugins anchored on it show the PRE-compression caliber forever +// (dsh-context#173); bili knows the exact post-fold bytes and publishes them +// here as a machine-readable twin of the /acp panel. Two load-bearing +// invariants: (1) every figure is the kernel countTokens estimate of the +// CURRENT sent view except `anchor`, which is the usage-grade reading (#2117 +// displayContextBest ladder) on its OWN scale — never mix the two in +// arithmetic; (2) the category math mirrors kernel buildStatusPanel +// one-to-one (sentTotal = classified + host system+tools), so segments sum +// to sentTotal and the view can never drift from the panel text. Events ride +// buildSessionCacheReport — the same ledger semantics the Web UI renders. + +import type { NudgeDecision } from "acp-kernel"; +import { buildSessionCacheReport, type ModelSwitchEvent } from "./cache-ledger.js"; +import { displayContextBest, type Session } from "./session.js"; + +/** Max events per trail published in the view (newest first). */ +const EVENT_CAP = 20; + +export interface ContextViewCategory { + /** sysprompt | tool | text | code | summaries | system */ + key: string; + tokens: number; + /** percent of sentTotal (rounded; segments may not sum to exactly 100). */ + pct: number; +} + +export interface ContextViewFold { + seq: number; + at: number; + /** S: original tokens folded out of the sent view. */ + s: number; + /** sigma: summary tokens that stayed in the window. */ + sigma: number; + /** S − sigma clamped at 0 — the pure token removal this fold achieved. */ + reclaimed: number; + /** (S−σ) × requestsAfter — tokens not billed because of this fold so far. */ + savedSoFar: number; + paidBack: boolean | null; +} + +export interface ContextViewSwitch { + dim: "model" | "key" | "prompt" | "restart"; + at: number; + from: string | null; + to: string; + /** ttlRepay tokens attributed to this event by the ledger partition. */ + attributed: number; +} + +export interface ContextViewAnchor { + tokens: number; + kind: "usage" | "estimate" | "upper"; + at: number | null; +} + +export interface ContextView { + /** Every token figure in this object is on ONE scale: the kernel + * countTokens estimate of the current sent view. The anchor is the + * exception — its own usage-grade scale, labeled via kind. */ + scale: "estimate"; + /** wall-clock of this computation (epoch ms). */ + at: number; + limit: number | null; + sentTotal: number; + /** growth since the last nudge reference (0 when none recorded). */ + growth: number; + categories: ContextViewCategory[]; + anchor: ContextViewAnchor | null; + folds: ContextViewFold[]; + switches: ContextViewSwitch[]; +} + +interface BuildInput { + nudge: NudgeDecision | undefined; + /** Host-measured system+tools overhead (prepare-time, same source as the + * panel's SysPrompt row). */ + systemPromptTokens: number; + limit: number; + session: Session; +} + +/** null when no breakdown exists yet (no messages processed this process) — + * consumers then show their waiting state instead of a zero card. */ +export function buildContextView(input: BuildInput): ContextView | null { + const bd = input.nudge?.contextBreakdown; + if (bd === undefined) return null; + // Same classification as kernel/src/panel/panel.ts buildStatusPanel. + const classified = bd.system + bd.tool + bd.summaries + bd.code + bd.text; + const sentTotal = classified + input.systemPromptTokens; + const pctOf = (v: number): number => (sentTotal > 0 ? Math.round((v / sentTotal) * 100) : 0); + const rows: Array<[string, number]> = [ + ["sysprompt", input.systemPromptTokens], + ["tool", bd.tool], + ["text", bd.text], + ["code", bd.code], + ["summaries", bd.summaries], + ["system", bd.system], + ]; + const categories: ContextViewCategory[] = []; + for (const [key, tokens] of rows) { + if (tokens <= 0) continue; + categories.push({ key, tokens, pct: pctOf(tokens) }); + } + const folds: ContextViewFold[] = []; + const switches: ContextViewSwitch[] = []; + try { + const report = buildSessionCacheReport(input.session); + for (const f of [...report.folds].reverse().slice(0, EVENT_CAP)) { + folds.push({ + seq: f.seq, + at: f.at, + s: f.S, + sigma: f.sigma, + reclaimed: Math.max(0, f.S - f.sigma), + savedSoFar: f.savedSoFar, + paidBack: f.paidBack, + }); + } + const evs: ContextViewSwitch[] = []; + const take = (dim: ContextViewSwitch["dim"], events: readonly ModelSwitchEvent[]): void => { + for (const e of events) evs.push({ dim, at: e.at, from: e.from, to: e.to, attributed: e.attributed }); + }; + take("model", report.modelSwitches.events); + take("key", report.keySwitches.events); + take("prompt", report.promptSwitches.events); + take("restart", report.restartDrops.events); + evs.sort((a, b) => b.at - a.at); + for (const e of evs.slice(0, EVENT_CAP)) switches.push(e); + } catch { + // Ledger/report unavailable (corrupt metadata, partial restore) — the + // view still serves its primary job (current composition); trails stay + // empty rather than failing the whole status read. + } + const best = displayContextBest(input.session); + return { + scale: "estimate", + at: Date.now(), + limit: Number.isFinite(input.limit) && input.limit > 0 ? input.limit : null, + sentTotal, + growth: bd.growth, + categories, + anchor: best !== null ? { tokens: best.tokens, kind: best.kind, at: best.at ?? null } : null, + folds, + switches, + }; +} diff --git a/src/plugin.ts b/src/plugin.ts index 610d33c81a..1eda8b0ada 100644 --- a/src/plugin.ts +++ b/src/plugin.ts @@ -10,6 +10,7 @@ import { getStore, storageStatusLabel } from "./persist.js"; import { cloneStoreForRefs } from "./store.js"; import { acquireInFlight, createSession, getSession, publishForkSession, diagnoseSuccessWithoutUsage, effectiveConfig, findSessionByCanonicalId, listSessions, markCompactionBoundary, markDirty, peekSession, releaseInFlight, statusInputBaseline, withSessionLock, type Session } from "./session.js"; import { clientConversationHeader } from "./session-id.js"; +import { buildContextView } from "./context-view.js"; import { ABSORB_TOOL_NAME, BILI_ACP_TOOLS_ANTHROPIC, BILI_ACP_TOOLS_ANTHROPIC_NO_RANGE, BILI_ACP_TOOLS_OPENAI, BILI_ACP_TOOLS_OPENAI_NO_RANGE, BILI_ACP_TOOLS_RESPONSES_NO_RANGE, PROXY_TOOL_NAMES, READ_ORIGINAL_IMAGE_TOOL, READ_ORIGINAL_IMAGE_TOOL_NAME, READ_ORIGINAL_IMAGE_TOOL_OPENAI, READ_ORIGINAL_IMAGE_TOOL_RESPONSES, RETRIEVE_TOOL_NAME, RULE_TOOL, RULE_TOOL_NAME, RULE_TOOL_OPENAI, RULE_TOOL_RESPONSES, SEARCH_CONTEXT_TOOL_NAME, absorbToolsFor, retrieveToolsFor, withAcpNotes, withAcpNotesOpenAI } from "./compress-tool.js"; import { externalSummaryEnabled, externalSummaryMaxToolDurationMs, withExternalSummaryTools } from "./external-summary-surface.js"; import { salvageCompressArgs } from "./plugin-compress-salvage.js"; @@ -1475,7 +1476,17 @@ function webSessionUrl(origin: string | undefined, sessionId: string): string | return `${o}/__bili/#/session/${encodeURIComponent(sessionId)}`; } -export function handlePluginStatus(conversationId: string, res: import("node:http").ServerResponse, deps: PluginToolDeps, fallbackLatest = false): void { +export function handlePluginStatus(conversationId: string, res: import("node:http").ServerResponse, deps: PluginToolDeps, fallbackLatest = false, trustedOrigin?: string): void { + // #3862: the dsh client's Context tab reads this route CROSS-ORIGIN from + // the dsh web app (its own loopback port / the dsh-app://app scheme). The + // trusted-origin gate upstream of dispatch already admitted the request; + // echoing that origin makes the cors-mode fetch readable in the browser — + // the same fix the HTML embed route carries (#3100 pre-flight). + const jsonHeaders = (): Record => { + const h: Record = { "content-type": "application/json" }; + if (trustedOrigin !== undefined && trustedOrigin.length > 0) h["access-control-allow-origin"] = trustedOrigin; + return h; + }; let session = resolveForkConversation(conversationId); const entry = conversations.get(conversationId); let viaFallback = false; @@ -1504,7 +1515,7 @@ export function handlePluginStatus(conversationId: string, res: import("node:htt // renderable panel; `phase` exposes the state for programmatic consumers. const verdict = chainVerdictFor(conversationId); if (verdict !== undefined) { - res.writeHead(200, { "content-type": "application/json" }); + res.writeHead(200, jsonHeaders()); res.end(JSON.stringify({ ok: true, conversationId, phase: "chain-advisory", chain: verdict, panel: chainAdvisoryPanel(verdict), sessionId: null, sessionRevision: null, model: null, contextLimit: null, contextTokens: null, contextTokensSource: "unavailable", contextTokensAt: null, contextGeneration: null })); return; } @@ -1515,7 +1526,7 @@ export function handlePluginStatus(conversationId: string, res: import("node:htt // with their agent name (dsh's fetchStatusLatest sends "dsh"). const pre = pluginRuntimeTable.get(conversationId) ?? pluginRuntimeByConversation.get(conversationId); if (pre !== undefined) { - res.writeHead(200, { "content-type": "application/json" }); + res.writeHead(200, jsonHeaders()); res.end(JSON.stringify({ ok: true, conversationId, phase: "pre-first-request", model: pre.model, contextLimit: pre.contextWindow ?? null, runtimeInfo: pre, panel: null, sessionId: null, sessionRevision: null, contextTokens: null, contextTokensSource: "unavailable", contextTokensAt: null, contextGeneration: null })); return; } @@ -1569,17 +1580,20 @@ export function handlePluginStatus(conversationId: string, res: import("node:htt if (nudge) { nudge = { ...nudge, compressibleRanges: excludeDeadRefRanges(nudge.compressibleRanges ?? [], session.state.deadRefs) }; } + // #532/#3862: host-measured system+tools overhead (prepare-time, same + // source as estimateInputTokens) — shared by the panel text below AND the + // structured context view, so both surfaces classify identically. + const sysTokRaw = session.metadata.systemPromptTokens; + const systemPromptTokens = typeof sysTokRaw === "number" && Number.isFinite(sysTokRaw) && sysTokRaw > 0 ? sysTokRaw : 0; + const contextView = buildContextView({ nudge, systemPromptTokens, limit: modelContextLimit, session }); let panel: string | undefined; try { - // #532: the kernel breakdown classifies messages only; bili measured - // the outbound system+tools overhead at prepare time (same source as - // estimateInputTokens) and stored it on the session. Feeding it in is + // #532: the kernel breakdown classifies messages only; feeding in the + // host-measured system+tools (hoisted above with the context view) is // what makes Sent/SysPrompt reflect reality instead of undercounting // by the full system+tools size every turn. unprunedTokens gets the // same addition so the Session-only derivation (unpruned − sent) still // isolates pruned originals on one scale. - const sysTokRaw = session.metadata.systemPromptTokens; - const systemPromptTokens = typeof sysTokRaw === "number" && Number.isFinite(sysTokRaw) && sysTokRaw > 0 ? sysTokRaw : 0; panel = buildStatusPanel({ version: `billion-context@${PROXY_VERSION}${BUILD_COMMIT && BUILD_COMMIT !== "unknown" ? ` (${BUILD_COMMIT})` : ""} · pack: ${session.meta.activePack ?? "default"}`, // #2671: effective storage mode — legacy/shadow/full, including @@ -1641,7 +1655,7 @@ export function handlePluginStatus(conversationId: string, res: import("node:htt // replace() pattern syntax ($&, $\`, $') and corrupt the box lines. panel = panel.replace(PANEL_BOX_FOOTER, `\n${preFooter.join("\n")}\n${PANEL_BOX_FOOTER}`.replace(/\$/g, "$$$$")); } - res.writeHead(200, { "content-type": "application/json" }); + res.writeHead(200, jsonHeaders()); res.end(JSON.stringify({ ok: true, conversationId: resolvedConversationId, @@ -1660,6 +1674,9 @@ export function handlePluginStatus(conversationId: string, res: import("node:htt contextTokensSource, contextTokensAt: observation?.at ?? null, contextGeneration: observation ? forkHash({ sessionId: session.id, sessionRevision, generation: observation.generation, contextTokens, contextTokensSource, limit, model: session.metadata.lastModel }) : null, + // #3862: structured twin of the panel's sent-view breakdown + event + // trails — additive field, null until the first request lands. + contextView, compressCreditTokens: session.stats.compressCreditTokens ?? 0, inputTokens: session.stats.inputTokens, outputTokens: session.stats.outputTokens, diff --git a/src/server/admin.ts b/src/server/admin.ts index 60a9783370..ecfa11d47e 100644 --- a/src/server/admin.ts +++ b/src/server/admin.ts @@ -406,7 +406,11 @@ export async function handleAdminRoute(req: http.IncomingMessage, res: http.Serv // Web UI origin as the user's browser dials it: the ACTUAL bound port // (req.socket.localPort differs from opts.port when listening on port 0). const webOrigin = `http://${opts.host === "0.0.0.0" ? "localhost" : opts.host}:${req.socket?.localPort ?? opts.port}`; - return handlePluginStatus(conversationId, res, { core, config, log, webOrigin }, params.get("fallback") === "latest"); + // #3862: pass the requesting origin through so the handler can echo it + // back for cross-origin browser readers (the dsh client Context tab); + // only origins the gate above admitted ever reach this line. + const reqOrigin = req.headers.origin; + return handlePluginStatus(conversationId, res, { core, config, log, webOrigin }, params.get("fallback") === "latest", typeof reqOrigin === "string" && reqOrigin.length > 0 ? reqOrigin : undefined); } if (req.method === "POST" && req.url === "/__bili/watcher") { // #7: an ATTACHING claude session registers its host pid so the shared diff --git a/tests/dsh-settings-ui.test.ts b/tests/dsh-settings-ui.test.ts index 4751919a3d..c7f91a5e2a 100644 --- a/tests/dsh-settings-ui.test.ts +++ b/tests/dsh-settings-ui.test.ts @@ -295,6 +295,19 @@ function collectButtons(node: unknown, out: ElementNode[] = []): ElementNode[] { return out; } +function collectEls(node: unknown, out: ElementNode[] = []): ElementNode[] { + if (Array.isArray(node)) { + for (const child of node) collectEls(child, out); + return out; + } + if (node !== null && typeof node === "object") { + const el = node as ElementNode; + out.push(el); + for (const child of el.children ?? []) collectEls(child, out); + } + return out; +} + // The element whose DIRECT children (including array children) contain an // element matching pred — used to pin which row parents a given tab. function findDivParenting(node: unknown, pred: (el: ElementNode) => boolean): ElementNode | undefined { @@ -399,7 +412,9 @@ async function mountClient(extra: Record, slotName = "settings. useState: (init: unknown): [unknown, (v: unknown) => void] => { const i = hookIndex++; if (!(i in hookStates)) hookStates[i] = typeof init === "function" ? (init as () => unknown)() : init; - return [hookStates[i], (v: unknown) => { hookStates[i] = v; }]; + // React's setState also takes an updater function — emulate it, or + // components using setX(x => x+1) would store the closure itself. + return [hookStates[i], (v: unknown) => { hookStates[i] = typeof v === "function" ? (v as (prev: unknown) => unknown)(hookStates[i]) : v; }]; }, useEffect: (fn: () => unknown | (() => void), deps?: readonly unknown[]): void => { const i = hookIndex++; @@ -488,8 +503,17 @@ test("#1590/#2125: client bundle registers the settings.section entry bili AND t const m = await mountClient(extra); assert.deepEqual(Array.from(m.inject), ["slots", "locale"]); - assert.deepEqual(m.slotsOrder, ["settings.section", "plugins.bundle.config"]); - assert.equal(m.optionsBySlot.size, 2); + assert.deepEqual(m.slotsOrder, ["settings.section", "plugins.bundle.config", "conversation.view"]); + assert.equal(m.optionsBySlot.size, 3); + // #3862: the per-session Context tab sits right of the built-in chat (0) / + // trajectory (10) faces and any third-party context tab (dsh-context: 20). + const viewSlot = m.optionsBySlot.get("conversation.view")!; + assert.equal(viewSlot.name, "conversation.view"); + assert.equal(viewSlot.id, "bili-context"); + assert.equal(viewSlot.order, 30); + assert.equal(viewSlot.locale, "bili"); + assert.equal(typeof viewSlot.label, "function"); + assert.equal((viewSlot.label as () => string)(), "上下文"); assert.ok(m.dicts["bili"] !== undefined); const settings = m.optionsBySlot.get("settings.section")!; assert.equal(settings.name, "settings.section"); @@ -1253,7 +1277,7 @@ test("#3100: embed pre-flight — a stale proxy build gets the restart notice in assert.equal(embedCalls, 3, "#3100: a cached verdict is never re-fetched"); m.runCleanups(); } -}); + }); test("#3816: remote page + loopback origin (relay off) shows the adminRelay guidance instead of spinning; gate negatives stay unchanged", async () => { // Positive: the page is reached through a non-loopback host while the @@ -1443,3 +1467,185 @@ test("#3816: remote page + loopback origin (relay off) shows the adminRelay guid m.runCleanups(); } }); + +// #3862: the per-session Context tab (conversation.view slot) — a native DOM +// card fed by /__bili/plugin/status contextView. Data comes from bili's live +// post-fold recompute (the proxy owns the truth dsh cannot see), so the tab +// shows sentTotal that actually dropped after compression, unlike any +// host-log-derived statistic. +test("#3862: conversation.view Context tab renders the live contextView card, polls at 10s, and degrades honestly", async () => { + const T = 1_700_000_000_000; + const canned = { + ok: true, + panel: "x", + contextView: { + scale: "estimate", at: T, limit: 100_000, sentTotal: 45_000, growth: 1234, + categories: [ + { key: "sysprompt", tokens: 12_000, pct: 27 }, + { key: "tool", tokens: 20_000, pct: 44 }, + { key: "text", tokens: 5_000, pct: 11 }, + { key: "code", tokens: 4_000, pct: 9 }, + { key: "summaries", tokens: 3_000, pct: 7 }, + { key: "system", tokens: 1_000, pct: 2 }, + ], + anchor: { tokens: 42_000, kind: "usage", at: null }, + folds: [{ seq: 1, at: T - 100_000, s: 5_000, sigma: 200, reclaimed: 4_800, savedSoFar: 14_400, paidBack: true }], + switches: [{ dim: "model", at: T - 50_000, from: "model-a", to: "model-b", attributed: 1_234 }], + }, + }; + const opened: string[] = []; + const intervals: Array<{ id: number; delay: number; fn: () => void }> = []; + let nextId = 1; + let statusCalls = 0; + const fakeSetInterval = ((fn: () => void, delay?: number): unknown => { + const id = nextId++; + intervals.push({ id, delay: delay ?? 0, fn }); + return id; + }) as unknown as typeof setInterval; + const fakeClearInterval = ((id: unknown): void => { + const i = intervals.findIndex((p) => p.id === id); + if (i >= 0) intervals.splice(i, 1); + }) as unknown as typeof clearInterval; + + const m = await mountClient({ + __BILI__: { origin: "http://127.0.0.1:8787" }, + open: (url: string) => opened.push(url), + fetch: async (url: string) => { + const u = String(url); + if (u.endsWith("/bili/origin")) return { ok: true, json: async () => ({ origin: "http://127.0.0.1:8787" }) }; + if (u.endsWith("/__bili/plugin/status?conversationId=dsh&fallback=latest")) { + statusCalls += 1; + return { ok: true, json: async () => canned }; + } + throw new Error(`unexpected fetch: ${u}`); + }, + setTimeout, + clearTimeout, + setInterval: fakeSetInterval, + clearInterval: fakeClearInterval, + }, "conversation.view"); + + m.resetHooks(); + m.component(); + await tick(); + const tree = m.component() as ElementNode; + const allText: string[] = []; + collectText(tree, allText); + const joined = allText.join(" "); + // Header: estimate-scale total vs the session's effective limit. + assert.ok(allText.some((x) => x === "45k / 100k (45%)"), `header carries sentTotal/limit/pct: ${JSON.stringify(allText)}`); + // The billed anchor rides its own labeled scale — never blended into the bar. + assert.ok(joined.includes("计费口径 42k · usage 实测"), "anchor chip labels its own usage scale"); + // Stacked bar: one segment per category, width from pct, palette pinned. + const segments = collectEls(tree).filter((el) => { + const s = el.props?.style as Record | undefined; + return s !== undefined && typeof s.width === "string" && typeof s.background === "string"; + }); + const byColor = new Map(segments.map((s) => [(s.props!.style as Record).background, s])); + const segWidth = (color: string): string | undefined => { + const w = (byColor.get(color)?.props?.style as Record | undefined)?.width; + return typeof w === "string" ? w : undefined; + }; + assert.equal(segWidth("#d29922"), "44%", "tool segment width follows pct"); + assert.equal(segWidth("#6e7781"), "27%", "sysprompt segment width follows pct"); + assert.equal(segWidth("#3fb950"), "7%", "summaries segment width follows pct"); + for (const label of ["系统提示与工具定义", "工具调用与结果", "对话文本", "代码", "压缩摘要", "历史系统消息"]) { + assert.ok(joined.includes(label), `legend names every category (${label})`); + } + // Events: newest first (the switch at T-50s precedes the fold at T-100s), + // fold math rendered verbatim, switch with its attributed cost. + assert.ok(joined.includes("模型切换"), "switch event head"); + assert.ok(joined.includes("model-a → model-b · ~1.2k"), "switch detail with attributed tokens"); + assert.ok(joined.includes("压缩 #1"), "fold event head"); + assert.ok(joined.includes("−5k → σ 200 · 回收 4.8k · 累计节省 14.4k"), "fold detail: S → sigma, reclaimed, savedSoFar"); + const switchIdx = joined.indexOf("模型切换"); + const foldIdx = joined.indexOf("压缩 #1"); + assert.ok(switchIdx < foldIdx, "events sorted newest-first"); + // Footer: refresh + the shared open-in-browser action, plus the scale hint. + assert.ok(joined.includes("柱状图为 bili 代理实时重算的估算口径"), "scale-discipline hint present"); + const buttons = collectButtons(tree); + assert.equal(buttons.length, 2, "refresh + open-WebUI only"); + const refresh = buttons.find((b) => { + const bt: string[] = []; + collectText(b, bt); + return bt.join("") === "刷新"; + }); + assert.ok(refresh !== undefined, "refresh button renders"); + const webBtn = buttons.find((b) => b.props?.title === "http://127.0.0.1:8787"); + assert.ok(webBtn !== undefined, "open-WebUI button keeps the origin tooltip"); + (webBtn!.props!.onClick as () => void)(); + assert.deepEqual(opened, ["http://127.0.0.1:8787/__bili/"]); + // Polling: exactly one loop, on the slow cadence. + assert.equal(intervals.length, 1, "one poll loop while mounted"); + assert.equal(intervals[0].delay, 10000, "poll cadence is 10s"); + // Refresh re-fetches immediately and replaces the loop (updater-form setState). + (refresh!.props!.onClick as () => void)(); + await tick(); + m.component(); + assert.equal(statusCalls >= 2, true, "refresh triggers an immediate reload"); + assert.equal(intervals.length, 1, "reload swaps the loop, does not stack it"); + m.runCleanups(); + assert.deepEqual(intervals, [], "unmount cancels the poll loop"); + + // Degraded states: each reads as its own notice, never a fabricated card. + const noopIntervals = { + setInterval: (() => 0) as unknown as typeof setInterval, + clearInterval: (() => {}) as unknown as typeof clearInterval, + }; + const subMount = async (body: unknown, snapshot?: unknown): Promise => { + const sm = await mountClient({ + ...(snapshot !== undefined ? { __BILI__: snapshot } : {}), + open: (_url: string) => {}, + fetch: async (url: string) => { + if (String(url).endsWith("/bili/origin")) return { ok: true, json: async () => ({ origin: "http://127.0.0.1:8787" }) }; + return { ok: true, json: async () => body }; + }, + setTimeout, + clearTimeout, + ...noopIntervals, + }, "conversation.view"); + sm.resetHooks(); + sm.component(); + await tick(); + const st = sm.component() as ElementNode; + sm.runCleanups(); + return st; + }; + { + const st = await subMount({ ok: true, phase: "pre-first-request" }, { origin: "http://127.0.0.1:8787" }); + const txt: string[] = []; + collectText(st, txt); + assert.ok(txt.join(" ").includes("等待首个模型请求…"), "pre-first-request phase waits, does not guess"); + assert.equal(findTag(st, "iframe"), undefined, "the tab is native — no iframe in any state"); + } + { + // Older running build: answers the URL (panel string present) but has + // no structured view yet — say so, point at the restart/Web UI. + const st = await subMount({ ok: true, panel: "x" }, { origin: "http://127.0.0.1:8787" }); + const txt: string[] = []; + collectText(st, txt); + assert.ok(txt.join(" ").includes("尚未提供结构化上下文数据"), "stale-build notice names the missing data"); + } + { + const st = await subMount({ ok: true }, { origin: "http://127.0.0.1:8787" }); + const txt: string[] = []; + collectText(st, txt); + assert.ok(txt.join(" ").includes("暂无上下文数据"), "no panel and no view reads as not-yet"); + } + { + const dm = await mountClient({ + open: (_url: string) => {}, + fetch: async () => { throw new Error("no route"); }, + setTimeout, + clearTimeout, + ...noopIntervals, + }, "conversation.view"); + dm.resetHooks(); + const dtree = dm.component() as ElementNode; + const dt: string[] = []; + collectText(dtree, dt); + assert.ok(dt.some((x) => x.includes("/acp")), "degraded hint points at /acp"); + assert.equal(collectButtons(dtree).length, 0, "no actions before the origin resolves"); + dm.runCleanups(); + } +}); diff --git a/tests/issue3862-context-view.test.ts b/tests/issue3862-context-view.test.ts new file mode 100644 index 0000000000..ed3f406e47 --- /dev/null +++ b/tests/issue3862-context-view.test.ts @@ -0,0 +1,315 @@ +import assert from "node:assert"; +import http from "node:http"; +import { once } from "node:events"; +import test from "node:test"; + +process.env.NODE_ENV = "test"; + +import type { NudgeDecision } from "acp-kernel"; +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 { _setForTest as setRegistryForTest } from "../src/registry.ts"; +import { _resetPluginStateForTest } from "../src/plugin.ts"; +import { buildContextView } from "../src/context-view.ts"; +import type { Session } from "../src/session.ts"; + +// #3862: the /__bili/plugin/status `contextView` field — the machine-readable +// twin of the panel breakdown that the dsh client Context tab renders. Two +// layers: unit math on buildContextView (categories sum exactly to sentTotal, +// anchor ladder, fold/switch trails from a seeded ledger) and an integration +// pass through the real server (field presence, additive regression, CORS +// echo for cross-origin browser readers). + +const AGG_KEYS = [ + "requests", "input", "cached", "output", "nc", "cr", "tr", + "switches", "switchMissed", "keySwitches", "keySwitchMissed", + "promptSwitches", "promptSwitchMissed", "projSwitches", "projSwitchMissed", + "wireSwitches", "wireSwitchMissed", "upstreamSwitches", "upstreamSwitchMissed", + "restartDrops", "restartDropMissed", "attributedMissed", + "unknownSamples", "unknownInput", "nbSamples", "nbInput", + "seamSuspects", "seamMissed", + "providerSideMisses", "providerSideMissed", "providerTtlMisses", "providerTtlMissed", + "rewinds", "rewindMissed", "abortCorrelated", "clientInserts", "clientInsertMissed", +] as const; + +function zeroAgg(overrides: Record = {}): Record { + const agg: Record = {}; + for (const k of AGG_KEYS) agg[k] = 0; + return { ...agg, ...overrides }; +} + +function nudgeWith(bd: { system: number; tool: number; summaries: number; code: number; text: number; total: number; growth: number }): NudgeDecision { + return { contextBreakdown: bd } as unknown as NudgeDecision; +} + +function minimalSession(overrides?: { stats?: Record; metadata?: Record }): Session { + return { + id: "unit-session", + stats: { + contextTokens: 0, + contextTokensSource: "estimate", + lastUsageGradeTokens: 0, + lastInputTokensSource: "estimate", + lastInputTokens: 0, + ...(overrides?.stats ?? {}), + }, + metadata: { ...(overrides?.metadata ?? {}) }, + state: { blocks: [] }, + } as unknown as Session; +} + +test("contextView: categories mirror the panel math and sum EXACTLY to sentTotal", () => { + // system+tools measured by the host at prepare time (sysprompt row); the + // kernel breakdown classifies messages only. + const view = buildContextView({ + nudge: nudgeWith({ system: 100, tool: 2000, summaries: 300, code: 400, text: 500, total: 3300, growth: 1234 }), + systemPromptTokens: 1200, + limit: 100_000, + session: minimalSession(), + }); + assert.ok(view !== null, "view built"); + assert.equal(view.scale, "estimate"); + assert.equal(view.limit, 100_000); + assert.equal(view.growth, 1234); + assert.equal(view.sentTotal, 4500, "sentTotal = classified(3300) + sysprompt(1200)"); + const byKey = Object.fromEntries(view.categories.map((c) => [c.key, c])); + assert.deepEqual(Object.keys(byKey), ["sysprompt", "tool", "text", "code", "summaries", "system"], "fixed category order, all present"); + assert.equal(byKey.sysprompt!.tokens, 1200); + assert.equal(byKey.tool!.tokens, 2000); + assert.equal(byKey.text!.tokens, 500); + assert.equal(byKey.code!.tokens, 400); + assert.equal(byKey.summaries!.tokens, 300); + assert.equal(byKey.system!.tokens, 100); + assert.equal(view.categories.reduce((n, c) => n + c.tokens, 0), view.sentTotal, "segments sum exactly to sentTotal"); + for (const c of view.categories) { + assert.ok(c.pct >= 0 && c.pct <= 100, `pct in range for ${c.key}`); + assert.equal(c.pct, Math.round((c.tokens / view.sentTotal) * 100), `pct rounding for ${c.key}`); + } + assert.deepEqual(view.folds, []); + assert.deepEqual(view.switches, []); + assert.equal(view.anchor, null, "no usage evidence yet ⇒ anchor null"); +}); + +test("contextView: zero categories are omitted and sentTotal can be host-only", () => { + const view = buildContextView({ + nudge: nudgeWith({ system: 0, tool: 0, summaries: 0, code: 0, text: 0, total: 0, growth: 0 }), + systemPromptTokens: 900, + limit: 0, + session: minimalSession(), + }); + assert.ok(view !== null); + assert.equal(view.sentTotal, 900); + assert.deepEqual(view.categories.map((c) => [c.key, c.tokens]), [["sysprompt", 900]]); + assert.equal(view.categories[0]!.pct, 100); + assert.equal(view.limit, null, "non-positive limit publishes null"); +}); + +test("contextView: null before any breakdown exists", () => { + assert.equal(buildContextView({ nudge: undefined, systemPromptTokens: 0, limit: 1, session: minimalSession() }), null); +}); + +test("contextView: anchor follows the displayContextBest ladder (usage > anchored estimate > upper)", () => { + const base = { + nudge: nudgeWith({ system: 0, tool: 10, summaries: 0, code: 0, text: 0, total: 10, growth: 0 }), + systemPromptTokens: 0, + limit: 100_000, + }; + const usage = buildContextView({ ...base, session: minimalSession({ stats: { contextTokensSource: "usage", contextTokens: 7777 }, metadata: { contextTokensAt: 111 } }) }); + assert.deepEqual(usage?.anchor, { tokens: 7777, kind: "usage", at: 111 }); + const estimate = buildContextView({ ...base, session: minimalSession({ stats: { contextTokensSource: "estimate", lastUsageGradeTokens: 5000, contextEstimateTokens: 6000 } }) }); + assert.deepEqual(estimate?.anchor, { tokens: 6000, kind: "estimate", at: null }); + const upper = buildContextView({ ...base, session: minimalSession({ stats: { contextTokens: 9999, contextTokensSource: "estimate" } }) }); + assert.deepEqual(upper?.anchor, { tokens: 9999, kind: "upper", at: null }); +}); + +test("contextView: fold and switch trails map the cache ledger (reclaimed/savedSoFar/paidBack math)", () => { + const T0 = 1_700_000_000_000; + const ledger = { + v: 1, + lastBlockId: 0, + consumedFoldSeq: 0, + sampleSeq: 2, + foldSeqCounter: 1, + folds: [{ seq: 1, at: T0, S: 5000, sigma: 200, T: 0, hPct: null, requestsAfter: 3, k: null }], + lines: [ + { seq: 1, at: T0 - 1000, input: 1000, cached: 900, output: 50, hitPct: 90, missed: 100, nc: 0, cr: 0, tr: 0, foldSeq: null, model: "model-a" }, + { seq: 2, at: T0 - 500, input: 1000, cached: 0, output: 50, hitPct: 0, missed: 1000, nc: 0, cr: 0, tr: 1234, foldSeq: null, model: "model-b", sw: 1, cause: "model" }, + ], + agg: zeroAgg({ switches: 1, switchMissed: 1234 }), + }; + const view = buildContextView({ + nudge: nudgeWith({ system: 0, tool: 10, summaries: 0, code: 0, text: 0, total: 10, growth: 0 }), + systemPromptTokens: 0, + limit: 100_000, + session: minimalSession({ metadata: { cacheLedger: ledger } }), + }); + assert.ok(view !== null); + assert.deepEqual(view.folds, [{ seq: 1, at: T0, s: 5000, sigma: 200, reclaimed: 4800, savedSoFar: 14400, paidBack: true }], + "reclaimed=S−σ; savedSoFar=(S−σ)×requestsAfter; default price w1/r0.1/q4 ⇒ breakeven 0.625 ≤ 3 requests"); + assert.deepEqual(view.switches, [{ dim: "model", at: T0 - 500, from: "model-a", to: "model-b", attributed: 1234 }]); +}); + +interface Rig { + proxyUrl: (path: string) => string; + messagesUrl: () => string; + closeAll(): Promise; +} + +function anthropicStream(): string { + const sse = (event: string, data: unknown): string => `event: ${event}\ndata: ${JSON.stringify(data)}\n\n`; + return ( + sse("message_start", { type: "message_start", message: { id: "m1", role: "assistant", usage: { input_tokens: 42 } } }) + + sse("content_block_start", { type: "content_block_start", index: 0, content_block: { type: "text", text: "" } }) + + sse("content_block_delta", { type: "content_block_delta", index: 0, delta: { type: "text_delta", text: "ok" } }) + + sse("content_block_stop", { type: "content_block_stop", index: 0 }) + + sse("message_delta", { type: "message_delta", delta: { stop_reason: "end_turn" }, usage: { output_tokens: 2 } }) + + sse("message_stop", { type: "message_stop" }) + ); +} + +async function startRig(): Promise { + const upstream = http.createServer((_req, res) => { + _req.resume(); + res.writeHead(200, { "content-type": "text/event-stream" }); + res.end(anthropicStream()); + }); + upstream.listen(0, "127.0.0.1"); + await once(upstream, "listening"); + const upstreamPort = (upstream.address() as { port: number }).port; + + _setStoreForTest(new SessionStore({ enabled: false })); + setRegistryForTest({}); + _resetPluginStateForTest(); + + const opts: ProxyOptions = { + port: 0, + host: "127.0.0.1", + upstream: "http://127.0.0.1", + routes: { [`http://127.0.0.1:${upstreamPort}`]: { models: { "claude-test": { context: 100_000 } } } }, + modelContextLimit: 100_000, + kernelConfig: defaultConfig(100_000), + compress: { injectTool: true, injectNudge: true }, + promptCache: { routing: "auto" }, + log: false, + sessionHeader: "x-acp-session", + debug: false, + passthrough: false, + autoUpdate: false, + mitm: { enabled: false, domains: [] }, + compat: { roles: {} }, streamErrorShape: "protocol", passthroughSource: null, autoRestartOnUpdate: false, updateTag: "latest", advisoryCheck: false, releaseNotesCheck: false, + }; + const proxy = await startServer(opts); + await once(proxy, "listening"); + const proxyPort = (proxy.address() as { port: number }).port; + const closeOne = (s: http.Server): Promise => new Promise((resolve, reject) => s.close((e) => (e ? reject(e) : resolve()))); + return { + proxyUrl: (path) => `http://127.0.0.1:${proxyPort}${path}`, + messagesUrl: () => `http://127.0.0.1:${proxyPort}/bili/http://127.0.0.1:${upstreamPort}/v1/messages`, + closeAll: async () => { + // undici keep-alive sockets outlive server.close() and would keep + // the test process alive; drain them first (admin-origin pattern). + proxy.closeAllConnections?.(); + upstream.closeAllConnections?.(); + await closeOne(proxy); + await closeOne(upstream); + }, + }; +} + +async function postTurn(rig: Rig, conversationId: string, text: string): Promise { + const res = await fetch(rig.messagesUrl(), { + method: "POST", + headers: { + "content-type": "application/json", + "x-api-key": "test", + "x-bili-plugin": "dsh", + "x-bili-plugin-conversation": conversationId, + }, + body: JSON.stringify({ model: "claude-test", max_tokens: 1024, messages: [{ role: "user", content: text }] }), + }); + assert.equal(res.status, 200, "plugin turn served"); + await res.body?.cancel().catch(() => {}); +} + +test("integration: plugin/status serves contextView after turns, additively, with CORS echo for trusted origins", async () => { + const rig = await startRig(); + try { + const reg = await fetch(rig.proxyUrl("/__bili/plugin/register"), { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ conversationId: "cv-test", agent: "dsh", identity: true }), + }); + assert.equal(reg.status, 200, "register accepted"); + await postTurn(rig, "cv-test", "first turn"); + await postTurn(rig, "cv-test", "second turn"); + + const res = await fetch(rig.proxyUrl("/__bili/plugin/status?conversationId=cv-test")); + assert.equal(res.status, 200); + const body = (await res.json()) as Record; + assert.equal(body.ok, true); + + // Additive regression: every pre-existing field still present. + assert.equal(typeof body.sessionId, "string"); + assert.equal(body.contextLimit, 100_000); + assert.equal(typeof body.contextTokens, "number"); + assert.equal(typeof body.contextTokensSource, "string"); + assert.equal(typeof body.panel, "string"); + assert.ok(Array.isArray(body.blocks)); + assert.ok(Array.isArray(body.compressibleRanges)); + + const cv = body.contextView; + assert.ok(cv !== null && typeof cv === "object", "contextView published after first request"); + assert.equal(cv.scale, "estimate"); + assert.equal(cv.limit, 100_000); + assert.equal(typeof cv.at, "number"); + assert.ok(cv.sentTotal > 0, "sentTotal positive"); + assert.ok(Array.isArray(cv.categories) && cv.categories.length > 0); + assert.equal(cv.categories.reduce((n: number, c: any) => n + c.tokens, 0), cv.sentTotal, "segments sum exactly to sentTotal"); + for (const c of cv.categories) { + assert.equal(typeof c.key, "string"); + assert.ok(Number.isFinite(c.tokens) && c.tokens > 0); + assert.ok(c.pct >= 0 && c.pct <= 100); + } + assert.ok(Number.isFinite(cv.growth), "growth is signed (tokenCount − reference); no sign assumption"); + assert.ok(Array.isArray(cv.folds)); + assert.ok(Array.isArray(cv.switches)); + if (cv.anchor !== null) { + assert.ok(["usage", "estimate", "upper"].includes(cv.anchor.kind), "anchor kind on its own scale label"); + assert.ok(cv.anchor.tokens > 0); + } + + // CORS: a cross-origin browser reader (the dsh client tab) must be + // able to READ this response — the gate-trusted loopback origin is + // echoed back. + // Close only AFTER listening resolved: calling close() on a still- + // pending listen suppresses the 'listening' event forever. + const foreignPort = await new Promise((resolve, reject) => { + const s = http.createServer(() => {}); + s.once("error", reject); + s.listen(0, "127.0.0.1", () => { + const port = (s.address() as { port: number }).port; + s.close(() => resolve(port)); + }); + }); + const corsRes = await fetch(rig.proxyUrl("/__bili/plugin/status?conversationId=cv-test"), { + headers: { origin: `http://127.0.0.1:${foreignPort}` }, + }); + assert.equal(corsRes.status, 200, "trusted loopback origin admitted"); + assert.equal(corsRes.headers.get("access-control-allow-origin"), `http://127.0.0.1:${foreignPort}`, "origin echoed for the browser read"); + await corsRes.body?.cancel().catch(() => {}); + + // Untrusted origin stays denied by the existing gate — the echo never + // widens access. + const denied = await fetch(rig.proxyUrl("/__bili/plugin/status?conversationId=cv-test"), { + headers: { origin: "http://example.com" }, + }); + assert.equal(denied.status, 403, "untrusted origin rejected"); + const deniedBody = (await denied.json()) as { error?: string }; + assert.ok(deniedBody.error !== undefined); + await denied.body?.cancel().catch(() => {}); + } finally { + await rig.closeAll(); + } +}); From a90d59a7778b6b8170e171ace668dceeab3942ed Mon Sep 17 00:00:00 2001 From: awork Date: Tue, 20 Oct 2026 08:29:44 +0800 Subject: [PATCH 2/6] fix: module-private the contextView type surface per unused-exports gate The five ContextView* shapes and ModelSwitchStats are consumed structurally (buildContextView's return value / cache-ledger internals); nothing outside their own files names them, so the #1440 P6 gate flags them as INTERNAL_ONLY. Drop the leading export keyword only - no behavior change. The remaining local gate hit (src/log-mask.ts maskUrlForPublish) is pre-existing master drift tracked by #3870 with fixes in flight (#3871/#3887); deliberately not bundled here. --- src/cache-ledger.ts | 2 +- src/context-view.ts | 10 +++++----- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/src/cache-ledger.ts b/src/cache-ledger.ts index a087ab4505..4162bfb3ca 100644 --- a/src/cache-ledger.ts +++ b/src/cache-ledger.ts @@ -1647,7 +1647,7 @@ export interface ModelSwitchEvent { attributed: number; } -export interface ModelSwitchStats { +interface ModelSwitchStats { count: number; missedTokens: number; events: ModelSwitchEvent[]; diff --git a/src/context-view.ts b/src/context-view.ts index 121d983880..329935ba37 100644 --- a/src/context-view.ts +++ b/src/context-view.ts @@ -18,7 +18,7 @@ import { displayContextBest, type Session } from "./session.js"; /** Max events per trail published in the view (newest first). */ const EVENT_CAP = 20; -export interface ContextViewCategory { +interface ContextViewCategory { /** sysprompt | tool | text | code | summaries | system */ key: string; tokens: number; @@ -26,7 +26,7 @@ export interface ContextViewCategory { pct: number; } -export interface ContextViewFold { +interface ContextViewFold { seq: number; at: number; /** S: original tokens folded out of the sent view. */ @@ -40,7 +40,7 @@ export interface ContextViewFold { paidBack: boolean | null; } -export interface ContextViewSwitch { +interface ContextViewSwitch { dim: "model" | "key" | "prompt" | "restart"; at: number; from: string | null; @@ -49,13 +49,13 @@ export interface ContextViewSwitch { attributed: number; } -export interface ContextViewAnchor { +interface ContextViewAnchor { tokens: number; kind: "usage" | "estimate" | "upper"; at: number | null; } -export interface ContextView { +interface ContextView { /** Every token figure in this object is on ONE scale: the kernel * countTokens estimate of the current sent view. The anchor is the * exception — its own usage-grade scale, labeled via kind. */ From f2614440403a77986b74b56f9b47085f8796d9f6 Mon Sep 17 00:00:00 2001 From: awork Date: Tue, 20 Oct 2026 08:41:10 +0800 Subject: [PATCH 3/6] fix: read chain-advisory status as not-yet, not as stale build (#3862) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The #1357 chain-advisory response carries a panel string exactly like the stale-running-build case, so the Context tab's degraded ladder misdiagnosed it as 'the running proxy predates this install — restart fixes it' when the real state is simply 'no session exists yet for this conversation'. The phase check routes it to the neutral not-yet notice; adds the negative test row pinning both directions. --- src/agent/dsh-native-client.ts | 5 ++++- tests/dsh-settings-ui.test.ts | 9 +++++++++ 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/src/agent/dsh-native-client.ts b/src/agent/dsh-native-client.ts index 77393d41e3..d8589fdea1 100644 --- a/src/agent/dsh-native-client.ts +++ b/src/agent/dsh-native-client.ts @@ -723,7 +723,10 @@ export function apply(ctx: ClientContext): void { } else if (status?.ok === true && status.phase === "pre-first-request") { middle = hintP("ctx_waiting"); } else if (status?.ok === true && status.contextView === null) { - middle = hintP(status.panelPresent ? "ctx_stale" : "ctx_nodata"); + // chain-advisory (#1357) also answers with a panel string but is NOT + // a stale running build — read it as not-yet, never as "restart fixes + // it". + middle = hintP(status.panelPresent && status.phase !== "chain-advisory" ? "ctx_stale" : "ctx_nodata"); } else if (status === undefined) { middle = hintP(fetchFailed ? "degraded" : "connecting"); } else if (!status.ok) { diff --git a/tests/dsh-settings-ui.test.ts b/tests/dsh-settings-ui.test.ts index c7f91a5e2a..5d054315ef 100644 --- a/tests/dsh-settings-ui.test.ts +++ b/tests/dsh-settings-ui.test.ts @@ -1626,6 +1626,15 @@ test("#3862: conversation.view Context tab renders the live contextView card, po collectText(st, txt); assert.ok(txt.join(" ").includes("尚未提供结构化上下文数据"), "stale-build notice names the missing data"); } + { + // #1357 chain-advisory also carries a panel string but is NOT a stale + // running build — it must read as not-yet, never as the restart notice. + const st = await subMount({ ok: true, phase: "chain-advisory", panel: "x" }, { origin: "http://127.0.0.1:8787" }); + const txt: string[] = []; + collectText(st, txt); + assert.ok(txt.join(" ").includes("暂无上下文数据"), "chain-advisory reads as not-yet"); + assert.ok(!txt.join(" ").includes("尚未提供结构化上下文数据"), "chain-advisory never claims a stale build"); + } { const st = await subMount({ ok: true }, { origin: "http://127.0.0.1:8787" }); const txt: string[] = []; From a3024200d238768bf3fcb5a1294cc6b171050e82 Mon Sep 17 00:00:00 2001 From: awork Date: Tue, 20 Oct 2026 08:41:27 +0800 Subject: [PATCH 4/6] chore: drop incidental whitespace churn from the #3862 diff MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Stray leading space before the closing brace of an unrelated test (#3100 embed pre-flight, tests/dsh-settings-ui.test.ts) and in CLIENTS.md (trailing-space blank line plus a leading space before the Kimi Code heading) — none of it related to the feature; keeps every diff line on-purpose. --- CLIENTS.md | 4 ++-- tests/dsh-settings-ui.test.ts | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/CLIENTS.md b/CLIENTS.md index c12ee82473..e3a9e15a3a 100644 --- a/CLIENTS.md +++ b/CLIENTS.md @@ -165,8 +165,8 @@ tokens. It refreshes every 10 s; when the running proxy predates this build the tab degrades to a restart notice plus an open-Web-UI button instead of guessing. Plain React from dsh's own runtime — no iframe, no added dependencies. - - ## Kimi Code (Moonshot) + +## Kimi Code (Moonshot) Three aligned modes: `bili kimi` (launcher, cert-MITM — README Quickstart Option 2), `/bili/` diff --git a/tests/dsh-settings-ui.test.ts b/tests/dsh-settings-ui.test.ts index 5d054315ef..aa7eecc20f 100644 --- a/tests/dsh-settings-ui.test.ts +++ b/tests/dsh-settings-ui.test.ts @@ -1277,7 +1277,7 @@ test("#3100: embed pre-flight — a stale proxy build gets the restart notice in assert.equal(embedCalls, 3, "#3100: a cached verdict is never re-fetched"); m.runCleanups(); } - }); +}); test("#3816: remote page + loopback origin (relay off) shows the adminRelay guidance instead of spinning; gate negatives stay unchanged", async () => { // Positive: the page is reached through a non-loopback host while the From 99528d3b27c13e99918fd1288c485c047220c792 Mon Sep 17 00:00:00 2001 From: awork Date: Tue, 20 Oct 2026 08:52:11 +0800 Subject: [PATCH 5/6] fix(ci): module-private maskUrlForPublish per unused-exports gate #3811 exported it, but its only reference is maskUrlsForPublish in the same file (INTERNAL_ONLY), which has kept the master unused-exports lane red. Drop the export keyword instead of deleting: the function is live internal code. --- src/log-mask.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/log-mask.ts b/src/log-mask.ts index ac2440b279..d34a619b1b 100644 --- a/src/log-mask.ts +++ b/src/log-mask.ts @@ -118,7 +118,7 @@ export function maskUrlsInText(text: string): string { * preference must not weaken the publish boundary (same stance as * redactSecretsInText, which is never gated by the switch). Userinfo, query * and hash are dropped exactly as in maskUrlForLog; the path is kept. */ -export function maskUrlForPublish(url: string): string { +function maskUrlForPublish(url: string): string { let u: URL; try { u = new URL(url); From 9770dfcb3212aa1563b712b0c1d884d7ce5ffbc5 Mon Sep 17 00:00:00 2001 From: awork Date: Tue, 20 Oct 2026 08:52:11 +0800 Subject: [PATCH 6/6] =?UTF-8?q?fix(docs):=20regenerate=20config=20docs=20?= =?UTF-8?q?=E2=80=94=20drop=20stale=20duplicate=20storage=20rows?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Committed CONFIGURATION.md/CONFIGURATION.zh-CN.md carried both the pre-#3818 'unset (shadow)' storage.unified row and the pre-#3788 sqliteAutoDownload row alongside their replacements, so docs-sync's git-diff-after-generate could never be clean. Regenerated from the current seeds; the diff removes exactly those four stale rows. --- CONFIGURATION.md | 2 -- CONFIGURATION.zh-CN.md | 2 -- 2 files changed, 4 deletions(-) diff --git a/CONFIGURATION.md b/CONFIGURATION.md index 09e953c4c5..d59b7e9cc6 100644 --- a/CONFIGURATION.md +++ b/CONFIGURATION.md @@ -174,8 +174,6 @@ This index is generated from `website/config-reference/*.yaml` — edit the seed | `persist.epermAlertRepeatMs` | number | 0 (no repeats) | BILI_PERSIST_EPERM_ALERT_REPEAT_MS | Repeat interval for the EPERM alert; 0 logs it once. | | `storage` | object | {} (all defaults) | — | Unified SQLite storage sidecar settings (#2671). | | `storage.unified` | legacy\|shadow\|full | unset (full) | BILI_STORAGE_UNIFIED | Tiered storage-migration switch (#2671): shadow = unified SQLite double-write dry-run with digest reconciliation; full = drop-in read path (unified-first loads with organic import, legacy fallback). Absent everywhere now defaults to FULL (#3818 flip - the shadow dry-run reconciled cleanly since #2815, so the index is the load path; JSON envelopes keep being written, and legacy remains the one-line escape hatch). File tier is strict legacy/shadow/full; the env tier also accepts 1/true (=shadow) and unified (=full) and wins over the file. Resolved once per lane boot - hot edits need a restart. Encryption (BILI_ENCRYPTION_KEY) hard-blocks the sidecar. | -| `storage.sqliteAutoDownload` | boolean | true | BILI_SQLITE_AUTO_DOWNLOAD | Gate for the one-time SQLite engine self-download (#2833): when no engine is available in-process (no built-in node:sqlite, no host-installed better-sqlite3) and the unified sidecar is wanted on this platform, bili downloads the pinned better-sqlite3 prebuilt tarball from the npm registry once (~11 MB, sha512-verified) into the cache dir and reuses it on every later start. Engine resolution order: built-in node:sqlite (Node >= 22.5) -> host-provided better-sqlite3 -> cached self-download -> self-download (gated by this switch) -> none (legacy-only, the #2825 degrade contract). The switch gates only the network fetch - a cached copy is used even when it is false; unsupported platforms never download. The tarball download walks a builtin mirror list (#3338): the configured registry (BILI_UPDATE_REGISTRY / update.registry) is tried first, then https://registry.npmjs.org, then https://registry.npmmirror.com - the first mirror that yields a sha512-verified tarball wins; a Node < 22.5 with no engine gets an explicit Node upgrade hint in the degrade reason (#3385). | -| `storage.unified` | legacy\|shadow\|full | unset (shadow) | BILI_STORAGE_UNIFIED | Tiered storage-migration switch (#2671): shadow = unified SQLite double-write dry-run with digest reconciliation; full = drop-in read path (unified-first loads with organic import, legacy fallback). Absent everywhere now defaults to shadow (JSON stays the sole source of truth; the index is digest-reconciled telemetry - set legacy to opt out). File tier is strict legacy/shadow/full; the env tier also accepts 1/true (=shadow) and unified (=full) and wins over the file. Resolved once per lane boot - hot edits need a restart. Encryption (BILI_ENCRYPTION_KEY) hard-blocks the sidecar. | | `storage.sqliteAutoDownload` | boolean | true | BILI_SQLITE_AUTO_DOWNLOAD | Gate for the one-time SQLite engine self-download (#2833): when no engine is available in-process (no built-in node:sqlite, no host-installed better-sqlite3) and the unified sidecar is wanted on this platform, bili downloads the pinned better-sqlite3 prebuilt tarball from the npm registry once (~11 MB, sha512-verified) into the cache dir and reuses it on every later start. Engine resolution order: built-in node:sqlite (Node >= 22.5) -> host-provided better-sqlite3 -> cached self-download -> self-download (gated by this switch) -> none (legacy-only, the #2825 degrade contract). The switch gates only the network fetch - a cached copy is used even when it is false; unsupported platforms never download. The tarball download walks a builtin mirror list (#3338): the configured registry (BILI_UPDATE_REGISTRY / update.registry) is tried first, then https://registry.npmjs.org, then https://registry.npmmirror.com - the first mirror that yields a sha512-verified tarball wins; a Node < 22.5 with no engine gets an explicit Node upgrade hint in the degrade reason (#3385). A failed download arms a 6-hour retry cooldown persisted as a marker file under the cache dir (billion-context/sqlite/.bootstrap-failed.json); the storage diagnostics blob shows the marker's absolute expiry time and path - delete that file and restart bili to force an immediate retry instead of waiting out the whole window (#3788). | | `storage.jsonWriter` | on\|off | on | BILI_STORAGE_JSON_WRITER | Phase 3 envelope switch (#2960): off stops writing the legacy JSON session envelope while storage.unified is full - the SQLite index becomes the only persistent copy (reads are already unified-first; boot enumerates the index union, so index-only sessions load normally). Only honored in effective-full mode: under shadow/legacy (or with encryption active) the request is ignored with a one-time warning because the JSON file remains the sole source of truth. Env tier 0/false/off = off and 1/true/on = on wins over the strict file spellings. Fail-safe: if the sidecar disables itself mid-run, envelope writes resume on the next save. Rollback: unset the knob - writing resumes, index-only sessions keep loading via the boot union, and replicas/restore re-materialize portable JSON envelopes. Downgrading the binary (or losing the SQLite engine) makes index-only sessions invisible to v0.1.196 and older until a >=v0.1.197 binary runs again - the data stays intact in index.db, it is just not read by the older code. The per-session content-store sidecar keeps being written either way. A jsonWriter=off lane must be the SOLE writer of its sessions directory: an off lane reads unified-first and never falls back to the file, so any peer instance running legacy/shadow against the same directory diverges silently (its JSON copy stops receiving updates, and the off lane never sees the peer's writes). | | `storage.walJournalSizeLimitBytes` | number | 8388608 | BILI_STORAGE_WAL_JOURNAL_SIZE_LIMIT_BYTES | WAL reclamation cap for index.db-wal (#3250), in bytes: every completed checkpoint truncates the WAL file back to this size, bounding disk use and crash-recovery replay in long-lived processes. NOT a per-session data quota - data lands in index.db as it is written and the WAL only stages frames between checkpoints, so session count/size does not scale this; a large burst can overshoot temporarily until the next completed checkpoint truncates back. Higher = rarer truncate IO but more steady disk use and a longer crash-replay tail. Env tier (positive integer) wins over the file tier; a garbage or non-positive env value falls through to the file/default tier instead of failing boot. Applied when the store opens at lane boot - hot edits need a restart. The effective value appears on the unified-enable log line and in the storage diagnostics blob. | diff --git a/CONFIGURATION.zh-CN.md b/CONFIGURATION.zh-CN.md index 758505a848..457bc4cbb3 100644 --- a/CONFIGURATION.zh-CN.md +++ b/CONFIGURATION.zh-CN.md @@ -174,8 +174,6 @@ | `persist.epermAlertRepeatMs` | number | 0 (no repeats) | BILI_PERSIST_EPERM_ALERT_REPEAT_MS | EPERM 告警的重复间隔;0 只记录一次。 | | `storage` | object | {} (all defaults) | — | 统一 SQLite 存储边车设置(#2671)。 | | `storage.unified` | legacy\|shadow\|full | unset (full) | BILI_STORAGE_UNIFIED | 分层存储迁移开关(#2671):shadow = 统一 SQLite 双写干跑 + digest 对账;full = 平替读路径(unified-first 加载 + 有机导入 + legacy 兜底)。两处均未设置时默认 full(#3818 翻转 —— shadow 干跑自 #2815 起对账一直干净,索引因此成为默认加载路径;JSON 信封照写,legacy 仍是一行逃生口)。文件层只接受 legacy/shadow/full;环境变量层还接受 1/true(=shadow)与 unified(=full)并优先于文件。每个 lane 启动时解析一次 —— 热改动需重启生效。加密(BILI_ENCRYPTION_KEY)会硬阻断边车。 | -| `storage.sqliteAutoDownload` | boolean | true | BILI_SQLITE_AUTO_DOWNLOAD | SQLite 引擎一次性自下载的闸门(#2833):进程内没有可用引擎(无内置 node:sqlite、宿主未装 better-sqlite3)且本平台希望启用统一边车时,bili 从 npm registry 一次性下载钉死的 better-sqlite3 预编译 tarball(约 11 MB,sha512 校验)到缓存目录,之后每次启动复用。引擎解析顺序:内置 node:sqlite(Node >= 22.5)-> 宿主机已装的 better-sqlite3 -> 缓存的自下载副本 -> 自下载(本开关控制)-> 无引擎(仅 legacy,即 #2825 降级契约)。开关只控制网络下载 —— 为 false 时缓存副本仍会使用;不支持的平台永不下载。 tarball 下载内置镜像列表兜底(#3338):先试配置的 registry(BILI_UPDATE_REGISTRY / update.registry),再试 https://registry.npmjs.org、https://registry.npmmirror.com —— 第一个通过 sha512 校验的镜像生效;Node < 22.5 且无引擎时,降级原因会给出明确的 Node 升级提示(#3385)。 | -| `storage.unified` | legacy\|shadow\|full | unset (shadow) | BILI_STORAGE_UNIFIED | 分层存储迁移开关(#2671):shadow = 统一 SQLite 双写干跑 + digest 对账;full = 平替读路径(unified-first 加载 + 有机导入 + legacy 兜底)。两处均未设置时默认 shadow(JSON 仍是唯一事实源,索引只做对账遥测 —— 设 legacy 可退出)。文件层只接受 legacy/shadow/full;环境变量层还接受 1/true(=shadow)与 unified(=full)并优先于文件。每个 lane 启动时解析一次 —— 热改动需重启生效。加密(BILI_ENCRYPTION_KEY)会硬阻断边车。 | | `storage.sqliteAutoDownload` | boolean | true | BILI_SQLITE_AUTO_DOWNLOAD | SQLite 引擎一次性自下载的闸门(#2833):进程内没有可用引擎(无内置 node:sqlite、宿主未装 better-sqlite3)且本平台希望启用统一边车时,bili 从 npm registry 一次性下载钉死的 better-sqlite3 预编译 tarball(约 11 MB,sha512 校验)到缓存目录,之后每次启动复用。引擎解析顺序:内置 node:sqlite(Node >= 22.5)-> 宿主机已装的 better-sqlite3 -> 缓存的自下载副本 -> 自下载(本开关控制)-> 无引擎(仅 legacy,即 #2825 降级契约)。开关只控制网络下载 —— 为 false 时缓存副本仍会使用;不支持的平台永不下载。 tarball 下载内置镜像列表兜底(#3338):先试配置的 registry(BILI_UPDATE_REGISTRY / update.registry),再试 https://registry.npmjs.org、https://registry.npmmirror.com —— 第一个通过 sha512 校验的镜像生效;Node < 22.5 且无引擎时,降级原因会给出明确的 Node 升级提示(#3385)。下载失败会置一个 6 小时的重试冷却,以标记文件形式持久化在缓存目录下(billion-context/sqlite/.bootstrap-failed.json);storage 诊断块会显示该标记的绝对到期时间与路径 —— 删除该文件并重启 bili 即可强制立即重试,不必等完整个冷却窗口(#3788)。 | | `storage.jsonWriter` | on\|off | on | BILI_STORAGE_JSON_WRITER | Phase 3 信封开关(#2960):off 时若 storage.unified 为 full 则不再写 legacy JSON 会话信封 —— SQLite 索引成为唯一持久化副本(读路径本就 unified-first;boot 枚举索引并集,纯索引会话可正常加载)。仅在有效 full 模式下生效:shadow/legacy(或加密激活)下请求会被忽略并警告一次,因为 JSON 文件仍是唯一事实源。环境变量层 0/false/off = off、1/true/on = on,优先于严格拼写的文件层。失败安全:若边车运行中自禁用,下次保存即恢复信封写入。回滚:去掉该开关 —— 写入恢复,纯索引会话经 boot 并集继续可加载,replicas/restore 可重新物化可移植的 JSON 信封。降级二进制(或丢失 SQLite 引擎)会让纯索引会话在 v0.1.196 及更早版本上不可见,直到重新运行 >=v0.1.197 —— 数据在 index.db 中完好无损,只是旧代码不读它。每会话的 content-store 边车无论开关如何都照写。jsonWriter=off 的 lane 必须是其会话目录的唯一写者:off lane 读路径 unified-first、永不回退到文件,因此同一目录上跑 legacy/shadow 的对等实例会静默分叉(它的 JSON 副本收不到更新,off lane 也看不到对等实例的写入)。 | | `storage.walJournalSizeLimitBytes` | number | 8388608 | BILI_STORAGE_WAL_JOURNAL_SIZE_LIMIT_BYTES | index.db-wal 的 WAL 回收上限(#3250),单位字节:每次完成的 checkpoint 把 WAL 文件截回该大小,约束长驻进程的磁盘占用与崩溃恢复重放。不是每会话数据配额 —— 数据写入时就已落进 index.db,WAL 只是两次 checkpoint 之间的帧暂存区,会话数量/大小不会放大它;大 burst 可能暂时超出,直到下一次完成的 checkpoint 截回。调大 = truncate IO 更稀疏,但稳态磁盘占用更多、崩溃恢复重放尾更长。环境变量层(正整数)优先于配置文件层;env 值非法或非正数时静默落到文件/默认层,boot 不崩。lane 启动、store open 时生效 —— 热改动需重启。实际取值会出现在 unified-enable 日志行与 storage 诊断块中。 |