diff --git a/.github/workflows/release-notes.yml b/.github/workflows/release-notes.yml index 64775b19c6..bca4b2cbd3 100644 --- a/.github/workflows/release-notes.yml +++ b/.github/workflows/release-notes.yml @@ -77,6 +77,27 @@ jobs: console.error(e.version, ': date must be YYYY-MM-DD, got', JSON.stringify(e.date)); process.exit(1); } + // #3719 item4: optional bilingual summary + version targeting. + if (e.summaryZh !== undefined && (typeof e.summaryZh !== 'string' || !e.summaryZh.trim())) { + console.error(e.version, ': summaryZh must be a non-empty string when present'); + process.exit(1); + } + if (e.summaryZh !== undefined && e.summaryZh.length > 400) { + console.error(e.version, ': summaryZh too long (' + e.summaryZh.length + ' chars, cap 400)'); + process.exit(1); + } + if (e.minVersion !== undefined && !semver.valid(e.minVersion)) { + console.error(e.version, ': minVersion must be valid semver, got', JSON.stringify(e.minVersion)); + process.exit(1); + } + if (e.maxVersion !== undefined && !semver.valid(e.maxVersion)) { + console.error(e.version, ': maxVersion must be valid semver, got', JSON.stringify(e.maxVersion)); + process.exit(1); + } + if (e.minVersion !== undefined && e.maxVersion !== undefined && semver.gt(e.minVersion, e.maxVersion)) { + console.error(e.version, ': minVersion must be <= maxVersion'); + process.exit(1); + } } " diff --git a/release-notes/README.md b/release-notes/README.md index 91558f0007..a39a5caeb5 100644 --- a/release-notes/README.md +++ b/release-notes/README.md @@ -24,6 +24,9 @@ Companion package mechanics mirror `advisories/` (#1481): | date | no | `YYYY-MM-DD` release date | | tier | yes | `routine` (default) / `recommended` (restart soon, record-only) / `critical` (see below) | | summary | yes | One user-meaningful line, ≤400 chars, model-written| +| summaryZh | no | Chinese one-liner (≤400 chars) — zh-locale web surfaces pick it; `/acp` text stays English. Unset = every locale uses `summary` | +| minVersion | no | Targeting: only RUNNING versions ≥ this (inclusive) see the entry. Unset = no floor | +| maxVersion | no | Targeting: only RUNNING versions ≤ this (inclusive) see the entry. Unset = no ceiling | Rules: newest-first, ≤20 entries, no duplicates. **Entries are opt-in since 2026-10-04**: only severe releases get one; ordinary releases ship with NO diff --git a/src/agent/dsh-native-client.ts b/src/agent/dsh-native-client.ts index 31c90ac83c..da5305fb9f 100644 --- a/src/agent/dsh-native-client.ts +++ b/src/agent/dsh-native-client.ts @@ -94,13 +94,14 @@ const SLOW_POLL_INTERVAL_MS = 10000; // the web UI's own nav terminology (src/web/i18n.ts) so each tab reads like // the title of the page inside the frame. "connect" stays out: it documents // how OTHER clients reach this proxy, which makes no sense from inside dsh. -const PAGE_IDS = ["overview", "sessions", "config", "logs"] as const; +const PAGE_IDS = ["overview", "sessions", "config", "logs", "updates"] as const; type PageId = (typeof PAGE_IDS)[number]; const PAGE_KEYS: Record = { overview: "tab_overview", sessions: "tab_sessions", config: "tab_config", logs: "tab_logs", + updates: "tab_updates", }; // #3816: the exact field a remote user adds to enable the #3373 relay. A @@ -358,6 +359,7 @@ const zh: Dict = { "tab_sessions": "会话", "tab_config": "配置", "tab_logs": "日志", + "tab_updates": "版本", "tab_ctx": "上下文", "ctx_waiting": "等待首个模型请求…", "ctx_nodata": "暂无上下文数据——完成一次模型请求后自动刷新。", @@ -378,6 +380,7 @@ const en: Dict = { "tab_sessions": "Sessions", "tab_config": "Config", "tab_logs": "Logs", + "tab_updates": "Versions", "tab_ctx": "Context", "ctx_waiting": "Waiting for the first model request…", "ctx_nodata": "No context data yet — refreshes automatically after the first model request.", diff --git a/src/cli.ts b/src/cli.ts index 6df365edc3..e8f0ed8cfc 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"; @@ -727,14 +728,16 @@ export async function main(): Promise { // Start background auto-update after the server is listening so a slow // registry check never delays startup or races the listen socket. - 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({ + // 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). + // #3719: one shared options object — the background loop and the web + // 更新/Updates tab's manual actions run on identical throttle/lock/ + // proxy/advisory gates. + 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,8 +764,13 @@ export async function main(): Promise { log: loggerLog, destroyLingeringSockets: restartForceCloseOf(server), }), - }); + }; + // The manual channel is independent of the auto channel: installs whose + // auto-update is off still need the panel's 立即检查/升级 buttons to work. + if (opts.autoUpdate) { + startAutoUpdate(updateOpts); } + registerUpdateActions(updateOpts); // #1481: the advisory watcher runs independently of autoUpdate — its whole // point is to reach installs whose auto-update is off. if (opts.advisoryCheck) { 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 d22f1ee82e..39974a2a3f 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"; @@ -31,6 +32,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, buildSessionTree, 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"; @@ -294,6 +296,21 @@ 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); + // #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(); @@ -835,6 +852,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..db08a9a159 --- /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). */ +interface UpdateNotice { + version: string; + tier: "routine" | "recommended" | "critical"; + summary: string; + date?: string; +} + +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.summaryZh ? { summaryZh: e.summaryZh } : {}), ...(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/update-notes.ts b/src/update-notes.ts index ca149b52ec..c74b517269 100644 --- a/src/update-notes.ts +++ b/src/update-notes.ts @@ -49,6 +49,14 @@ export type ReleaseNoteEntry = { tier: ReleaseTier; /** Model-written, user-meaningful one-liner (what changes for you). */ summary: string; + /** Optional Chinese one-liner (#3719 item4): web surfaces pick it when + * the UI locale is zh; /acp text stays English (compat boundary). */ + summaryZh?: string; + /** Optional targeting (#3719 item4): only RUNNING versions inside + * [minVersion, maxVersion] (inclusive) see this entry. Unset = + * everyone — historic entries keep their default reach untouched. */ + minVersion?: string; + maxVersion?: string; }; type ReleaseNotesState = { @@ -111,11 +119,20 @@ export function parseReleaseNotesDoc(raw: unknown): { entries: ReleaseNoteEntry[ const version = typeof e.version === "string" ? e.version.trim() : ""; const tier = e.tier === "recommended" || e.tier === "routine" || e.tier === "critical" ? e.tier : undefined; const summary = typeof e.summary === "string" ? e.summary.trim() : ""; + const summaryZh = typeof e.summaryZh === "string" ? e.summaryZh.trim() : ""; + const minVersion = typeof e.minVersion === "string" ? e.minVersion.trim() : ""; + const maxVersion = typeof e.maxVersion === "string" ? e.maxVersion.trim() : ""; if (!semver.valid(version) || tier === undefined || !summary) continue; + if (minVersion && !semver.valid(minVersion)) continue; + if (maxVersion && !semver.valid(maxVersion)) continue; + if (minVersion && maxVersion && semver.gt(minVersion, maxVersion)) continue; entries.push({ version, tier, summary, + ...(summaryZh ? { summaryZh } : {}), + ...(minVersion ? { minVersion } : {}), + ...(maxVersion ? { maxVersion } : {}), ...(typeof e.date === "string" && e.date.trim() ? { date: e.date.trim() } : {}), }); } @@ -134,7 +151,13 @@ export function spanNotes(entries: ReleaseNoteEntry[], fromVersion: string): Rel return entries .filter((e) => { try { - return semver.gt(e.version, fromVersion); + if (!semver.gt(e.version, fromVersion)) return false; + // #3719 item4: optional targeting — the entry only reaches + // RUNNING versions inside [minVersion, maxVersion] (inclusive). + // Unset bounds keep the pre-targeting reach (compat). + if (e.minVersion !== undefined && semver.lt(fromVersion, e.minVersion)) return false; + if (e.maxVersion !== undefined && semver.gt(fromVersion, e.maxVersion)) return false; + return true; } catch { return false; } @@ -214,16 +237,16 @@ export function describeUpdateReady(v: UpdateVisibility): string { * (first critical in the ascending span; anything ≥ it is safe). * ready → version = the on-disk version a restart delivers. * null when the span is invisible (#1977: routine/recommended stay silent). */ -export function updateBannerPayload(v: UpdateVisibility & { visible: boolean }): { kind: "available" | "ready"; version: string; summary: string } | null { +export function updateBannerPayload(v: UpdateVisibility & { visible: boolean }): { kind: "available" | "ready"; version: string; summary: string; summaryZh?: string } | null { if (!v.visible) return null; const criticals = v.span.filter((e) => e.tier === "critical"); const first = criticals[0]; const newest = criticals[criticals.length - 1] ?? first; if (first === undefined || newest === undefined) return null; // defensive: visible implies a critical, but stay total if (v.pendingRestart && v.diskVersion !== undefined) { - return { kind: "ready", version: v.diskVersion, summary: newest.summary }; + return { kind: "ready", version: v.diskVersion, summary: newest.summary, ...(newest.summaryZh ? { summaryZh: newest.summaryZh } : {}) }; } - return { kind: "available", version: first.version, summary: first.summary }; + return { kind: "available", version: first.version, summary: first.summary, ...(first.summaryZh ? { summaryZh: first.summaryZh } : {}) }; } function throttleFile(): string { diff --git a/src/web/changelog.ts b/src/web/changelog.ts new file mode 100644 index 0000000000..e621352c7a --- /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"; + +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; +}; + +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 2e868368f1..320d197a7d 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. @@ -647,6 +647,274 @@ 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 changelogCatOf(rawLine) { + const s = rawLine.replace(/^\\*?\\s*\\[PR\\]\\s*/i, "").trim(); + if (/^kernel([(:\\s]|$)/i.test(s)) return "cat_kernel"; + if (/(^|[.(,\\s])(dsh|pi(?:-subagents)?|codex|claude(?:-code)?|opencode(?:v?\\d)?|hermes|kimi|zcode|trae)([):,\\s]|$)/i.test(s)) return "cat_host"; + const m = s.match(/^([a-z]+)(\\([^)]*\\))?[:\\s]/); + if (m) { + const p = m[1].toLowerCase(); + if (p === "feat" || p === "feature" || p === "improve") return "cat_feat"; + if (p === "fix" || p === "perf") return "cat_fix"; + if (p === "docs") return "cat_web"; + if (p === "ci" || p === "build" || p === "test" || p === "chore" || p === "refactor" || p === "style") return "cat_infra"; + } + if (/(persist|storage|session|sqlite|index\\.db|unified)/i.test(s)) return "cat_store"; + if (/(self-update|auto-update|update policy|release|publish|stagger|version bump)/i.test(s)) return "cat_upd"; + if (/\\b(web|panel|i18n|changelog|favicon)\\b/i.test(s)) return "cat_web"; + return "cat_other"; + } + const CHLOG_CATS = ["cat_feat", "cat_fix", "cat_kernel", "cat_host", "cat_store", "cat_upd", "cat_web", "cat_infra", "cat_other"]; + // One release body → intro (headings/prose) + categorized bullet groups. + function changelogBodyHtml(escaped) { + const intro = []; + let para = []; + const flushPara = () => { if (para.length) { intro.push('
' + para.map((s)=>s.replace(/\\*\\*([^*]+)\\*\\*/g,"$1")).join("
") + "
"); para = []; } }; + const cats = {}; + for (const raw of escaped.split("\\n")) { + const tl = raw.trim(); + const bm = tl.match(/^(?:[-*]|\\d+[.)])\\s+(.*)$/); + if (bm) { + flushPara(); + const item = linkifyText(bm[1]); + const key = changelogCatOf(bm[1]); + if (!cats[key]) cats[key] = []; + cats[key].push(item); + } else if (/^#{1,6}\\s/.test(tl)) { + flushPara(); + intro.push('
' + linkifyText(tl.replace(/^#{1,6}\\s*/, "")) + "
"); + } else if (tl === "") flushPara(); + else para.push(linkifyText(tl)); + } + flushPara(); + let html = intro.join(""); + for (const key of CHLOG_CATS) { + const items = cats[key]; + if (!items) continue; + // Inline t() per key: the #1024 scanner counts literal t("…") refs only. + const label = { cat_feat: t("sys.changelog_cat_feat"), cat_fix: t("sys.changelog_cat_fix"), cat_kernel: t("sys.changelog_cat_kernel"), cat_host: t("sys.changelog_cat_host"), cat_store: t("sys.changelog_cat_store"), cat_upd: t("sys.changelog_cat_upd"), cat_web: t("sys.changelog_cat_web"), cat_infra: t("sys.changelog_cat_infra"), cat_other: t("sys.changelog_cat_other") }[key]; + html += '
' + label + ' ' + items.length + "
" + items.map(function (x) { return '
' + x + "
"; }).join(""); + } + return html; + } + // Version-select → scroll that release open and flash it briefly. + function focusChangelogRelease(val) { + const el = $("changelog-body"); + if (!el) return; + const want = String(val).replace(/^v/, ""); + const items = el.querySelectorAll("details.cl-item"); + if (typeof items.forEach !== "function") return; + items.forEach((it) => { + const hit = String(it.getAttribute("data-tag") || "").replace(/^v/, "") === want; + try { it.open = hit; } catch (_) { /* harness */ } + it.classList.remove("cl-flash"); + }); + const target = el.querySelector('details.cl-item[data-tag="' + want.replace(/"/g, "") + '"]'); + if (!target) return; + try { target.open = true; } catch (_) { /* harness */ } + target.classList.add("cl-flash"); + if (target.scrollIntoView) target.scrollIntoView({ behavior: "smooth", block: "start" }); + setTimeout(() => target.classList.remove("cl-flash"), 2500); + } + 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 tagRaw = String(r.tag || ""); + const tag = escapeHtml(tagRaw); + const dataTag = tagRaw.replace(/^v/, "").replace(/"/g, ""); + const name = (typeof r.name === "string" && r.name !== r.tag) ? escapeHtml(r.name) + " · " : ""; + const latest = i === 0 ? ' ' + t("sys.changelog_latest") + "" : ""; + 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() ? '
' + changelogBodyHtml(escapeHtml(r.body)) + '
' + view + "
" : view; + html += '
' : '">' ) + '' + tag + "" + name + latest + date + "" + body + "
"; + }); + html += '
' + t("sys.changelog_all") + "
"; + el.innerHTML = html; + const expandAll = $("cl-expand-all"); + const collapseAll = $("cl-collapse-all"); + if (expandAll) expandAll.addEventListener("click", () => el.querySelectorAll("details.cl-item").forEach((it) => { try { it.open = true; } catch (_) { /* harness */ } })); + if (collapseAll) collapseAll.addEventListener("click", () => el.querySelectorAll("details.cl-item").forEach((it) => { try { it.open = false; } catch (_) { /* harness */ } })); + } + 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" }); + } + } + + // #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")); + // #3719 item4: locale-aware summary — zh picks summaryZh when the + // entry carries one; every other locale (and legacy payloads) + // falls back to the English one-liner. + const summaryText = (locale === "zh-CN" && typeof n.summaryZh === "string" && n.summaryZh) ? n.summaryZh : String(n.summary || ""); + html += '
' + escapeHtml(tierLabel) + "" + escapeHtml(String(n.version || "")) + "" + (n.date ? ' ' + escapeHtml(String(n.date)) + "" : "") + "
" + escapeHtml(summaryText) + "
"; + }); + 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"); @@ -718,10 +986,36 @@ export const WEB_CLIENT = `(function () { // carries the MINIMUM fixed version, so each locale can say // "v{version} 或更新版本" / "v{version} or newer" separately. const vars = { version: u.version, summary: u.summary || "" }; + // #3719 item3: locale-aware summary — zh gets summaryZh when + // the entry carries one (release-notes bilingual support). + if (locale === "zh-CN" && typeof u.summaryZh === "string" && u.summaryZh) vars.summary = u.summaryZh; const line = u.kind === "ready" ? t("sys.update_ready", vars) : t("sys.update_available", vars); ub.hidden = false; ub.classList.add("show"); ub.innerHTML = "" + t("sys.update") + " " + escapeHtml(line); + // #3719 item3: one-click upgrade straight from the banner when + // the fix is still "available" (ready = already on disk, just + // restart). Reuses the phase-2 install endpoint + its safety + // chain; feedback stays inside the banner. + if (u.kind === "available") { + const btn = document.createElement("button"); + btn.type = "button"; + btn.className = "banner-upgrade-now"; + btn.textContent = t("sys.update_now", { version: u.version }); + btn.addEventListener("click", async () => { + btn.disabled = true; + btn.textContent = t("sys.updating", {}); + try { + const r = await json(API_ROOT + "/update/install", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ version: u.version }) }); + if (r && (r.ok || r.already)) btn.textContent = t("sys.update_done", { version: u.version }); + else { btn.textContent = String((r && r.error) || "install failed"); btn.disabled = false; } + } catch (e) { + btn.textContent = String((e && e.message) || e); + btn.disabled = false; + } + }); + ub.appendChild(btn); + } } else { ub.hidden = true; ub.classList.remove("show"); @@ -3691,7 +3985,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); @@ -3711,6 +4005,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); @@ -3749,6 +4044,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; focusChangelogRelease(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); }); @@ -3925,6 +4230,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 723875a271..a04aca9fab 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": "运行日志", @@ -103,9 +104,55 @@ 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.changelog_latest": "最新", + "sys.changelog_cat_feat": "新功能", + "sys.changelog_cat_fix": "缺陷修复", + "sys.changelog_cat_kernel": "压缩引擎", + "sys.changelog_cat_host": "宿主车道", + "sys.changelog_cat_store": "存储与会话", + "sys.changelog_cat_upd": "自更新与发版", + "sys.changelog_cat_web": "Web UI 与文档", + "sys.changelog_cat_infra": "构建·CI·测试", + "sys.changelog_cat_other": "其他", + "up.cl_expand_all": "全部展开", + "up.cl_collapse_all": "收起全部", + // #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 即可生效", + "sys.update_now": "升级到 v{version}", + "sys.updating": "升级中…", + "sys.update_done": "已安装 v{version} — 重启宿主后生效", "sys.stale": "磁盘已有新版本 v{disk} —— 当前运行 v{running},重启宿主后新代码才生效", "sys.stale_auto": "自动重启已启用,空闲时自动切换", "sys.stale_manual": "自动重启未启用(需要 --auto-restart-on-update)", @@ -575,6 +622,7 @@ export const MESSAGES: Record> = { "nav.overview": "Overview", "nav.sessions": "Sessions", "nav.config": "Configuration", + "nav.updates": "Versions", "nav.connect": "Connect", "nav.logs": "Logs", "logs.title": "Run log", @@ -648,9 +696,55 @@ 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.changelog_latest": "Latest", + "sys.changelog_cat_feat": "Features", + "sys.changelog_cat_fix": "Bug fixes", + "sys.changelog_cat_kernel": "Compression engine", + "sys.changelog_cat_host": "Host lanes", + "sys.changelog_cat_store": "Storage & sessions", + "sys.changelog_cat_upd": "Self-update & releases", + "sys.changelog_cat_web": "Web UI & docs", + "sys.changelog_cat_infra": "Build \u00b7 CI \u00b7 tests", + "sys.changelog_cat_other": "Other", + "up.cl_expand_all": "Expand all", + "up.cl_collapse_all": "Collapse all", + // #3719 phase 2: dedicated Updates tab + "up.title": "Versions", + "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", + "sys.update_now": "Upgrade to v{version}", + "sys.updating": "Upgrading…", + "sys.update_done": "v{version} installed — restart the host to apply", "sys.stale": "Newer version v{disk} on disk — running v{running}; restart the host to load the new code", "sys.stale_auto": "Auto-restart enabled — switches automatically when idle", "sys.stale_manual": "Auto-restart not enabled (needs --auto-restart-on-update)", diff --git a/src/web/page.ts b/src/web/page.ts index c0b71745bf..1f16792416 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}
@@ -129,6 +129,30 @@ export function renderPage(origin: string, version: string, embed = false, theme
+