diff --git a/CONFIGURATION.md b/CONFIGURATION.md index f64eb05267..2c7efe6a1f 100644 --- a/CONFIGURATION.md +++ b/CONFIGURATION.md @@ -809,8 +809,6 @@ Environment variables take precedence over the config file. They are useful for | `BILI_MODEL_INFO_RETRY_MS` | Cooldown (ms) before the dsh native plugin re-resolves the current model's context window after a resolve that failed or returned no window (#1812/#1836): a cached entry without a window is not final — instead of latching headerless for the process lifetime, the next request after this cooldown triggers a retry. Default `30000`; non-numeric or negative values fall back to `30000`. Test hook — shortened by the dsh-native unit test so it never waits wall-clock; leave unset in production. | | `BILI_ADVISORY_CHECK` | Set to `0` to disable the critical-defect advisory watcher (#1481). Default ON — it runs independently of `ACP_AUTO_UPDATE` so that installs with auto-update off still get force-updated out of a known-broken version range. Fail-open: an unreachable/malformed source only warns, never blocks model traffic. File-config key: `advisoryCheck`. | | `BILI_ADVISORY_URL` | Override for the advisory document URL. Default: the companion package `billion-context-advisories` on the configured registry (`BILI_UPDATE_REGISTRY` aware). File-config key: `advisoryUrl`. | -| `BILI_RELEASE_NOTES_CHECK` | Set to `0` to disable the tiered release-notes visibility watcher (#1870). Default ON — pure visibility: fetches the companion release-notes doc and surfaces "update ready — restart to finish" (disk newer than running) or "recommended update available" on `acp_status` and the `/acp` panel. Never installs, never restarts; fail-open. File-config key: `releaseNotesCheck`. | -| `BILI_RELEASE_NOTES_URL` | Override for the release-notes document URL. Default: the companion package `billion-context-release-notes` on the configured registry (`BILI_UPDATE_REGISTRY` aware). File-config key: `releaseNotesUrl`. | | ~~`BILI_HOST_USAGE_CREDIT`~~ / ~~`hostUsageCredit`~~ | **Removed in #660.** Used to select the host-facing usage mode. The #408 uncompressed-baseline backfill is gone entirely — every host now reports the actually-forwarded (post-fold) request as provider-measured (matches `[acp-usage] input=`). Old values left in env or the config file are ignored; remove them. See the "Bug history lesson" section of PR #691. | | `ACP_PROVIDERS` | Path to an external `providers.json` (legacy / shared file). | | `BILI_REPLAY_RETRY_BASE_MS` | Base backoff delay (ms) for replay retries after a transient upstream rejection (default `1500`; set `0` to disable the delay). See #189. Also drives the main-path transport-retry backoff (#1688). | diff --git a/CONFIGURATION.zh-CN.md b/CONFIGURATION.zh-CN.md index d916721e59..7894b017ac 100644 --- a/CONFIGURATION.zh-CN.md +++ b/CONFIGURATION.zh-CN.md @@ -808,8 +808,6 @@ | `BILI_MODEL_INFO_RETRY_MS` | dsh 原生模型窗口解析失败(或解析结果不带窗口)后的重试冷却(毫秒,#1812/#1836):匹配的缓存条目没有 context window 时不视为最终结果 —— 不再让整个进程生命周期 latching 成无 header 状态,而是该冷却过期后由下一个请求触发重新解析。默认 `30000`;非数字或负值回退 `30000`。测试钩子 —— dsh-native 单元测试用它缩短冷却、避免真实等待;生产环境保持 unset。 | | `BILI_ADVISORY_CHECK` | 设为 `0` 禁用严重缺陷公告监视器(#1481)。默认开启 —— 它独立于 `ACP_AUTO_UPDATE` 运行,确保关闭了自动更新的安装也能被强制移出已知缺陷版本范围。fail-open:公告源不可达/格式错误只告警,绝不阻断模型流量。文件配置键:`advisoryCheck`。 | | `BILI_ADVISORY_URL` | 公告文档 URL 覆盖。默认:已配置 registry(感知 `BILI_UPDATE_REGISTRY`)上的伴生包 `billion-context-advisories`。文件配置键:`advisoryUrl`。 | -| `BILI_RELEASE_NOTES_CHECK` | 设为 `0` 禁用分级发版说明可见性监视器(#1870)。默认开启 —— 纯可见性:拉取伴生发版说明文档,并在 `acp_status` 与 `/acp` 面板提示「更新已就绪待重启」(磁盘版本新于运行版本)或「存在推荐更新」。绝不安装、绝不重启;fail-open。文件配置键:`releaseNotesCheck`。 | -| `BILI_RELEASE_NOTES_URL` | 发版说明文档 URL 覆盖。默认:已配置 registry(感知 `BILI_UPDATE_REGISTRY`)上的伴生包 `billion-context-release-notes`。文件配置键:`releaseNotesUrl`。 | | ~~`BILI_HOST_USAGE_CREDIT`~~ / ~~`hostUsageCredit`~~ | **#660 已移除。** 曾用于选择宿主可见的用量模式。#408 的未折叠基线回补(backfill)已整体删除 —— 所有宿主现在统一上报“实际转发(后折叠)请求”的 provider 实测用量,与 `[acp-usage] input=` 一致。遗留该环境变量 / 配置键的旧值会被忽略,请删除。教训详见 PR #691 的 “Bug 历史教训” 一节。 | | `ACP_PROVIDERS` | 指向外部 `providers.json` 的路径(旧版 / 共享文件)。 | | `BILI_REPLAY_RETRY_BASE_MS` | 回放重试的基础退避延迟(毫秒):上游瞬时拒绝后重试(默认 `1500`;设 `0` 关闭延迟)。见 #189。同时驱动主路径传输重试的退避(#1688)。 | diff --git a/release-notes/README.md b/release-notes/README.md index b220861d44..167401c133 100644 --- a/release-notes/README.md +++ b/release-notes/README.md @@ -1,10 +1,12 @@ # billion-context-release-notes (companion payload, #1870) -Tiered, model-written release notes consumed by the proxy's visibility -watcher (`src/update-notes.ts`): acp_status and the `/acp` panel use them to -tell users and agents "an update is ready — restart to finish" or "a -recommended release exists", with a per-release summary and the user-side -span (everything between the running version and the newest release). +Tiered, model-written release notes. Since #1977 the proxy-side visibility +watcher is gone — updates are silent by default and only critical +advisories (`advisories/`, #1481) auto-surface — so this doc is now a +release-process artifact: the dispatch-time release gate (release-manual.yml / +release.yml, #1870) requires an entry for every stable release, and the tier + +summary record what each release changed for the user. The companion package +publish stays as the machine-readable carrier for any future consumer. Companion package mechanics mirror `advisories/` (#1481): diff --git a/src/acp-status.ts b/src/acp-status.ts index 1381bd40ac..773895fc91 100644 --- a/src/acp-status.ts +++ b/src/acp-status.ts @@ -14,7 +14,6 @@ import { ccrEnabled, ccrLoopConfig, contentStoreOf } from "./store.js"; import { coveredRefSpan } from "./decompress-shared.js"; import { preCompactionArchiveOf, type Session } from "./session.js"; import { describeAdvisory, getAdvisoryState } from "./advisory.js"; -import { getUpdateVisibility } from "./update-notes.js"; import { VERSION } from "./version.js"; export interface AcpStatusCtx { @@ -148,29 +147,6 @@ export function handleAcpStatus(args: Record, ctx: AcpStatusCtx extra.push(""); extra.push(`CRITICAL ADVISORY (instance-level): bili is auto-updating through the self-updater's safety chain — ${describeAdvisory(adv.active, adv.lastError)}. Live state: GET /__bili/status → advisory.`); } - const upd = getUpdateVisibility(VERSION); - if (upd.visible) { - // #1870: the self-updater is a silent courier on native lanes — the - // "Restart to finish" log line never reaches pi/opencode/dsh users, - // so disk runs new while the process runs old. This is the surface - // agents actually poll: tell them a restart is actionable NOW, or - // that a recommended release exists when auto-update is off. - extra.push(""); - const lines: string[] = []; - if (upd.pendingRestart) { - lines.push(`UPDATE READY (instance-level): ${upd.diskVersion} downloaded — restart this agent's proxy to finish (running ${upd.runningVersion}).`); - } else { - lines.push(`UPDATE AVAILABLE (instance-level): newer recommended release on the channel — running ${upd.runningVersion}.`); - } - for (const e of upd.span) { - lines.push(` · ${e.version} [${e.tier}] ${e.summary}`); - } - if (!upd.pendingRestart) { - lines.push(` Update with: npm install -g billion-context@${upd.span[upd.span.length - 1]?.version ?? "latest"}`); - } - lines.push("Live state: GET /__bili/status → update."); - extra.push(...lines); - } const blind = getBlindTunnelStats(); if (blind.total > 0) { // #897: CONNECT traffic to non-MITM hosts was blind-relayed — it never diff --git a/src/cli.ts b/src/cli.ts index 2886ab6bca..68a6956b0b 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -28,7 +28,6 @@ import { log as loggerLog } from "./logger.js"; import { createAutoRestartHandler } from "./restart.js"; import { checkForUpdate, startAutoUpdate } from "./update.js"; import { startAdvisoryWatcher, getAdvisoryState, advisoryDeferring, advisoryBlocksVersion } from "./advisory.js"; -import { startReleaseNotesWatcher } from "./update-notes.js"; import { resolveProxy } from "./upstream-proxy.js"; import { runMcpStdio } from "./mcp.js"; import { PLUGIN_AGENTS, isPluginAgent, pluginInstall, pluginRemove, pluginStatusAll, pluginUpdate, type PluginAgent } from "./plugin-install.js"; @@ -631,16 +630,6 @@ export async function main(): Promise { }), }); } - // #1870: tiered release-notes visibility — fetch + cache only (never - // installs, never restarts). Runs independently of autoUpdate for the - // same reason as the advisory watcher: installs with auto-update off - // still deserve to learn a recommended update exists. - if (opts.releaseNotesCheck) { - startReleaseNotesWatcher({ - packageName: PACKAGE_NAME, - currentVersion: VERSION, - releaseNotesUrl: opts.releaseNotesUrl, - resolveProxy: (url) => resolveProxy(opts.routes, opts.proxy, url, opts.proxyFallback), - }); - } + // #1977: the release-notes visibility watcher is gone — updates are + // silent by default; only critical advisories (#1481) auto-surface. } diff --git a/src/config.ts b/src/config.ts index b8fcc919c5..d43d6fef52 100644 --- a/src/config.ts +++ b/src/config.ts @@ -664,14 +664,8 @@ export type ProxyOptions = { * autoUpdate and force-installs the owner-recommended version when the * local version falls inside an affected range. Default ON. */ advisoryCheck: boolean; - /** Tiered release-notes visibility (#1870): fetch + cache only — never - * installs, never restarts. Default ON. */ - releaseNotesCheck: boolean; /** Override for the advisory document URL (env BILI_ADVISORY_URL wins). */ advisoryUrl?: string; - /** Override for the release-notes document URL (env - * BILI_RELEASE_NOTES_URL wins) (#1870). */ - releaseNotesUrl?: string; logFile?: string; /** MITM transparent-proxy mode. When enabled, an HTTP CONNECT handler is * attached so clients that only know how to set HTTP_PROXY (ZCode with a @@ -1112,11 +1106,7 @@ export function loadOptions(env: NodeJS.ProcessEnv = process.env): ProxyOptions // Default ON: unlike autoRestartOnUpdate, this never touches process // liveness — it only installs files and warns (#1481). advisoryCheck: (env.BILI_ADVISORY_CHECK ?? (fileConfig.advisoryCheck === false ? "0" : "1")) !== "0", - // Default ON: same reasoning as advisoryCheck — pure visibility (fetch - // + cache; never installs, never restarts) (#1870). - releaseNotesCheck: (env.BILI_RELEASE_NOTES_CHECK ?? (fileConfig.releaseNotesCheck === false ? "0" : "1")) !== "0", advisoryUrl: env.BILI_ADVISORY_URL || fileConfig.advisoryUrl || undefined, - releaseNotesUrl: env.BILI_RELEASE_NOTES_URL || fileConfig.releaseNotesUrl || undefined, logFile: env.ACP_LOG_FILE !== undefined ? (env.ACP_LOG_FILE || undefined) : fileConfig.logFile, mitm: { enabled: (env.BILI_MITM ?? (fileConfig.mitm?.enabled === false ? "0" : "1")) !== "0", @@ -1198,14 +1188,8 @@ type FileConfig = { /** Set `false` to disable the critical-defect advisory watcher (#1481); * env BILI_ADVISORY_CHECK wins when set. */ advisoryCheck?: boolean; - /** Set `false` to disable the tiered release-notes visibility watcher - * (#1870); env BILI_RELEASE_NOTES_CHECK wins when set. */ - releaseNotesCheck?: boolean; /** Override for the advisory document URL (env BILI_ADVISORY_URL wins). */ advisoryUrl?: string; - /** Override for the release-notes document URL (env - * BILI_RELEASE_NOTES_URL wins) (#1870). */ - releaseNotesUrl?: string; upstreamProxy?: string; upstreamProxyMode?: string; logFile?: string; diff --git a/src/plugin.ts b/src/plugin.ts index 64f7c01da4..3b460fb0e3 100644 --- a/src/plugin.ts +++ b/src/plugin.ts @@ -19,7 +19,6 @@ import { emitStreamError, emitUpstreamTruncation } from "./stream-error.js"; import { degenerateTurnWarning } from "./degenerate-turn.js"; import { PANEL_BOX_FOOTER } from "./acp-panel.js"; import { describeAdvisory, getAdvisoryState } from "./advisory.js"; -import { describeUpdateReady, getUpdateVisibility } from "./update-notes.js"; import { warnCacheCollapse } from "./cache-warn.js"; import { settleUsageReport } from "./cache-ledger.js"; import { promptInputTotal, type WireProtocol } from "./util.js"; @@ -866,13 +865,8 @@ export function handlePluginStatus(conversationId: string, res: import("node:htt if (adv.active) { preFooter.push(`⚠️ CRITICAL ADVISORY: ${describeAdvisory(adv.active, adv.lastError)}`); } - const upd = getUpdateVisibility(VERSION); - if (upd.visible) { - // #1870: visibility for the silent courier — one line, same - // before-footer slot as the advisory (remote-doc text; the $-escape - // below already covers it). - preFooter.push(describeUpdateReady(upd)); - } + // #1977: release-notes visibility is silent by default — the advisory + // above is the only auto-visible update channel left here. const webUrl = webSessionUrl(deps.webOrigin, session.id); if (webUrl !== undefined) { preFooter.push(`Web UI: ${webUrl}`); diff --git a/src/update-notes.ts b/src/update-notes.ts deleted file mode 100644 index c3a1108896..0000000000 --- a/src/update-notes.ts +++ /dev/null @@ -1,323 +0,0 @@ -/** - * Tiered release-notes visibility (#1870). - * - * The npm companion package `billion-context-release-notes` (published by CI - * from this repo's release-notes/ directory, exactly like the advisories - * companion) carries one model-written summary per release with a tier label: - * - routine — default; worth having, no urgency - * - recommended — worth restarting soon (correctness/cache fixes) - * Critical defects stay in the ADVISORY doc (#1481) — it is the only - * authoritative source for force-upgrades; this doc never claims critical. - * - * Why a watcher at all: the self-updater is a silent courier — it downloads a - * new version and writes one log line ("Restart to finish") that native-lane - * users (pi/opencode/dsh) never see, so disk runs new while the process runs - * old for days. This module keeps the state the visibility surfaces - * (acp_status, the /acp panel) read: the running version, the disk version - * (restart pending = disk newer than running), and the release notes SPAN — - * every entry strictly newer than the running version, which is exactly - * "what you'll get when you restart" from the USER's point of view. - * - * Fail-open everywhere: an unreachable or malformed source must never degrade - * a working proxy. No install side effects here — visibility only. - */ -import { readFile, writeFile, mkdir } from "node:fs/promises"; -import path from "node:path"; -import semver from "semver"; -import { cacheDir } from "./paths.js"; -import { log as loggerLog, type Logger } from "./logger.js"; -import type { FetchOptions } from "./fetch-util.js"; -import { CHECK_INTERVAL_MS, egressDispatcher, findInstallDir, readDiskVersion, registryUrlFor } from "./update.js"; - -const RELEASE_NOTES_PACKAGE = "billion-context-release-notes"; -const SUPPORTED_SCHEMA = 1; -/** Producer-side cap (release-notes/README): the doc keeps ~20 entries. */ -export const MAX_RELEASE_NOTES_ENTRIES = 20; - -export type ReleaseTier = "routine" | "recommended"; - -export type ReleaseNoteEntry = { - /** Exact released version this entry describes. */ - version: string; - /** ISO date (YYYY-MM-DD) of the release. */ - date?: string; - tier: ReleaseTier; - /** Model-written, user-meaningful one-liner (what changes for you). */ - summary: string; -}; - -export type ReleaseNotesState = { - /** Newest-first as published; empty until the first successful check. */ - entries: ReleaseNoteEntry[]; - /** Disk version captured by the last watcher cycle (restart-pending - * signal: disk newer than the RUNNING version). */ - diskVersion?: string; - lastCheckAt?: number; - lastError?: string; -}; - -let state: ReleaseNotesState = { entries: [] }; - -export function getReleaseNotesState(): ReleaseNotesState { - return state; -} - -/** Test seam: replace the live state without driving the watcher. */ -export function _setReleaseNotesStateForTest(s: ReleaseNotesState): void { - state = s; -} - -/** Test seam: clear state, warn dedupe, and stop the timer. */ -export function _resetReleaseNotesWatcherForTest(): void { - state = { entries: [] }; - warnedKeys.clear(); - stopReleaseNotesWatcher(); -} - -/** Default source: the companion package's `latest` doc on the SAME - * configured registry as the updater (BILI_UPDATE_REGISTRY aware via - * registryUrlFor) — mirroring the advisory source. An explicit override wins - * verbatim. */ -export function resolveReleaseNotesUrl(configured: string | undefined): string { - const v = configured?.trim(); - if (v) return v; - return registryUrlFor(RELEASE_NOTES_PACKAGE, "latest"); -} - -/** Validate the raw release-notes document (the companion package's packument - * entry, whose custom field carries the payload). Malformed entries are - * skipped individually; a document with entries but zero usable ones is an - * error so callers can distinguish "no notes" from "broken feed". */ -export function parseReleaseNotesDoc(raw: unknown): { entries: ReleaseNoteEntry[]; error?: string } { - if (typeof raw !== "object" || raw === null || Array.isArray(raw)) { - return { entries: [], error: "document is not a JSON object" }; - } - const payload = (raw as Record).billionContextReleaseNotes; - if (typeof payload !== "object" || payload === null || Array.isArray(payload)) { - return { entries: [], error: "missing billionContextReleaseNotes object" }; - } - const p = payload as Record; - if (p.schema !== SUPPORTED_SCHEMA) { - return { entries: [], error: `unsupported schema ${String(p.schema)} (supported: ${SUPPORTED_SCHEMA})` }; - } - if (!Array.isArray(p.releases)) { - return { entries: [], error: "releases field is not an array" }; - } - const entries: ReleaseNoteEntry[] = []; - for (const item of p.releases) { - if (typeof item !== "object" || item === null) continue; - const e = item as Record; - const version = typeof e.version === "string" ? e.version.trim() : ""; - const tier = e.tier === "recommended" || e.tier === "routine" ? e.tier : undefined; - const summary = typeof e.summary === "string" ? e.summary.trim() : ""; - if (!semver.valid(version) || tier === undefined || !summary) continue; - entries.push({ - version, - tier, - summary, - ...(typeof e.date === "string" && e.date.trim() ? { date: e.date.trim() } : {}), - }); - } - if (p.releases.length > 0 && entries.length === 0) { - return { entries: [], error: "no valid release-note entries in document" }; - } - return { entries }; -} - -/** The notes a caller RUNNING `fromVersion` would gain — every entry strictly - * newer, ordered oldest→newest so the span reads chronologically ("you'll - * get 0.1.180, then 0.1.181"). This is the user-side diff between the - * current version and the newest release. Invalid `fromVersion` → empty. */ -export function spanNotes(entries: ReleaseNoteEntry[], fromVersion: string): ReleaseNoteEntry[] { - if (!semver.valid(fromVersion)) return []; - return entries - .filter((e) => { - try { - return semver.gt(e.version, fromVersion); - } catch { - return false; - } - }) - .sort((a, b) => semver.compare(a.version, b.version)); -} - -/** The newest valid entry, or undefined when the feed is empty/unknown. */ -export function latestKnownVersion(entries: ReleaseNoteEntry[]): string | undefined { - let best: string | undefined; - for (const e of entries) { - if (best === undefined || semver.gt(e.version, best)) best = e.version; - } - return best; -} - -export type UpdateVisibility = { - runningVersion: string; - /** Disk version if the watcher saw one (undefined = unknown). */ - diskVersion?: string; - /** Disk holds a strictly newer version than this process — a restart - * finishes the update. The one action that clears the notice. */ - pendingRestart: boolean; - /** Notes for everything between running and the newest known release. */ - span: ReleaseNoteEntry[]; - /** A recommended-tier entry sits in the span — worth updating soon even - * without a pending restart (e.g. auto-update disabled). */ - recommended: boolean; -}; - -/** Derived, synchronous view for the visibility surfaces (#1870): reads the - * watcher's cached state — no network, no fs. Clean installs (no span, no - * pending restart) yield visible=false and every surface stays - * byte-identical to the pre-#1870 output. */ -export function getUpdateVisibility(runningVersion: string): UpdateVisibility & { visible: boolean } { - const diskVersion = state.diskVersion; - const pendingRestart = - diskVersion !== undefined && - semver.valid(diskVersion) === diskVersion && - semver.gt(diskVersion, runningVersion); - const span = spanNotes(state.entries, runningVersion); - const recommended = span.some((e) => e.tier === "recommended"); - return { - runningVersion, - ...(diskVersion !== undefined ? { diskVersion } : {}), - pendingRestart, - span, - recommended, - visible: pendingRestart || recommended, - }; -} - -/** Shared wording for the /acp panel line — one line, stripper-safe slot is - * the caller's job. Kept compact: the panel is small, and acp_status carries - * the full span. */ -export function describeUpdateReady(v: UpdateVisibility): string { - const latest = v.span.length > 0 ? v.span[v.span.length - 1].version : v.diskVersion; - const topRec = v.span.find((e) => e.tier === "recommended"); - if (v.pendingRestart && latest !== undefined) { - const notable = topRec ? ` Notable since ${v.runningVersion}: ${topRec.summary}` : ""; - return `Update ready: ${latest} — restart to finish.${notable}`; - } - if (topRec && latest !== undefined) { - return `Update available: ${latest} (recommended) — ${topRec.summary} (npm install -g billion-context@${latest})`; - } - return `Update available: ${latest ?? "newer version"} — npm install -g billion-context@${latest ?? "latest"}`; -} - -function throttleFile(): string { - return path.join(cacheDir(), ".release-notes-check"); -} - -async function readLastCheck(): Promise { - try { - const data = await readFile(throttleFile(), "utf-8"); - return parseInt(data.trim(), 10) || 0; - } catch { - return 0; - } -} - -async function writeLastCheck(ts: number): Promise { - try { - await mkdir(path.dirname(throttleFile()), { recursive: true }); - await writeFile(throttleFile(), String(ts), "utf-8"); - } catch { - // best-effort - } -} - -export type ReleaseNotesWatcherOptions = { - packageName: string; - /** Running process version (disk wins when readable, same rule as the - * updater). */ - currentVersion: string; - /** Override for the notes document URL (config `releaseNotesUrl` / env - * BILI_RELEASE_NOTES_URL). Absent = companion package on the configured - * registry. */ - releaseNotesUrl?: string; - resolveProxy?: (url: string) => string | undefined; - /** Test seam: pin the install directory instead of findInstallDir(). */ - installDir?: string; - log?: Logger; -}; - -let timer: ReturnType | undefined; -let inFlight = false; -let firstCheckDone = false; -const warnedKeys = new Set(); - -function warnOnce(log: Logger, key: string, message: string): void { - if (warnedKeys.has(key)) return; - warnedKeys.add(key); - log("warn", message); -} - -/** Run one release-notes check (throttled unless `force`). Fetches the notes - * doc and re-reads the disk version — visibility only, NEVER installs. */ -export async function runReleaseNotesCheck(opts: ReleaseNotesWatcherOptions, force = false): Promise { - if (inFlight) return; - inFlight = true; - const log = opts.log ?? loggerLog; - try { - const now = Date.now(); - const lastCheck = await readLastCheck(); - if (!force && firstCheckDone && now - lastCheck < CHECK_INTERVAL_MS) return; - await writeLastCheck(now); - firstCheckDone = true; - - const url = resolveReleaseNotesUrl(opts.releaseNotesUrl); - let data: unknown; - try { - const dispatcher = egressDispatcher({ resolveProxy: opts.resolveProxy }, url); - const init: FetchOptions = { - method: "GET", - headers: { Accept: "application/json" }, - signal: AbortSignal.timeout(5000), - ...(dispatcher ? { dispatcher } : {}), - }; - const res = await fetch(url, init as RequestInit); - if (!res.ok) throw new Error(`release-notes source returned HTTP ${res.status}`); - data = await res.json(); - } catch (e) { - state.lastError = String(e); - warnOnce(log, `fetch:${String(e)}`, `[release-notes] check failed (${String(e)}) — continuing without release notes`); - return; - } - const parsed = parseReleaseNotesDoc(data); - if (parsed.error) { - state.lastError = parsed.error; - warnOnce(log, `parse:${parsed.error}`, `[release-notes] ignoring malformed document: ${parsed.error}`); - return; - } - state.entries = parsed.entries.slice(0, MAX_RELEASE_NOTES_ENTRIES); - state.lastError = undefined; - state.lastCheckAt = now; - - // Restart-pending signal: disk vs the RUNNING process version. - const installDir = opts.installDir ?? (await findInstallDir(opts.packageName)); - state.diskVersion = installDir ? await readDiskVersion(installDir) : undefined; - } catch (e) { - state.lastError = String(e); - warnOnce(log, `check:${String(e)}`, `[release-notes] check failed: ${String(e)}`); - } finally { - inFlight = false; - } -} - -export function startReleaseNotesWatcher(opts: ReleaseNotesWatcherOptions): void { - if (timer) return; - loggerLog("info", `[release-notes] watcher enabled (checking every ${CHECK_INTERVAL_MS / 1000 | 0}s, visibility only — never installs)`); - setTimeout(() => { - void runReleaseNotesCheck(opts); - }, 15_000); - timer = setInterval(() => { - void runReleaseNotesCheck(opts); - }, CHECK_INTERVAL_MS); - timer.unref?.(); -} - -/** Stop the periodic check loop (for tests / clean shutdown). */ -export function stopReleaseNotesWatcher(): void { - if (timer) { - clearInterval(timer); - timer = undefined; - } -} diff --git a/tests/update-notes.test.ts b/tests/update-notes.test.ts deleted file mode 100644 index b03a95cd35..0000000000 --- a/tests/update-notes.test.ts +++ /dev/null @@ -1,272 +0,0 @@ -// #1870: tiered release-notes visibility. The self-updater is a silent -// courier on native lanes (its "Restart to finish" line only reaches a log -// file), so disk runs new while the process runs old. These tests pin the -// three behaviors that make the fix safe and useful: -// 1. parsing/validation of the remote doc (bad entries skipped, bad doc = error), -// 2. the user-side span + visibility derivation (restart-pending beats -// everything; recommended surfaces even without pending restart; clean -// installs see NOTHING — byte-identical to pre-#1870 output), -// 3. the two surfaces: acp_status section + /acp panel line before the -// footer (stripper-safe), with remote-doc text escaped for replace(). -import { test } from "node:test"; -import assert from "node:assert/strict"; -import http from "node:http"; -import type { Config, CoreMessage } from "acp-kernel"; -import { createCore, createInitialState, assignRefs, emptyRefMap, defaultConfig } from "acp-kernel"; -import type { Session } from "../src/session.ts"; -import { - _resetReleaseNotesWatcherForTest, - _setReleaseNotesStateForTest, - parseReleaseNotesDoc, - spanNotes, - getUpdateVisibility, - describeUpdateReady, - type ReleaseNoteEntry, -} from "../src/update-notes.ts"; -import { VERSION } from "../src/version.ts"; -import semver from "semver"; - -// #1870 follow-up: the two SURFACE tests below exercise the real running -// version (package.json at runtime), so their fixtures must be derived FROM -// it — hardcoded 0.1.18x strings rotted the moment v0.1.180 shipped and put -// master's CI red after the #1870 merge. The explicit-version unit tests -// above keep hardcoded strings (they pin spanNotes logic, not this repo's -// current version). -const RUNNING = semver.valid(VERSION) ?? "0.0.1"; -const NEXT = semver.inc(RUNNING, "patch") ?? "0.0.2"; -const NEXT2 = semver.inc(NEXT, "patch") ?? "0.0.3"; -const SURFACE_ENTRIES: ReleaseNoteEntry[] = [ - { version: NEXT2, tier: "routine", summary: "docs and log polish" }, - { version: NEXT, date: "2026-10-02", tier: "recommended", summary: "OpenCode WebSocket traffic intercepted again (#1844)" }, - { version: RUNNING, tier: "recommended", summary: "compression survives restart/resume forks (#1834)" }, -]; - -const ENTRIES: ReleaseNoteEntry[] = [ - { version: "0.1.181", tier: "routine", summary: "docs and log polish" }, - { version: "0.1.180", date: "2026-10-02", tier: "recommended", summary: "OpenCode WebSocket traffic intercepted again (#1844)" }, - { version: "0.1.179", tier: "recommended", summary: "compression survives restart/resume forks (#1834)" }, -]; - -test("#1870 parseReleaseNotesDoc: valid doc parses; malformed entries skip; broken doc errors", () => { - const doc = { - billionContextReleaseNotes: { - schema: 1, - releases: [ - { version: "0.1.181", tier: "routine", summary: "ok" }, - { version: "not-semver", tier: "routine", summary: "skipped" }, - { version: "0.1.180", tier: "urgent", summary: "bad tier skipped" }, - { version: "0.1.179", tier: "routine", summary: " " }, - { version: "0.1.178", tier: "recommended", date: "2026-10-01", summary: "ok with date" }, - ], - }, - }; - const parsed = parseReleaseNotesDoc(doc); - assert.equal(parsed.error, undefined); - assert.equal(parsed.entries.length, 2); - assert.equal(parsed.entries[0].version, "0.1.181"); - assert.equal(parsed.entries[1].date, "2026-10-01"); - - assert.equal(parseReleaseNotesDoc(null).error, "document is not a JSON object"); - assert.equal(parseReleaseNotesDoc({}).error, "missing billionContextReleaseNotes object"); - assert.equal(parseReleaseNotesDoc({ billionContextReleaseNotes: { schema: 2, releases: [] } }).error, "unsupported schema 2 (supported: 1)"); - assert.equal(parseReleaseNotesDoc({ billionContextReleaseNotes: { schema: 1, releases: "no" } }).error, "releases field is not an array"); - // Entries present but ALL invalid → error (distinguish broken feed from empty). - const allBad = parseReleaseNotesDoc({ billionContextReleaseNotes: { schema: 1, releases: [{ version: "x", tier: "routine", summary: "s" }] } }); - assert.equal(allBad.error, "no valid release-note entries in document"); - // Empty releases array = legitimate empty feed, not an error. - assert.deepEqual(parseReleaseNotesDoc({ billionContextReleaseNotes: { schema: 1, releases: [] } }), { entries: [] }); -}); - -test("#1870 spanNotes: strictly-newer entries, ascending (user-side diff), invalid base = none", () => { - const span = spanNotes(ENTRIES, "0.1.179"); - assert.deepEqual(span.map((e) => e.version), ["0.1.180", "0.1.181"], "excludes the running version itself, oldest first"); - assert.deepEqual(spanNotes(ENTRIES, "0.1.180").map((e) => e.version), ["0.1.181"]); - assert.deepEqual(spanNotes(ENTRIES, "0.1.181"), [], "up to date → empty span"); - assert.deepEqual(spanNotes(ENTRIES, "0.1.182"), [], "future version → empty span"); - assert.deepEqual(spanNotes(ENTRIES, "garbage"), [], "invalid running version → empty (no crash)"); -}); - -test("#1870 getUpdateVisibility: pending restart beats everything; recommended-only still visible; clean = invisible", () => { - _resetReleaseNotesWatcherForTest(); - try { - // Clean install: no disk info, no span → invisible (byte-identical surfaces). - const clean = getUpdateVisibility(VERSION); - assert.equal(clean.visible, false); - assert.equal(clean.pendingRestart, false); - assert.deepEqual(clean.span, []); - - // Recommended release exists beyond running version (auto-update off). - _setReleaseNotesStateForTest({ entries: ENTRIES }); - const recOnly = getUpdateVisibility("0.1.179"); - assert.equal(recOnly.pendingRestart, false); - assert.equal(recOnly.recommended, true); - assert.equal(recOnly.visible, true, "recommended alone must surface (updater may be off)"); - assert.deepEqual(recOnly.span.map((e) => e.version), ["0.1.180", "0.1.181"]); - - // Disk newer than running → restart-pending, the actionable case. - _setReleaseNotesStateForTest({ entries: ENTRIES, diskVersion: "0.1.181" }); - const pending = getUpdateVisibility("0.1.179"); - assert.equal(pending.pendingRestart, true); - assert.equal(pending.visible, true); - - // Disk older or equal (edge: rollback / same) → not pending. - assert.equal(getUpdateVisibility("0.1.181").pendingRestart, false); - _setReleaseNotesStateForTest({ entries: ENTRIES, diskVersion: "0.1.175" }); - assert.equal(getUpdateVisibility("0.1.179").pendingRestart, false); - // Disk version garbage → never pending (fail-closed on visibility, no crash). - _setReleaseNotesStateForTest({ entries: [], diskVersion: "not-semver" }); - const garbage = getUpdateVisibility("0.1.179"); - assert.equal(garbage.pendingRestart, false); - assert.equal(garbage.visible, false); - } finally { - _resetReleaseNotesWatcherForTest(); - } -}); - -test("#1870 describeUpdateReady: actionable wording + byte-stability", () => { - _resetReleaseNotesWatcherForTest(); - try { - _setReleaseNotesStateForTest({ entries: ENTRIES, diskVersion: "0.1.181" }); - const pending = getUpdateVisibility("0.1.179"); - const line = describeUpdateReady(pending); - assert.ok(line.startsWith("Update ready: 0.1.181 — restart to finish."), `pending-restart wording (got: ${line})`); - assert.ok(line.includes("#1844"), "top recommended summary carried"); - assert.equal(line, describeUpdateReady(getUpdateVisibility("0.1.179")), "byte-stable for identical state"); - - _setReleaseNotesStateForTest({ entries: ENTRIES }); // no disk info - const rec = describeUpdateReady(getUpdateVisibility("0.1.179")); - assert.ok(rec.startsWith("Update available: 0.1.181 (recommended) —"), `recommended wording (got: ${rec})`); - assert.ok(rec.includes("npm install -g billion-context@0.1.181"), "manual command when restart cannot finish it"); - - // Span with NO recommended entry + no pending restart = invisible; the - // routine-only branch exists for panel completeness only. - const routineOnly = getUpdateVisibility("0.1.178"); // span = 179(rec),… — pick a base where span is routine-only - const routineEntries: ReleaseNoteEntry[] = [{ version: "0.2.0", tier: "routine", summary: "polish" }]; - _setReleaseNotesStateForTest({ entries: routineEntries }); - const ro = getUpdateVisibility("0.1.179"); - assert.equal(ro.recommended, false); - assert.equal(ro.visible, false); - assert.ok(describeUpdateReady(ro).includes("0.2.0"), "fallback line still names the version"); - assert.ok(routineOnly !== undefined); - } finally { - _resetReleaseNotesWatcherForTest(); - } -}); - -// --------------------------------------------------------------------------- -// Surfaces. Mirrors the #1577 advisory-surface tests. - -function textMsg(id: string, role: "user" | "assistant", text: string): CoreMessage { - return { id, role, contentType: "text", text }; -} - -function makeCtx(messages: CoreMessage[]): { core: ReturnType; config: Config; messages: CoreMessage[]; session: Session; log: (m: string) => void } { - return { - core: createCore(), - config: defaultConfig(200000), - messages, - session: { - id: "update-notes-test", - meta: {}, - stats: { requests: 0, tokensSaved: 0, inputTokens: 0, cachedTokens: 0, outputTokens: 0, cacheSamples: 0, lastInputTokens: 15000, compressCreditTokens: 0, contextTokens: 0 }, - metadata: {}, - state: createInitialState(), - createdAt: Date.now(), - lastSeen: Date.now(), - blockContents: new Map(), - inFlight: 0, - persisted: false, - }, - log: () => {}, - }; -} - -function makeCtx12(): ReturnType { - const msgs: CoreMessage[] = []; - for (let i = 1; i <= 12; i++) msgs.push(textMsg(`raw_${i}`, i % 2 === 1 ? "user" : "assistant", "x".repeat(5000))); - const ctx = makeCtx(msgs); - ctx.session.state.messageRefs = assignRefs(ctx.messages, { existing: emptyRefMap(), nextIndex: 0 }).map; - return ctx; -} - -function mockRes(): { res: http.ServerResponse; status: number; body: string } { - const out = { res: undefined as unknown as http.ServerResponse, status: 0, body: "" }; - const res = { - writeHead(code: number) { out.status = code; return res; }, - end(chunk?: unknown) { if (typeof chunk === "string") out.body = chunk; return res; }, - } as unknown as http.ServerResponse; - out.res = res; - return out; -} - -test("#1870 acp_status: UPDATE READY section lists the span; clean state stays byte-absent", async () => { - _resetReleaseNotesWatcherForTest(); - const { handleAcpStatus } = await import("../src/acp-status.ts"); - try { - const ctx = makeCtx12(); - const clean = handleAcpStatus({}, ctx); - assert.ok(!clean.includes("UPDATE READY") && !clean.includes("UPDATE AVAILABLE"), "no section on a clean install"); - - _setReleaseNotesStateForTest({ entries: SURFACE_ENTRIES, diskVersion: NEXT2 }); - const out = handleAcpStatus({}, ctx); - assert.ok(out.includes(`UPDATE READY (instance-level): ${NEXT2} downloaded — restart this agent's proxy to finish`), "actionable headline names the disk version"); - assert.ok(out.includes(`(running ${VERSION})`), "names the running version for contrast"); - assert.ok(out.includes(`· ${NEXT} [recommended] OpenCode WebSocket traffic intercepted again (#1844)`), "span renders versions below disk but above running, tier-first"); - assert.ok(out.includes(`· ${NEXT2} [routine] docs and log polish`), "span renders up to the disk version the restart will finish"); - assert.ok(out.includes("GET /__bili/status → update"), "points at the live-state field"); - - // No disk info (auto-update off): AVAILABLE wording + manual command. - _setReleaseNotesStateForTest({ entries: SURFACE_ENTRIES }); - const avail = handleAcpStatus({}, ctx); - assert.ok(avail.includes("UPDATE AVAILABLE (instance-level):"), "available headline when nothing is pending"); - assert.ok(avail.includes(`npm install -g billion-context@${NEXT2}`), "manual update command present"); - assert.ok(!avail.includes("UPDATE READY"), "ready wording reserved for the pending-restart case"); - } finally { - _resetReleaseNotesWatcherForTest(); - } -}); - -test("#1870 /acp panel: one update line BEFORE the footer, stripper-safe, byte-exact when clean; $ survives", async () => { - _resetReleaseNotesWatcherForTest(); - const { _resetSessionsForTest } = await import("../src/session.ts"); - const { handlePluginStatus } = await import("../src/plugin.ts"); - const { PANEL_BOX_FOOTER } = await import("../src/acp-panel.ts"); - try { - _resetSessionsForTest(); - const { getSession } = await import("../src/session.ts"); - getSession("upd-sess", { protocol: "anthropic", label: "UPD" }); - const deps = { core: createCore(), config: defaultConfig(200000), log: (_l: string, _m: string) => {} }; - - const r0 = mockRes(); - handlePluginStatus("never-seen", r0.res, deps, true); - assert.equal(r0.status, 200); - const p0 = JSON.parse(r0.body).panel as string; - assert.ok(!p0.includes("Update ready") && !p0.includes("Update available"), "no update line when clean"); - assert.ok(p0.includes(PANEL_BOX_FOOTER), "footer present when clean"); - - _setReleaseNotesStateForTest({ entries: SURFACE_ENTRIES, diskVersion: NEXT2 }); - const r1 = mockRes(); - handlePluginStatus("never-seen", r1.res, deps, true); - const p1 = JSON.parse(r1.body).panel as string; - assert.ok(p1.includes(`Update ready: ${NEXT2} — restart to finish.`), "panel line present"); - assert.ok(p1.includes(PANEL_BOX_FOOTER), "footer still present with the update line"); - assert.ok(p1.indexOf("Update ready") < p1.indexOf(PANEL_BOX_FOOTER), "update line sits BEFORE the footer (stripper anchor)"); - const footerEsc = PANEL_BOX_FOOTER.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); - assert.equal((p1.match(new RegExp(footerEsc, "g")) ?? []).length, 1, "footer appears exactly once"); - - // Remote-doc summary containing replace() pattern syntax must survive - // byte-exact (same escape the advisory line relies on). - const dollarSummary = "saves $5 and echoes $& `$'` verbatim"; - _setReleaseNotesStateForTest({ - entries: [{ version: NEXT, tier: "recommended", summary: dollarSummary }], - diskVersion: NEXT, - }); - const r2 = mockRes(); - handlePluginStatus("never-seen", r2.res, deps, true); - const p2 = JSON.parse(r2.body).panel as string; - assert.ok(p2.includes(dollarSummary), "dollar-sign summary survives byte-exact"); - } finally { - _resetReleaseNotesWatcherForTest(); - _resetSessionsForTest(); - } -});