diff --git a/CHANGELOG.md b/CHANGELOG.md index 4ea5e594a8..220781101a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -23,6 +23,10 @@ Versions follow the merge of a `*_release-v*` branch; CI publishes to npm on tag - **fork 克隆保号**:`cloneSessionRows`(store+mysql 双后端)把父会话行整段复制到子(session,seq) 保号 + lineage 列(parentSessionId/forkPointSeq 真值)+content/media CAS refcount 提升 + 幂等重放;子 append 自然从父 maxSeq+1(remapPlanToAbsolute)。fork 端点接线,存储不可用降级=kernel-only 克隆(现行为)。 - **验收桩**:kernel 4 测(BLOCKED 偏移重排/交换原子性/无行引用保留+被夺号重安居+死 ref 不动/已对齐幂等)+host 4 测(整段克隆保号+lineage+幂等+子续号/部分分支/superseded 拒绝+当前号通过/冷加载纯视图+服务触达对齐一次+二次幂等)。 +### 面板内置博客与长文(#4587) + +- **`/__bili/blog` JSON feed + `/__bili/blog-assets/*` 图片路由**:随 npm 包内置的 markdown(website/blog/posts/*.md + website/articles.json 清单列出的仓库长文,paper 中英文)由服务端 `web/markdown.ts`(转义优先、XSS-safe)渲染进面板自己的「博客 Blog」页——卡片列表点展正文,双语随面板语言切换,离线可读;`web/markdown.ts` 顺带支持了图片引用(http(s)/面板资产路由以外的一律丢弃)和 GFM 管道表格(复用 .data 表格样式)。图片路由带穿越/编码/扩展名三重门。内容随自更新前进,GitHub Pages(#4561)仍是永远最新的完整文库。零新配置键/env/磁盘缓存。 + ### 修复 master 回归(搭乘) - **#4525 合并把 `sidScope` 改名 `dispatchScope` 漏改一处**:dsh fork-blind-spot 日志(C10b,#4215)仍读旧名 → master tsc 红(`TS2304: Cannot find name 'sidScope'`,dsh-native.ts:1287,CI run 40093629255 failure 同因)。修复=读 `dispatchScope.getStore()` 并按 `{sid,msgIds}` 形状取 `.sid`,语义不变(作用域归因活跃判定)。 diff --git a/README.md b/README.md index 01cef318a1..604bfa942a 100644 --- a/README.md +++ b/README.md @@ -378,7 +378,9 @@ report above. **Can I query sessions and config over the web?** Yes — open [http://localhost:8787](http://localhost:8787): an overview dashboard, session list with per-session detail, live logs, a config editor, and an upstream -connectivity test. Everything is also plain JSON for scripting +connectivity test. A Blog view renders a few bundled notes and long-form +articles inside the panel itself (offline-readable; the full always-fresh +library lives on GitHub Pages). Everything else is also plain JSON for scripting (`/__bili/stats`, `/__bili/sessions`, `/__bili/config`, …). **When does compression happen?** It is model-driven: the injected context diff --git a/README.zh-CN.md b/README.zh-CN.md index 59aa0cf060..353bbdc3ab 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -285,7 +285,7 @@ bili --version **`/acp` 显示什么?** 带原生插件的客户端(opencode、dsh)里,`/acp` 直接从代理取当前会话的 ACP 状态面板(会话、块、可压缩区间、用量);首个模型请求到来前显示空闲提示。`/acp-cache [full]` 打印上面的缓存报告。 -**能用网页查会话和配置吗?** 能 —— 打开 [http://localhost:8787](http://localhost:8787):总览仪表盘、会话列表(含逐会话详情)、实时日志、配置编辑器、上游连通性测试。全部功能同样以纯 JSON 提供(`/__bili/stats`、`/__bili/sessions`、`/__bili/config`、…),方便脚本化。 +**能用网页查会话和配置吗?** 能 —— 打开 [http://localhost:8787](http://localhost:8787):总览仪表盘、会话列表(含逐会话详情)、实时日志、配置编辑器、上游连通性测试。「博客」页还在面板内直接渲染几篇随装内置的发布笔记与长文(离线可看;完整文库在 GitHub Pages)。其余功能同样以纯 JSON 提供(`/__bili/stats`、`/__bili/sessions`、`/__bili/config`、…),方便脚本化。 **压缩什么时候发生?** 由模型驱动:注入的上下文工具由模型在上下文增长时自行调用,温和的增长 nudge(按设计固定约 50K token 步长,可用 `compress.nudgeGrowthTokens` 调整)沿途提醒它,仅输入就超窗时预检作为硬兜底触发(#470)。用 `/acp` 或网页界面实时观察。 diff --git a/package.json b/package.json index 1e6ea3d534..ae5864a507 100644 --- a/package.json +++ b/package.json @@ -103,8 +103,10 @@ "dist", "dsh.bundle.patch.yml", "hermes-plugin", - "paper/model-driven-incremental-hierarchical-compression-training-free-multi-generational-context-management-for-long-lived-coding-agents.md", - "paper/figures/*.png" + "paper/*.md", + "paper/figures/*.png", + "website/articles.json", + "website/blog/posts" ], "pi": { "image": "https://raw.githubusercontent.com/ranxianglei/billion-context/master/docs/logo.png", diff --git a/reference/architecture.md b/reference/architecture.md index 465c26f7ea..bfe16b9e51 100644 --- a/reference/architecture.md +++ b/reference/architecture.md @@ -179,6 +179,8 @@ billion-context/ │ │ └── native.ts # Routing scope/exemptions policy (#1622) │ └── web/ # Web UI (config editor, sessions, logs) │ ├── api.ts # REST handlers (config get/put with parse-state guard) +│ ├── blogfeed.ts # Panel blog/articles feed from bundled markdown (#4587) +│ ├── changelog.ts # GitHub Releases feed for the panel changelog (#3719) │ ├── sessions-data.ts # Read-only session browsing (live pool + on-disk, #1420); tier tree + lazy block content (#3917) │ ├── logs-query.ts # GET /__bili/logs selection engine │ ├── markdown.ts # Escape-safe Markdown → HTML (#1420) diff --git a/src/server/admin.ts b/src/server/admin.ts index 6f57a24bf2..89d251f0e3 100644 --- a/src/server/admin.ts +++ b/src/server/admin.ts @@ -33,6 +33,7 @@ import { getPlannedUpgrade, getUpdatePolicyState } from "../update-policy.js"; import { PACKAGE_NAME, VERSION, BUILD_COMMIT } from "../version.js"; import { buildBlockContent, buildMessageContent, buildOverview, buildSessionDetail, buildSessionList, buildSessionPage, buildSessionTree, handleConfigGet, handleConfigPut, hiddenEmptyCount, renderUI, type BlockContentView } from "../web/index.js"; import { handleChangelogGet } from "../web/changelog.js"; +import { handleBlogAssetGet, handleBlogGet } from "../web/blogfeed.js"; import { buildSessionReportMd, buildSessionReportSvg } from "../web/report.js"; import { queryLogLines } from "../web/logs-query.js"; import { buildDiagnostics } from "../web/diagnostics.js"; @@ -332,6 +333,17 @@ export async function handleAdminRoute(req: http.IncomingMessage, res: http.Serv // read-only admin gating as every other /__bili/ GET above (the gates run // before dispatch). Always answers 200; offline degrades to empty+error. if (req.method === "GET" && req.url === "/__bili/changelog") return handleChangelogGet(res); + // #4587: panel-embedded blog/articles — bundled markdown rendered server-side + // into a JSON feed, plus its images under a guarded asset route. Read-only, + // fail-soft, no config surface; same gating as every other /__bili/ GET above. + if (req.method === "GET" && req.url === "/__bili/blog") { + handleBlogGet(res); + return; + } + if (req.method === "GET" && req.url !== undefined && req.url.startsWith("/__bili/blog-assets/")) { + handleBlogAssetGet(res, req.url); + return; + } // #3719: dedicated 更新/Updates tab — self-update state plus manual // check/install actions. Same gating as every /__bili/ route above (the // gates run before dispatch); an unwired process (autoUpdate off) answers diff --git a/src/web/blogfeed.ts b/src/web/blogfeed.ts new file mode 100644 index 0000000000..6efe1560a7 --- /dev/null +++ b/src/web/blogfeed.ts @@ -0,0 +1,332 @@ +/** + * Panel-embedded blog & articles (#4587): the few long-form markdown pieces we + * ship INSIDE the install (website/blog/posts/*.md + the curated list in + * website/articles.json) are rendered server-side with web/markdown.ts and + * served to the panel as a JSON feed (GET /__bili/blog); their images ride + * GET /__bili/blog-assets/. The panel renders them with its own look — + * no full site is served. Content is frozen per package release and advances + * with self-update; GitHub Pages stays the always-fresh canonical copy. + * + * Fail-soft like web/changelog.ts: missing folders/manifest → empty feed or + * plain 404s, never an exception out of the handler. No config keys, no env + * vars, no disk cache — it reads static bytes from the install itself. + */ +import { existsSync, readFileSync, readdirSync, statSync } from "node:fs"; +import { dirname, join, resolve, sep } from "node:path"; +import { fileURLToPath } from "node:url"; +import type { ServerResponse } from "node:http"; +import { markdownToHtml } from "./markdown.js"; + +const BLOG_ASSET_PREFIX = "/__bili/blog-assets"; + +const ASSET_TYPES: Record = { + ".png": "image/png", + ".jpg": "image/jpeg", + ".jpeg": "image/jpeg", + ".gif": "image/gif", + ".svg": "image/svg+xml", + ".webp": "image/webp", +}; + +let rootOverride: string | undefined; +let probedRoot: string | undefined; +let state: { items: BlogItem[] } | undefined; + +type BlogItem = { + id: string; + kind: "post" | "article"; + /** "" when the source carries no usable date. */ + date: string; + title: string; + titleZh: string; + excerpt: string; + excerptZh: string; + /** Rendered via web/markdown.ts — escaped by construction. */ + html: string; + htmlZh: string; +}; + +function probeRoot(): string | undefined { + // dist/index.js → ../package.json (installed layout) + // src/web/blogfeed.ts → ../../package.json (repository layout) + const here = dirname(fileURLToPath(import.meta.url)); + for (const cand of [join(here, ".."), join(here, "..", ".."), join(here, "..", "..", "..")]) { + try { + if (statSync(join(cand, "package.json")).isFile()) return cand; + } catch { + // keep probing + } + } + return undefined; +} + +function pkgRoot(): string | undefined { + if (rootOverride !== undefined) return rootOverride; + if (probedRoot === undefined) probedRoot = probeRoot(); + return probedRoot; +} + +/** Test seam (same pattern as _resetChangelogForTest): point at a fixture + * package root, or pass null to restore probing. Also clears the feed cache. */ +export function _setBlogRootForTest(root: string | null): void { + rootOverride = root ?? undefined; + probedRoot = undefined; + state = undefined; +} + +/** Mirror of the website tools' frontmatter parser (key: value between --- fences). */ +function parseFrontmatter(text: string): { fm: Record; body: string } { + const fm: Record = {}; + let body = text; + if (text.startsWith("---\n")) { + const end = text.indexOf("\n---\n", 4); + if (end !== -1) { + for (const line of text.slice(4, end).split("\n")) { + const j = line.indexOf(":"); + if (j > 0) fm[line.slice(0, j).trim()] = line.slice(j + 1).trim().replace(/^["']|["']$/g, ""); + } + body = text.slice(end + 5); + } + } + return { fm, body }; +} + +const validDate = (s: string): boolean => /^\d{4}-\d{2}-\d{2}$/.test(s); + +/** Rewrite relative image targets onto the panel asset route when the file + * actually ships inside the package root; drop references that would 404 so + * the rendered article carries no broken images. Absolute http(s) pass through. */ +function rewriteImages(md: string, srcDirAbs: string, root: string): string { + return md.replace(/!\[([^\]]*)\]\(([^)\s]+)\)/g, (_m, _alt: string, target: string) => { + if (/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i.test(target)) return `![${_alt}](${target})`; + let abs: string; + try { + abs = resolve(srcDirAbs, decodeURIComponent(target)); + } catch { + return ""; + } + if (!abs.startsWith(root + sep)) return ""; + const ext = abs.slice(abs.lastIndexOf(".")).toLowerCase(); + if (ASSET_TYPES[ext] === undefined || !statSyncSafe(abs)) return ""; + const rel = abs.slice(root.length + sep.length).split(sep).join("/"); + return `![${_alt}](${BLOG_ASSET_PREFIX}/${rel})`; + }); +} + +function statSyncSafe(p: string): boolean { + try { + return statSync(p).isFile(); + } catch { + return false; + } +} + +/** Strip a leading H1 line; returns [titleTextOrEmpty, rest]. */ +function splitH1(body: string): [string, string] { + const m = body.match(/^#[ \t]+([^ \t\n][^\n]*)\r?\n?/); + if (!m) return ["", body]; + return [m[1].replace(/[*_`]/g, "").trim(), body.slice(m[0].length)]; +} + +function renderBody(absFile: string, root: string): { html: string; h1: string } { + const { body } = parseFrontmatter(readFileSync(absFile, "utf8")); + const [h1, rest] = splitH1(body); + const srcDir = dirname(absFile); + return { html: markdownToHtml(rewriteImages(rest, srcDir, root)), h1 }; +} + +function collectPosts(root: string): BlogItem[] { + const postsDir = join(root, "website", "blog", "posts"); + let names: string[] = []; + try { + names = readdirSync(postsDir).filter((f) => f.endsWith(".md")).sort(); + } catch { + return []; + } + const pairs = new Map(); + for (const f of names) { + const base = f.endsWith(".zh.md") ? f.slice(0, -".zh.md".length) : f.slice(0, -".md".length); + if (!pairs.has(base)) pairs.set(base, {}); + pairs.get(base)![f.endsWith(".zh.md") ? "zh" : "en"] = f; + } + const items: BlogItem[] = []; + for (const [base, pair] of pairs) { + const slug = base.replace(/^\d{4}-\d{2}-\d{2}_/, "") || base; + const renderOne = (kind: "en" | "zh"): { html: string; h1: string; fm: Record } | undefined => { + const name = pair[kind]; + if (!name) return undefined; + let raw: string; + try { + raw = readFileSync(join(postsDir, name), "utf8"); + } catch { + return undefined; + } + const { fm, body } = parseFrontmatter(raw); + const [h1, rest] = splitH1(body); + return { html: markdownToHtml(rewriteImages(rest, postsDir, root)), h1, fm }; + }; + const en = renderOne("en"); + const zh = renderOne("zh"); + if (!en && !zh) continue; + items.push({ + id: slug, + kind: "post", + date: validDate(en?.fm.date || "") ? en!.fm.date : validDate(zh?.fm.date || "") ? zh!.fm.date : (validDate(base.slice(0, 10)) ? base.slice(0, 10) : ""), + title: en?.fm.title || en?.h1 || slug, + titleZh: zh?.fm.title_zh || zh?.fm.title || zh?.h1 || "", + excerpt: en?.fm.excerpt || "", + excerptZh: zh?.fm.excerpt_zh || "", + html: en?.html || "", + htmlZh: zh?.html || "", + }); + } + return items; +} + +function collectArticles(root: string): BlogItem[] { + const manifestPath = join(root, "website", "articles.json"); + if (!statSyncSafe(manifestPath)) return []; + let manifest: unknown; + try { + manifest = JSON.parse(readFileSync(manifestPath, "utf8")); + } catch { + return []; + } + const list = Array.isArray((manifest as { articles?: unknown })?.articles) ? (manifest as { articles: unknown[] }).articles : []; + const items: BlogItem[] = []; + for (const entryRaw of list) { + const entry = entryRaw as { file?: unknown; zh_file?: unknown; slug?: unknown; title?: unknown; title_zh?: unknown; date?: unknown }; + const file = typeof entry.file === "string" ? entry.file : ""; + if (!file || file.includes("\0")) continue; + let abs: string; + try { + abs = resolve(root, decodeURIComponent(file)); + } catch { + continue; + } + if (!abs.startsWith(root + sep) || !statSyncSafe(abs)) continue; + let raw: string; + try { + raw = readFileSync(abs, "utf8"); + } catch { + continue; + } + const { fm, body } = parseFrontmatter(raw); + const [h1, rest] = splitH1(body); + const slugIn = typeof entry.slug === "string" && entry.slug ? entry.slug : file.replace(/\.md$/, "").split("/").pop()!; + let zhHtml = ""; + let zhTitle = ""; + if (typeof entry.zh_file === "string") { + const zhAbs = resolve(root, entry.zh_file); + if (zhAbs.startsWith(root + sep) && statSyncSafe(zhAbs)) { + try { + const zparsed = parseFrontmatter(readFileSync(zhAbs, "utf8")); + const [zhH1, zhRest] = splitH1(zparsed.body); + zhHtml = markdownToHtml(rewriteImages(zhRest, dirname(zhAbs), root)); + zhTitle = (typeof entry.title_zh === "string" && entry.title_zh ? entry.title_zh : "") || zparsed.fm.title_zh || zparsed.fm.title || zhH1 || ""; + } catch { + zhHtml = ""; + } + } + } + const date = (typeof entry.date === "string" ? entry.date : "") || fm.date || ""; + items.push({ + id: `${slugIn}`, + kind: "article", + date: validDate(date) ? date : "", + title: (typeof entry.title === "string" && entry.title ? entry.title : "") || fm.title || h1 || slugIn, + titleZh: zhTitle, + excerpt: fm.excerpt || "", + excerptZh: fm.excerpt_zh || "", + html: markdownToHtml(rewriteImages(rest, dirname(abs), root)), + htmlZh: zhHtml, + }); + } + return items; +} + +function collect(): BlogItem[] { + const root = pkgRoot(); + if (!root) return []; + const items = [...collectPosts(root), ...collectArticles(root)]; + // Dated entries newest-first; undated ones keep a stable id-ordered tail. + items.sort((a, b) => { + if (a.date && b.date) return a.date === b.date ? a.id.localeCompare(b.id) : a.date < b.date ? 1 : -1; + if (a.date !== b.date) return a.date ? -1 : 1; + return a.id.localeCompare(b.id); + }); + return items; +} + +/** Cached feed (content only changes across package updates → one compute per + * process). Never throws: any surprise degrades to an empty list. */ +export function getBlogFeed(): { items: BlogItem[]; error?: string } { + if (state === undefined) { + try { + state = { items: collect() }; + } catch { + state = { items: [] }; + } + } + return state; +} + +/** GET /__bili/blog — always 200 JSON; the panel degrades on an empty list. */ +export function handleBlogGet(res: ServerResponse): void { + const data = getBlogFeed(); + res.writeHead(200, { "content-type": "application/json; charset=utf-8", "cache-control": "no-cache" }); + res.end(JSON.stringify(data)); +} + +/** One decoded-and-validated path segment list, or undefined for every + * rejection class: bad percent-encoding, empty/"."/".."/NUL segments. */ +function safeSegments(urlPath: string): string[] | undefined { + const raw = urlPath.slice(BLOG_ASSET_PREFIX.length + 1); + const parts = raw === "" ? [] : raw.split("/"); + const out: string[] = []; + for (const segRaw of parts) { + if (segRaw === "") continue; + let seg: string; + try { + seg = decodeURIComponent(segRaw); + } catch { + return undefined; + } + if (seg === "" || seg === "." || seg === ".." || seg.includes("\0")) return undefined; + out.push(seg); + } + return out; +} + +/** GET /__bili/blog-assets/ — bundled image bytes only (extension gate + + * traversal gate); anything else is a plain-text 404. */ +export function handleBlogAssetGet(res: ServerResponse, urlPath: string): void { + const notFound = () => { + res.writeHead(404, { "content-type": "text/plain; charset=utf-8", "cache-control": "no-cache" }); + res.end(`404 Not Found: ${urlPath}\n`); + }; + const clean = urlPath.split(/[?#]/)[0]; + if (!clean.startsWith(BLOG_ASSET_PREFIX + "/")) { + notFound(); + return; + } + const root = pkgRoot(); + const segments = safeSegments(clean); + if (!root || segments === undefined) { + notFound(); + return; + } + const file = resolve(root, ...segments); + if (!file.startsWith(root + sep)) { + notFound(); + return; + } + const ext = file.slice(file.lastIndexOf(".")).toLowerCase(); + const type = ASSET_TYPES[ext]; + if (type === undefined || !statSyncSafe(file)) { + notFound(); + return; + } + res.writeHead(200, { "content-type": type, "cache-control": "no-cache" }); + res.end(readFileSync(file)); +} diff --git a/src/web/client.ts b/src/web/client.ts index 419a216ef9..1a2c182f2e 100644 --- a/src/web/client.ts +++ b/src/web/client.ts @@ -479,7 +479,7 @@ export const WEB_CLIENT = `(function () { if (tog) tog.textContent = locale === "zh-CN" ? "English" : "中文"; } - const PAGES = ["overview", "sessions", "config", "updates", "connect", "logs"]; + const PAGES = ["overview", "sessions", "config", "updates", "connect", "logs", "blog"]; let current = "overview"; let sessionsCache = []; // #1682: last overview alert payload — lets a dismiss re-render without refetching. @@ -865,6 +865,64 @@ function changelogCatOf(rawLine) { // the snapshot — keep the buttons held down until it settles. if (st.checking || st.installing) upSetButtons(true); } + // #4587: panel-embedded blog & articles — the server renders the bundled + // markdown with web/markdown.ts (escaped by construction), so this side only + // lays out cards and expands bodies. Language rides the page-level locale; + // switching languages reloads the page, so no incremental re-render hook. + let blogCache = null; + async function loadBlog(sub) { + const host = $("bl-list"); + if (!host) return; + let data = blogCache; + if (!data) { + try { + data = blogCache = await json(API_ROOT + "/blog"); + } catch (e) { + host.innerHTML = ""; + toast(t("toast.failed", { msg: e.message }), "err"); + return; + } + } + const items = (data && Array.isArray(data.items)) ? data.items : []; + const zhOn = locale === "zh-CN"; + if (sub) { + const item = items.find((x) => String(x.id) === String(sub)) || null; + if (!item) { + host.innerHTML = '
' + escapeHtml(t("bl.back")) + " " + escapeHtml(t("bl.nf")) + "
"; + return; + } + const kindLabel = item.kind === "post" ? t("bl.kind_post") : t("bl.kind_article"); + const title = zhOn && item.titleZh ? item.titleZh : (item.title || ""); + const html = zhOn ? (item.htmlZh || item.html || "") : (item.html || ""); + host.innerHTML = '
' + escapeHtml(item.date || "\u2014") + '' + escapeHtml(kindLabel) + '' + escapeHtml(t("bl.back")) + "
" + + '

' + escapeHtml(title) + "

" + + '
' + html + "
"; + return; + } + if (!items.length) { + const wrap = document.createElement("div"); + wrap.className = "card"; + const box = document.createElement("div"); + box.className = "card-b"; + box.textContent = t("bl.empty"); + wrap.appendChild(box); + host.innerHTML = ""; + host.appendChild(wrap); + return; + } + host.innerHTML = '
' + items.map((it) => { + const title = zhOn && it.titleZh ? it.titleZh : (it.title || ""); + const alt = zhOn ? (it.title || "") : (it.titleZh || ""); + let kindLabel; + if (it.kind === "post") kindLabel = t("bl.kind_post"); + else kindLabel = t("bl.kind_article"); + return '' + + '' + escapeHtml(it.date || "\u2014") + '' + + '' + escapeHtml(kindLabel) + '' + + '' + escapeHtml(title) + (alt ? ' ' + escapeHtml(alt) + "" : "") + "" + + '→'; + }).join("") + "
"; + } async function loadUpdates() { try { const [st, cl] = await Promise.all([json(API_ROOT + "/update/state"), json(API_ROOT + "/changelog")]); @@ -4069,15 +4127,19 @@ if (d.keepalive) kv(parts, t("det.keepalive"), d.keepalive.tierLabel + " · " + const hq = qi < 0 ? "" : hash.slice(qi + 1); let name = "overview"; let detailId = null; - const top = hbase.match(new RegExp("^#/(overview|config|updates|connect|logs)$")); + const top = hbase.match(new RegExp("^#/(overview|config|updates|connect|logs|blog)$")); if (top) { name = top[1]; if (name === "logs" && hq) applyLogFilter(hq); } else { const ses = hash.match(new RegExp("^#/sessions(?:/(.+))?$")) || hash.match(new RegExp("^#/session/(.+)$")); + const blg = hash.match(new RegExp("^#/blog/([A-Za-z0-9_-]+)$")); if (ses) { name = "sessions"; if (ses[1]) detailId = decodeURIComponent(ses[1]); + } else if (blg) { + name = "blog"; + detailId = decodeURIComponent(blg[1]); } } PAGES.forEach((p) => { @@ -4090,6 +4152,7 @@ if (d.keepalive) kv(parts, t("det.keepalive"), d.keepalive.tierLabel + " · " + else if (name === "sessions") loadSessions(detailId); else if (name === "config") loadConfig(); else if (name === "updates") loadUpdates(); + else if (name === "blog") loadBlog(detailId); else if (name === "logs") loadLogs(); } window.addEventListener("hashchange", route); diff --git a/src/web/i18n.ts b/src/web/i18n.ts index cd941b96ab..6f820ea7bf 100644 --- a/src/web/i18n.ts +++ b/src/web/i18n.ts @@ -31,6 +31,14 @@ export const MESSAGES: Record> = { "nav.sessions": "会话", "nav.config": "配置", "nav.updates": "版本", + "nav.blog": "博客", + "bl.title": "博客 / 文库", + "bl.sub": "几篇发布笔记与长文在面板内直接渲染——随安装包内置,离线可读;永远最新的完整文库在 GitHub Pages。", + "bl.kind_post": "发布笔记", + "bl.kind_article": "长文", + "bl.empty": "这个版本还没内置文章。", + "bl.back": "← 全部文章", + "bl.nf": "文章不存在或已被移除。", "nav.connect": "接入", "nav.logs": "日志", "logs.title": "运行日志", @@ -635,6 +643,14 @@ export const MESSAGES: Record> = { "nav.sessions": "Sessions", "nav.config": "Configuration", "nav.updates": "Versions", + "nav.blog": "Blog", + "bl.title": "Blog & Articles", + "bl.sub": "A few release notes and long-form pieces rendered right here — shipped inside your install, readable offline; the always-fresh full library lives on GitHub Pages.", + "bl.kind_post": "Post", + "bl.kind_article": "Article", + "bl.empty": "No bundled articles in this build.", + "bl.back": "\u2190 All articles", + "bl.nf": "Article not found or removed from this build.", "nav.connect": "Connect", "nav.logs": "Logs", "logs.title": "Run log", diff --git a/src/web/markdown.ts b/src/web/markdown.ts index dacfba897c..6570c83e3f 100644 --- a/src/web/markdown.ts +++ b/src/web/markdown.ts @@ -3,7 +3,8 @@ * reaches the output unescaped), then transform structure only. Supports the * subset kernel renderHandoff actually emits: headings, paragraphs, fenced * code, inline code, bold/italic, lists, blockquotes, links (sanitized), - * horizontal rules. No external dependency — dist/index.js stays dep-free. */ + * horizontal rules, pipe tables and image refs (http(s)/panel asset routes + * only). No external dependency — dist/index.js stays dep-free. */ function escapeHtml(s: string): string { return s.replace(/&/g, "&").replace(//g, ">").replace(/"/g, """); @@ -12,6 +13,14 @@ function escapeHtml(s: string): string { function inlineMd(s: string): string { let out = escapeHtml(s); out = out.replace(/`([^`]+)`/g, (_m, code: string) => `${code}`); + // ![alt](url) — must run before the link rule so the image syntax is consumed + // whole. Only published image sources survive: http(s), or the panel's own + // bundled-asset route (/__bili/blog-assets/*, see web/blogfeed.ts). Quotes are + // already escaped by escapeHtml, so attribute injection is impossible. + out = out.replace(/!\[([^\]]*)\]\(([^)\s]+)\)/g, (_m, alt: string, url: string) => { + if (/^(?:https?:\/\/|\/__bili\/blog-assets\/)/i.test(url)) return `${alt}`; + return ""; + }); out = out.replace(/\*\*([^*]+)\*\*/g, "$1"); out = out.replace(/(^|[^*])\*([^*\n]+)\*/g, "$1$2"); // [text](url) — only http/https/relative URLs survive; anything else @@ -48,6 +57,19 @@ export function markdownToHtml(md: string): string { continue; } if (/^\s*(---+|\*\*\*+)\s*$/.test(line)) { html.push("
"); i += 1; continue; } + // Pipe tables (header + dash separator row + body rows). The kernel + // handoff never emits these; bundled articles do. Rendered with the + // panel's own .data table classes so they match every other table. + if (/^\s*\|.*\|\s*$/.test(line) && i + 1 < lines.length && /^\s*\|[\s:|-]+\|\s*$/.test(lines[i + 1])) { + const cells = (row: string): string[] => row.trim().replace(/^\|/, "").replace(/\|$/, "").split("|").map((c) => inlineMd(c.trim())); + const head = cells(line); + i += 2; + const rows: string[][] = []; + while (i < lines.length && /^\s*\|.*\|\s*$/.test(lines[i])) { rows.push(cells(lines[i])); i += 1; } + html.push(`${head.map((c) => ``).join("")}` + + `${rows.map((r) => `${r.map((c) => ``).join("")}`).join("")}
${c}
${c}
`); + continue; + } // Indented runs (machine-emitted tool arguments, nested lists) stay verbatim in //
 instead of being merged into one run-on paragraph by space-joining.
         if (/^\s{2,}\S/.test(line)) {
diff --git a/src/web/page.ts b/src/web/page.ts
index 881b0c77ca..9d47752098 100644
--- a/src/web/page.ts
+++ b/src/web/page.ts
@@ -23,7 +23,7 @@ export function renderPage(origin: string, version: string, embed = false, theme
     // that request used to miss every admin route and get relayed onto the
     // configured upstream (a wasted request + 403 noise in the log).
     return `billion-context
-
billion-contextv${version}
+
billion-contextv${version}
@@ -228,6 +228,10 @@ rendering/linkify in client.js into #changelog-body (collapsed by default). -->

${zh("zcode.hint_a")} ~ ${zh("zcode.hint_b")} ~/... ${zh("zcode.hint_c")}

+
diff --git a/src/web/styles.ts b/src/web/styles.ts index e575c80671..7c25e40f2d 100644 --- a/src/web/styles.ts +++ b/src/web/styles.ts @@ -537,4 +537,23 @@ pre.tool-args, pre.tool-out { margin: 6px 0 0; padding: 8px; background: var(--b embed face a little breathing room instead of zero gutter. */ .embed main { max-width: none; padding: 8px 10px 16px; } .embed .banner { margin: 8px 0 0; } + +/* #4587: panel-embedded blog & article view (#/blog index + #/blog/ pages) */ +.bl-row { display: flex; align-items: baseline; gap: 10px; padding: 9px 14px; border-bottom: 1px solid var(--border-soft); text-decoration: none; color: inherit; } +.bl-row:last-child { border-bottom: none; } +.bl-row:hover .bl-title { color: var(--accent); } +.bl-date { color: var(--text-faint); font-size: 12px; } +.bl-title { flex: 1; font-weight: 600; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.bl-title-alt { color: var(--text-faint); font-weight: 400; } +.bl-arrow { color: var(--text-faint); font-size: 12px; } +.bl-back { color: var(--accent); text-decoration: none; font-size: 12px; } +.bl-back:hover { text-decoration: underline; } +.bl-h { margin: 10px 0 0; font-size: 20px; line-height: 1.35; } +.post-body p { line-height: 1.7; } +.post-body pre { background: var(--bg-elev); border: 1px solid var(--border-soft); border-radius: 8px; padding: 12px; overflow-x: auto; } +.post-body code { font-family: var(--mono); font-size: 0.92em; background: var(--bg-elev); padding: 1px 5px; border-radius: 4px; } +.post-body pre code { background: none; padding: 0; } +.post-body blockquote { border-left: 3px solid var(--accent); margin: 12px 0; padding: 4px 14px; color: var(--text-muted); background: var(--bg-elev); border-radius: 0 8px 8px 0; } +.post-body h2 { margin-top: 22px; } +.post-body .md-img { max-width: 100%; border-radius: 8px; border: 1px solid var(--border-soft); } `; diff --git a/tests/web-blog-route.test.ts b/tests/web-blog-route.test.ts new file mode 100644 index 0000000000..7f290105bc --- /dev/null +++ b/tests/web-blog-route.test.ts @@ -0,0 +1,123 @@ +/** + * Blog view routing (#4587) — the REAL WEB_CLIENT exercised in a vm sandbox + * (same harness pattern as the #2321 cases in web-i18n.test.ts). Regression for + * the owner-reported "点不了博客": the route() hash whitelist had drifted from + * the PAGES list, so #/blog silently fell through to overview. Both directions + * are pinned: #/blog activates the blog section AND fetches the feed; the + * default hash does neither. The #/blog/ sub-route renders a single + * article page (unknown slugs degrade to a back-link, no crash). + */ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import vm from "node:vm"; +import { WEB_CLIENT } from "../src/web/client.ts"; + +type HarnessEl = { + textContent: string; innerHTML: string; value: string; hidden: boolean; + style: Record; dataset: Record; + attrs: Record; children: unknown[]; handlers: Record void>; + setAttribute(k: string, v: string): void; getAttribute(k: string): string | null; + appendChild(c: unknown): unknown; prepend(c: unknown): unknown; + removeChild(): void; remove(): void; focus(): void; click(): void; + addEventListener(type: string, fn: () => void): void; removeEventListener(): void; + querySelectorAll(): unknown[]; querySelector(): null; +}; +const mkHarnessEl = (): HarnessEl => ({ + textContent: "", innerHTML: "", value: "", hidden: false, style: {}, dataset: {}, + attrs: {}, children: [], handlers: {}, + setAttribute(k, v) { this.attrs[k] = String(v); }, + getAttribute(k) { return k in this.attrs ? this.attrs[k] : null; }, + appendChild(c) { this.children.push(c); return c; }, + prepend(c) { this.children.unshift(c); return c; }, + removeChild() { }, remove() { }, focus() { }, click() { }, + addEventListener(type, fn) { this.handlers[type] = fn; }, removeEventListener() { }, + querySelectorAll: () => [], querySelector: () => null, +}); + +const FEED = { items: [{ id: "demo", kind: "post", date: "2026-10-08", title: "Demo post", titleZh: "演示", excerpt: "ex", html: "

hi

", htmlZh: "

你好

" }] }; + +async function runClient(hash: string): Promise<{ els: Map; blogHits: number; unhandled: unknown[] }> { + const unhandled: unknown[] = []; + const onRej = (r: unknown) => unhandled.push(r); + process.on("unhandledRejection", onRej); + try { + const byId = new Map(); + const idEl = (id: string): HarnessEl => { let e = byId.get(id); if (!e) { e = mkHarnessEl(); byId.set(id, e); } return e; }; + let blogHits = 0; + const documentStub = { + hidden: false, + documentElement: { lang: "" as string }, + body: mkHarnessEl(), + getElementById: (id: string) => idEl(id), + createElement: () => mkHarnessEl(), + querySelectorAll: () => [] as unknown[], + querySelector: () => null, + addEventListener() { }, removeEventListener() { }, + execCommand() { return true; }, + }; + const sandbox: Record = { + console, + setTimeout, clearTimeout, clearInterval, + setInterval: () => 0, + fetch: async (url: string | URL | Request) => { + if (String(url).endsWith("/blog")) { + blogHits += 1; + return { ok: true, status: 200, json: async () => FEED }; + } + return { ok: true, status: 200, json: async () => ({}) }; + }, + document: documentStub, + window: { addEventListener() { }, innerWidth: 1440, innerHeight: 900 }, + location: { hash, pathname: "/__bili/", reload() { } }, + navigator: { language: "zh-CN" }, + localStorage: { getItem: () => null, setItem() { } }, + }; + vm.createContext(sandbox); + vm.runInNewContext(WEB_CLIENT, sandbox, { timeout: 5000 }); + await new Promise((r) => setTimeout(r, 100)); + return { els: byId, blogHits, unhandled }; + } finally { + process.removeListener("unhandledRejection", onRej); + } +} + +test("#/blog routes to the index and lists articles as links (owner repro: nav click did nothing)", async () => { + const r = await runClient("#/blog"); + assert.equal(r.unhandled.length, 0, `client raised unhandled rejection: ${r.unhandled.join("; ")}`); + assert.equal(r.blogHits, 1, "feed fetched exactly once for #/blog"); + const blog = r.els.get("page-blog"); + const overview = r.els.get("page-overview"); + assert.ok(blog && !blog.hidden, "blog section is shown"); + assert.ok(overview && overview.hidden, "overview section is hidden"); + const list = r.els.get("bl-list"); + assert.ok(list, "blog list host rendered"); + assert.ok(list!.innerHTML.includes('href="#/blog/demo"'), "index row links to the article sub-route"); + assert.ok(!list!.innerHTML.includes("post-body"), "index renders metadata only — no article bodies"); +}); + +test("#/blog/ renders that single article with a back link", async () => { + const r = await runClient("#/blog/demo"); + assert.equal(r.unhandled.length, 0, `client raised unhandled rejection: ${r.unhandled.join("; ")}`); + assert.equal(r.blogHits, 1, "feed fetched once for the article page"); + assert.ok(r.els.get("page-blog") && !r.els.get("page-blog")!.hidden, "article stays inside the blog view (nav active)"); + const list = r.els.get("bl-list")!; + assert.ok(list.innerHTML.includes("post-body") && (list.innerHTML.includes("

hi

") || list.innerHTML.includes("\u4f60\u597d

")), "article body rendered (locale-twin aware)"); + assert.ok(list.innerHTML.includes(''), "back link to the index present"); +}); + +test("unknown slug degrades to a back link without a crash", async () => { + const r = await runClient("#/blog/nope"); + assert.equal(r.unhandled.length, 0, `client raised unhandled rejection: ${r.unhandled.join("; ")}`); + const list = r.els.get("bl-list")!; + assert.ok(list.innerHTML.includes(''), "back link present for unknown slug"); + assert.ok(!list.innerHTML.includes("post-body"), "no article body for an unknown slug"); +}); + +test("default and other hashes do NOT activate the blog view or hit the blog endpoint", async () => { + for (const hash of ["#/overview", "#/logs"]) { + const r = await runClient(hash); + assert.equal(r.unhandled.length, 0, `${hash} raised unhandled rejection`); + assert.equal(r.blogHits, 0, `${hash} must not fetch the blog feed`); + assert.ok(r.els.get("page-blog")!.hidden, `${hash} keeps the blog section hidden`); + } +}); diff --git a/tests/web-blogfeed.test.ts b/tests/web-blogfeed.test.ts new file mode 100644 index 0000000000..0d1d820907 --- /dev/null +++ b/tests/web-blogfeed.test.ts @@ -0,0 +1,151 @@ +/** + * Panel blog/articles feed (#4587, src/web/blogfeed.ts) — bundled markdown → + * server-rendered JSON feed + guarded image assets. Covers both directions of + * every gate: dated/undated ordering, bilingual pairing, frontmatter titles, + * XSS-escaped rendering, image rewrite vs drop (incl. traversal refs), + * GFM tables, asset route (png allowed / md denied / traversal / encoding / + * missing), malformed manifest degradation, absent-root empty feed, and the + * real-tree probe finding the repository's website/blog/posts. + */ +import { test, beforeEach, afterEach } from "node:test"; +import assert from "node:assert/strict"; +import { mkdtempSync, rmSync, writeFileSync, mkdirSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import type { ServerResponse } from "node:http"; +import { getBlogFeed, handleBlogGet, handleBlogAssetGet, _setBlogRootForTest } from "../src/web/blogfeed.ts"; + +let pkgRoot = ""; +let outsideDir = ""; + +function fakeRes(): { res: ServerResponse; status: number | undefined; headers: Record; body: string } { + const out: { res: ServerResponse; status: number | undefined; headers: Record; body: string } = + { res: undefined as unknown as ServerResponse, status: undefined, headers: {}, body: "" }; + out.res = { + writeHead(_status: number, headers?: Record) { out.status = _status; out.headers = headers ?? {}; }, + end(chunk?: string | Uint8Array) { if (chunk !== undefined) out.body += Buffer.from(chunk).toString("utf8"); }, + } as unknown as ServerResponse; + return out; +} + +function buildFixture(): void { + mkdirSync(join(pkgRoot, "website", "blog", "posts"), { recursive: true }); + mkdirSync(join(pkgRoot, "website", "blog", "posts", "figures"), { recursive: true }); + mkdirSync(join(pkgRoot, "paper", "figures"), { recursive: true }); + writeFileSync(join(pkgRoot, "package.json"), "{}"); + writeFileSync(join(pkgRoot, "outside-secret.yaml"), "nope"); + const posts = join(pkgRoot, "website", "blog", "posts"); + writeFileSync(join(posts, "2026-10-08_demo.md"), + "---\ntitle: \"Demo post\"\nexcerpt: \"EN excerpt.\"\n---\n\n## Body\n\nText with inline.\n\n![shot](figures/shot.png)\n\n![escape](../../outside-secret.yaml)\n"); + writeFileSync(join(posts, "2026-10-08_demo.zh.md"), + "---\ntitle_zh: \"演示文章\"\nexcerpt_zh: \"中文摘要。\"\n---\n\n## 正文\n\n中文内容。\n"); + writeFileSync(join(posts, "2026-10-09_new.md"), "# Undated-by-frontmatter post\n\nNewer content.\n"); + writeFileSync(join(posts, "notes.md"), "# Plain notes\n\nNo date anywhere.\n"); + writeFileSync(join(posts, "figures", "shot.png"), "POSTPNG"); + writeFileSync(join(pkgRoot, "website", "articles.json"), JSON.stringify({ articles: [ + { file: "paper/a.md", zh_file: "paper/b.md", slug: "alpha" }, + { file: "paper/missing.md" }, + ] })); + writeFileSync(join(pkgRoot, "paper", "a.md"), + "# Article Alpha\n\nTable below:\n\n| k | v |\n|---|---|\n| 1 | two |\n\n![fig](figures/p.png)\n"); + writeFileSync(join(pkgRoot, "paper", "b.md"), "# 文章 Alpha(中文)\n\n中文正文。\n"); + writeFileSync(join(pkgRoot, "paper", "figures", "p.png"), "PAPERPNG"); +} + +beforeEach(() => { + outsideDir = mkdtempSync(join(tmpdir(), "bili-blogroot-")); + pkgRoot = join(outsideDir, "pkg"); + buildFixture(); + _setBlogRootForTest(pkgRoot); +}); + +afterEach(() => { + _setBlogRootForTest(null); + rmSync(outsideDir, { recursive: true, force: true }); +}); + +test("feed composes posts + manifest articles, dated newest-first, undated tail", () => { + const data = getBlogFeed(); + assert.equal(data.items.length, 4); // demo + new(10-09) + alpha(article, undated) + notes(no date anywhere) + assert.deepEqual(data.items.map((i) => i.id), ["new", "demo", "alpha", "notes"]); + // A post with neither a filename date nor a frontmatter date must degrade to an + // empty date (stable undated tail), not a garbage 10-char slice of the filename. + assert.equal(data.items[3].date, ""); + assert.equal(data.items[1].kind, "post"); + assert.equal(data.items[2].kind, "article"); + assert.equal(data.items[2].date, ""); + assert.equal(data.items[1].title, "Demo post"); + assert.equal(data.items[1].titleZh, "演示文章"); + assert.ok(data.items[1].excerpt.endsWith("EN excerpt.")); + assert.equal(data.items[1].excerptZh, "中文摘要。"); + assert.ok(data.items[2].title === "Article Alpha", "article title falls back to H1"); + assert.equal(data.items[2].titleZh, "文章 Alpha(中文)"); + assert.ok(!JSON.stringify(data.items).includes("missing.md"), "unresolvable manifest entry is skipped, not fatal"); +}); + +test("rendering is escape-first: script tags survive only escaped; tables become panel data tables", () => { + const data = getBlogFeed(); + const demo = data.items.find((i) => i.id === "demo")!; + assert.ok(demo.html.includes("<script>alert(1)</script>")); + assert.ok(!demo.html.includes("