diff --git a/docs/architecture/update.ja.md b/docs/architecture/update.ja.md index df65eac377..28e8516236 100644 --- a/docs/architecture/update.ja.md +++ b/docs/architecture/update.ja.md @@ -19,6 +19,8 @@ **セルフアップデータ (`update.ts`)。** デフォルトでは 3 分ごとに npm レジストリをチェックする (`CHECK_INTERVAL_MS`、ノブで上書き可能 #2030; プロセスごとの最初のチェックはスロットリングを無視する)。更新は tarball の展開であり、`npm install` ではない——ユーザーの環境ではライフサイクルスクリプトは決して実行されない。グローバルインストールはインプレースで切り替わる。プラグインモードでは、注入されたコードは HOST プロセス内に存在する: 新しいコードはホストの再起動後にのみ有効になり、壊れた注入はモデルトラフィックを非圧縮の直接通信に劣化させる——パネルのバナーと `/__bili/status` の `attribution` で確認可能 (#3581)。 +**バージョンゲート (#6804)。** ロールアウトポリシーの前に、ユーザーに見える 2 つのルールがある: リリースチャネル (`tag="latest"`) にインストールされたプリリリース/一時ビルドは、リリースに自動的に前へ掃き上げられることは決してない——チェックは実行され、新しいバージョンは報告されるが、インストールはされない(`updateTag=dev` のようなプリリリースチャネルは一時ビルドのあいだを依然として移動する)。また、`bili pin [duration]` でピンされたバージョンはチェック専用——新しいバージョンは発見・報告されるが、自動的にインストールされることはなく、ピンは期限で自動的に解除される(`bili unpin` で早期解除)。明示的な `bili update` は両方のゲートを貫通する。ピン状態はマシンレベルのランタイム状態 (`update-pin.ts`) であり、設定キーではない。 + **インストールレーン。** グローバル (`npm i -g`、自己更新) · 参照レーン (omp/claude/codex/kimi/zcode/hermes — コピーなし、グローバル dist を指す) · ホストワールド (dsh プロファイルバンドル、opencode/pi ツリー — ホスト自身のチャネルを通じて更新され、グローバル自己更新と、グローバルが実行されない場合のコピー自身の定期的チェックによって駆動される、#1196) · ランチャー (`bili ` オーバーレイモード: 永続コピーゼロ)。 **台帳の収束。** デスクトップの dsh プロファイルは、bili が完全に所有する唯一のコピーである; その自己修復は `node_modules/billion-context` を直接切り替えるため、`convergeDshLedger` (`src/dsh-ledger.ts`) は、プロファイルマニフェストの宣言された spec と、ロックファイルに記録された解決結果を同じ操作で移動する (#3496) — コピーのみを移動するライターは、#3224 が検出するドリフトを生み出す。既存のドリフトは明示的な要求時のみ収束する: `bili doctor --fix`。`plugin-install.ts` はホスト自身のチャネル (`dsh plugin add`) のみ駆動し、その隣に第二のコピーをインストールすることは決してしない (#966)。 @@ -31,7 +33,7 @@ ## 主要エントリ -`src/update.ts` (アップデータ — 重要) · `src/advisory.ts` · `src/restart.ts` · `src/plugin-install.ts` · `src/dsh-ledger.ts` · `src/dsh-channel.ts` · `src/pi-channel.ts` · `src/launcher.ts` +`src/update.ts` (アップデータ — 重要) · `src/update-pin.ts` (マシンレベルのバージョンピン, #6804) · `src/advisory.ts` · `src/restart.ts` · `src/plugin-install.ts` · `src/dsh-ledger.ts` · `src/dsh-channel.ts` · `src/pi-channel.ts` · `src/launcher.ts` ## 関連 diff --git a/docs/architecture/update.md b/docs/architecture/update.md index d72efc3528..f2aebc4db2 100644 --- a/docs/architecture/update.md +++ b/docs/architecture/update.md @@ -19,6 +19,8 @@ Get every copy of bili on a machine to the newest version without bricking anyth **Self-updater (`update.ts`).** Checks the npm registry every 3 min by default (`CHECK_INTERVAL_MS`, knob-overridable #2030; the first check per process ignores the throttle). Updates are tarball extraction, NOT `npm install` — no lifecycle scripts ever run on user boxes. The global install swaps in place. In plugin mode the injected code lives in the HOST process: new code only takes effect after a host restart, and a broken injection degrades model traffic to uncompressed direct — visible via the panel banner and `/__bili/status` `attribution` (#3581). +**Version gates (#6804).** Before the rollout policy, two user-facing rules: an installed prerelease/temp build on the release channel (`tag="latest"`) is never auto-swept forward to a release — the check runs, the new version is reported, nothing is installed (a prerelease channel like `updateTag=dev` still moves between temp builds); and a version pinned via `bili pin [duration]` is check-only — new versions are discovered and reported but never auto-installed, with the pin lifting itself at expiry (`bili unpin` lifts it early). An explicit `bili update` breaks through both. Pin state is machine-level runtime state in `update-pin.ts`, not a config key. + **Install lanes.** Global (`npm i -g`, self-updating) · reference lanes (omp/claude/codex/kimi/zcode/hermes — no copy, point at the global dist) · host worlds (dsh profile bundle, opencode/pi trees — updated through the host's own channel, driven by the global self-update AND by the copy's own periodic check when no global ever runs, #1196) · launchers (`bili ` overlay mode: zero persistent copy). **Ledger convergence.** The desktop dsh profile is the one copy bili owns outright; its self-heal swaps `node_modules/billion-context` directly, so `convergeDshLedger` (`src/dsh-ledger.ts`) also moves the profile manifest's declared spec AND the lockfile's recorded resolution in the same operation (#3496) — a writer that moves only the copy manufactures the drift #3224 detects. Pre-existing drift converges on explicit demand only: `bili doctor --fix`. `plugin-install.ts` only drives the host's own channel (`dsh plugin add`), never installs a second copy beside it (#966). @@ -31,7 +33,7 @@ Human-review tier (§7.4) — no auto-merge; changing `update.ts` requires a NO- ## Key entries -`src/update.ts` (updater — load-bearing) · `src/advisory.ts` · `src/restart.ts` · `src/plugin-install.ts` · `src/dsh-ledger.ts` · `src/dsh-channel.ts` · `src/pi-channel.ts` · `src/launcher.ts` +`src/update.ts` (updater — load-bearing) · `src/update-pin.ts` (per-machine version pin, #6804) · `src/advisory.ts` · `src/restart.ts` · `src/plugin-install.ts` · `src/dsh-ledger.ts` · `src/dsh-channel.ts` · `src/pi-channel.ts` · `src/launcher.ts` ## Related diff --git a/docs/architecture/update.zh-CN.md b/docs/architecture/update.zh-CN.md index cee0272a98..00f177cd72 100644 --- a/docs/architecture/update.zh-CN.md +++ b/docs/architecture/update.zh-CN.md @@ -19,6 +19,8 @@ **自更新器(`update.ts`)。** 默认每 3 分钟查一次 npm 注册表(`CHECK_INTERVAL_MS`,旋钮可覆盖 #2030;每进程首查忽略节流)。更新是 tarball 解包,**不是** `npm install`——用户机器上永不跑 lifecycle 脚本。全局安装就地换包。插件模式里注入的代码跑在**宿主进程**中:新代码要宿主重启才生效;注入坏掉则模型流量退化为不压缩直连——面板 banner 与 `/__bili/status` 的 `attribution` 可见(#3581)。 +**版本门(#6804)。** 在 rollout 策略之前有两条用户可见规则:发布通道(`tag="latest"`)上安装的预发布/临时构建**永不**被自动扫到正式版——检查照常跑、新版本照常上报、但不安装(预发布通道如 `updateTag=dev` 仍在临时构建之间前进);`bili pin [duration]` 固定的版本为 check-only——新版本照常发现并上报,但永不自动安装,pin 到期自动解除(`bili unpin` 提前解除)。显式 `bili update` 可穿透两条门。pin 状态是机器级运行态(`update-pin.ts`),不是配置键。 + **安装车道。** 全局(`npm i -g`,就地自更新) · 引用车道(omp/claude/codex/kimi/zcode/hermes——无拷贝、指全局 dist) · 宿主世界(dsh profile bundle、opencode/pi 树——走宿主自己的通道更新,由全局自更新驱动 + 无全局时拷贝自己的周期检查兜底,#1196) · 启动器(`bili ` overlay 模式:零持久拷贝)。 **三账收敛。** 桌面 dsh profile 是 bili 唯一完全自有的拷贝;它的自愈直接换 `node_modules/billion-context`,所以 `convergeDshLedger`(`src/dsh-ledger.ts`)同一操作里还要挪 profile manifest 的声明 spec 与 lockfile 的记录(#3496)——只挪拷贝的写者会亲手造出 #3224 检测的那种漂移。既有漂移只在显式要求时收敛:`bili doctor --fix`。`plugin-install.ts` 只驱动宿主自己的通道(`dsh plugin add`),绝不在旁边装第二份(#966)。 @@ -31,7 +33,7 @@ ## 关键入口 -`src/update.ts`(更新器——承重件) · `src/advisory.ts` · `src/restart.ts` · `src/plugin-install.ts` · `src/dsh-ledger.ts` · `src/dsh-channel.ts` · `src/pi-channel.ts` · `src/launcher.ts` +`src/update.ts`(更新器——承重件) · `src/update-pin.ts`(机器级版本 pin,#6804) · `src/advisory.ts` · `src/restart.ts` · `src/plugin-install.ts` · `src/dsh-ledger.ts` · `src/dsh-channel.ts` · `src/pi-channel.ts` · `src/launcher.ts` ## 相关 diff --git a/reference/architecture.md b/reference/architecture.md index 6fb6f6adef..5029bbde31 100644 --- a/reference/architecture.md +++ b/reference/architecture.md @@ -171,6 +171,7 @@ billion-context/ │ ├── external-summary-surface.ts # Tool/schema and client-facing summary contract │ ├── external-summary-marker.ts # Zero-import marker contract for externally summarized blocks │ ├── update.ts # Self-updater (load-bearing — no-op release protocol) + install lanes +│ ├── update-pin.ts # Per-machine version pin state for the updater (#6804) │ ├── advisory.ts # Critical-defect advisory watcher (#1481) │ ├── plugin-advisory.ts # dsh cost-advisory detection + TTL cache (#2462) │ ├── host-plugin-notice.ts # Known host-side metering plugin notice + dismiss state (#2861) diff --git a/src/cli.ts b/src/cli.ts index 475738511c..1b3c240125 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -40,7 +40,8 @@ import { recordEngineBootstrap } from "./storage/runtime-status.js"; import { configFile as defaultConfigFile, checkNamedConfigRef } from "./paths.js"; import { log as loggerLog } from "./logger.js"; import { createAutoRestartHandler } from "./restart.js"; -import { checkForUpdate, startAutoUpdate } from "./update.js"; +import { checkForUpdate, startAutoUpdate, forceInstallVersion, findInstallDir } from "./update.js"; +import { setPin, clearPin, activePin, parsePinDuration } from "./update-pin.js"; import { registerUpdateActions } from "./server/update-actions.js"; import { startAdvisoryWatcher, getAdvisoryState, advisoryDeferring, advisoryBlocksVersion, advisoryAwaitingFirstCheck } from "./advisory.js"; import { startReleaseNotesWatcher } from "./update-notes.js"; @@ -134,7 +135,13 @@ Usage: each (pure-append / mid-stream-rewrite / prefix-stable-miss); --json machine output, --log FILE correlates [acp-usage] lines (default /bili.log), --no-log skips, --session SID filters - bili update check for & install a newer version now + bili update [version] check for & install a newer version now; with a + version argument, installs that exact published + version (release or prerelease/temp build) + bili pin [duration] pin the installed version (1h/12h/1d/7d/forever; + default indefinite) — auto-upgrade becomes + check-only until the pin lifts or bili unpin + bili unpin lift the pin early bili doctor audit every install lane: versions, owners, freshness vs registry, running proxy processes (read-only; --json for machine-readable output); @@ -226,7 +233,7 @@ Docs: https://github.com/ranxianglei/billion-context `; type Parsed = { - command: "start" | "update" | "doctor" | "help" | "version" | "launch" | "test" | "export" | "plugin-register" | "mcp" | "plugin" | "acp-cache" | "sessions" | "storage" | "pack"; + command: "start" | "update" | "pin" | "unpin" | "doctor" | "help" | "version" | "launch" | "test" | "export" | "plugin-register" | "mcp" | "plugin" | "acp-cache" | "sessions" | "storage" | "pack"; client?: ClientName; clientArgs: string[]; mitmDomains: string[]; @@ -261,6 +268,8 @@ type Parsed = { jsonOutput?: boolean; doctorJson?: boolean; doctorFix?: boolean; + updateVersion?: string; + pinDuration?: string; }; export function parseArgs(argv: string[]): Parsed { @@ -301,6 +310,8 @@ export function parseArgs(argv: string[]): Parsed { let jsonOutput = false; let doctorJson = false; let doctorFix = false; + let updateVersion: string | undefined; + let pinDuration: string | undefined; for (let i = 0; i < argv.length; i++) { const a = argv[i]!; @@ -531,6 +542,12 @@ export function parseArgs(argv: string[]): Parsed { command = "start"; } else if (cmd === "update") { command = "update"; + updateVersion = positional[1]; + } else if (cmd === "pin") { + command = "pin"; + pinDuration = positional[1]; + } else if (cmd === "unpin") { + command = "unpin"; } else if (cmd === "doctor") { command = "doctor"; } else if (cmd === "export") { @@ -656,11 +673,11 @@ export function parseArgs(argv: string[]): Parsed { } } - return { command, client, clientArgs, mitmDomains, overrides, exportSelector, exportOutput, exportFull, exportJsonl, registerConversationId, pluginAction, pluginAgent, pluginWithMcp, acpCacheDir, acpCacheLog, acpCacheNoLog, acpCacheSession, sessionsSub, sessionsTarget, sessionsNoVacuum, sessionsApply, sessionsRestoreTarget, storageDays, storageVacuum, storageDryRun, storageSub, storageKeep, storageFrom, jsonOutput, doctorJson, doctorFix, packAction, packSpec, packProject, packForce }; + return { command, client, clientArgs, mitmDomains, overrides, exportSelector, exportOutput, exportFull, exportJsonl, registerConversationId, pluginAction, pluginAgent, pluginWithMcp, acpCacheDir, acpCacheLog, acpCacheNoLog, acpCacheSession, sessionsSub, sessionsTarget, sessionsNoVacuum, sessionsApply, sessionsRestoreTarget, storageDays, storageVacuum, storageDryRun, storageSub, storageKeep, storageFrom, jsonOutput, doctorJson, doctorFix, packAction, packSpec, packProject, packForce, updateVersion, pinDuration }; } export async function main(): Promise { - const { command, client, clientArgs, mitmDomains, overrides, exportSelector, exportOutput, exportFull, exportJsonl, registerConversationId, pluginAction, pluginAgent, pluginWithMcp, acpCacheDir, acpCacheLog, acpCacheNoLog, acpCacheSession, sessionsSub, sessionsTarget, sessionsNoVacuum, sessionsApply, sessionsRestoreTarget, storageDays, storageVacuum, storageDryRun, storageSub, storageKeep, storageFrom, jsonOutput, doctorJson, doctorFix, packAction, packSpec, packProject, packForce } = parseArgs(process.argv.slice(2)); + const { command, client, clientArgs, mitmDomains, overrides, exportSelector, exportOutput, exportFull, exportJsonl, registerConversationId, pluginAction, pluginAgent, pluginWithMcp, acpCacheDir, acpCacheLog, acpCacheNoLog, acpCacheSession, sessionsSub, sessionsTarget, sessionsNoVacuum, sessionsApply, sessionsRestoreTarget, storageDays, storageVacuum, storageDryRun, storageSub, storageKeep, storageFrom, jsonOutput, doctorJson, doctorFix, packAction, packSpec, packProject, packForce, updateVersion, pinDuration } = parseArgs(process.argv.slice(2)); // -c/--config fail-fast: a bare NAME that resolves to a missing // /NAME.json names the typo + the available siblings instead of // silently starting on an empty config (see paths.ts for path behavior). @@ -885,6 +902,7 @@ export async function main(): Promise { } let updaterResolveProxy: ((url: string) => string | undefined) | undefined; let updateTag: string | undefined; + let installDir: string | undefined; try { const o = loadOptions(); updaterResolveProxy = (url) => resolveProxy(o.routes, o.proxy, url, o.proxyFallback); @@ -892,12 +910,72 @@ export async function main(): Promise { } catch (e) { console.error(`bili update: config load failed (${String(e)}); updater egress goes direct`); } + if (updateVersion) { + // #6804: install a specific published version (release or + // prerelease/temp build). Explicit action = user intent, so this + // bypasses the pin and the tag-channel rule. + try { + installDir = await findInstallDir(PACKAGE_NAME); + } catch { + // installDir stays undefined — forceInstallVersion will refuse + } + const result = await forceInstallVersion( + updateVersion, + installDir, + { packageName: PACKAGE_NAME, currentVersion: VERSION, autoUpdate: true, resolveProxy: updaterResolveProxy, updateTag }, + "manual-cli", + "manual", + ); + if (result.ok) { + console.log(`bili: installed ${updateVersion}`); + } else { + console.error(`bili update ${updateVersion}: ${result.error ?? "install failed"}`); + process.exit(1); + } + return; + } await checkForUpdate( { packageName: PACKAGE_NAME, currentVersion: VERSION, autoUpdate: true, resolveProxy: updaterResolveProxy, updateTag }, true, ); return; } + if (command === "pin") { + // #6804: pin the installed version for a duration. The pin is + // machine-level runtime state — no config file involved. + const version = VERSION; + let durationMs: number | undefined; + if (pinDuration) { + if (pinDuration === "forever") { + // indefinite — no `until` field + } else { + durationMs = parsePinDuration(pinDuration); + if (durationMs === undefined) { + console.error(`bili pin: invalid duration "${pinDuration}" (expected h or d, e.g. 1h, 12h, 1d, 7d, or forever)`); + process.exit(2); + } + } + } + const pin = await setPin(version, durationMs); + if (pin) { + console.log(`bili: pinned ${version}${pin.until !== undefined ? ` until ${new Date(pin.until).toISOString()}` : " (indefinite)"}`); + } else { + console.error("bili pin: failed to write pin state"); + process.exit(1); + } + return; + } + if (command === "unpin") { + // #6804: lift the pin early. + const hadPin = (await activePin()) !== undefined; + await clearPin(); + if (hadPin) { + console.log("bili: pin lifted"); + } else { + console.log("bili: no active pin"); + } + return; + } if (command === "test") { if (client === "pi") { await runTestPi({ overrides, mitmDomains }); diff --git a/src/server/admin.ts b/src/server/admin.ts index dd3684131b..d5308fac55 100644 --- a/src/server/admin.ts +++ b/src/server/admin.ts @@ -20,7 +20,7 @@ import { handlePluginAttribution, handlePluginCompact, handlePluginFork, handleP import { parseAgentProviderReport, recordAgentProviders, agentProviderRecipes, sanitizeAgentProviderField } from "../agent-providers.js"; import { configDir, defaultLogFile } from "../paths.js"; import { getUpdateVisibility, updateBannerPayload } from "../update-notes.js"; -import { installVersionAction, triggerManualCheck, updateActionsAvailable, updateStateSnapshot } from "./update-actions.js"; +import { installVersionAction, triggerManualCheck, updateActionsAvailable, updateStateSnapshot, pinAction, unpinAction } from "./update-actions.js"; import { getUnrecognizedPathStats } from "./observability.js"; import { getStore } from "../persist.js"; import { BodyTooLargeError, headerValue, readBody } from "../server.js"; @@ -410,6 +410,8 @@ export async function handleAdminRoute(req: http.IncomingMessage, res: http.Serv } 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 === "POST" && req.url === "/__bili/update/pin") return handleUpdatePin(req, res, log); + if (req.method === "POST" && req.url === "/__bili/update/unpin") return handleUpdateUnpin(res, log); if (req.method === "PUT" && req.url === "/__bili/config") { return handleConfigPut(req, res, () => { const fresh = loadOptions(); @@ -1027,6 +1029,47 @@ async function handleUpdateInstall(req: http.IncomingMessage, res: http.ServerRe res.end(JSON.stringify(await installVersionAction(version), null, 2)); } +/** POST /__bili/update/pin {"version":"x.y.z","duration":"1h|12h|1d|7d|forever"} + * — #6804: set a pin on the installed version. Malformed JSON or an invalid + * duration → 400; execution always answers 200 {ok, error?, pin?}. */ +async function handleUpdatePin(req: http.IncomingMessage, res: http.ServerResponse, log: (level: string, msg: string) => void): Promise { + let version: string | undefined; + let duration: string | undefined; + try { + const doc: unknown = JSON.parse((await readBody(req)).toString("utf8")); + if (doc && typeof doc === "object") { + const d = doc as { version?: unknown; duration?: unknown }; + if (typeof d["version"] === "string") version = d["version"].trim(); + if (typeof d["duration"] === "string") duration = d["duration"].trim(); + } + } catch { + res.writeHead(400, { "content-type": "application/json" }); + res.end(JSON.stringify({ error: 'expected JSON body {"version": "", "duration": "<1h|12h|1d|7d|forever>"}' }, null, 2)); + return; + } + 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; + } + if (duration !== undefined && duration !== "forever" && !/^\d+[hd]$/.test(duration)) { + res.writeHead(400, { "content-type": "application/json" }); + res.end(JSON.stringify({ error: "duration must be h or d (e.g. 1h, 12h, 1d, 7d), or forever" }, null, 2)); + return; + } + log("info", `[update] web panel requested pin ${version}${duration ? ` for ${duration}` : " (indefinite)"}`); + res.writeHead(200, { "content-type": "application/json" }); + res.end(JSON.stringify(await pinAction(version, duration), null, 2)); +} + +/** POST /__bili/update/unpin — #6804: lift the pin early. Always 200 + * {ok, error?}. */ +async function handleUpdateUnpin(res: http.ServerResponse, log: (level: string, msg: string) => void): Promise { + log("info", `[update] web panel requested unpin`); + res.writeHead(200, { "content-type": "application/json" }); + res.end(JSON.stringify(await unpinAction(), 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 index dafcff436a..59f0bc7fc1 100644 --- a/src/server/update-actions.ts +++ b/src/server/update-actions.ts @@ -16,6 +16,7 @@ * nothing here throws into the HTTP handlers. */ import { checkForUpdate, findInstallDir, forceInstallVersion, lastUpdateCheckTime, readDiskVersion, staleInstallStatus, type UpdateCheckOutcome, type UpdateOptions } from "../update.js"; +import { activePin, setPin, clearPin, parsePinDuration, type PinState } from "../update-pin.js"; import { getUpdateVisibility } from "../update-notes.js"; import { log as loggerLog } from "../logger.js"; @@ -44,6 +45,8 @@ interface UpdateStateSnapshotData { checking: boolean; /** True while a pinned install is in flight in this process. */ installing: boolean; + /** #6804: the active pin state (undefined = no pin). */ + pin?: PinState; } let registeredOpts: UpdateOptions | undefined; @@ -139,6 +142,7 @@ export async function updateStateSnapshot(runningVersion: string): Promise { + if (registeredOpts === undefined) return { ok: false, error: "self-update not wired in this process" }; + if (duration === undefined || duration === "forever") { + const pin = await setPin(version); + if (!pin) return { ok: false, error: "pin state could not be persisted (cache dir unwritable)" }; + return { ok: true, pin }; + } + const ms = parsePinDuration(duration); + if (ms === undefined) return { ok: false, error: `invalid duration: ${duration} (expected 1h, 12h, 1d, 7d, or forever)` }; + const pin = await setPin(version, ms); + if (!pin) return { ok: false, error: "pin state could not be persisted (cache dir unwritable)" }; + return { ok: true, pin }; +} + +/** #6804: lift the pin early. `hadPin` reports whether a pin was actually + * active and cleared (false = there was nothing to clear). Never throws. */ +export async function unpinAction(): Promise<{ ok: boolean; error?: string; hadPin: boolean }> { + if (registeredOpts === undefined) return { ok: false, error: "self-update not wired in this process", hadPin: false }; + const hadPin = (await activePin()) !== undefined; + await clearPin(); + return { ok: true, hadPin }; +} + /** Test seam: clear the registered options and both in-flight flags. */ export function _resetUpdateActionsForTest(): void { registeredOpts = undefined; diff --git a/src/update-pin.ts b/src/update-pin.ts new file mode 100644 index 0000000000..604dbb7a8f --- /dev/null +++ b/src/update-pin.ts @@ -0,0 +1,118 @@ +// #6804: per-machine version pin — a user-intent "hold" on the installed +// version that makes the auto-updater check-only (report but never install). +// Distinct from the #3619 remote policy `pinned` (a fleet-wide upgrade +// ceiling): this is local, per-machine, and survives config edits because it +// is runtime state, not a config key (Configuration Surface Discipline). +// +// The #1481 critical-bug advisory force-install lane still overrides a local +// pin (owner-directed repair wins over user convenience) — the advisory +// watcher calls forceInstallVersion directly, bypassing checkForUpdate. +// +// State file: ~/.cache/billion-context/.pin.json +// { v: 1, version: "0.1.215", setAt: 1700000000000, until?: 1700086400000 } +// `until` absent = indefinite (forever). The pin lifts itself at expiry. + +import { readFile, writeFile, mkdir, rm, rename } from "node:fs/promises"; +import path from "node:path"; +import { cacheDir } from "./paths.js"; + +export interface PinState { + v: 1; + version: string; + setAt: number; + until?: number; +} + +// Resolved per call, not at import time: paths.ts reads env live, and the +// hermetic suites swap XDG_CACHE_HOME per scenario (same pattern as +// update-policy.ts's stagger/policy files). +function pinFile(): string { + return path.join(cacheDir(), ".pin.json"); +} + +/** Parse a duration string ("1h", "12h", "1d", "7d") into milliseconds. + * Returns undefined for unrecognized input. "forever" is handled by the + * caller (no `until` field). */ +export function parsePinDuration(s: string): number | undefined { + const match = s.trim().match(/^(\d+)\s*([hd])$/i); + if (!match) return undefined; + const amount = Number(match[1]); + if (!Number.isFinite(amount) || amount <= 0) return undefined; + const unit = match[2].toLowerCase(); + if (unit === "h") return amount * 60 * 60 * 1000; + return amount * 24 * 60 * 60 * 1000; // "d" +} + +/** Best-effort read. `undefined` = absent or unreadable/corrupt. */ +export async function readPin(): Promise { + try { + const raw = await readFile(pinFile(), "utf-8"); + const doc = JSON.parse(raw) as PinState; + if (!doc || typeof doc !== "object" || doc.v !== 1) return undefined; + if (typeof doc.version !== "string" || doc.version.length === 0) return undefined; + if (typeof doc.setAt !== "number" || !Number.isFinite(doc.setAt)) return undefined; + if (doc.until !== undefined && (typeof doc.until !== "number" || !Number.isFinite(doc.until))) return undefined; + return doc; + } catch { + return undefined; + } +} + +/** Write the pin state atomically (tmp+rename). Returns false when the state + * file could not be written (e.g. unwritable cache dir) — the caller must + * NOT report the pin as active in that case. */ +export async function writePin(pin: PinState): Promise { + try { + const file = pinFile(); + await mkdir(path.dirname(file), { recursive: true }); + const tmp = `${file}.${process.pid}.tmp`; + await writeFile(tmp, JSON.stringify(pin), "utf-8"); + await rename(tmp, file); + return true; + } catch { + return false; + } +} + +/** Clear the pin state (remove the file). Never rejects. */ +export async function clearPin(): Promise { + try { + await rm(pinFile(), { force: true }); + } catch { + // best-effort + } +} + +/** Return the active pin (or undefined if absent or expired). */ +export async function activePin(): Promise { + const pin = await readPin(); + if (!pin) return undefined; + if (pin.until !== undefined && Date.now() > pin.until) return undefined; + return pin; +} + +/** Check if the given version is currently pinned (version matches and the + * pin has not expired). */ +export async function isVersionPinned(version: string): Promise { + const pin = await activePin(); + if (!pin) return false; + return pin.version === version; +} + +/** Set a pin for the given version. `durationMs` undefined = indefinite. + * Returns the pin state that was written, or undefined when the state file + * could not be written — in that case the pin is NOT active. */ +export async function setPin(version: string, durationMs?: number): Promise { + const now = Date.now(); + const pin: PinState = { v: 1, version, setAt: now }; + if (durationMs !== undefined) { + pin.until = now + durationMs; + } + if (!(await writePin(pin))) return undefined; + return pin; +} + +/** Test-only: remove the pin state file. */ +export async function _resetPinForTest(): Promise { + await rm(pinFile(), { force: true }); +} diff --git a/src/update.ts b/src/update.ts index 6393774f3c..59cd5e3e3c 100644 --- a/src/update.ts +++ b/src/update.ts @@ -38,6 +38,7 @@ import { resolveDshHome, resolveKimiHome, resolveOmpHome, resolvePiHome } from " import { proxyDispatcher } from "./upstream-proxy.js"; import type { FetchOptions } from "./fetch-util.js"; import { updateRegistryBase as knobUpdateRegistryBase, updateCheckIntervalMs as knobUpdateCheckIntervalMs, updatePolicyUrl as knobUpdatePolicyUrl, updateStaggerMinDelayMs as knobUpdateStaggerMinDelayMs, updateStaggerMaxDelayMs as knobUpdateStaggerMaxDelayMs } from "./knobs.js"; +import { activePin, isVersionPinned } from "./update-pin.js"; import { POLICY_URL_DEFAULT, ensureStaggerDraw, loadUpdatePolicy, resolveStaggerWindow, resolveUpgradeCandidate, setPlannedUpgrade, staggerKey } from "./update-policy.js"; // BILI_UPDATE_REGISTRY overrides the registry base URL (full URL, e.g. a @@ -1696,6 +1697,39 @@ export async function checkForUpdate(opts: UpdateOptions, force = false, checkOn return; } + // #6804: tag-channel rule — an installed prerelease/temp build is never + // auto-swept forward to a release when the updateTag is the release + // channel ("latest"). The check runs, the new version is reported, + // nothing is installed. A prerelease channel target (e.g. + // updateTag=dev) still moves between temp builds (tag !== "latest"). + // Explicit `bili update` (force=true) bypasses this rule. + if (!force && tag === "latest") { + const parsed = parseSemVer(currentVersion); + if (parsed !== undefined && parsed.pre.length > 0) { + if (checkOnly) { + loggerLog("info", `[update] manual web check: installed ${currentVersion} is a prerelease/temp build on the release channel — new version ${latest} reported but not auto-installed (#6804)`); + return { status: "update-available", latest, note: `installed ${currentVersion} is a prerelease/temp build — not auto-swept to a release (#6804)` }; + } + loggerLog("info", `[update] installed ${currentVersion} is a prerelease/temp build on the release channel (tag "latest") — new version ${latest} reported but not auto-installed (#6804)`); + return; + } + } + + // #6804: pin check-only gate — a pinned version is check-only: the + // updater keeps discovering and reporting new versions but never + // auto-installs. An explicit `bili update` (force=true) breaks + // through the pin (explicit action = user intent). The #1481 + // advisory force-install lane overrides the pin (it calls + // forceInstallVersion directly, bypassing checkForUpdate). + if (!force && (await isVersionPinned(currentVersion))) { + if (checkOnly) { + loggerLog("info", `[update] manual web check: version ${currentVersion} is pinned — new version ${latest} reported but not auto-installed (#6804)`); + return { status: "update-available", latest, note: `version ${currentVersion} is pinned — not auto-installing (#6804)` }; + } + loggerLog("info", `[update] version ${currentVersion} is pinned — new version ${latest} reported but not auto-installed (#6804)`); + return; + } + // #3619: remote update policy + staggered rollout. The gate resolves // the final install candidate (pin ceiling / blocked stepping) and the // per-version upgrade moment; any gate failure degrades to the legacy diff --git a/src/web/client.ts b/src/web/client.ts index 5ca025d133..4486496321 100644 --- a/src/web/client.ts +++ b/src/web/client.ts @@ -948,6 +948,11 @@ function changelogCatOf(rawLine) { // while any action runs (the server dedupes a second call too). let upBusyAction = false; let upReleases = []; + // #6804: last /update/state snapshot — the pin must target the ON-DISK + // version (what checkForUpdate compares), not the running one: in the + // pending-restart state the two differ and a pin on the running version + // would silently be a no-op. Shape: { running, disk }. + let upState = null; function upSetButtons(on) { [$("up-check"), $("up-upgrade-now"), $("up-install")].forEach((b) => { if (!b) return; @@ -1034,6 +1039,20 @@ function changelogCatOf(rawLine) { sel.innerHTML = opt; if (cur) sel.value = cur; } + // #6804: pin status display + const pinStatus = $("up-pin-status"); + const pinBtn = $("up-pin"); + const unpinBtn = $("up-unpin"); + if (pinStatus) { + if (st.pin) { + const until = st.pin.until ? new Date(st.pin.until).toLocaleString() : t("up.pin_indefinite"); + pinStatus.textContent = t("up.pin_active", { v: st.pin.version, until: until || "indefinite" }); + } else { + pinStatus.textContent = t("up.pin_none"); + } + } + if (pinBtn) pinBtn.disabled = upBusyAction || Boolean(st.pin); + if (unpinBtn) unpinBtn.disabled = upBusyAction || !st.pin; applyUpdateButtons(st); // A check/install started from another tab of this process shows in // the snapshot — keep the buttons held down until it settles. @@ -1139,6 +1158,7 @@ function changelogCatOf(rawLine) { 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) : []; + upState = (st && typeof st === "object") ? st : null; renderUpdateState(st); } catch (e) { // Both endpoints are fail-soft 200s; reaching here = proxy unreachable. @@ -1167,6 +1187,50 @@ function changelogCatOf(rawLine) { } function upUpgradeNow() { upInstall(upNewestVersion(null).replace(/^v/, "")); } function upInstallSelected() { const sel = $("up-select"); if (sel && sel.value) upInstall(String(sel.value).replace(/^v/, "")); } + function upInstallVersion() { + const input = $("up-version-input"); + if (input && input.value.trim()) upInstall(input.value.trim().replace(/^v/, "")); + } + async function upPin() { + if (upBusyAction) return; + // Pin the ON-DISK version (see upState): the gate compares against + // diskVersion ?? runningVersion, so a pending-restart install must be + // pinned at its disk version or the pin never fires. + const version = (upState && (upState.disk || upState.running)) || ""; + if (!version || version === "?") return; + const durSel = $("up-pin-duration"); + const duration = durSel ? durSel.value : "forever"; + upBusyAction = true; + upSetButtons(true); + showUpdateResult(t("up.installing", {}), true); + try { + const r = await json(API_ROOT + "/update/pin", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ version: version, duration: duration }) }); + if (r.ok) showUpdateResult(t("up.pin_set", { v: version, until: duration }), true); + else showUpdateResult(String(r.error || t("up.pin_failed", { err: "unknown" })), false); + } catch (e) { + showUpdateResult(e.message, false); + } finally { + upBusyAction = false; + upSetButtons(false); + loadUpdates(); + } + } + async function upUnpin() { + if (upBusyAction) return; + upBusyAction = true; + upSetButtons(true); + try { + const r = await json(API_ROOT + "/update/unpin", { method: "POST", headers: { "content-type": "application/json" }, body: "{}" }); + if (r.ok) showUpdateResult(r.hadPin === false ? t("up.pin_none") : t("up.pin_cleared"), true); + else showUpdateResult(String(r.error || t("toast.failed", { msg: "unpin failed" })), false); + } catch (e) { + showUpdateResult(e.message, false); + } finally { + upBusyAction = false; + upSetButtons(false); + loadUpdates(); + } + } async function upCheckNow() { if (upBusyAction) return; upBusyAction = true; @@ -5759,6 +5823,13 @@ if (d.keepalive) kv(parts, t("det.keepalive"), d.keepalive.tierLabel + " · " + 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()); + // #6804: free-text version install + pin/unpin controls + const upvins = $("up-install-version"); + if (upvins) upvins.addEventListener("click", () => upInstallVersion()); + const uppin = $("up-pin"); + if (uppin) uppin.addEventListener("click", () => upPin()); + const upunpin = $("up-unpin"); + if (upunpin) upunpin.addEventListener("click", () => upUnpin()); 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 45d66a429b..8e09a52251 100644 --- a/src/web/i18n.ts +++ b/src/web/i18n.ts @@ -180,6 +180,15 @@ export const MESSAGES: Record> = { "up.upgrade_none": "(暂无已知的更新版本)", "up.upgrade_now": "立即升级到 {v} Upgrade now", "up.install_selected": "安装所选版本 Install selected", + "up.install_version": "安装指定版本 Install version", + "up.pin": "固定版本 Pin", + "up.unpin": "解除固定 Unpin", + "up.pin_active": "已固定 {v} {until}", + "up.pin_indefinite": "永久 indefinite", + "up.pin_none": "未固定 no pin", + "up.pin_set": "已固定 {v} {until}", + "up.pin_cleared": "已解除固定 pin lifted", + "up.pin_failed": "固定失败 {err}", "up.select_placeholder": "选择版本… Select a version…", "up.installing": "正在处理… in flight…", "up.already_in_flight": "已有操作在进行中… an operation is already in flight…", @@ -983,6 +992,15 @@ export const MESSAGES: Record> = { "up.upgrade_none": "(no newer version known)", "up.upgrade_now": "Upgrade now to {v}", "up.install_selected": "Install selected", + "up.install_version": "Install version", + "up.pin": "Pin", + "up.unpin": "Unpin", + "up.pin_active": "Pinned {v} {until}", + "up.pin_indefinite": "indefinite", + "up.pin_none": "No pin", + "up.pin_set": "Pinned {v} {until}", + "up.pin_cleared": "Pin lifted", + "up.pin_failed": "Pin failed: {err}", "up.select_placeholder": "Select a version…", "up.installing": "In flight…", "up.already_in_flight": "An operation is already in flight…", diff --git a/src/web/page.ts b/src/web/page.ts index 45fba31d2d..13a6d5284f 100644 --- a/src/web/page.ts +++ b/src/web/page.ts @@ -169,6 +169,22 @@ export function renderPage(origin: string, version: string, embed = false, theme +
+ + +
+
+ + + + +