diff --git a/src/agent/dsh-native-client.ts b/src/agent/dsh-native-client.ts index d8589fdea1..f62412cad4 100644 --- a/src/agent/dsh-native-client.ts +++ b/src/agent/dsh-native-client.ts @@ -40,11 +40,14 @@ // 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. +// at the pre-compression caliber, dsh-context#173). Instead of a second +// native re-rendering of the data, the tab EMBEDS the web UI's OWN session +// page (?embed=1 + #/session/) — compression tree and ledger readouts +// stay in one place, the frame. The session id is resolved from the SAME +// status URL the dsh lane uses server-side (/acp command → GET +// /__bili/plugin/status `sessionId`), so tab and command never read two +// different sessions; while no session exists yet the tab shows an honest +// hint instead of an empty frame. import { createElement, useEffect, useState } from "react"; @@ -120,128 +123,63 @@ const ACTION_BTN_STYLE = { // #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. +// the slash command can never read two different sessions; its `sessionId` +// field is what the embedded frame navigates to (#/session/). Polling is +// slow by design: the id only changes when a conversation re-binds or a new +// one lands, so 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 }; +type CtxStatus = { ok: boolean; phase?: string; panelPresent: boolean; sessionId: string | 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); + const o = raw !== null && typeof raw === "object" ? (raw as Record) : null; 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 }; + return { + ok: o.ok, + phase: typeof o.phase === "string" ? o.phase : undefined, + panelPresent: o.panel !== undefined, + sessionId: typeof o.sessionId === "string" && o.sessionId.length > 0 ? o.sessionId : null, + }; +} + +/** #3816: the unreachable-by-construction notice for remote browsers + * (loopback panel) — shared by the settings panel and the Context tab so the + * fix text, relay snippet and jump target cannot drift between placements. + * The jump button targets the panel's config page (#/config) in a fresh tab; + * for a purely remote browser that address is still unreachable — the + * file-edit text is the primary route, the button serves same-LAN/tunneled + * access where it lands on the exact field to set. */ +function renderRemoteBlock(t: (key: string) => string, origin: string): ReturnType { + const cfgUrl = `${origin}/__bili/#/config`; + return createElement( + "div", + { style: { display: "flex", flexDirection: "column", gap: 8, alignItems: "flex-start" } }, + createElement("p", { style: { margin: 0, opacity: 0.7, lineHeight: 1.6 } }, t("remote_blocked")), + createElement( + "code", + { + style: { + display: "block", + padding: "6px 10px", + borderRadius: 8, + border: "1px solid rgba(127,127,127,0.4)", + background: "rgba(127,127,127,0.08)", + fontSize: 13, + lineHeight: 1.6, + }, + }, + REMOTE_RELAY_SNIPPET, + ), + createElement( + "button", + { type: "button", title: cfgUrl, onClick: () => openExternal(cfgUrl), style: ACTION_BTN_STYLE }, + t("remote_open_config"), + ), + ); } /** Shared open-in-browser action — one builder for the settings-panel footer, @@ -392,32 +330,9 @@ const zh: Dict = { "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 = { @@ -435,32 +350,9 @@ const en: Dict = { "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 { @@ -609,15 +501,37 @@ 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. + // #3862: per-session Context tab (conversation.view slot). Embeds the web + // UI's OWN session page (?embed=1 + #/session/) — the same framed face + // the settings panel drives, so the compression tree and ledger readouts + // live in ONE place instead of a second native re-rendering of them. The + // session id comes from the status poll above; while it is unknown (no + // request yet / chain-advisory) the tab shows an honest hint, never a + // stale or empty frame. const contextPanel = (): ((props: Record) => unknown) => () => { const [origin, setOrigin] = useState(readOrigin()); + // #2559: pin the frame palette to the host ground, same discipline as + // the settings panel (sampled synchronously for first paint). + const [theme, setTheme] = useState<("light" | "dark") | undefined>(detectHostTheme); + // #3100: embed pre-flight verdict for the CURRENT origin — a verdict + // recorded for a previous origin (mid-session re-bind) is stale by + // definition until its own probe lands (shared cache with panel()). + const [embed, setEmbed] = useState(() => { + const o = readOrigin(); + const v = o !== undefined ? embedVerdicts.get(o) : undefined; + return o !== undefined && v !== undefined ? { origin: o, verdict: v } : undefined; + }); + const [sessionId, setSessionId] = useState(null); const [status, setStatus] = useState(undefined); const [fetchFailed, setFetchFailed] = useState(false); const [reloadTick, setReloadTick] = useState(0); - useEffect(() => probeOrigin(setOrigin), []); + // #3100: every resolution probes the new origin's embed route in + // flight, and every poll tick re-drives pending origins (snapshot-only + // hosts never resolve through onOrigin again after mount). + useEffect(() => probeOrigin((o) => { setOrigin(o); probeEmbedRoute(o, setEmbed); }, setTheme, (o) => probeEmbedRoute(o, setEmbed)), []); + useEffect(() => { + if (origin !== undefined) probeEmbedRoute(origin, setEmbed); + }, [origin]); useEffect(() => { if (origin === undefined) return; let cancelled = false; @@ -629,9 +543,13 @@ export function apply(ctx: ClientContext): void { const parsed = parseCtxStatus(raw); setStatus(parsed); setFetchFailed(parsed === undefined); + setSessionId(parsed !== undefined && parsed.sessionId !== null ? parsed.sessionId : null); }) .catch(() => { - if (!cancelled) setFetchFailed(true); + if (!cancelled) { + setStatus(undefined); + setFetchFailed(true); + } }); }; load(); @@ -641,98 +559,52 @@ export function apply(ctx: ClientContext): void { clearInterval(timer); }; }, [origin, reloadTick]); + const liveEmbed: EmbedVerdict | undefined = embed !== undefined && embed.origin === origin ? embed.verdict : undefined; + // #3816: remote page + loopback origin ⇒ unreachable by construction — + // ANY resolved verdict outranks the mismatch (a verdict means THIS + // browser actually reached the origin). + const remoteBlocked = remoteMismatch(origin) && liveEmbed === undefined; 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 (remoteBlocked) { + middle = renderRemoteBlock(t, origin); + } else if (liveEmbed === "stale") { + // Frozen proxy predates the ?embed=1 route: framing is impossible + // on any page, including the session one. + middle = hintP("stale"); + } else if (liveEmbed === "ok" && sessionId !== null) { + middle = createElement( + "iframe", + { + src: `${origin}/__bili/?embed=1&lang=${lang}${theme !== undefined ? `&theme=${theme}` : ""}#/session/${encodeURIComponent(sessionId)}`, + title: t("title"), + style: { + display: "block", + width: "100%", + height: EMBED_HEIGHT, + border: "1px solid rgba(127,127,127,0.4)", + borderRadius: 8, + background: "transparent", + }, + }, + ); } else if (status?.ok === true && status.phase === "pre-first-request") { + // No session row exists yet: waiting is truthful, framing impossible. middle = hintP("ctx_waiting"); - } else if (status?.ok === true && status.contextView === null) { - // 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) { middle = hintP("ctx_nodata"); } else { - middle = renderCard(status.contextView!); + // Session resolved but the embed verdict has not landed yet (first + // probe tick) — or a status build that answers without a session id: + // honest connecting / not-yet hints instead of an empty frame. + // chain-advisory lands here with liveEmbed "ok" ⇒ ctx_nodata, and + // must NEVER read as a stale-build claim. + middle = hintP(liveEmbed === "ok" ? "ctx_nodata" : "connecting"); } return createElement( "div", @@ -810,32 +682,7 @@ export function apply(ctx: ClientContext): void { // unreachable — the file-edit text above is the primary route; // the button serves same-LAN/tunneled access where it lands on // the exact field to set. - const cfgUrl = `${origin}/__bili/#/config`; - middle = createElement( - "div", - { style: { display: "flex", flexDirection: "column", gap: 8, alignItems: "flex-start" } }, - createElement("p", { style: { margin: 0, opacity: 0.7, lineHeight: 1.6 } }, t("remote_blocked")), - createElement( - "code", - { - style: { - display: "block", - padding: "6px 10px", - borderRadius: 8, - border: "1px solid rgba(127,127,127,0.4)", - background: "rgba(127,127,127,0.08)", - fontSize: 13, - lineHeight: 1.6, - }, - }, - REMOTE_RELAY_SNIPPET, - ), - createElement( - "button", - { type: "button", title: cfgUrl, onClick: () => openExternal(cfgUrl), style: ACTION_BTN_STYLE }, - t("remote_open_config"), - ), - ); + middle = renderRemoteBlock(t, origin); } else if (liveEmbed === "stale") { middle = createElement("p", { style: { margin: 0, opacity: 0.7, lineHeight: 1.6 } }, t("stale")); } else if (liveEmbed === "ok") { diff --git a/tests/dsh-settings-ui.test.ts b/tests/dsh-settings-ui.test.ts index aa7eecc20f..27e5dcbc89 100644 --- a/tests/dsh-settings-ui.test.ts +++ b/tests/dsh-settings-ui.test.ts @@ -1468,31 +1468,19 @@ test("#3816: remote page + loopback origin (relay off) shows the adminRelay guid } }); -// #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 }], - }, - }; +// #3862: the per-session Context tab (conversation.view slot). The tab does +// NOT re-render the data natively (#3886 v1); it EMBEDS the web UI's own +// session page (?embed=1 + #/session/) so compression tree and ledger +// stay in one place — the frame. Pins: the iframe appears only when the +// embed pre-flight verdict is "ok" AND the status poll resolved a session +// id; every other state shows its own honest notice, never an empty or +// stale frame. +test("#3862: conversation.view Context tab embeds the web UI session page, polls at 10s, and degrades honestly", async () => { + const SESSION_ID = "01a152ba-38b9-7611-950c-53b211f0dea6"; + const ORIGIN = "http://127.0.0.1:8787"; + const statusUrl = "/__bili/plugin/status?conversationId=dsh&fallback=latest"; + const EXPECTED_SRC = `${ORIGIN}/__bili/?embed=1&lang=zh#/session/${SESSION_ID}`; + const cannedStatus = { ok: true, panel: "x", sessionId: SESSION_ID }; const opened: string[] = []; const intervals: Array<{ id: number; delay: number; fn: () => void }> = []; let nextId = 1; @@ -1508,15 +1496,16 @@ test("#3862: conversation.view Context tab renders the live contextView card, po }) as unknown as typeof clearInterval; const m = await mountClient({ - __BILI__: { origin: "http://127.0.0.1:8787" }, + __BILI__: { origin: ORIGIN }, 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")) { + if (u.endsWith("/bili/origin")) return { ok: true, json: async () => ({ origin: ORIGIN }) }; + if (u.endsWith(statusUrl)) { statusCalls += 1; - return { ok: true, json: async () => canned }; + return { ok: true, json: async () => cannedStatus }; } + if (u.endsWith("/__bili/?embed=1")) return htmlOk(); throw new Error(`unexpected fetch: ${u}`); }, setTimeout, @@ -1527,42 +1516,17 @@ test("#3862: conversation.view Context tab renders the live contextView card, po m.resetHooks(); m.component(); + // First paint: no verdict yet and no session id ⇒ never an empty/stale frame. + const first = m.component() as ElementNode; + assert.equal(findTag(first, "iframe"), undefined, "first paint waits for the pre-flight verdict + session id"); 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 frame = findTag(tree, "iframe"); + assert.ok(frame !== undefined && frame !== null, "verdict ok + resolved session id ⇒ the session page is framed"); + assert.ok(frame.props !== null, "frame carries props"); + assert.equal(frame.props.src, EXPECTED_SRC, "frame navigates to #/session/ on the ?embed=1 face"); + assert.equal(frame.props.title, "billion-context 压缩代理", "frame keeps the shared bili frame title"); + // Footer: refresh + the shared open-in-browser action. const buttons = collectButtons(tree); assert.equal(buttons.length, 2, "refresh + open-WebUI only"); const refresh = buttons.find((b) => { @@ -1571,38 +1535,43 @@ test("#3862: conversation.view Context tab renders the live contextView card, po return bt.join("") === "刷新"; }); assert.ok(refresh !== undefined, "refresh button renders"); - const webBtn = buttons.find((b) => b.props?.title === "http://127.0.0.1:8787"); + const webBtn = buttons.find((b) => b.props?.title === ORIGIN); 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.deepEqual(opened, [`${ORIGIN}/__bili/`]); + // Polling: exactly one loop on the slow cadence — counting STATUS reads + // only (the embed pre-flight has its own fetches and is not the poll). 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). + assert.equal(statusCalls, 1, "one status read on mount"); + // Refresh re-fetches immediately and swaps (not stacks) the loop. (refresh!.props!.onClick as () => void)(); await tick(); m.component(); - assert.equal(statusCalls >= 2, true, "refresh triggers an immediate reload"); + assert.equal(statusCalls, 2, "refresh triggers an immediate status 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 = { + // Every non-framed state shows its own honest notice — never an iframe. + const noopTimers = { + setTimeout, + clearTimeout, setInterval: (() => 0) as unknown as typeof setInterval, clearInterval: (() => {}) as unknown as typeof clearInterval, }; - const subMount = async (body: unknown, snapshot?: unknown): Promise => { + const subMount = async (body: unknown, embedRouteResult: unknown = htmlOk()): Promise => { const sm = await mountClient({ - ...(snapshot !== undefined ? { __BILI__: snapshot } : {}), + __BILI__: { origin: ORIGIN }, 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 }; + const u = String(url); + if (u.endsWith("/bili/origin")) return { ok: true, json: async () => ({ origin: ORIGIN }) }; + if (u.endsWith(statusUrl)) return { ok: true, json: async () => body }; + if (u.endsWith("/__bili/?embed=1")) return embedRouteResult; + throw new Error(`unexpected fetch: ${u}`); }, - setTimeout, - clearTimeout, - ...noopIntervals, + ...noopTimers, }, "conversation.view"); sm.resetHooks(); sm.component(); @@ -1611,49 +1580,51 @@ test("#3862: conversation.view Context tab renders the live contextView card, po sm.runCleanups(); return st; }; + const textOf = (node: ElementNode): string => { + const out: string[] = []; + collectText(node, out); + return out.join(" "); + }; { - 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"); + // Session row not created yet: waiting is truthful, framing impossible. + const st = await subMount({ ok: true, phase: "pre-first-request", sessionId: null }); + assert.ok(textOf(st).includes("等待首个模型请求…"), "pre-first-request waits, does not guess"); + assert.equal(findTag(st, "iframe"), undefined); } { - // 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"); + // #1357 chain-advisory carries a panel string but NO session id: reads + // as not-yet data — and can NEVER read as the frozen-build claim. + const st = await subMount({ ok: true, phase: "chain-advisory", panel: "x" }); + const txt = textOf(st); + assert.ok(txt.includes("暂无上下文数据"), "chain-advisory reads as not-yet"); + assert.ok(!txt.includes("比已安装的配置文件旧"), "chain-advisory never claims a frozen build"); + assert.equal(findTag(st, "iframe"), undefined); } { - // #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"); + // Frozen proxy predates the ?embed=1 route: framing impossible on any page. + const st = await subMount(cannedStatus, { ok: true, headers: { get: (_k: string) => "application/json" } }); + const txt = textOf(st); + assert.ok(txt.includes("比已安装的配置文件旧"), "stale-route notice names the frozen proxy"); + assert.ok(!txt.includes("暂无上下文数据"), "stale-route has its own copy, not the not-yet hint"); + assert.equal(findTag(st, "iframe"), undefined, "never frame a host without the route"); } { - 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"); + // The URL answered but not with our contract shape: degrade honestly. + const st = await subMount({ something: "else" }); + assert.ok(textOf(st).includes("/acp"), "unparseable status degrades to the /acp hint"); + assert.equal(findTag(st, "iframe"), undefined); } { + // No bili bound at all (/bili/origin unreachable too). const dm = await mountClient({ open: (_url: string) => {}, fetch: async () => { throw new Error("no route"); }, - setTimeout, - clearTimeout, - ...noopIntervals, + ...noopTimers, }, "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"); + const dt = textOf(dtree); + assert.ok(dt.includes("/acp"), "degraded hint points at /acp"); assert.equal(collectButtons(dtree).length, 0, "no actions before the origin resolves"); dm.runCleanups(); }