From 231ebf73afe6db1b4e8f7ee82d84151e2370cefe Mon Sep 17 00:00:00 2001 From: ranxianglei Date: Wed, 21 Oct 2026 18:40:33 +0800 Subject: [PATCH 01/10] =?UTF-8?q?feat(web):=20changelog=20section=20?= =?UTF-8?q?=E2=80=94=20per-release=20notes=20from=20GitHub=20Releases=20(#?= =?UTF-8?q?3719)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - GET /__bili/changelog: GitHub Releases API (per_page=20), in-memory cache, one network hit per 10 minutes (mirrors update-notes throttle discipline); fail-soft — offline/HTTP/malformed failures return 200 {releases, error:"offline"} - web panel overview page: collapsible 更新日志 / Changelog card, per-release expandable notes (escaped plain text + URL links, no markdown dependency), GitHub links; bilingual i18n - /acp panel footer: 'changelog: ' line once the cache is warm (sync read only; once-per-process background warm-up, fail silent) --- src/plugin.ts | 10 +++ src/server/admin.ts | 5 ++ src/web/changelog.ts | 153 +++++++++++++++++++++++++++++++++ src/web/client.ts | 45 ++++++++++ src/web/i18n.ts | 12 +++ src/web/page.ts | 3 + src/web/styles.ts | 13 +++ tests/web-changelog.test.ts | 166 ++++++++++++++++++++++++++++++++++++ 8 files changed, 407 insertions(+) create mode 100644 src/web/changelog.ts create mode 100644 tests/web-changelog.test.ts diff --git a/src/plugin.ts b/src/plugin.ts index e04a08b76c..fa02d130dd 100644 --- a/src/plugin.ts +++ b/src/plugin.ts @@ -57,6 +57,7 @@ function tailLooksTerminal(tail: string, protocol: WireProtocol | "responses"): /"type"\s*:\s*"response\.(?:completed|failed|incomplete)"/.test(tail); } import { degenerateTurnWarning, endsWithDraftClose, requestExpectsProseSummary } from "./degenerate-turn.js"; +import { getChangelog, latestChangelog, warmChangelogOnce } from "./web/changelog.js"; import { PANEL_BOX_FOOTER } from "./acp-panel.js"; import { excludeDeadRefRanges } from "./acp-status.js"; import { describeAdvisory, getAdvisoryState } from "./advisory.js"; @@ -1723,6 +1724,15 @@ export function handlePluginStatus(conversationId: string, res: import("node:htt if (webUrl !== undefined) { preFooter.push(`Web UI: ${webUrl}`); } + // #3719: latest-release pointer — sync cache read only, so the status path + // stays network-free and fast; the web endpoint (and the fire-and-forget + // refresh below) warm the cache. Fail silent: no line until a fetch lands. + const clLatest = latestChangelog(); + if (clLatest !== undefined) { + preFooter.push(`changelog: ${clLatest.tag} ${clLatest.url}`); + } else { + warmChangelogOnce(); // once per process; never throws + } if (panel !== undefined && preFooter.length > 0) { // Escape $ so advisory text (remote doc content) cannot be read as // replace() pattern syntax ($&, $\`, $') and corrupt the box lines. diff --git a/src/server/admin.ts b/src/server/admin.ts index 2029c5ec7b..36cbff1f65 100644 --- a/src/server/admin.ts +++ b/src/server/admin.ts @@ -31,6 +31,7 @@ import { detectStaleInstall, getLastInstall } from "../update.js"; import { getPlannedUpgrade, getUpdatePolicyState } from "../update-policy.js"; import { PACKAGE_NAME, VERSION, BUILD_COMMIT } from "../version.js"; import { buildBlockContent, buildMessageContent, buildOverview, buildSessionDetail, buildSessionList, buildSessionPage, handleConfigGet, handleConfigPut, hiddenEmptyCount, renderUI, type BlockContentView } from "../web/index.js"; +import { handleChangelogGet } from "../web/changelog.js"; import { buildSessionReportMd, buildSessionReportSvg } from "../web/report.js"; import { queryLogLines } from "../web/logs-query.js"; import { buildDiagnostics } from "../web/diagnostics.js"; @@ -283,6 +284,10 @@ export async function handleAdminRoute(req: http.IncomingMessage, res: http.Serv return; } if (req.method === "GET" && req.url === "/__bili/config") return handleConfigGet(res); + // #3719: per-release notes for the panel's changelog section — same + // 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); if (req.method === "PUT" && req.url === "/__bili/config") { return handleConfigPut(req, res, () => { const fresh = loadOptions(); diff --git a/src/web/changelog.ts b/src/web/changelog.ts new file mode 100644 index 0000000000..81b04da8bc --- /dev/null +++ b/src/web/changelog.ts @@ -0,0 +1,153 @@ +/** + * Web changelog (#3719): per-release notes for the admin panel, sourced from + * the GitHub Releases API. The web UI shows a collapsible "更新日志 / Changelog" + * section (see page.ts/client.ts) and the /acp panel appends a latest-release + * pointer line from the same cache (plugin.ts). + * + * Fail-soft by contract, mirroring the release-notes watcher discipline in + * src/update-notes.ts but kept in-memory only (no disk cache files, no config + * keys, no env vars): one network hit per THROTTLE_MS window; every failure — + * offline, HTTP error, malformed document — degrades to the cached view with + * `error: "offline"` and never throws into the caller. A GitHub failure must + * never break the panel or the status endpoint. + */ +import type { ServerResponse } from "node:http"; +import { fetchWithTimeout } from "../fetch-util.js"; +import { log as loggerLog } from "../logger.js"; + +export type ChangelogRelease = { + /** GitHub release tag (e.g. v0.1.203). */ + tag: string; + /** Release title when distinct from the tag. */ + name?: string; + /** ISO publish timestamp. */ + publishedAt?: string; + /** Release notes body (markdown source; the UI renders it as escaped + * plain text with URL links — no markdown dependency). */ + body?: string; + /** GitHub release page URL. */ + url: string; +}; + +export type ChangelogData = { + releases: ChangelogRelease[]; + /** Set on a failed/stale-throttled read ("offline"); absent when the + * cached data is fresh. HTTP is always 200 — the UI degrades gracefully. */ + error?: string; +}; + +const GITHUB_RELEASES_URL = "https://api.github.com/repos/ranxianglei/billion-context/releases?per_page=20"; +/** One network hit per window (mirrors the release-notes checker cadence); + * failures are throttled too, so an offline machine hammers nothing. */ +const THROTTLE_MS = 10 * 60 * 1000; +/** Newest-first cap on entries served to the panel. */ +const MAX_ENTRIES = 20; +const FETCH_TIMEOUT_MS = 5000; + +type State = { + releases: ChangelogRelease[]; + lastError?: string; + lastCheckAt: number; +}; + +let state: State = { releases: [], lastCheckAt: 0 }; +let inflight: Promise | undefined; +/** One background warm-up per process for network-free callers (/acp panel); + * real cadence is driven by the admin endpoint's 10-minute throttle. */ +let warmAttempted = false; + +/** Test seam: clear cache + throttle + in-flight + warm-up guards. */ +export function _resetChangelogForTest(): void { + state = { releases: [], lastCheckAt: 0 }; + inflight = undefined; + warmAttempted = false; +} + +/** Synchronous read of the newest cached release for surfaces that must not + * await the network (the /acp panel line). Undefined until the first + * successful fetch. */ +export function latestChangelog(): ChangelogRelease | undefined { + return state.releases[0]; +} + +/** Map one GitHub Releases API item. Items without a usable tag+url are + * skipped individually so one bad row cannot kill the feed. */ +function parseRelease(raw: unknown): ChangelogRelease | undefined { + if (typeof raw !== "object" || raw === null) return undefined; + const e = raw as Record; + const tag = typeof e.tag_name === "string" ? e.tag_name.trim() : ""; + const url = typeof e.html_url === "string" ? e.html_url.trim() : ""; + if (!tag || !url) return undefined; + const name = typeof e.name === "string" ? e.name.trim() : ""; + const publishedAt = typeof e.published_at === "string" ? e.published_at.trim() : ""; + const body = typeof e.body === "string" ? e.body : undefined; + return { + tag, + url, + ...(name !== "" && name !== tag ? { name } : {}), + ...(publishedAt !== "" ? { publishedAt } : {}), + ...(body !== undefined ? { body } : {}), + }; +} + +async function runCheck(): Promise { + try { + const result = await fetchWithTimeout( + GITHUB_RELEASES_URL, + { method: "GET", headers: { Accept: "application/json", "user-agent": "billion-context-changelog" } }, + FETCH_TIMEOUT_MS, + ); + try { + if (!result.response.ok) throw new Error(`GitHub Releases returned HTTP ${result.response.status}`); + const raw = await result.response.json(); + if (!Array.isArray(raw)) throw new Error("response is not a JSON array"); + const releases: ChangelogRelease[] = []; + for (const item of raw) { + const rel = parseRelease(item); + if (rel !== undefined) releases.push(rel); + if (releases.length >= MAX_ENTRIES) break; + } + state = { releases, lastCheckAt: Date.now() }; + } finally { + // Fully consumed the body — stop the idle watchdog so the timer + // cannot pin the event loop (fetch-util's #552 contract). + result.stopIdleTimer(); + } + } catch (e) { + // Fail soft: keep any stale cache, record the error, throttle retries. + state = { ...state, lastError: "offline", lastCheckAt: Date.now() }; + loggerLog("warn", `[changelog] GitHub Releases check failed (${String(e)}) — serving cached view`); + } +} + +/** Fire at most one background refresh per process from sync callers that + * must not await the network (the /acp panel footer line). Fail silent by + * construction — getChangelog never throws. */ +export function warmChangelogOnce(): void { + if (warmAttempted || latestChangelog() !== undefined) return; + warmAttempted = true; + void getChangelog(); +} + +/** Throttled changelog read (at most one network hit per THROTTLE_MS; + * `force` bypasses the window). Never throws: offline/malformed sources + * yield `{ releases: , error: "offline" }`. */ +export async function getChangelog(opts?: { force?: boolean }): Promise { + const stale = Date.now() - state.lastCheckAt >= THROTTLE_MS; + if ((opts?.force ?? false) || stale) { + if (inflight === undefined) { + inflight = runCheck().finally(() => { inflight = undefined; }); + } + await inflight; + } + return { releases: state.releases, ...(state.lastError !== undefined ? { error: state.lastError } : {}) }; +} + +/** GET /__bili/changelog handler (admin-gated like the other read-only + * /__bili/ routes in server/admin.ts). Always HTTP 200 — even for the + * offline/error payload — so the panel can degrade instead of erroring. */ +export async function handleChangelogGet(res: ServerResponse): Promise { + const data = await getChangelog(); + res.writeHead(200, { "content-type": "application/json" }); + res.end(JSON.stringify(data)); +} diff --git a/src/web/client.ts b/src/web/client.ts index 6dac7f63dc..e2a9ae51ff 100644 --- a/src/web/client.ts +++ b/src/web/client.ts @@ -647,6 +647,50 @@ export const WEB_CLIENT = `(function () { return tr; } + // #3719: changelog section (overview page, collapsed card) — one fetch per + // page load; the server caches with a 10-minute throttle, so this costs at + // most one GitHub API hit per 10 minutes fleet-wide. + let chlogLoaded = false; + // Escaped-plain-text → anchor tags. Function-form replacer on purpose: + // URL characters ($, &) would corrupt "string" replacement patterns. + function linkifyText(escaped) { + return escaped.replace(/(https?:\\/\\/[^\\s<>]+)/g, (u) => '' + u + ""); + } + function renderChangelog(d) { + const el = $("changelog-body"); + if (!el) return; + const rels = (d && typeof d === "object" && Array.isArray(d.releases)) ? d.releases : []; + if (!rels.length) { + el.textContent = (d && d.error) ? t("sys.changelog_offline") : t("sys.changelog_empty"); + return; + } + let html = ""; + rels.forEach((r, i) => { + const tag = escapeHtml(String(r.tag || "")); + const name = (typeof r.name === "string" && r.name !== r.tag) ? escapeHtml(r.name) + " · " : ""; + const date = r.publishedAt ? ' ' + escapeHtml(String(r.publishedAt).slice(0, 10)) + "" : ""; + const view = '' + t("sys.changelog_view") + ""; + const body = typeof r.body === "string" && r.body.trim() ? "
" + linkifyText(escapeHtml(r.body)).replace(/\\n/g, "
") + "
" + view + "
" : view; + html += '
" + name + tag + date + "" + body + "
"; + }); + html += '"; + el.innerHTML = html; + } + async function loadChangelog() { + if (chlogLoaded) return; + const el = $("changelog-body"); + if (!el) return; + chlogLoaded = true; + el.textContent = t("sys.changelog_loading"); + try { + renderChangelog(await json(API_ROOT + "/changelog")); + } catch (e) { + // The endpoint itself never errors (fail-soft); reaching here means + // the PROXY is unreachable — same offline wording either way. + renderChangelog({ releases: [], error: "offline" }); + } + } + async function loadOverview(silent) { try { const d = await json(API_ROOT + "/overview"); @@ -3668,6 +3712,7 @@ if (d.keepalive) kv(parts, t("det.keepalive"), d.keepalive.tierLabel + " · " + hydrate(); initStaticHandlers(); + loadChangelog(); route(); // #1937: failures back off exponentially (5s → 10s → … cap 60s) with a // persistent error strip instead of silent toast-spam retries, and a slow diff --git a/src/web/i18n.ts b/src/web/i18n.ts index 83ba91a6a2..6b0052a16d 100644 --- a/src/web/i18n.ts +++ b/src/web/i18n.ts @@ -103,6 +103,12 @@ export const MESSAGES: Record> = { "sys.disk_version": "磁盘版本", "sys.inflight": "进行中请求", "sys.blind_tunnels": "MITM 盲隧道(CONNECT 后无 TLS)", + "sys.changelog": "更新日志 / Changelog", + "sys.changelog_loading": "加载中…", + "sys.changelog_empty": "暂无可显示的发布说明", + "sys.changelog_offline": "加载失败(可能离线)——稍后重试", + "sys.changelog_view": "在 GitHub 查看", + "sys.changelog_all": "全部版本(GitHub Releases)", "sys.update": "升级提醒:", "sys.update_available": "发现 critical 修复,请升级到 v{version} 或更新版本 — {summary}", "sys.update_ready": "critical 修复已就绪 v{version} — 重启 bili 即可生效", @@ -645,6 +651,12 @@ export const MESSAGES: Record> = { "sys.disk_version": "On-disk version", "sys.inflight": "In-flight requests", "sys.blind_tunnels": "MITM blind tunnels (CONNECT without TLS)", + "sys.changelog": "Changelog", + "sys.changelog_loading": "Loading…", + "sys.changelog_empty": "No release notes available", + "sys.changelog_offline": "Could not load release notes (offline?) — retry later", + "sys.changelog_view": "View on GitHub", + "sys.changelog_all": "All releases (GitHub Releases)", "sys.update": "Update notice:", "sys.update_available": "critical fix available — upgrade to v{version} or newer: {summary}", "sys.update_ready": "critical fix ready (v{version}) — restart bili to apply", diff --git a/src/web/page.ts b/src/web/page.ts index c0b71745bf..42031b2966 100644 --- a/src/web/page.ts +++ b/src/web/page.ts @@ -55,6 +55,9 @@ export function renderPage(origin: string, version: string, embed = false, theme
${zh("sys.inflight")}
0
${zh("sys.blind_tunnels")}
0
+ +
${zh("sys.changelog")}
${zh("ov.recent")}${zh("ov.view_all")}
diff --git a/src/web/styles.ts b/src/web/styles.ts index 27f6942135..152d577e04 100644 --- a/src/web/styles.ts +++ b/src/web/styles.ts @@ -238,6 +238,19 @@ td.num, th.num { text-align: right; font-variant-numeric: tabular-nums; font-fam .block-item .body { padding: 0 16px 12px 78px; font-size: 12.5px; color: var(--text-muted); white-space: pre-wrap; } .block-item .body.md { white-space: normal; } .block-item .body.md p { margin: 6px 0; } + +/* Changelog section (#3719): collapsible releases inside the overview card */ +.cl-card summary { list-style: none; cursor: pointer; padding: 12px 16px; font-weight: 600; font-size: 13px; display: flex; gap: 8px; align-items: center; } +.cl-card summary::-webkit-details-marker { display: none; } +.cl-card summary::before { content: "\25B8"; color: var(--text-muted); font-size: 11px; transition: transform .12s; } +.cl-card[open] summary::before { transform: rotate(90deg); } +.cl-card summary:hover { background: var(--bg-muted); } +.cl-item { border-bottom: 1px solid var(--border-soft); } +.cl-item:last-of-type { border-bottom: none; } +.cl-item summary { list-style: none; cursor: pointer; padding: 8px 16px; font-family: var(--mono); font-size: 12px; font-weight: 600; display: flex; gap: 8px; align-items: baseline; } +.cl-item summary::-webkit-details-marker { display: none; } +.cl-item summary:hover { background: var(--bg-muted); } +.cl-item > div { white-space: normal; overflow-wrap: anywhere; } .block-item .body.md h2, .block-item .body.md h3, .block-item .body.md h4 { margin: 12px 0 6px; line-height: 1.35; color: var(--text); } .block-item .body.md h2 { font-size: 13.5px; } .block-item .body.md h3 { font-size: 13px; } .block-item .body.md h4 { font-size: 12.5px; } .block-item .body.md ul, .block-item .body.md ol { margin: 6px 0; padding-left: 22px; } diff --git a/tests/web-changelog.test.ts b/tests/web-changelog.test.ts new file mode 100644 index 0000000000..1d44ec9a94 --- /dev/null +++ b/tests/web-changelog.test.ts @@ -0,0 +1,166 @@ +/** + * #3719 web changelog — GitHub Releases → panel cache + endpoint. + * Covers: JSON mapping (passthrough, newest-first, 20-cap, bad-row skip), + * the 10-minute throttle (no refetch within TTL, force bypasses), fail-soft + * on network + HTTP errors (empty/stale releases + error:"offline", never + * throws), and handleChangelogGet's always-200 JSON response. + */ +import { test, beforeEach, afterEach } from "node:test"; +import assert from "node:assert/strict"; +import type { ServerResponse } from "node:http"; +import { getChangelog, latestChangelog, _resetChangelogForTest } from "../src/web/changelog.ts"; + +const GH = "https://api.github.com/repos/ranxianglei/billion-context/releases?per_page=20"; + +/** One canned GitHub Releases API item; `over` lets individual tests mutate. */ +function ghRelease(n: number, over?: Record) { + return { + tag_name: `v0.9.${100 - n}`, + name: n === 3 ? `v0.9.${100 - n}` : `v0.9.${100 - n} — release ${n}`, // row 3 name == tag (dropped) + published_at: `2026-09-1${n % 9 + 1}T08:00:00Z`, + body: `notes for ${n}\nsee https://github.com/ranxianglei/billion-context for details`, + html_url: `https://github.com/ranxianglei/billion-context/releases/tag/v0.9.${100 - n}`, + ...over, + }; +} + +function fetchStub(body: unknown, status = 200): typeof fetch { + return ((url: string | URL | Request) => { + assert.equal(String(url), GH); + return Promise.resolve(new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } })); + }) as typeof fetch; +} + +const origFetch = globalThis.fetch; + +beforeEach(() => { + _resetChangelogForTest(); +}); +afterEach(() => { + _resetChangelogForTest(); + globalThis.fetch = origFetch; +}); + +test("maps GitHub releases: passthrough fields, newest-first order, 20-entry cap", async () => { + const feed: unknown[] = []; + for (let i = 0; i < 25; i++) feed.push(ghRelease(i)); // GitHub lists newest first + let hits = 0; + globalThis.fetch = ((..._a: unknown[]) => { hits += 1; return Promise.resolve(new Response(JSON.stringify(feed), { status: 200 })); }) as typeof fetch; + + const data = await getChangelog(); + assert.equal(data.error, undefined); + assert.equal(data.releases.length, 20); + assert.equal(hits, 1); + // Newest (feed[0]) first; order preserved verbatim. + assert.equal(data.releases[0].tag, "v0.9.100"); + assert.equal(data.releases[19].tag, "v0.9.81"); + // Passthrough mapping. + const r0 = data.releases[0]; + assert.equal(r0.name, "v0.9.100 — release 0"); + assert.equal(r0.publishedAt, "2026-09-11T08:00:00Z"); + assert.ok(r0.body?.includes("see https://github.com/")); + assert.match(r0.url, /^https:\/\/github\.com\/.*releases\/tag\//); + // Row with name === tag: field dropped, not duplicated in UI. + const r3 = data.releases[3]; + assert.equal(r3.tag, "v0.9.97"); + assert.equal(r3.name, undefined); + // Synchronous surface sees the same newest entry. + assert.equal(latestChangelog()?.tag, "v0.9.100"); +}); + +test("skips malformed rows without failing the feed", async () => { + const feed = [ghRelease(0), { id: 1 }, null, { tag_name: "no-url" }, ghRelease(1)]; + globalThis.fetch = fetchStub(feed); + const data = await getChangelog(); + assert.deepEqual(data.releases.map((r) => r.tag), ["v0.9.100", "v0.9.99"]); + assert.equal(data.error, undefined); +}); + +test("throttle: second read within TTL does not re-fetch; force bypasses", async () => { + let hits = 0; + globalThis.fetch = (() => { hits += 1; return Promise.resolve(fetchStub([ghRelease(0)])(GH)); }) as typeof fetch; + const first = await getChangelog(); + const second = await getChangelog(); // inside the 10-min window + assert.equal(hits, 1); + assert.deepEqual(second.releases, first.releases); + const forced = await getChangelog({ force: true }); + assert.equal(hits, 2); + assert.equal(forced.releases.length, 1); +}); + +test("network failure: resolves empty + error, never throws, latest stays undefined", async () => { + globalThis.fetch = (() => Promise.reject(new Error("ENOTFOUND"))) as typeof fetch; + const data = await getChangelog(); // must not reject + assert.deepEqual(data, { releases: [], error: "offline" }); + assert.equal(latestChangelog(), undefined); + // Failures are throttled too — no retry storm while offline. + let hits = 0; + globalThis.fetch = (() => { hits += 1; return Promise.reject(new Error("ECONNREFUSED")); }) as typeof fetch; + const again = await getChangelog(); + assert.equal(hits, 0); + assert.equal(again.error, "offline"); +}); + +test("keeps stale releases on failure and recovers on a successful forced check", async () => { + globalThis.fetch = fetchStub([ghRelease(0)]); + assert.equal((await getChangelog()).releases[0].tag, "v0.9.100"); + globalThis.fetch = (() => Promise.reject(new Error("EAI_AGAIN"))) as typeof fetch; + const failed = await getChangelog({ force: true }); + assert.equal(failed.error, "offline"); + assert.equal(failed.releases[0]?.tag, "v0.9.100"); // stale view retained + globalThis.fetch = fetchStub([ghRelease(5)]); + const ok = await getChangelog({ force: true }); + assert.equal(ok.error, undefined); + assert.equal(ok.releases[0]?.tag, "v0.9.95"); +}); + +test("HTTP 500 fails soft like a network error", async () => { + globalThis.fetch = fetchStub({}, 500); + const data = await getChangelog(); + assert.deepEqual(data, { releases: [], error: "offline" }); +}); + +test("non-array / non-object payloads fail soft", async () => { + globalThis.fetch = fetchStub({ message: "API rate limit exceeded" }); + let data = await getChangelog(); + assert.equal(data.releases.length, 0); + assert.equal(data.error, "offline"); + _resetChangelogForTest(); + globalThis.fetch = fetchStub('"just a string"'); + data = await getChangelog(); + assert.equal(data.releases.length, 0); + assert.equal(data.error, "offline"); +}); + +function fakeRes(): { res: ServerResponse; status: number | undefined; ct: unknown; body: string } { + const out: { res: ServerResponse; status: number | undefined; ct: unknown; body: string } = + { res: undefined as unknown as ServerResponse, status: undefined, ct: undefined, body: "" }; + out.res = { + writeHead(status: number, headers?: Record) { out.status = status; out.ct = headers?.["content-type"]; }, + end(chunk?: string) { if (chunk !== undefined) out.body += chunk; }, + } as unknown as ServerResponse; + return out; +} + +test("handleChangelogGet answers 200 JSON — cached path and offline path", async () => { + // Cached: no network needed once warm. + globalThis.fetch = fetchStub([ghRelease(0)]); + await getChangelog(); + const warm = fakeRes(); + const { handleChangelogGet } = await import("../src/web/changelog.ts"); + await handleChangelogGet(warm.res); + assert.equal(warm.status, 200); + assert.equal(warm.ct, "application/json"); + const parsed = JSON.parse(warm.body) as { releases: Array<{ tag: string }>; error?: string }; + assert.equal(parsed.releases[0].tag, "v0.9.100"); + assert.equal(parsed.error, undefined); + // Offline: still 200 so the panel degrades gracefully. + _resetChangelogForTest(); + globalThis.fetch = (() => Promise.reject(new Error("offline"))) as typeof fetch; + const cold = fakeRes(); + await handleChangelogGet(cold.res); + assert.equal(cold.status, 200); + const parsedCold = JSON.parse(cold.body) as { releases: unknown[]; error: string }; + assert.deepEqual(parsedCold.releases, []); + assert.equal(parsedCold.error, "offline"); +}); From 21041b2d169ad037b6ced4d827aa2487fa0dd033 Mon Sep 17 00:00:00 2001 From: ranxianglei Date: Wed, 21 Oct 2026 19:28:42 +0800 Subject: [PATCH 02/10] =?UTF-8?q?feat(web):=20dedicated=20Updates=20tab=20?= =?UTF-8?q?=E2=80=94=20notices,=20install/rollback=20buttons=20(#3719)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A nav tab parallel to config/connect holding everything self-update: running/disk version + last-check time, pushed release notices with tier badges, a forced check now, upgrade-now and install-specific- version actions (a selection below the running version confirms as a rollback), plus the changelog card moved here from overview. src/update.ts stays untouched: the new update-actions module only holds the process's UpdateOptions (registered once by the CLI alongside startAutoUpdate on the SAME object) and calls its existing exports — checkForUpdate(force) / forceInstallVersion / readDiskVersion / lastUpdateCheckTime — each behind an in-flight dedupe flag. Three new admin-gated routes (/__bili/update/state|check|install) follow the existing POST 400 shape and the DNS-rebinding origin gate. --- src/cli.ts | 12 +- src/server/admin.ts | 53 ++++++++ src/server/update-actions.ts | 151 ++++++++++++++++++++++ src/web/client.ts | 159 ++++++++++++++++++++++- src/web/i18n.ts | 52 ++++++++ src/web/page.ts | 29 ++++- src/web/styles.ts | 5 + tests/web-updates.test.ts | 236 +++++++++++++++++++++++++++++++++++ 8 files changed, 688 insertions(+), 9 deletions(-) create mode 100644 src/server/update-actions.ts create mode 100644 tests/web-updates.test.ts diff --git a/src/cli.ts b/src/cli.ts index 6df365edc3..540bf92d9b 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -32,6 +32,7 @@ import { configFile as defaultConfigFile } from "./paths.js"; import { log as loggerLog } from "./logger.js"; import { createAutoRestartHandler } from "./restart.js"; import { checkForUpdate, startAutoUpdate } from "./update.js"; +import { registerUpdateActions } from "./server/update-actions.js"; import { startAdvisoryWatcher, getAdvisoryState, advisoryDeferring, advisoryBlocksVersion, advisoryAwaitingFirstCheck } from "./advisory.js"; import { startReleaseNotesWatcher } from "./update-notes.js"; import { resolveProxy } from "./upstream-proxy.js"; @@ -730,11 +731,14 @@ export async function main(): Promise { if (opts.autoUpdate) { // Resolver reads opts fields per call, so web-UI hot-reload of proxy // settings (server.ts mutates opts in place) is picked up live (#609). - startAutoUpdate({ + // #3719: one shared options object — the background loop and the web + // 更新/Updates tab's manual actions run on identical throttle/lock/ + // proxy/advisory gates (registerUpdateActions is the only addition). + const updateOpts = { packageName: PACKAGE_NAME, currentVersion: VERSION, autoUpdate: true, - resolveProxy: (url) => resolveProxy(opts.routes, opts.proxy, url, opts.proxyFallback), + resolveProxy: (url: string) => resolveProxy(opts.routes, opts.proxy, url, opts.proxyFallback), updateTag: opts.updateTag, // F2 (review): an advisory whose target cannot be resolved on the // registry must not stall the normal self-update loop forever — @@ -761,7 +765,9 @@ export async function main(): Promise { log: loggerLog, destroyLingeringSockets: restartForceCloseOf(server), }), - }); + }; + startAutoUpdate(updateOpts); + registerUpdateActions(updateOpts); } // #1481: the advisory watcher runs independently of autoUpdate — its whole // point is to reach installs whose auto-update is off. diff --git a/src/server/admin.ts b/src/server/admin.ts index 36cbff1f65..13d75a708d 100644 --- a/src/server/admin.ts +++ b/src/server/admin.ts @@ -17,6 +17,7 @@ import { handlePluginAttribution, handlePluginCompact, handlePluginFork, handleP import { parseAgentProviderReport, recordAgentProviders, agentProviderRecipes, sanitizeAgentProviderField } from "../agent-providers.js"; import { defaultLogFile } from "../paths.js"; import { getUpdateVisibility, updateBannerPayload } from "../update-notes.js"; +import { installVersionAction, triggerManualCheck, updateActionsAvailable, updateStateSnapshot } from "./update-actions.js"; import { getUnrecognizedPathStats } from "./observability.js"; import { getStore } from "../persist.js"; import { BodyTooLargeError, headerValue, readBody } from "../server.js"; @@ -288,6 +289,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); + // #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 + // the state read normally and the action POSTs with fail-soft error strings. + if (req.method === "GET" && req.url === "/__bili/update/state") { + res.writeHead(200, { "content-type": "application/json" }); + res.end(JSON.stringify(await updateStateSnapshot(VERSION))); + return; + } + if (req.method === "POST" && req.url === "/__bili/update/check") return handleUpdateCheck(res); + if (req.method === "POST" && req.url === "/__bili/update/install") return handleUpdateInstall(req, res, log); if (req.method === "PUT" && req.url === "/__bili/config") { return handleConfigPut(req, res, () => { const fresh = loadOptions(); @@ -829,6 +841,47 @@ function handleConflictsClear(url: string, res: http.ServerResponse, log: (level res.end(JSON.stringify({ ok: true, cleared }, null, 2)); } +// ---- #3719: web 更新/Updates tab actions --------------------------------- + +/** POST /__bili/update/check — force one registry check through the shared + * update options (same lock/throttle/proxy gates as the background loop). + * Always HTTP 200: an unwired process answers {ok:false, error} so the panel + * can show the string verbatim instead of failing the fetch. */ +async function handleUpdateCheck(res: http.ServerResponse): Promise { + if (!updateActionsAvailable()) { + res.writeHead(200, { "content-type": "application/json" }); + res.end(JSON.stringify({ ok: false, error: "self-update not wired in this process" }, null, 2)); + return; + } + res.writeHead(200, { "content-type": "application/json" }); + res.end(JSON.stringify(await triggerManualCheck(), null, 2)); +} + +/** POST /__bili/update/install {"version":"x.y.z"} — pin a specific version + * (upgrade or rollback). Malformed JSON or a version outside plain semver + * characters → 400 like the other POSTs; execution always answers 200 + * {ok, error?} with the updater's own result shape. */ +async function handleUpdateInstall(req: http.IncomingMessage, res: http.ServerResponse, log: (level: string, msg: string) => void): Promise { + let rawVersion: string | undefined; + try { + const doc: unknown = JSON.parse((await readBody(req)).toString("utf8")); + if (doc && typeof doc === "object" && typeof (doc as { version?: unknown })["version"] === "string") rawVersion = (doc as { version: string })["version"]; + } catch { + res.writeHead(400, { "content-type": "application/json" }); + res.end(JSON.stringify({ error: 'expected JSON body {"version": ""}' }, null, 2)); + return; + } + const version = rawVersion?.trim(); + if (version === undefined || version.length === 0 || !/^[0-9A-Za-z.+-]+$/.test(version)) { + res.writeHead(400, { "content-type": "application/json" }); + res.end(JSON.stringify({ error: "version must be plain semver characters (digits, dots, +, -) only" }, null, 2)); + return; + } + log("info", `[update] web panel requested install ${version}`); + res.writeHead(200, { "content-type": "application/json" }); + res.end(JSON.stringify(await installVersionAction(version), null, 2)); +} + // #2861: server-side dismissal of a host-plugin notice (body {"id": string}). async function handleHostPluginDismiss(req: http.IncomingMessage, res: http.ServerResponse, log: (level: string, msg: string) => void): Promise { let id = ""; diff --git a/src/server/update-actions.ts b/src/server/update-actions.ts new file mode 100644 index 0000000000..a49015e514 --- /dev/null +++ b/src/server/update-actions.ts @@ -0,0 +1,151 @@ +/** + * Web 更新/Updates tab — wiring point for self-update ACTIONS (#3719). + * + * src/update.ts stays load-bearing and human-gated: this module never edits + * the updater, it only holds THIS process's UpdateOptions (registered once by + * the CLI alongside startAutoUpdate — the SAME object the background loop + * runs on) and exposes guarded actions on top of its existing exports: + * - a forced registry check → checkForUpdate(opts, true) + * - a pinned-version install → forceInstallVersion(v, dir, opts, "web-panel") + * (upgrade to a newer release OR rollback to an older one) + * Each action carries one in-process dedupe flag so the panel cannot stack + * concurrent runs — a second concurrent caller gets {ok:true, already:true} + * instead of a duplicate registry/install storm. An unregistered process + * (autoUpdate off, embedded use, tests) degrades to plain error strings; + * nothing here throws into the HTTP handlers. + */ +import { checkForUpdate, findInstallDir, forceInstallVersion, lastUpdateCheckTime, readDiskVersion, staleInstallStatus, type UpdateOptions } from "../update.js"; +import { getUpdateVisibility } from "../update-notes.js"; +import { log as loggerLog } from "../logger.js"; + +/** One pushed release note mapped for the wire (span entries are oldest→newest). */ +export interface UpdateNotice { + version: string; + tier: "routine" | "recommended" | "critical"; + summary: string; + date?: string; +} + +export interface UpdateStateSnapshotData { + /** This process's version (package.json at startup). */ + running: string; + /** On-disk version if resolvable (undefined = unknown → UI shows "—"). */ + disk?: string; + /** Disk strictly newer than running — a host restart finishes the update. */ + pendingRestart: boolean; + /** A critical-tier entry sits in the pushed span (#1977 surfaces). */ + critical: boolean; + /** Pushed notices between running and the newest known release (oldest→newest). */ + notices: UpdateNotice[]; + /** Epoch ms of the last completed registry check; undefined = never. */ + lastCheckAt?: number; + /** True while a manual check is in flight in this process. */ + checking: boolean; + /** True while a pinned install is in flight in this process. */ + installing: boolean; +} + +let registeredOpts: UpdateOptions | undefined; +let checking = false; +let installing = false; + +/** CLI seam: store THIS process's live UpdateOptions (the same object passed + * to startAutoUpdate) so the web panel can drive the updater in-process. */ +export function registerUpdateActions(opts: UpdateOptions): void { + registeredOpts = opts; +} + +/** False when the CLI never registered options (autoUpdate off / embedded / tests). */ +export function updateActionsAvailable(): boolean { + return registeredOpts !== undefined; +} + +/** Loose semver shape check for panel input — optional v prefix, prerelease/ + * build suffixes tolerated. Anything else (spaces, shell metachars, …) is + * rejected before it ever reaches the updater. */ +function looksLikeSemver(v: string): boolean { + return /^v?[0-9]+\.[0-9]+\.[0-9]+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/.test(v); +} + +/** Force ONE registry check through the shared update options — same lock, + * throttle and proxy gates as the background loop (force=true skips the + * throttle window and advisory deferrals by design). A concurrent second + * call reports {ok:true, already:true}; network failures come back as + * {ok:false, error} — never a throw. */ +export async function triggerManualCheck(): Promise<{ ok: boolean; error?: string; already?: boolean }> { + const opts = registeredOpts; + if (opts === undefined) return { ok: false, error: "self-update not wired in this process" }; + if (checking) return { ok: true, already: true }; + checking = true; + try { + await checkForUpdate(opts, true); + return { ok: true }; + } catch (e) { + loggerLog("warn", `[update] manual web check failed: ${String(e)}`); + return { ok: false, error: String(e) }; + } finally { + checking = false; + } +} + +/** Pin ONE specific version onto this install (upgrade OR rollback to an + * older release). One install at a time — a concurrent second call gets + * {ok:true, already:true} while the first finishes. Never throws. */ +export async function installVersionAction(v: string): Promise<{ ok: boolean; error?: string; already?: boolean }> { + const opts = registeredOpts; + if (opts === undefined) return { ok: false, error: "self-update not wired in this process" }; + if (installing) return { ok: true, already: true }; + if (!looksLikeSemver(v)) return { ok: false, error: `version shape rejected: ${v}` }; + installing = true; + loggerLog("info", `[update] web panel install attempt: ${v}`); + try { + // Same resolution the background loop uses: explicit override wins + // (test seam), otherwise walk up from the running module (#1628). + const dir = opts.installDir ?? (await findInstallDir(opts.packageName)); + const result = await forceInstallVersion(v, dir, opts, "web-panel"); + loggerLog(result.ok ? "info" : "warn", `[update] web panel install ${v}: ${result.ok ? "installed — restart the host to finish" : `failed (${result.error})`}`); + return result; + } catch (e) { + loggerLog("warn", `[update] web panel install ${v} threw: ${String(e)}`); + return { ok: false, error: String(e) }; + } finally { + installing = false; + } +} + +/** Panel state read — no network by construction (the registry is only ever + * touched behind an explicit check/install action). Async only because the + * last-check timestamp and the fresh on-disk version read touch the + * filesystem. Falls back to the release-notes watcher's cached disk view + * when the install dir cannot be resolved. */ +export async function updateStateSnapshot(runningVersion: string): Promise { + const vis = getUpdateVisibility(runningVersion); + let disk = vis.diskVersion; + const opts = registeredOpts; + if (opts !== undefined) { + try { + const dir = opts.installDir ?? (await findInstallDir(opts.packageName)); + if (dir !== undefined) disk = (await readDiskVersion(dir)) ?? disk; + } catch { + // keep the watcher's cached view + } + } + const lastCheckAt = await lastUpdateCheckTime(); + return { + running: runningVersion, + ...(disk !== undefined ? { disk } : {}), + pendingRestart: disk !== undefined ? staleInstallStatus(disk, runningVersion) === "restart" : vis.pendingRestart, + critical: vis.critical, + notices: vis.span.map((e) => ({ version: e.version, tier: e.tier, summary: e.summary, ...(e.date !== undefined ? { date: e.date } : {}) })), + ...(lastCheckAt !== undefined ? { lastCheckAt } : {}), + checking, + installing, + }; +} + +/** Test seam: clear the registered options and both in-flight flags. */ +export function _resetUpdateActionsForTest(): void { + registeredOpts = undefined; + checking = false; + installing = false; +} diff --git a/src/web/client.ts b/src/web/client.ts index e2a9ae51ff..e355ea22c5 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", "connect", "logs"]; + const PAGES = ["overview", "sessions", "config", "updates", "connect", "logs"]; let current = "overview"; let sessionsCache = []; // #1682: last overview alert payload — lets a dismiss re-render without refetching. @@ -691,6 +691,150 @@ export const WEB_CLIENT = `(function () { } } + // #3719 phase 2: dedicated 更新/Updates tab — self-update state, pushed + // notices, and install/rollback actions. All writes go through the + // admin-gated POST /__bili/update/* routes (same json() pattern as + // putCfg); one shared in-flight flag keeps ALL action buttons disabled + // while any action runs (the server dedupes a second call too). + let upBusyAction = false; + let upReleases = []; + function upSetButtons(on) { + [$("up-check"), $("up-upgrade-now"), $("up-install")].forEach((b) => { + if (!b) return; + b.classList.toggle("busy", on); + b.disabled = on; + }); + // Install-selected additionally needs an actual selection. + const ins = $("up-install"); + const sel = $("up-select"); + if (ins) ins.disabled = on || !(sel && sel.value); + } + function showUpdateResult(msg, ok) { + const el = $("up-result"); + if (!el || !msg) return; + el.hidden = false; + el.textContent = msg; + el.style.color = ok ? "var(--green)" : "var(--red)"; + } + // Loose numeric compare on major/minor/patch — enough to decide the + // rollback confirm without pulling semver into the panel. + function upVerParts(v) { + return String(v || "").replace(/^v/i, "").split(/[.+]/).slice(0, 3).map((p) => parseInt(p, 10)); + } + function upCmpVer(a, b) { + const x = upVerParts(a); + const y = upVerParts(b); + for (let i = 0; i < 3; i++) { + const d = (x[i] || 0) - (y[i] || 0); + if (d !== 0) return d < 0 ? -1 : 1; + } + return 0; + } + function renderNotices(items) { + const el = $("up-notices"); + if (!el) return; + if (!items.length) { el.textContent = t("up.notice_empty"); return; } + let html = ""; + items.slice().reverse().forEach((n) => { + const tier = n.tier === "critical" ? "critical" : (n.tier === "recommended" ? "recommended" : "routine"); + // Fully literal keys below: the i18n dead-key scanner (#1024) + // greps t() call sites and would flag a dynamically built + // tier-prefix key. + const tierLabel = tier === "critical" ? t("up.tier_critical") : (tier === "recommended" ? t("up.tier_recommended") : t("up.tier_routine")); + html += '
' + escapeHtml(tierLabel) + "" + escapeHtml(String(n.version || "")) + "" + (n.date ? ' ' + escapeHtml(String(n.date)) + "" : "") + "
" + escapeHtml(String(n.summary || "")) + "
"; + }); + el.innerHTML = html; + } + // Newest release known to the panel: the newest pushed notice wins, the + // changelog tag list is the fallback (tags arrive newest-first, capped at + // what the endpoint returns). Leading "v" is stripped before install — + // the updater takes plain semver. + function upNewestVersion(notices) { + if (notices && notices.length) return String(notices[notices.length - 1].version || ""); + return String(upReleases[0] || "").replace(/^v/, ""); + } + function applyUpdateButtons(st) { + const now = $("up-upgrade-now"); + const target = upNewestVersion(st && st.notices); + if (now) { + const lbl = $("up-upgrade-now-label"); + if (lbl) lbl.textContent = target ? t("up.upgrade_now", { v: target }) : t("up.upgrade_none"); + now.disabled = upBusyAction || !target; + } + } + function renderUpdateState(st) { + if (!st || typeof st !== "object") return; + const set = (id, text) => { const el = $(id); if (el) el.textContent = text; }; + set("up-running", st.running || "?"); + set("up-disk", st.disk || t("common.none")); + set("up-latest", upNewestVersion(st.notices) || t("common.none")); + set("up-last-check", st.lastCheckAt ? new Date(st.lastCheckAt).toLocaleString() : t("common.none")); + const hint = $("up-pending-hint"); + if (hint) hint.hidden = !st.pendingRestart; + renderNotices(Array.isArray(st.notices) ? st.notices : []); + const sel = $("up-select"); + if (sel) { + const cur = sel.value; + let opt = '"; + upReleases.forEach((tag) => { opt += '"; }); + sel.innerHTML = opt; + if (cur) sel.value = cur; + } + applyUpdateButtons(st); + // A check/install started from another tab of this process shows in + // the snapshot — keep the buttons held down until it settles. + if (st.checking || st.installing) upSetButtons(true); + } + async function loadUpdates() { + try { + const [st, cl] = await Promise.all([json(API_ROOT + "/update/state"), json(API_ROOT + "/changelog")]); + upReleases = (cl && Array.isArray(cl.releases)) ? cl.releases.map((r) => String(r.tag || "")).filter(Boolean) : []; + renderUpdateState(st); + } catch (e) { + // Both endpoints are fail-soft 200s; reaching here = proxy unreachable. + toast(t("toast.failed", { msg: e.message }), "err"); + } + } + async function upInstall(version) { + if (upBusyAction || !version) return; + const running = $($("up-running") && "up-running") ? $("up-running").textContent.replace(/^v/i, "") : ""; + if (upCmpVer(version, running) < 0 && !window.confirm(t("up.rollback_confirm", { v: version }))) return; + upBusyAction = true; + upSetButtons(true); + showUpdateResult(t("up.installing", {}), true); + try { + const r = await json(API_ROOT + "/update/install", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ version: version }) }); + if (r.already) showUpdateResult(t("up.already_in_flight"), true); + else if (r.ok) showUpdateResult(t("up.installed", { v: version }), true); + else showUpdateResult(String(r.error || t("toast.failed", { msg: "install failed" })), false); + } catch (e) { + showUpdateResult(e.message, false); + } finally { + upBusyAction = false; + upSetButtons(false); + loadUpdates(); + } + } + function upUpgradeNow() { upInstall(upNewestVersion(null).replace(/^v/, "")); } + function upInstallSelected() { const sel = $("up-select"); if (sel && sel.value) upInstall(String(sel.value).replace(/^v/, "")); } + async function upCheckNow() { + if (upBusyAction) return; + upBusyAction = true; + upSetButtons(true); + try { + const r = await json(API_ROOT + "/update/check", { method: "POST", headers: { "content-type": "application/json" }, body: "{}" }); + if (r.already) showUpdateResult(t("up.already_in_flight"), true); + else if (r.ok) showUpdateResult(t("up.check_ok"), true); + else showUpdateResult(String(r.error || t("toast.failed", { msg: "check failed" })), false); + } catch (e) { + showUpdateResult(e.message, false); + } finally { + upBusyAction = false; + upSetButtons(false); + loadUpdates(); + } + } + async function loadOverview(silent) { try { const d = await json(API_ROOT + "/overview"); @@ -3513,7 +3657,7 @@ 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|connect|logs)$")); + const top = hbase.match(new RegExp("^#/(overview|config|updates|connect|logs)$")); if (top) { name = top[1]; if (name === "logs" && hq) applyLogFilter(hq); @@ -3533,6 +3677,7 @@ if (d.keepalive) kv(parts, t("det.keepalive"), d.keepalive.tierLabel + " · " + if (name === "overview") loadOverview(); else if (name === "sessions") loadSessions(detailId); else if (name === "config") loadConfig(); + else if (name === "updates") loadUpdates(); else if (name === "logs") loadLogs(); } window.addEventListener("hashchange", route); @@ -3571,6 +3716,16 @@ if (d.keepalive) kv(parts, t("det.keepalive"), d.keepalive.tierLabel + " · " + if (prev) prev.addEventListener("click", () => goToSessionPage(sesPage - 1)); const next = $("ses-next"); if (next) next.addEventListener("click", () => goToSessionPage(sesPage + 1)); + // #3719 phase 2: 更新/Updates tab actions — check now / upgrade now / + // install selected. One shared in-flight flag (see upSetButtons). + const uchk = $("up-check"); + if (uchk) uchk.addEventListener("click", () => upCheckNow()); + const unow = $("up-upgrade-now"); + if (unow) unow.addEventListener("click", () => upUpgradeNow()); + const usel = $("up-select"); + const unins = $("up-install"); + if (usel) usel.addEventListener("change", () => { if (unins) unins.disabled = upBusyAction || !usel.value; }); + if (unins) unins.addEventListener("click", () => upInstallSelected()); let logTimer = null; const lsearch = $("log-search"); if (lsearch) lsearch.addEventListener("input", () => { clearTimeout(logTimer); logTimer = setTimeout(loadLogs, 400); }); diff --git a/src/web/i18n.ts b/src/web/i18n.ts index 6b0052a16d..29a2b95557 100644 --- a/src/web/i18n.ts +++ b/src/web/i18n.ts @@ -30,6 +30,7 @@ export const MESSAGES: Record> = { "nav.overview": "总览", "nav.sessions": "会话", "nav.config": "配置", + "nav.updates": "更新", "nav.connect": "接入", "nav.logs": "日志", "logs.title": "运行日志", @@ -109,6 +110,31 @@ export const MESSAGES: Record> = { "sys.changelog_offline": "加载失败(可能离线)——稍后重试", "sys.changelog_view": "在 GitHub 查看", "sys.changelog_all": "全部版本(GitHub Releases)", + // #3719 phase 2: dedicated 更新/Updates tab + "up.title": "更新", + "up.sub": "版本状态、推送信息与版本安装(含回退)", + "up.version": "当前版本 Current version", + "up.running": "运行中 Running", + "up.disk": "磁盘上 Disk", + "up.latest_known": "最新已知 Latest known", + "up.last_check": "上次检查 Last checked", + "up.pending_hint": "磁盘已是新版本 —— 重启宿主后生效。", + "up.check_now": "立即检查 Check now", + "up.notices": "推送信息 Notices", + "up.notice_empty": "暂无推送 No notices yet", + "up.tier_critical": "关键 critical", + "up.tier_recommended": "推荐 recommended", + "up.tier_routine": "例行 routine", + "up.install": "版本安装 Install", + "up.upgrade_none": "(暂无已知的更新版本)", + "up.upgrade_now": "立即升级到 {v} Upgrade now", + "up.install_selected": "安装所选版本 Install selected", + "up.select_placeholder": "选择版本… Select a version…", + "up.installing": "正在处理… in flight…", + "up.already_in_flight": "已有操作在进行中… an operation is already in flight…", + "up.rollback_confirm": "所选版本低于运行中的版本,将回退到 {v},重启宿主后生效,继续?", + "up.check_ok": "检查完成 check finished", + "up.installed": "已安装 {v} —— 重启宿主后生效", "sys.update": "升级提醒:", "sys.update_available": "发现 critical 修复,请升级到 v{version} 或更新版本 — {summary}", "sys.update_ready": "critical 修复已就绪 v{version} — 重启 bili 即可生效", @@ -578,6 +604,7 @@ export const MESSAGES: Record> = { "nav.overview": "Overview", "nav.sessions": "Sessions", "nav.config": "Configuration", + "nav.updates": "Updates", "nav.connect": "Connect", "nav.logs": "Logs", "logs.title": "Run log", @@ -657,6 +684,31 @@ export const MESSAGES: Record> = { "sys.changelog_offline": "Could not load release notes (offline?) — retry later", "sys.changelog_view": "View on GitHub", "sys.changelog_all": "All releases (GitHub Releases)", + // #3719 phase 2: dedicated Updates tab + "up.title": "Updates", + "up.sub": "Version status, pushed notices & version install (incl. rollback)", + "up.version": "Current version", + "up.running": "Running", + "up.disk": "On disk", + "up.latest_known": "Latest known", + "up.last_check": "Last checked", + "up.pending_hint": "A newer version is already on disk — it takes effect after restarting the host.", + "up.check_now": "Check now", + "up.notices": "Notices", + "up.notice_empty": "No notices yet", + "up.tier_critical": "critical", + "up.tier_recommended": "recommended", + "up.tier_routine": "routine", + "up.install": "Install version", + "up.upgrade_none": "(no newer version known)", + "up.upgrade_now": "Upgrade now to {v}", + "up.install_selected": "Install selected", + "up.select_placeholder": "Select a version…", + "up.installing": "In flight…", + "up.already_in_flight": "An operation is already in flight…", + "up.rollback_confirm": "The selected version is OLDER than the running one — this rolls back to {v}. It takes effect after restarting the host. Continue?", + "up.check_ok": "Check finished", + "up.installed": "{v} installed — takes effect after restarting the host", "sys.update": "Update notice:", "sys.update_available": "critical fix available — upgrade to v{version} or newer: {summary}", "sys.update_ready": "critical fix ready (v{version}) — restart bili to apply", diff --git a/src/web/page.ts b/src/web/page.ts index 42031b2966..cc4addacec 100644 --- a/src/web/page.ts +++ b/src/web/page.ts @@ -19,7 +19,7 @@ export function renderPage(origin: string, version: string, embed = false, theme const caPathEsc = escapeHtml(caPath); const caReady = existsSync(caPath); return `billion-context -
billion-contextv${version}
+
billion-contextv${version}
@@ -55,9 +55,6 @@ export function renderPage(origin: string, version: string, embed = false, theme
${zh("sys.inflight")}
0
${zh("sys.blind_tunnels")}
0
- -
${zh("sys.changelog")}
${zh("ov.recent")}${zh("ov.view_all")}
${zh("ses.th_title")}${zh("ses.th_client")}${zh("ses.th_proto")}${zh("ses.th_upstream")}${zh("ses.th_reqs")}${zh("ses.th_ctx")}${zh("ses.th_input")}${zh("ses.th_saved")}${zh("ses.th_hit")}${zh("ses.th_switches")}${zh("ses.th_folds")}${zh("ses.th_blocks")}${zh("ses.th_seen")}
@@ -116,6 +113,30 @@ fetched lazily by client.js into #changelog-body (collapsed by default). -->
${zh("cfg.resign")}

${zh("cfg.resign_desc")}

${zh("cfg.resign_loading")}
+ + -
${zh("ses.th_title")}${zh("ses.th_client")}${zh("ses.th_proto")}${zh("ses.th_upstream")}${zh("ses.th_reqs")}${zh("ses.th_ctx")}${zh("ses.th_input")}${zh("ses.th_saved")}${zh("ses.th_hit")}${zh("ses.th_switches")}${zh("ses.th_folds")}${zh("ses.th_blocks")}${zh("ses.th_seen")}