diff --git a/src/cli.ts b/src/cli.ts index 45166f5fc8..f41bda689d 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -685,7 +685,7 @@ export async function main(): Promise { packageName: PACKAGE_NAME, resolveProxy: updaterResolveProxy, updateTag, - globalCheck: () => checkForUpdate({ packageName: PACKAGE_NAME, currentVersion: VERSION, autoUpdate: true, resolveProxy: updaterResolveProxy, updateTag }, true), + globalCheck: async () => { await checkForUpdate({ packageName: PACKAGE_NAME, currentVersion: VERSION, autoUpdate: true, resolveProxy: updaterResolveProxy, updateTag }, true); }, log: (_level, msg) => console.log(msg), }); for (const line of lines) console.log(line); diff --git a/src/client-ua-registry.ts b/src/client-ua-registry.ts new file mode 100644 index 0000000000..48910b16d2 --- /dev/null +++ b/src/client-ua-registry.ts @@ -0,0 +1,114 @@ +// #4649: recently observed client user-agents, per client family. The +// diagnostics blob used to carry ONLY dsh profile-bundle versions, so a +// conflict report from a non-dsh client (e.g. codex, #4648) had neither the +// client's own version nor — before the codex entries in CONFLICT_LOG_PATTERNS +// landed — any log evidence to adjudicate with, forcing a manual round-trip +// for `codex --version` and hand-picked log lines. +// +// The proxy sees the requesting UA on every model request; this module keeps +// a bounded in-memory map of what was observed and the "host client versions" +// section of the report publishes it. Process-scoped by design: a restart +// starts fresh, and a report generated while traffic flows reflects live +// clients. In-memory only — nothing here is persisted or sent upstream. +// +// Publish discipline: the values are raw client-supplied header bytes, but +// they only leave the process through buildDiagnostics' sink-level +// redactForPublish (#4427), which scrubs credential shapes, masks private +// hosts, and ~-normalizes home paths across the whole blob. Length is bounded +// at ingest (UA_MAX_CHARS) so one hostile UA cannot bloat the pasteable blob. + +import { isCodexClient } from "./codex-compact.js"; +import { sniffScanClient } from "./thirdparty-scan.js"; + +// Read directly (wire literal) instead of via plugin.ts — same discipline as +// codex-compact.ts / session-id.ts: importing plugin.ts back into the request +// path would close an ESM cycle through loop/tag-echo-filter.ts. +const BILI_PLUGIN_MARKER = "x-bili-plugin"; + +const FAMILY_CAP = 24; +const UA_CAP_PER_FAMILY = 8; +const UA_MAX_CHARS = 120; +const OTHER_FAMILY = "other"; + +interface FamilyEntry { + uas: Map; +} + +const families = new Map(); + +function headerString(headers: Record, name: string): string | undefined { + const v = headers[name]; + if (Array.isArray(v)) return typeof v[0] === "string" ? v[0] : undefined; + return typeof v === "string" ? v : undefined; +} + +/** Client family for UA bookkeeping — mirrors conflictClientOf's resolution + * ladder (declared plugin agent > header sniff > codex UA shape) keyed off + * the raw request headers. "mcp" is not a client name (MCP evidence flip, + * #760b), so it falls through like in conflict-watch. */ +export function clientFamilyOf(headers: Record): string { + const agent = headerString(headers, BILI_PLUGIN_MARKER); + if (agent && agent !== "mcp") return agent; + const sniffed = sniffScanClient(headers); + if (sniffed) return sniffed; + const ua = headerString(headers, "user-agent"); + if (ua && isCodexClient({ "user-agent": ua })) return "codex"; + return OTHER_FAMILY; +} + +/** Latest-wins per exact UA string; evicts the oldest UA inside a family past + * UA_CAP_PER_FAMILY, and the least-recently-seen family past FAMILY_CAP, so a + * hostile or churning client can only occupy bounded slots. */ +export function recordClientUa(headers: Record): void { + const raw = headerString(headers, "user-agent"); + if (!raw || !raw.trim()) return; + const ua = raw.trim().slice(0, UA_MAX_CHARS); + const now = Date.now(); + let fam = families.get(clientFamilyOf(headers)); + if (!fam) { + if (families.size >= FAMILY_CAP) { + let oldestKey: string | undefined; + let oldestAt = Infinity; + for (const [k, v] of families) { + let newest = -Infinity; + for (const t of v.uas.values()) if (t > newest) newest = t; + if (newest < oldestAt) { oldestAt = newest; oldestKey = k; } + } + if (oldestKey !== undefined) families.delete(oldestKey); + } + fam = { uas: new Map() }; + families.set(clientFamilyOf(headers), fam); + } + fam.uas.set(ua, now); + while (fam.uas.size > UA_CAP_PER_FAMILY) { + let oldestUa: string | undefined; + let oldestAt = Infinity; + for (const [u, t] of fam.uas) { + // strict < keeps first-inserted on timestamp ties (FIFO eviction) + if (t < oldestAt) { oldestAt = t; oldestUa = u; } + } + if (oldestUa === undefined) break; + fam.uas.delete(oldestUa); + } +} + +interface ObservedUa { + family: string; + ua: string; +} + +/** All recorded observations — families alphabetical, newest-first within a + * family — for the diagnostics section to render under its own display cap. */ +export function recentClientUas(): ObservedUa[] { + const out: ObservedUa[] = []; + const sortedFamilies = [...families.entries()].sort((a, b) => a[0].localeCompare(b[0])); + for (const [family, fam] of sortedFamilies) { + const sortedUas = [...fam.uas.entries()].sort((a, b) => b[1] - a[1]); + for (const [ua] of sortedUas) out.push({ family, ua }); + } + return out; +} + +export function _resetClientUaRegistryForTest(): void { + families.clear(); +} diff --git a/src/server/admin.ts b/src/server/admin.ts index 248fe7bc1f..128ae7751a 100644 --- a/src/server/admin.ts +++ b/src/server/admin.ts @@ -976,10 +976,12 @@ function handleConflictsClear(url: string, res: http.ServerResponse, log: (level // ---- #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. */ +/** POST /__bili/update/check — run ONE check-only registry pass through the + * shared update options (#4791): full gate ladder, structured verdict + * ({status, latest?, candidate?, note?}), NO download/install — installs + * happen on /__bili/update/install. 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" }); diff --git a/src/server/handle.ts b/src/server/handle.ts index 441428230a..54b4fce7f1 100644 --- a/src/server/handle.ts +++ b/src/server/handle.ts @@ -13,6 +13,7 @@ import { FALLBACK_EFFECTIVE_WINDOW_FLOOR, findRoute, findRouteKey, lookupContext import { resolveProxyDecision } from "../upstream-proxy.js"; import { contextFromRegistry, peekRegistryContext, peekRegistryOutputLimit, peekRegistryPriceProfile } from "../registry.js"; import { stampBillingPrice } from "../billing.js"; +import { recordClientUa } from "../client-ua-registry.js"; import { codexAlignedWindow } from "../codex-models.js"; import { DecodedRequestAdmission, DecodedRequestBusyError } from "../request-body-budget.js"; import { hostIdForLog, maskHeadersForLog, maskUrlForLog, maskUrlsInText } from "../log-mask.js"; @@ -1673,6 +1674,12 @@ async function handleRequest( } if (!pluginAgent && typeof session.metadata.pluginAgent === "string") pluginAgent = session.metadata.pluginAgent; if (pluginAgent && !pluginConversation) pluginConversation = conversation; + // #4649: remember this request's client UA in the bounded registry so a + // diagnostics report carries the client's own version (non-dsh lanes + // have no profile bundle to read it from). Runs for EVERY model + // request — unlike the clientHint block below, which only fills the + // session's first-seen hint. + recordClientUa(req.headers); // #1426 web UI: persist which client this session came from, first hit wins. // Plugin agents are already recorded above as metadata.pluginAgent; non-plugin // clients fall back to header sniffing, then to a truncated User-Agent hint. diff --git a/src/server/update-actions.ts b/src/server/update-actions.ts index db08a9a159..dafcff436a 100644 --- a/src/server/update-actions.ts +++ b/src/server/update-actions.ts @@ -5,8 +5,9 @@ * 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") + * - a check-only registry pass → checkForUpdate(opts, false, true) (#4791): + * full gate ladder, structured verdict, NO download/install + * - a pinned-version install → forceInstallVersion(v, dir, opts, "web-panel", "manual-web") * (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} @@ -14,7 +15,7 @@ * (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 { checkForUpdate, findInstallDir, forceInstallVersion, lastUpdateCheckTime, readDiskVersion, staleInstallStatus, type UpdateCheckOutcome, type UpdateOptions } from "../update.js"; import { getUpdateVisibility } from "../update-notes.js"; import { log as loggerLog } from "../logger.js"; @@ -67,19 +68,26 @@ 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 }> { +/** Run ONE check-only registry pass through the shared update options + * (#4791): the full gate ladder runs with every safety gate armed — advisory + * block/deferral, source-checkout guard, single-writer guard, remote policy — + * but nothing downloads or installs. force stays FALSE so a gate reports its + * verdict instead of being bypassed; only the pacing gates (throttle window, + * install-failure backoff) are skipped, and the last-checked marker still + * refreshes. The structured verdict ({status, latest?, candidate?, note?}) is + * passed through for the panel; installs happen on /__bili/update/install. + * A concurrent second call reports {ok:true, already:true}; failures come + * back as {ok:false, error} — never a throw. */ +export async function triggerManualCheck(): Promise<{ ok: boolean; error?: string; already?: boolean; status?: UpdateCheckOutcome["status"]; latest?: string; candidate?: string; note?: string }> { 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 }; + const outcome = await checkForUpdate(opts, false, true); + if (outcome === undefined) return { ok: true }; + if (outcome.status === "error") return { ok: false, error: outcome.note ?? "registry check failed" }; + return { ok: true, ...outcome }; } catch (e) { loggerLog("warn", `[update] manual web check failed: ${String(e)}`); return { ok: false, error: String(e) }; @@ -102,7 +110,7 @@ export async function installVersionAction(v: string): Promise<{ ok: boolean; er // 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"); + const result = await forceInstallVersion(v, dir, opts, "web-panel", "manual-web"); 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) { diff --git a/src/update.ts b/src/update.ts index e8410764bc..5a7b28e828 100644 --- a/src/update.ts +++ b/src/update.ts @@ -371,7 +371,10 @@ const LAST_INSTALL_FILE = path.join(cacheDir(), ".last-install.json"); export interface LastInstallRecord { from?: string; version: string; - source: "auto-update" | "manual" | `advisory:${string}`; + /** How it got here: "auto-update" (background loop), "manual" (explicit + * CLI), "manual-web" (the web panel's explicit install button, #4791), or + * "advisory:" — a critical-bug advisory's rollback form (#1588). */ + source: "auto-update" | "manual" | "manual-web" | `advisory:${string}`; at: number; } @@ -1438,13 +1441,17 @@ async function passUpdatePolicyGate(args: { latest: string; tag: string; force: boolean; + /** #4791: user-initiated query — skip rollout PACING (hold/stagger are + * scheduling side-effects a read-only check must not trigger or clear); + * pin/blocked stepping still applies to the reported candidate. */ + skipPacing?: boolean; resolveProxy?: (url: string) => string | undefined; }): Promise<{ candidate: string } | { reason: string }> { const { force } = args; try { const policy = await loadUpdatePolicy({ url: knobUpdatePolicyUrl() ?? POLICY_URL_DEFAULT, resolveProxy: args.resolveProxy }); const doc = policy.doc; - if (!force && doc?.hold) { + if (!force && !args.skipPacing && doc?.hold) { setPlannedUpgrade(undefined); policyGateLogOnce("policy:hold", `[update] HOLD active in the remote update policy — ${args.latest} is available but auto-upgrade is frozen fleet-wide until the owner lifts it; manual escape: \`bili update\` (bypasses hold) or npm install -g ${args.packageName}@${args.latest} (#3619)`); return { reason: "hold" }; @@ -1473,7 +1480,7 @@ async function passUpdatePolicyGate(args: { policyGateLogOnce(`policy:stepped:${args.latest}->${candidate}`, `[update] installing ${candidate} instead of dist-tag ${args.latest} per the remote policy (#3619)`); } } - if (!force) { + if (!force && !args.skipPacing) { const win = resolveStaggerWindow(candidate, doc, knobUpdateStaggerMinDelayMs(), knobUpdateStaggerMaxDelayMs()); const now = Date.now(); const draw = await ensureStaggerDraw({ key: staggerKey(args.tag, candidate), minDelayMs: win.minMs, maxDelayMs: win.maxMs, now }); @@ -1484,7 +1491,7 @@ async function passUpdatePolicyGate(args: { return { reason: "stagger" }; } } - setPlannedUpgrade(undefined); + if (!args.skipPacing) setPlannedUpgrade(undefined); return { candidate }; } catch (e) { policyGateLogOnce(`policy:gatefail:${String(e)}`, `[update] policy gate failed (${String(e)}) — proceeding with the legacy immediate install (#3619)`); @@ -1497,9 +1504,31 @@ export function _resetPolicyGateForTest(): void { policyGateLogged.clear(); } -/** Run a single check (throttled unless `force`). Safe to call frequently. */ -export async function checkForUpdate(opts: UpdateOptions, force = false): Promise { - if (!opts.autoUpdate && !force) return; +/** #4791: structured verdict of a CHECK-ONLY registry pass. The web panel's + * "Check now" runs the full gate ladder (registry fetch, version compare, + * advisory deferral and block, policy stepping) but stops before any download + * — the button reports what an install WOULD do without doing it. Returned + * only on the check-only path; background/forced callers keep the legacy + * void shape. */ +export interface UpdateCheckOutcome { + status: "up-to-date" | "update-available" | "blocked-advisory" | "deferred-advisory" | "refused" | "error"; + /** Registry dist-tag version (when the registry was reached). */ + latest?: string; + /** Version a manual install would land on after policy stepping (pin/block). */ + candidate?: string; + /** One-line machine reason for refused/error verdicts. */ + note?: string; +} + +/** Run a single check (throttled unless `force`). Safe to call frequently. + * `checkOnly` (#4791): run the full gate ladder and report its verdict as an + * outcome, cutting off BEFORE the download/install tail — the web panel's + * "Check now" uses this so a query never installs. Every safety gate stays + * armed on this path: they report their verdict instead of being bypassed; + * only the pacing gates (throttle window, install-failure backoff) are + * skipped. Never throws. */ +export async function checkForUpdate(opts: UpdateOptions, force = false, checkOnly = false): Promise { + if (!opts.autoUpdate && !force && !checkOnly) return; if (inFlight) return; inFlight = true; try { @@ -1515,7 +1544,7 @@ export async function checkForUpdate(opts: UpdateOptions, force = false): Promis const intervalMs = ownerLane ? ownerLaneIntervalMs() : CHECK_INTERVAL_MS; const lastCheck = await readLastCheck(throttleFile); const sinceLastSec = lastCheck ? ((now - lastCheck) / 1000 | 0) : -1; - if (!force && firstCheckDone && now - lastCheck < intervalMs) { + if (!force && !checkOnly && firstCheckDone && now - lastCheck < intervalMs) { const retryIn = ((intervalMs - (now - lastCheck)) / 1000 | 0); loggerLog("info", `[update] throttled \u2014 last checked ${sinceLastSec}s ago, retry in ${retryIn}s`); return; @@ -1524,6 +1553,12 @@ export async function checkForUpdate(opts: UpdateOptions, force = false): Promis firstCheckDone = true; if (!force && opts.advisoryActive?.()) { + if (checkOnly) { + // Report the deferral instead of acting on it — no owner-channel + // refresh either (that IS an update action). + loggerLog("info", "[update] manual web check: deferring to the advisory loop (an active critical-bug advisory owns this install)"); + return { status: "deferred-advisory", note: "an active critical-bug advisory owns this install (#1481)" }; + } // The advisory watcher is working on this install dir: let its target // version win instead of racing it with "follow latest". if (managed && installDir) { @@ -1542,6 +1577,7 @@ export async function checkForUpdate(opts: UpdateOptions, force = false): Promis // to self-update here instead of proceeding. if (installDir && await isGitWorkingTree(installDir)) { loggerLog("info", `[update] running from a source checkout (${installDir}) \u2014 skipping auto-update (use npm install -g ${opts.packageName})`); + if (checkOnly) return { status: "refused", note: `running from a source checkout \u2014 use npm install -g ${opts.packageName} manually (#580)` }; return; } @@ -1551,6 +1587,7 @@ export async function checkForUpdate(opts: UpdateOptions, force = false): Promis // global self-updater. if (managed && installDir) { loggerLog("info", `[update] install dir is managed by ${managed.owner} (${installDir}) \u2014 skipping in-place self-update; update it via ${managed.channel} (#991)`); + if (checkOnly) return { status: "refused", note: `install dir is managed by ${managed.owner} \u2014 update it via ${managed.channel} (#991)` }; // #1196: a copy inside a host's own tree (dsh profile bundle, pi // npm dir) cannot wait for a global self-update that may never // come — drive the lockstep refresh through the host's own @@ -1569,6 +1606,10 @@ export async function checkForUpdate(opts: UpdateOptions, force = false): Promis // once the advisory's first check completes the predicate goes false and // the normal loop resumes (or the gate above skips the affected candidate). if (!force && opts.advisoryAwaitingFirstCheck?.()) { + if (checkOnly) { + loggerLog("info", "[update] manual web check: the advisory's first check has not landed yet (#2456) \u2014 nothing installed"); + return { status: "deferred-advisory", note: "the advisory's first check has not landed yet (#2456)" }; + } loggerLog("info", "[update] deferring this cycle: the advisory's first check has not landed yet (#2456) \u2014 will follow latest next cycle once its state is known"); return; } @@ -1589,6 +1630,7 @@ export async function checkForUpdate(opts: UpdateOptions, force = false): Promis }); if (!res.ok) { loggerLog("warn", `[update] registry returned ${res.status} ${res.statusText}, skipping`); + if (checkOnly) return { status: "error", note: `registry returned ${res.status} ${res.statusText}` }; return; } const data = (await res.json()) as { @@ -1598,6 +1640,7 @@ export async function checkForUpdate(opts: UpdateOptions, force = false): Promis const latest = data.version; if (!latest) { loggerLog("warn", `[update] registry response had no version, skipping`); + if (checkOnly) return { status: "error", note: "registry response had no version" }; return; } @@ -1607,6 +1650,7 @@ export async function checkForUpdate(opts: UpdateOptions, force = false): Promis const currentVersion = diskVersion ?? opts.currentVersion; if (reportNotNewer(latest, tag, diskVersion, opts.currentVersion, loggerLog)) { + if (checkOnly) return { status: "up-to-date", latest }; // Up to date, but this process is behind the on-disk install — // surface it to the opt-in self-restart handler (#811). if (diskVersion && staleInstallStatus(diskVersion, opts.currentVersion) === "restart") { @@ -1627,6 +1671,10 @@ export async function checkForUpdate(opts: UpdateOptions, force = false): Promis // Skip the candidate: the blocklist wins over "follow latest" until // the advisory document stops covering it. if (!force && opts.advisoryBlocksVersion?.(latest)) { + if (checkOnly) { + loggerLog("info", `[update] manual web check: ${latest} is covered by a critical-bug advisory's affected range (#1588) \u2014 not installing`); + return { status: "blocked-advisory", latest, note: `${latest} is covered by a critical-bug advisory's affected range (#1588)` }; + } loggerLog("info", `[update] skipping ${latest}: covered by a critical-bug advisory's affected range (#1588) — not pulling this install back into the defect; retrying next cycle`); return; } @@ -1641,9 +1689,13 @@ export async function checkForUpdate(opts: UpdateOptions, force = false): Promis latest, tag, force, + skipPacing: checkOnly, resolveProxy: opts.resolveProxy, }); - if ("reason" in gate) return; + if ("reason" in gate) { + if (checkOnly) return { status: "refused", latest, note: `remote update policy (${gate.reason}) \u2014 not installing` }; + return; + } const target = gate.candidate; let tarballUrl = data.dist?.tarball; @@ -1656,6 +1708,7 @@ export async function checkForUpdate(opts: UpdateOptions, force = false): Promis const steppedDoc = await fetchVersionDoc(opts, opts.packageName, target); if (!steppedDoc?.tarball) { loggerLog("warn", `[update] registry has no tarball for policy-selected ${target}, skipping`); + if (checkOnly) return { status: "refused", latest, note: `registry has no tarball for policy-selected ${target}` }; return; } tarballUrl = steppedDoc.tarball; @@ -1664,14 +1717,20 @@ export async function checkForUpdate(opts: UpdateOptions, force = false): Promis } if (!tarballUrl) { loggerLog("warn", `[update] registry response for ${latest} had no tarball URL`); + if (checkOnly) return { status: "error", note: `registry response for ${latest} had no tarball URL` }; return; } const bkey = backoffKey(installDir, target); - if (!force && (await backoffInCooldown(bkey))) { + if (!force && !checkOnly && (await backoffInCooldown(bkey))) { return; } + if (checkOnly) { + loggerLog("info", `[update] manual web check: new version available ${currentVersion} \u2192 ${target}${target !== latest ? ` (dist-tag says ${latest})` : ""} \u2014 check only, not downloading (#4791)`); + return { status: "update-available", latest, candidate: target }; + } + loggerLog("info", `[update] new version found: ${currentVersion} \u2192 ${target}${target !== latest ? ` (dist-tag says ${latest})` : ""}, downloading\u2026`); // Acquire lock to prevent concurrent updates across processes. @@ -1702,6 +1761,7 @@ export async function checkForUpdate(opts: UpdateOptions, force = false): Promis } } catch (e) { loggerLog("warn", `[update] check failed: ${String(e)}`); + if (checkOnly) return { status: "error", note: String(e) }; } finally { inFlight = false; } @@ -2159,12 +2219,16 @@ async function fetchVersionDoc( * same cross-process lock, same backup/verify/rollback tarball install, same * #580 source-checkout and #991 single-writer guards (those refuse with an * actionable error instead of installing). Returns ok:false with a reason on - * any refusal/failure; never throws. */ + * any refusal/failure; never throws. The web panel's explicit install button + * shares this path too (#3719/#4791): it passes "web-panel" as advisoryId and + * an explicit installSource so .last-install.json attributes it as + * "manual-web" instead of the legacy `advisory:` label. */ export async function forceInstallVersion( targetVersion: string, installDir: string | undefined, opts: UpdateOptions, advisoryId: string, + installSource?: LastInstallRecord["source"], ): Promise<{ ok: boolean; error?: string }> { if (!installDir) { const error = "cannot locate the install directory"; @@ -2206,8 +2270,11 @@ export async function forceInstallVersion( if (diskUnderLock === targetVersion) return { ok: true }; const result = await installViaTarball(targetVersion, doc.tarball, installDir, doc.integrity, doc.shasum, egressDispatcher(opts, doc.tarball)); if (result.ok) { - await persistLastInstall(diskUnderLock ?? opts.currentVersion, targetVersion, `advisory:${advisoryId}`); - loggerLog("info", `[update] advisory ${advisoryId}: installed ${diskUnderLock ?? opts.currentVersion} → ${targetVersion}. Restart to finish.`); + const channel = installSource ?? `advisory:${advisoryId}`; + await persistLastInstall(diskUnderLock ?? opts.currentVersion, targetVersion, channel); + // Advisory callers keep their pre-existing log wording exactly (#4791 review); only explicit sources get the channel label. + const logLabel = installSource ? channel : `advisory ${advisoryId}`; + loggerLog("info", `[update] ${logLabel}: installed ${diskUnderLock ?? opts.currentVersion} → ${targetVersion}. Restart to finish.`); await runProfileBundlesRefresh(targetVersion, loggerLog); await refreshDshDesktopCopy(targetVersion, loggerLog, process.env, opts.resolveProxy); notifyStaleInstall(opts, targetVersion); diff --git a/src/web/client.ts b/src/web/client.ts index bee2681af0..047e2d89df 100644 --- a/src/web/client.ts +++ b/src/web/client.ts @@ -543,6 +543,80 @@ export const WEB_CLIENT = `(function () { if (!p || p === "unknown") return '' + escapeHtml(t("protocol.unmarked")) + ""; return '' + escapeHtml(p) + ""; } + function bindSessionColumns() { + document.querySelectorAll(".twide table.data").forEach((table) => { + const cols = Array.from(table.querySelectorAll("col")); + const headers = Array.from(table.querySelectorAll("thead th")); + headers.forEach((header, index) => { + if (index === headers.length - 1) return; + const label = () => t("ses.resize_column") + ": " + header.textContent; + const existing = header.querySelector(".col-resize"); + if (existing) { + existing.title = t("ses.resize_column"); + existing.setAttribute("aria-label", label()); + return; + } + const handle = document.createElement("button"); + handle.type = "button"; + handle.className = "col-resize"; + handle.title = t("ses.resize_column"); + handle.setAttribute("aria-label", label()); + const start = () => { + const widths = headers.map((cell) => cell.getBoundingClientRect().width); + const total = table.getBoundingClientRect().width; + table.style.width = total + "px"; + table.style.minWidth = "100%"; + widths.forEach((width, i) => { if (width > 0) cols[i].style.width = width + "px"; }); + table.classList.add("columns-resized"); + return widths; + }; + const resize = (initial, delta) => { + const widths = initial.slice(); + const direction = delta >= 0 ? 1 : -1; + const receiver = direction > 0 ? index : initial.findIndex((width, i) => i > index && width > 0); + if (receiver < 0 || initial[receiver] <= 0) return; + let remaining = Math.abs(delta); + let transferred = 0; + for (let i = direction > 0 ? index + 1 : index; i >= 0 && i < widths.length; i += direction) { + const available = Math.max(0, initial[i] - (i === 0 ? 120 : 48)); + const amount = Math.min(remaining, available); + widths[i] -= amount; + transferred += amount; + remaining -= amount; + if (remaining === 0) break; + } + widths[receiver] += transferred; + widths.forEach((width, i) => { if (initial[i] > 0) cols[i].style.width = width + "px"; }); + }; + handle.addEventListener("pointerdown", (ev) => { + if (ev.button !== 0) return; + ev.preventDefault(); + try { handle.setPointerCapture(ev.pointerId); } catch (err) {} + let initial = null; + const move = (e) => { + if (!initial) initial = start(); + resize(initial, e.clientX - ev.clientX); + }; + const stop = () => { + handle.removeEventListener("pointermove", move); + handle.removeEventListener("pointerup", stop); + handle.removeEventListener("pointercancel", stop); + handle.removeEventListener("lostpointercapture", stop); + }; + handle.addEventListener("pointermove", move); + handle.addEventListener("pointerup", stop); + handle.addEventListener("pointercancel", stop); + handle.addEventListener("lostpointercapture", stop); + }); + handle.addEventListener("keydown", (ev) => { + if (ev.key !== "ArrowLeft" && ev.key !== "ArrowRight") return; + ev.preventDefault(); + resize(start(), ev.key === "ArrowRight" ? 20 : -20); + }); + header.appendChild(handle); + }); + }); + } function hydrate() { document.documentElement.lang = locale; document.querySelectorAll("[data-i18n]").forEach((el) => { el.textContent = t(el.getAttribute("data-i18n")); }); @@ -550,6 +624,7 @@ export const WEB_CLIENT = `(function () { document.querySelectorAll("[data-i18n-title]").forEach((el) => { el.setAttribute("title", t(el.getAttribute("data-i18n-title"))); }); const tog = $("language-toggle"); if (tog) tog.textContent = locale === "zh-CN" ? "English" : "中文"; + bindSessionColumns(); } const PAGES = ["overview", "sessions", "config", "updates", "connect", "logs", "blog"]; @@ -1086,8 +1161,13 @@ function changelogCatOf(rawLine) { 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); + else if (!r.ok) showUpdateResult(String(r.error || t("toast.failed", { msg: "check failed" })), false); + else if (r.status === "update-available") showUpdateResult(t("up.check_available", { v: String(r.candidate || r.latest || "") }), true); + else if (r.status === "up-to-date") showUpdateResult(t("up.check_up_to_date"), true); + else if (r.status === "blocked-advisory") showUpdateResult(t("up.check_blocked", { v: String(r.latest || "") }), true); + else if (r.status === "deferred-advisory") showUpdateResult(t("up.check_deferred"), true); + else if (r.note) showUpdateResult(String(r.note), true); + else showUpdateResult(t("up.check_ok"), true); } catch (e) { showUpdateResult(e.message, false); } finally { diff --git a/src/web/diagnostics.ts b/src/web/diagnostics.ts index cda36e76f9..5b8df3ce3d 100644 --- a/src/web/diagnostics.ts +++ b/src/web/diagnostics.ts @@ -42,6 +42,7 @@ import { snapshotShadowStatusWire } from "../server/snapshot-render.js"; import { dshProfileDirs } from "../dsh-channel.js"; import { resolveDshHome } from "../client-config.js"; import { safeReadJson } from "../config.js"; +import { recentClientUas } from "../client-ua-registry.js"; import { redactForPublish } from "../log-mask.js"; import { getLogPath } from "../logger.js"; import { configFile, defaultLogFile } from "../paths.js"; @@ -60,6 +61,9 @@ const CONFIG_SECTION_MAX_CHARS = 1600; const CONFLICT_LOG_TAIL_LINES = 20; const LOG_LINE_MAX_CHARS = 240; const DSH_PROFILE_CAP = 8; +// #4649: display budget for the observed-UA lines (the registry itself is +// bounded tighter — 24 families × 8 UAs — so the blob stays pasteable). +const OBSERVED_UA_LINES = 12; const DSH_REPORT_PACKAGES = ["@deepseek-ai/dsh", "@deepseek-ai/dsh-compaction-basic", "@deepseek-ai/dsh-web-app"] as const; function humanUptime(seconds: number): string { @@ -128,12 +132,24 @@ function storageLogTail(lines: string[]): string[] { // routed-call refusals (#1729), the destruction verdict (#2193), successful // rebases (#2432), and the web-app preset notice that says whether the #3354 // load-time overlay applies to this machine's profiles. +// #4649: the same evidence chain for the codex lane — before these entries a +// codex conflict report matched ZERO lines and could not be adjudicated +// without a manual log round-trip (#4648). One entry per distinct message +// shape (a shape may fire on more than one site): the not-intercepted forward +// (src/server/handle.ts), the inline auto-compact detection + rebase +// (#3008/#2372, both openai and responses wires), the intercepted forge +// (trigger form AND endpoint form share the prefix), and the forge failure +// that passes through (src/server/prepare-responses.ts). const CONFLICT_LOG_PATTERNS = [ "takeover gate refused", "dsh native compaction call identified", "compression substrate appears destroyed", "native compaction boundary", "profile bundles include @deepseek-ai/dsh-web-app", + "codex compaction_trigger request not intercepted", + "codex local auto-compaction detected", + "codex compact intercepted", + "codex compact forge failed", ]; function conflictLogTail(lines: string[]): string[] { @@ -201,29 +217,49 @@ function dshPackageVersion(profileDir: string, pkg: string): string | undefined } } +// #4649: the dsh profile bundles only carry the version truth for the dsh lane; +// every OTHER client's version lives in its User-Agent, which bili sees on each +// request. The registry (src/client-ua-registry.ts) keeps a bounded recent +// sample; publish this so a non-dsh conflict report carries its own client +// version instead of forcing `codex --version` round-trips (#4648). The values +// are raw header bytes — the sink-level redactForPublish in buildDiagnostics +// (#4427) is what makes them publish-safe, same as every other section here. +function observedUaLines(): string[] { + const obs = recentClientUas(); + if (obs.length === 0) return ["observed client user-agents: (none recorded by this process yet)"]; + const shown = obs.slice(0, OBSERVED_UA_LINES); + const lines = shown.map((o) => `observed client user-agents: ${o.family}: ${o.ua}`); + if (obs.length > OBSERVED_UA_LINES) lines.push(`observed client user-agents: … ${obs.length - OBSERVED_UA_LINES} more observation(s)`); + return lines; +} + function hostClientVersionLines(): string[] { const lines: string[] = ["--- host client versions ---"]; let dirs: string[] = []; try { dirs = dshProfileDirs(process.env); } catch { dirs = []; } if (dirs.length === 0) { lines.push(`dsh: no profiles under DSH_HOME (${path.basename(resolveDshHome(process.env)) || "?"}/profiles missing — dsh has never run here, or DSH_HOME points elsewhere)`); - return lines; - } - for (const dir of dirs.slice(0, DSH_PROFILE_CAP)) { - const versions = DSH_REPORT_PACKAGES.map((p) => dshPackageVersion(dir, p)); - if (versions.every((v) => v === undefined)) { - // #5146: three bare "?"s told triage nothing about WHERE the version - // truth lives — on DSH Desktop bundle installs the @deepseek-ai core - // ships inside the app, not under the profile's node_modules (which - // holds third-party plugins like billion-context alone), so every - // lookup missed and reports lost the host-version dimension entirely. - lines.push(`dsh profile ${path.basename(dir)}: (no @deepseek-ai packages under this profile bundle — on desktop installs the core ships inside the app; include the app version)`); - } else { - const vers = DSH_REPORT_PACKAGES.map((p, i) => `${p.split("/")[1]} ${versions[i] ?? "?"}`).join(", "); - lines.push(`dsh profile ${path.basename(dir)}: ${vers}`); + } else { + for (const dir of dirs.slice(0, DSH_PROFILE_CAP)) { + const versions = DSH_REPORT_PACKAGES.map((p) => dshPackageVersion(dir, p)); + if (versions.every((v) => v === undefined)) { + // #5146: three bare "?"s told triage nothing about WHERE the version + // truth lives — on DSH Desktop bundle installs the @deepseek-ai core + // ships inside the app, not under the profile's node_modules (which + // holds third-party plugins like billion-context alone), so every + // lookup missed and reports lost the host-version dimension entirely. + lines.push(`dsh profile ${path.basename(dir)}: (no @deepseek-ai packages under this profile bundle — on desktop installs the core ships inside the app; include the app version)`); + } else { + const vers = DSH_REPORT_PACKAGES.map((p, i) => `${p.split("/")[1]} ${versions[i] ?? "?"}`).join(", "); + lines.push(`dsh profile ${path.basename(dir)}: ${vers}`); + } } + if (dirs.length > DSH_PROFILE_CAP) lines.push(`… ${dirs.length - DSH_PROFILE_CAP} more profile(s)`); } - if (dirs.length > DSH_PROFILE_CAP) lines.push(`… ${dirs.length - DSH_PROFILE_CAP} more profile(s)`); + // #4649: appended AFTER the dsh part and outside the early-return path — a + // machine with no dsh profiles at all (the #4648 codex case) must still get + // its observed client versions. + lines.push(...observedUaLines()); return lines; } diff --git a/src/web/i18n.ts b/src/web/i18n.ts index 4ab1cb0e55..774e940743 100644 --- a/src/web/i18n.ts +++ b/src/web/i18n.ts @@ -184,6 +184,10 @@ export const MESSAGES: Record> = { "up.already_in_flight": "已有操作在进行中… an operation is already in flight…", "up.rollback_confirm": "所选版本低于运行中的版本,将回退到 {v},重启宿主后生效,继续?", "up.check_ok": "检查完成 check finished", + "up.check_up_to_date": "已是最新 up to date", + "up.check_available": "发现新版本 v{v}(未安装)—— 需要时点「立即升级」", + "up.check_blocked": "v{v} 被严重缺陷公告(advisory)封锁,未安装", + "up.check_deferred": "严重缺陷公告正在处置此安装目录,本次检查让位给它", "up.installed": "已安装 {v} —— 重启宿主后生效", "sys.update": "升级提醒:", "sys.update_available": "发现 critical 修复,请升级到 v{version} 或更新版本 — {summary}", @@ -329,6 +333,7 @@ export const MESSAGES: Record> = { "ses.empty": "还没有会话", "ses.empty_hint": "通过 bili 代理的第一个请求会自动创建会话", "ses.count": "{count} 个会话", + "ses.resize_column": "拖动调整列宽,或用左右方向键调整", "ses.refresh": "刷新", "ses.filter_protocol_tip": "按协议筛选", "ses.filter_client_tip": "按客户端筛选", @@ -928,6 +933,10 @@ export const MESSAGES: Record> = { "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.check_up_to_date": "Up to date", + "up.check_available": "New version v{v} available (not installed) — click Upgrade now to install it", + "up.check_blocked": "v{v} is blocked by a critical-bug advisory — not installed", + "up.check_deferred": "An active critical-bug advisory owns this install — the check deferred to its loop", "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}", @@ -1070,6 +1079,7 @@ export const MESSAGES: Record> = { "ses.empty": "No sessions yet", "ses.empty_hint": "The first request through the proxy creates one automatically", "ses.count": "{count} sessions", + "ses.resize_column": "Drag to resize column, or use the left and right arrow keys", "ses.refresh": "Refresh", "ses.filter_protocol_tip": "Filter by protocol", "ses.filter_client_tip": "Filter by client", diff --git a/src/web/styles.ts b/src/web/styles.ts index 2cc1a103d2..49ab091bdd 100644 --- a/src/web/styles.ts +++ b/src/web/styles.ts @@ -22,6 +22,14 @@ export const WEB_STYLES = String.raw` --amber: #9a6700; --amber-soft: rgba(154, 103, 0, 0.1); --purple: #8250df; + /* #5417: treemap per-tier node fills. Light values are the pre-existing + hardcoded hues verbatim (zero light-mode drift); the dark counterparts + below give each tier a legible low-luminance ground in dark mode. */ + --tm-base-fill: #ffffff; + --tm-t1-fill: #f2f7ff; + --tm-t2-fill: #f6f3ff; + --tm-t3-fill: #fffaf0; + --tm-tn-fill: #f7f8fa; --shadow: 0 1px 3px rgba(31, 35, 40, 0.06), 0 1px 2px rgba(31, 35, 40, 0.04); --radius: 10px; --mono: ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, "Liberation Mono", monospace; @@ -51,6 +59,11 @@ export const WEB_STYLES = String.raw` --amber: #d29922; --amber-soft: rgba(210, 153, 34, 0.14); --purple: #a371f7; + --tm-base-fill: #161b22; + --tm-t1-fill: #182338; + --tm-t2-fill: #241a38; + --tm-t3-fill: #2c2416; + --tm-tn-fill: #1c2129; --shadow: 0 1px 3px rgba(0, 0, 0, 0.4); } } @@ -73,6 +86,11 @@ export const WEB_STYLES = String.raw` --amber: #d29922; --amber-soft: rgba(210, 153, 34, 0.14); --purple: #a371f7; + --tm-base-fill: #161b22; + --tm-t1-fill: #182338; + --tm-t2-fill: #241a38; + --tm-t3-fill: #2c2416; + --tm-tn-fill: #1c2129; --shadow: 0 1px 3px rgba(0, 0, 0, 0.4); } :root[data-theme="light"] { @@ -298,11 +316,11 @@ details.cl-item.cl-flash { outline: 2px solid var(--accent); outline-offset: -2p .tm-inner { position: relative; margin: 0 auto; } .g-edge { stroke: var(--accent); stroke-width: 1.6; opacity: .5; } .g-node { cursor: pointer; } -.g-node rect { fill: #fff; stroke: var(--border-soft); stroke-width: 1.4; } -.g-node.tier-1 rect { stroke: var(--accent); fill: #f2f7ff; } -.g-node.tier-2 rect { stroke: #7a5af8; fill: #f6f3ff; } -.g-node.tier-3 rect { stroke: #bf8700; fill: #fffaf0; } -.g-node.tier-n rect { stroke: #8a8f99; fill: #f7f8fa; } +.g-node rect { fill: var(--tm-base-fill); stroke: var(--border-soft); stroke-width: 1.4; } +.g-node.tier-1 rect { stroke: var(--accent); fill: var(--tm-t1-fill); } +.g-node.tier-2 rect { stroke: #7a5af8; fill: var(--tm-t2-fill); } +.g-node.tier-3 rect { stroke: #bf8700; fill: var(--tm-t3-fill); } +.g-node.tier-n rect { stroke: #8a8f99; fill: var(--tm-tn-fill); } .g-node.inactive rect { stroke: var(--border-soft); fill: var(--bg-muted); stroke-dasharray: 4 3; } .g-node.inactive text { opacity: .5; } .g-node:hover rect { stroke-width: 2.4; } @@ -482,6 +500,11 @@ table.data.fold-table th, table.data.fold-table td { display: table-cell; } .twrap { overflow-x: auto; } .tproc table.data { min-width: 520px; } .twide table.data { min-width: 940px; table-layout: fixed; } +.twide th { position: relative; } +.col-resize { position: absolute; top: 0; right: 0; width: 8px; height: 100%; padding: 0; border: 0; border-right: 1px solid var(--border); background: transparent; cursor: col-resize; touch-action: none; } +.col-resize:hover, .col-resize:focus-visible { background: var(--accent-soft); border-color: var(--accent); outline: 2px solid var(--accent); outline-offset: -2px; } +.twide .columns-resized .w-title, .twide .columns-resized .row-id, .twide .columns-resized .w-up { max-width: 100%; } +.twide .columns-resized th, .twide .columns-resized td { overflow: hidden; text-overflow: ellipsis; } .hitc { font-size: 11px; letter-spacing: -0.2px; } .clip { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .client-cell { min-width: 0; } diff --git a/tests/issue4649-conflict-report-client-coverage.test.ts b/tests/issue4649-conflict-report-client-coverage.test.ts new file mode 100644 index 0000000000..a79f8513f8 --- /dev/null +++ b/tests/issue4649-conflict-report-client-coverage.test.ts @@ -0,0 +1,180 @@ +// #4649: the conflict-report blob recognized ONLY dsh clients — a codex +// conflict report (#4648) shipped with zero matching log lines and no client +// version, forcing manual round-trips. These tests pin BOTH directions of the +// fix: (a) CONFLICT_LOG_PATTERNS now covers the codex lane's actual log sites +// (positive: every site matched; negative: unrelated lines still excluded, +// dsh coverage unregressed); (b) the bounded observed-UA registry feeds the +// "host client versions" section so non-dsh reports carry their own client +// version (dedupe, caps, truncation, family resolution, publish discipline). +import test from "node:test"; +import assert from "node:assert/strict"; +import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from "node:fs"; +import os from "node:os"; +import * as path from "node:path"; +import { buildDiagnostics } from "../src/web/diagnostics.js"; +import { clientFamilyOf, recentClientUas, recordClientUa, _resetClientUaRegistryForTest } from "../src/client-ua-registry.js"; + +const ENV_KEYS = ["BILI_CONFIG_FILE", "DSH_HOME", "XDG_STATE_HOME", "XDG_CONFIG_HOME", "XDG_DATA_HOME", "XDG_CACHE_HOME"] as const; + +/** Pin every path-relevant env var (unset ones deleted, so homedir fallbacks + * can never reach the real machine's dirs); restored in finally. */ +function withEnv(overrides: Record, fn: () => T): T { + const saved: Record = {}; + for (const k of ENV_KEYS) { + saved[k] = process.env[k]; + if (overrides[k] !== undefined) process.env[k] = overrides[k]; + else delete process.env[k]; + } + try { return fn(); } finally { + for (const k of ENV_KEYS) { + if (saved[k] === undefined) delete process.env[k]; + else process.env[k] = saved[k]; + } + } +} + +function makeRoot(tag: string): string { + const root = mkdtempSync(path.join(os.tmpdir(), tag)); + mkdirSync(path.join(root, "state", "billion-context"), { recursive: true }); + return root; +} + +// The five codex-lane evidence lines, byte shapes taken from the actual log +// sites (src/server/handle.ts not-intercepted forward; src/server/ +// prepare-openai.ts + prepare-responses.ts local-auto-compact +// detection/rebase, both intercepted forge forms, and the forge failure). +const CODEX_LOG_LINES = [ + "[ses_codex1] codex compaction_trigger request not intercepted (BILI_CODEX_COMPACT=pass) — forwarding verbatim (no preflight, no rebuild, no window clamp)", + "[ses_codex1] codex local auto-compaction detected (320/771 covered ids retained) — rebasing ACP state onto the compacted history (#2372)", + "[ses_codex1] codex compact intercepted (trigger form); forged SSE with 3 block summary(s), upstream not contacted", + "[ses_codex1] codex compact intercepted (endpoint); forged history with 12 item(s), upstream not contacted", + "[ses_codex1] codex compact forge failed (transform blew up); passing through to upstream", +]; +// Lines that MUST stay out of the conflict tail: unrelated traffic plus a +// codex-adjacent line that is budget alignment, not a compaction episode. +const NON_CONFLICT_LINES = [ + "[acp-usage] round 7 input=120000 cached=110000 (cache hit 91%)", + "[storage] index.db healthy (sqlite unified)", + "[codex] effective window clamped 200000 → 192000 (client-window alignment for model=gpt-x; current client metadata preferred over bundled fallback) upstream=none route=default", + "processTurn: 42 msgs, protocol openai", +]; +// Pre-existing dsh coverage must survive the extension verbatim. +const DSH_LOG_LINE = "[ses_dsh1] dsh native compaction call identified (final user message = COMPACTION_INSTRUCTION, 42 msgs) — REFUSED, not forwarded (#1729)"; + +test("#4649 codex conflict signatures are captured; unrelated and dsh behavior unchanged", (t) => { + const root = makeRoot("bili-diag-4649-log-"); + t.after(() => rmSync(root, { recursive: true, force: true })); + _resetClientUaRegistryForTest(); + writeFileSync(path.join(root, "state", "billion-context", "bili.log"), + [...CODEX_LOG_LINES, DSH_LOG_LINE, ...NON_CONFLICT_LINES].join("\n") + "\n"); + const blob = withEnv({ DSH_HOME: path.join(root, "none"), XDG_STATE_HOME: path.join(root, "state"), XDG_CONFIG_HOME: root, XDG_DATA_HOME: root, XDG_CACHE_HOME: root }, + () => buildDiagnostics("conflict-banner")).blob; + + assert.ok(blob.includes("--- recent conflict-related log lines ---"), "log section present"); + assert.ok(blob.includes("codex compaction_trigger request not intercepted"), "not-intercepted forward captured (handle.ts site)"); + assert.ok(blob.includes("codex local auto-compaction detected"), "inline auto-compact detection + rebase captured (#3008/#2372)"); + assert.ok(blob.includes("codex compact intercepted (trigger form)"), "intercepted forge, trigger form captured"); + assert.ok(blob.includes("codex compact intercepted (endpoint)"), "intercepted forge, endpoint form captured"); + assert.ok(blob.includes("codex compact forge failed"), "forge failure passthrough captured"); + assert.ok(blob.includes(DSH_LOG_LINE), "pre-existing dsh coverage unregressed"); + for (const l of NON_CONFLICT_LINES) { + assert.ok(!blob.includes(l), `unrelated line must stay out of the tail:\n${l}`); + } +}); + +test("#4649 observed UA registry feeds the host client versions section", (t) => { + const root = makeRoot("bili-diag-4649-ua-"); + t.after(() => rmSync(root, { recursive: true, force: true })); + _resetClientUaRegistryForTest(); + recordClientUa({ "user-agent": "codex_cli_rs/0.162.1" }); + recordClientUa({ "x-claude-code-session-id": "abc", "user-agent": "claude-cli/1.0.55 (external, cli)" }); + recordClientUa({ "user-agent": "curl/8.5.0" }); + // #4648 scenario: NO dsh profiles on this machine — the observed UAs must + // still be published (the old early-return dropped the whole section body). + const blob = withEnv({ DSH_HOME: path.join(root, "none"), XDG_STATE_HOME: path.join(root, "state"), XDG_CONFIG_HOME: root, XDG_DATA_HOME: root, XDG_CACHE_HOME: root }, + () => buildDiagnostics("conflict-banner")).blob; + const section = blob.slice(blob.indexOf("--- host client versions ---")); + assert.ok(section.includes("observed client user-agents: codex: codex_cli_rs/0.162.1"), `codex UA published despite missing dsh profiles:\n${section}`); + assert.ok(section.includes("observed client user-agents: claude: claude-cli/1.0.55 (external, cli)"), "claude UA published"); + assert.ok(section.includes("observed client user-agents: other: curl/8.5.0"), "unidentified client lands in the other bucket"); + // the UA lines sit INSIDE the host client versions section (before config) + assert.ok(section.indexOf("observed client user-agents:") < section.indexOf("--- bili config"), "UA lines precede the config section"); +}); + +test("#4649 registry: dedupe, per-family cap, truncation, honest empty note", (t) => { + t.after(() => _resetClientUaRegistryForTest()); + _resetClientUaRegistryForTest(); + // empty registry → honest note, not an empty section + assert.deepEqual(recentClientUas(), [], "fresh registry is empty"); + // dedupe: same exact UA twice → one observation + recordClientUa({ "user-agent": "codex_cli_rs/1.0.0" }); + recordClientUa({ "user-agent": "codex_cli_rs/1.0.0" }); + assert.equal(recentClientUas().length, 1, "identical UA dedupes"); + // per-family cap: 10 distinct codex UAs → 8 kept, the two oldest evicted + for (let i = 1; i <= 10; i++) recordClientUa({ "user-agent": `codex_cli_rs/1.0.${i}` }); + const codexObs = recentClientUas().filter((o) => o.family === "codex"); + assert.equal(codexObs.length, 8, "family capped at 8 UAs"); + assert.ok(codexObs.some((o) => o.ua === "codex_cli_rs/1.0.10"), "newest UA survives"); + assert.ok(!codexObs.some((o) => o.ua === "codex_cli_rs/1.0.1"), "oldest UA evicted"); + assert.ok(!codexObs.some((o) => o.ua === "codex_cli_rs/1.0.2"), "second-oldest UA evicted"); + // truncation: hostile long UA cannot bloat the blob + recordClientUa({ "user-agent": "codex_cli_rs/2.0.0 " + "x".repeat(300) }); + const longObs = recentClientUas().find((o) => o.family === "codex" && o.ua.startsWith("codex_cli_rs/2.0.0")); + assert.ok(longObs, "long UA recorded"); + assert.ok(longObs!.ua.length <= 120, `UA truncated to the ingest bound, got ${longObs!.ua.length}`); +}); + +test("#4649 registry: display cap keeps the blob pasteable", (t) => { + t.after(() => _resetClientUaRegistryForTest()); + _resetClientUaRegistryForTest(); + // 3 families × 8 UAs = 24 observations > the 12-line display budget + for (const fam of ["codex", "claude", "other"]) { + for (let i = 1; i <= 8; i++) { + const headers: Record = { "user-agent": `${fam}_ua/${i}` }; + if (fam === "claude") headers["x-claude-code-session-id"] = "s"; + recordClientUa(headers); + } + } + assert.equal(recentClientUas().length, 24, "registry holds all observations"); + const root = makeRoot("bili-diag-4649-cap-"); + t.after(() => rmSync(root, { recursive: true, force: true })); + const blob = withEnv({ DSH_HOME: path.join(root, "none"), XDG_STATE_HOME: path.join(root, "state"), XDG_CONFIG_HOME: root, XDG_DATA_HOME: root, XDG_CACHE_HOME: root }, + () => buildDiagnostics()).blob; + const uaLineCount = blob.split("\n").filter((l) => l.startsWith("observed client user-agents: ") && !l.includes("more observation")).length; + assert.equal(uaLineCount, 12, "display capped at 12 lines"); + assert.ok(blob.includes("more observation(s)"), "overflow noted honestly"); +}); + +test("#4649 registry: family resolution mirrors the conflict ladder", () => { + assert.equal(clientFamilyOf({ "user-agent": "codex_cli_rs/0.162.1" }), "codex", "registered codex prefix"); + assert.equal(clientFamilyOf({ "user-agent": "Codex Desktop/9.9.9" }), "codex", "capitalized variant prefix"); + assert.equal(clientFamilyOf({ "user-agent": "vendor/tool codex_foo/1.0" }), "codex", "token-level lenient fallback (#645)"); + assert.equal(clientFamilyOf({ "user-agent": "vendor/codex-wrapper" }), "other", "mid-token codex mention is NOT codex (#1641)"); + assert.equal(clientFamilyOf({ "x-claude-code-session-id": "s", "user-agent": "anything/1" }), "claude", "header sniff beats UA guess"); + assert.equal(clientFamilyOf({ "x-opencode-session": "ses_1", "user-agent": "anything/1" }), "opencode", "opencode header sniff"); + assert.equal(clientFamilyOf({ "x-bili-plugin": "dsh", "user-agent": "codex_cli_rs/1.0" }), "dsh", "declared plugin agent wins over UA shape"); + assert.equal(clientFamilyOf({ "x-bili-plugin": "mcp", "user-agent": "curl/8" }), "other", "mcp is not a client name (#760b)"); + assert.equal(clientFamilyOf({}), "other", "no signal → other"); +}); + +test("#4649 registry: family cap bounds hostile churn", (t) => { + t.after(() => _resetClientUaRegistryForTest()); + _resetClientUaRegistryForTest(); + // 30 distinct declared plugin agents × 1 UA each → families evict past 24 + for (let i = 1; i <= 30; i++) recordClientUa({ "x-bili-plugin": `agent-${i}`, "user-agent": `agent-${i}/1.0` }); + const obs = recentClientUas(); + const families = new Set(obs.map((o) => o.family)); + assert.ok(families.size <= 24, `family cap enforced, got ${families.size}`); + assert.ok(obs.some((o) => o.family === "agent-30"), "most recently seen family survives"); +}); + +test("#4649 publish discipline: credential-shaped UA bytes never reach the blob", (t) => { + const root = makeRoot("bili-diag-4649-pub-"); + t.after(() => { rmSync(root, { recursive: true, force: true }); _resetClientUaRegistryForTest(); }); + _resetClientUaRegistryForTest(); + recordClientUa({ "user-agent": "codex_cli_rs/1.0.0 sk-live-abcdefgh123456789" }); + const blob = withEnv({ DSH_HOME: path.join(root, "none"), XDG_STATE_HOME: path.join(root, "state"), XDG_CONFIG_HOME: root, XDG_DATA_HOME: root, XDG_CACHE_HOME: root }, + () => buildDiagnostics()).blob; + assert.ok(!blob.includes("sk-live-abcdefgh123456789"), "credential shape scrubbed by the sink net (#4427)"); + assert.ok(blob.includes("observed client user-agents: codex: codex_cli_rs/1.0.0"), "the UA itself still publishes"); +}); diff --git a/tests/issue5719-msgid-lane-identity.test.ts b/tests/issue5719-msgid-lane-identity.test.ts index b3a700ef96..a67f971bed 100644 --- a/tests/issue5719-msgid-lane-identity.test.ts +++ b/tests/issue5719-msgid-lane-identity.test.ts @@ -112,8 +112,13 @@ test("#5719 T1: composite field failure + overlapping host ids re-anchor the raw ); assert.equal(res.key, raw, `expected raw re-anchor, got ${res.key} (${res.action})`); assert.equal(res.action, "reanchor"); - assert.match(res.reason ?? "", /msgid identity \(#5719\)/); - assert.match(res.reason ?? "", /1 host message id\(s\) match/); + // #5734 realignment (after 30a8bc2d): this incident cell carries the authored + // checkpoint's conv declaration, so the self-declaration rung now fires BEFORE + // the store-overlap rung — same outcome (reanchor on the raw key), earlier + // reason. Pre-#5734 the pin read /msgid identity \(#5719\)/ + + // /1 host message id\(s\) match/. + assert.match(res.reason ?? "", /self-authored checkpoint declares this raw id/); + assert.match(res.reason ?? "", /#5719/); }); test("#5719 T2: same composite failure but DISJOINT ids still forks (owner rule 3 guard rail)", () => { @@ -261,12 +266,15 @@ test("#5719 T7: personaConversationOrder forwards observer + ids + lazy lookup", assert.ok(lookups <= 1, `lazy contract: store queried at most once (got ${lookups})`); }); -test("#5719 T8: store unavailable (lookup → null) degrades to byte evidence only → fork", () => { +test("#5719 T8: store unavailable (lookup → null) — self-declared checkpoint still re-anchors (#5734)", () => { resetSessionOrderForTest(); const raw = "session-5719-t8"; assert.equal(resolveSessionOrder(raw, chain(10, "h"), SYSTEM_A).key, raw); - // Overlapping ids WOULD prove identity — but the unified store view is - // null (latch-off / legacy epoch, #4407/#5536): degrade, never guess. + // Overlapping ids WOULD prove identity — and the unified store view is + // null (latch-off / legacy epoch, #4407/#5536). Pre-#5734 this degraded to + // byte evidence only → fork (action "derived-persona", key `${raw}|sub:`). + // #5734 (30a8bc2d): the checkpoint's conv declaration rides the WIRE, so the + // self-declaration rung re-anchors on the raw key even with a null store. const res = resolveSessionOrder( raw, incidentHistory(raw, uid("h", 3), "v".repeat(120)), @@ -277,6 +285,7 @@ test("#5719 T8: store unavailable (lookup → null) degrades to byte evidence on ["s-1", "s-2", uid("h", 3), "s-3"], () => null, ); - assert.equal(res.action, "derived-persona"); - assert.ok(res.key.startsWith(`${raw}|sub:`), res.key); + assert.equal(res.action, "reanchor"); + assert.equal(res.key, raw); + assert.match(res.reason ?? "", /self-authored checkpoint declares this raw id/); }); diff --git a/tests/web-blocks-tree.test.ts b/tests/web-blocks-tree.test.ts index 79e803f6ff..2a434701c8 100644 --- a/tests/web-blocks-tree.test.ts +++ b/tests/web-blocks-tree.test.ts @@ -348,3 +348,22 @@ test("#4737 review: pane surfaces follow the theme and list markdown rules keep assert.match(WEB_STYLES, new RegExp(`\\.block-item \\.body\\.md ${sel},`), `list-mode ${sel} rule keeps its element suffix`); } }); + +test("#5417: the treemap node fills follow the theme instead of pinning light hues", () => { + // Dark mode turns var(--text) light; a pinned light fill would bury it. Node fills must stay var-driven. + const nodeRules = [".g-node rect", ".g-node.tier-1 rect", ".g-node.tier-2 rect", ".g-node.tier-3 rect", ".g-node.tier-n rect"]; + for (const sel of nodeRules) { + const rule = WEB_STYLES.match(new RegExp("^" + sel.replace(/\./g, "\\.") + " \\{[^}]*}", "m"))?.[0]; + assert.ok(rule, `rule present: ${sel}`); + assert.match(rule, /fill:\s*var\(--tm-[a-z0-9-]+-fill\)/, `${sel}: fill must be a themed --tm-*-fill var`); + assert.ok(!/fill:\s*#[0-9a-fA-F]{3,8}\b/i.test(rule), `${sel}: no hardcoded fill hex (breaks dark mode)`); + } + const tmVars = ["--tm-base-fill", "--tm-t1-fill", "--tm-t2-fill", "--tm-t3-fill", "--tm-tn-fill"]; + const darkMedia = WEB_STYLES.match(/@media \(prefers-color-scheme: dark\) \{[\s\S]*?\n \}/)?.[0] ?? ""; + const darkPin = WEB_STYLES.match(/:root\[data-theme="dark"\] \{[\s\S]*?\n\}/)?.[0] ?? ""; + assert.ok(darkMedia.length > 0 && darkPin.length > 0, "both dark palettes located"); + for (const v of tmVars) { + assert.ok(darkMedia.includes(v + ":"), `OS-dark palette defines ${v}`); + assert.ok(darkPin.includes(v + ":"), `pinned-dark palette defines ${v}`); + } +}); diff --git a/tests/web-i18n.test.ts b/tests/web-i18n.test.ts index 90e5084817..d99f3a4c00 100644 --- a/tests/web-i18n.test.ts +++ b/tests/web-i18n.test.ts @@ -8,6 +8,79 @@ import { LOCALES, MESSAGES, translate } from "../src/web/i18n.ts"; import { renderPage } from "../src/web/page.ts"; import { WEB_CLIENT } from "../src/web/client.ts"; +test("session column resizing redistributes across each side and keeps both outer edges fixed", () => { + const start = WEB_CLIENT.indexOf(" function bindSessionColumns()"); + const end = WEB_CLIENT.indexOf(" function hydrate()", start); + assert.ok(start >= 0 && end > start); + const result = vm.runInNewContext(` + const cols = [270, 502, 80].map(width => ({ style: { width: width + "px" } })); + const handles = []; + const headers = cols.map((col, i) => ({ + textContent: "Column " + i, + querySelector: () => handles[i] || null, + getBoundingClientRect: () => ({ width: parseFloat(col.style.width) }), + appendChild: handle => { handles[i] = handle; } + })); + const table = { + style: {}, classList: { add() {} }, + getBoundingClientRect: () => ({ width: parseFloat(table.style.width) || 852 }), + querySelectorAll: selector => selector === "col" ? cols : headers + }; + const document = { + querySelectorAll: () => [table], + createElement: () => ({ + handlers: {}, setAttribute() {}, setPointerCapture() {}, + addEventListener(name, fn) { this.handlers[name] = fn; }, + removeEventListener(name) { delete this.handlers[name]; } + }) + }; + const t = key => key; + ${WEB_CLIENT.slice(start, end)} + bindSessionColumns(); + bindSessionColumns(); + const event = { button: 0, clientX: 100, pointerId: 1, preventDefault() {} }; + const stray = { button: 0, clientX: 100, pointerId: 3, preventDefault() {} }; + handles[1].handlers.pointerdown(stray); + handles[1].handlers.pointerup(); + const unpinned = table.style.width === undefined && table.style.minWidth === undefined; + handles[0].handlers.pointerdown(event); + handles[0].handlers.pointermove({ clientX: 550 }); + const grown = [cols[0].style.width, cols[1].style.width, cols[2].style.width, table.style.width]; + handles[0].handlers.pointermove({ clientX: 580 }); + const cascaded = cols.map(col => col.style.width); + handles[0].handlers.pointermove({ clientX: 5000 }); + const capped = [cols[0].style.width, cols[1].style.width, cols[2].style.width, table.style.width]; + handles[0].handlers.pointermove({ clientX: 550 }); + handles[0].handlers.pointercancel(); + const cleaned = !handles[0].handlers.pointermove; + handles[0].handlers.keydown({ key: "ArrowLeft", preventDefault() {} }); + const keyboard = cols[0].style.width; + handles[0].handlers.pointerdown(event); + handles[0].handlers.pointermove({ clientX: -1000 }); + const minimum = cols[0].style.width; + handles[0].handlers.pointerup(); + handles[1].handlers.pointerdown(event); + handles[1].handlers.pointermove({ clientX: -1000 }); + const leftCascade = cols.map(col => col.style.width); + handles[1].handlers.pointerup(); + cols[1].style.width = "0px"; + handles[0].handlers.keydown({ key: "ArrowRight", preventDefault() {} }); + const hidden = cols[1].style.width; + ({ unpinned, grown, cascaded, capped, cleaned, keyboard, minimum, leftCascade, hidden, minWidth: table.style.minWidth, handles: handles.length }); + `); + assert.equal(result.unpinned, true); + assert.equal(JSON.stringify(result.grown), JSON.stringify(["720px", "52px", "80px", "852px"])); + assert.equal(JSON.stringify(result.cascaded), JSON.stringify(["750px", "48px", "54px"])); + assert.equal(JSON.stringify(result.capped), JSON.stringify(["756px", "48px", "48px", "852px"])); + assert.equal(JSON.stringify(result.leftCascade), JSON.stringify(["120px", "48px", "684px"])); + assert.equal(result.hidden, "0px"); + assert.equal(result.cleaned, true); + assert.equal(result.keyboard, "700px"); + assert.equal(result.minimum, "120px"); + assert.equal(result.minWidth, "100%"); + assert.equal(result.handles, 2); +}); + const here = dirname(fileURLToPath(import.meta.url)); const han = /\p{Script=Han}/u; const placeholders = (text: string) => [...text.matchAll(/\{(\w+)\}/g)].map((m) => m[1]).sort(); diff --git a/tests/web-updates.test.ts b/tests/web-updates.test.ts index a5832bcff8..6d6742328d 100644 --- a/tests/web-updates.test.ts +++ b/tests/web-updates.test.ts @@ -1,11 +1,13 @@ import { after } from "node:test"; import test from "node:test"; import assert from "node:assert/strict"; +import crypto from "node:crypto"; import http from "node:http"; -import { mkdirSync, writeFileSync } from "node:fs"; +import { mkdirSync, writeFileSync, readFileSync } from "node:fs"; import { tmpdir } from "node:os"; import path from "node:path"; import { fileURLToPath } from "node:url"; +import * as tar from "tar"; import { defaultConfig } from "acp-kernel"; import type { ProxyOptions } from "../src/config.ts"; @@ -20,23 +22,31 @@ process.env.XDG_CACHE_HOME = path.join(root, "cache"); const biliConfig = path.join(root, "billion-context.json"); writeFileSync(biliConfig, '{"providers":{}}\n', "utf8"); process.env.BILI_CONFIG_FILE = biliConfig; +// #4791: point the remote update policy at the in-process mock registry so the +// check-only tests' policy fetch is a deterministic local 404 (fail-open), not +// a real network call. +const prevPolicyUrl = process.env.BILI_UPDATE_POLICY_URL; +process.env.BILI_UPDATE_POLICY_URL = "https://registry.test/policy.json"; after(() => { if (prevCache === undefined) delete process.env.XDG_CACHE_HOME; else process.env.XDG_CACHE_HOME = prevCache; if (prevConfig === undefined) delete process.env.BILI_CONFIG_FILE; else process.env.BILI_CONFIG_FILE = prevConfig; + if (prevPolicyUrl === undefined) delete process.env.BILI_UPDATE_POLICY_URL; else process.env.BILI_UPDATE_POLICY_URL = prevPolicyUrl; }); -// #3719 phase 2: web 更新/Updates tab actions. Nothing in here fakes a registry -// SUCCESS path — every updater invocation below lands on a deterministic local -// guard (unwired process, bad input, or the source-checkout refusal) so the -// tests make zero network calls. The panel's own buttons live behind the same -// DNS-rebinding gate as every other /__bili/ route; that is asserted against a -// real startServer below. +// #3719 phase 2: web 更新/Updates tab actions. The guard tests land every +// updater invocation on a deterministic local guard (unwired process, bad +// input, or the source-checkout refusal); the #4791 check-only section swaps +// globalThis.fetch for an in-process mock registry (restored per test). Either +// way these tests make zero real network calls. The panel's own buttons live +// behind the same DNS-rebinding gate as every other /__bili/ route; that is +// asserted against a real startServer below. const { startServer } = await import("../src/server.ts"); const { SessionStore, _setStoreForTest } = await import("../src/persist.ts"); const { _setForTest: setRegistryForTest } = await import("../src/registry.ts"); const { VERSION } = await import("../src/version.ts"); const { _setReleaseNotesStateForTest, _resetReleaseNotesWatcherForTest } = await import("../src/update-notes.ts"); const ua = await import("../src/server/update-actions.ts"); +const { forceInstallVersion, getLastInstall, readDiskVersion, lastUpdateCheckTime, _resetLastInstallForTest } = await import("../src/update.ts"); const { rmrf } = await import("./tmp-rm.ts"); /** Fresh fixture "install" — a plain dir whose package.json pins a version @@ -134,6 +144,179 @@ test("concurrent checks and installs each collapse to one in-flight run (#3719)" } }); +// ---- #4791: "Check now" is check-only — full gate ladder, zero installs ---- +// The mock registry is an in-process Map behind a swapped globalThis.fetch +// (restored per test); the policy URL answers a deterministic local 404 +// (fail-open), so even these success-path tests make zero real network calls. + +interface RegistryStubState { + latest?: string; + tarballs: Map; + hits: Record; +} + +function integrityField(buf: Buffer, alg = "sha512"): string { + return `${alg}-${crypto.createHash(alg).update(buf).digest("base64")}`; +} + +/** A real npm-layout tarball (package/ prefix) for one version — enough + * structure to pass verifyEntries' declared-main check on the install path. */ +function makeNpmTgz(version: string): Buffer { + const srcRoot = path.join(root, `pkg-src-${version}`); + const pkgDir = path.join(srcRoot, "package"); + mkdirSync(path.join(pkgDir, "dist"), { recursive: true }); + writeFileSync(path.join(pkgDir, "package.json"), `${JSON.stringify({ name: "billion-context", version, type: "module", main: "dist/index.js" }, null, 2)}\n`, "utf8"); + writeFileSync(path.join(pkgDir, "dist", "index.js"), `export const loaded = '${version}';\n`, "utf8"); + const tgzPath = path.join(srcRoot, `bc-${version}.tgz`); + tar.c({ cwd: srcRoot, file: tgzPath, gzip: true, sync: true }, ["package"]); + return readFileSync(tgzPath); +} + +function stubRegistryFetch(state: RegistryStubState): () => void { + const prev = globalThis.fetch; + globalThis.fetch = ((input: string | URL | Request) => { + const u = String(input); + if (u.endsWith("/policy.json")) { + return Promise.resolve(new Response(JSON.stringify({ error: "no remote policy in this test" }), { status: 404, headers: { "content-type": "application/json" } })); + } + if (u.endsWith("/billion-context/latest")) { + state.hits.latest = (state.hits.latest ?? 0) + 1; + if (!state.latest) { + return Promise.resolve(new Response(JSON.stringify({ name: "billion-context" }), { status: 200, headers: { "content-type": "application/json" } })); + } + const tgz = state.tarballs.get(state.latest); + return Promise.resolve(new Response(JSON.stringify({ + name: "billion-context", + version: state.latest, + dist: { tarball: `https://registry.test/bc-${state.latest}.tgz`, ...(tgz !== undefined ? { integrity: integrityField(tgz) } : {}) }, + }), { status: 200, headers: { "content-type": "application/json" } })); + } + const tgzMatch = u.match(/\/bc-(.+)\.tgz$/); + if (tgzMatch) { + const key = `tarball:${tgzMatch[1]}`; + state.hits[key] = (state.hits[key] ?? 0) + 1; + const buf = state.tarballs.get(tgzMatch[1]); + if (buf === undefined) return Promise.resolve(new Response("unknown tarball", { status: 404 })); + return Promise.resolve(new Response(buf)); + } + const verMatch = u.match(/\/billion-context\/(\d[\d.]*)$/); + const verTgz = verMatch ? state.tarballs.get(verMatch[1]) : undefined; + if (verTgz !== undefined) { + const key = `doc:${verMatch![1]}`; + state.hits[key] = (state.hits[key] ?? 0) + 1; + return Promise.resolve(new Response(JSON.stringify({ + name: "billion-context", + version: verMatch![1], + dist: { tarball: `https://registry.test/bc-${verMatch![1]}.tgz`, integrity: integrityField(verTgz) }, + }), { status: 200, headers: { "content-type": "application/json" } })); + } + return Promise.reject(new Error(`unexpected fetch in test: ${u}`)); + }) as typeof globalThis.fetch; + return () => { globalThis.fetch = prev; }; +} + +test("web panel Check now is check-only: gate ladder runs, nothing downloads or installs (#4791)", async () => { + const fixture = makeFixture("0.9.300"); + const state: RegistryStubState = { latest: "0.9.400", tarballs: new Map([["0.9.400", makeNpmTgz("0.9.400")]]), hits: {} }; + const restore = stubRegistryFetch(state); + try { + ua._resetUpdateActionsForTest(); + // autoUpdate:false is exactly the reported setup — the old force=true + // wiring sailed past every gate and installed anyway. + ua.registerUpdateActions({ packageName: "billion-context", currentVersion: VERSION, autoUpdate: false, installDir: fixture }); + const r = await ua.triggerManualCheck(); + assert.equal(r.ok, true); + assert.equal(r.status, "update-available"); + assert.equal(r.latest, "0.9.400"); + assert.equal(r.candidate, "0.9.400"); + assert.equal(state.hits["tarball:0.9.400"] ?? 0, 0, "check-only must never fetch the tarball"); + assert.equal(await readDiskVersion(fixture), "0.9.300", "check-only must never install — on-disk version untouched"); + assert.ok(await lastUpdateCheckTime(), "the last-checked marker still refreshes — that is what the button promises"); + } finally { + restore(); + ua._resetUpdateActionsForTest(); + } +}); + +test("web panel Check now reports an advisory-blocked version instead of installing it (#4791/#1588)", async () => { + const fixture = makeFixture("0.9.300"); + const state: RegistryStubState = { latest: "0.9.400", tarballs: new Map([["0.9.400", makeNpmTgz("0.9.400")]]), hits: {} }; + const restore = stubRegistryFetch(state); + try { + ua._resetUpdateActionsForTest(); + ua.registerUpdateActions({ packageName: "billion-context", currentVersion: VERSION, autoUpdate: false, installDir: fixture, advisoryBlocksVersion: (v) => v === "0.9.400" }); + const r = await ua.triggerManualCheck(); + assert.equal(r.ok, true); + assert.equal(r.status, "blocked-advisory"); + assert.equal(r.latest, "0.9.400"); + assert.equal(state.hits["tarball:0.9.400"] ?? 0, 0); + assert.equal(await readDiskVersion(fixture), "0.9.300"); + } finally { + restore(); + ua._resetUpdateActionsForTest(); + } +}); + +test("web panel Check now reports up-to-date when dist-tag equals the on-disk version (#4791)", async () => { + const fixture = makeFixture("0.9.400"); + const state: RegistryStubState = { latest: "0.9.400", tarballs: new Map([["0.9.400", makeNpmTgz("0.9.400")]]), hits: {} }; + const restore = stubRegistryFetch(state); + try { + ua._resetUpdateActionsForTest(); + ua.registerUpdateActions({ packageName: "billion-context", currentVersion: VERSION, autoUpdate: false, installDir: fixture }); + const r = await ua.triggerManualCheck(); + assert.equal(r.ok, true); + assert.equal(r.status, "up-to-date"); + assert.equal(r.latest, "0.9.400"); + assert.equal(state.hits["tarball:0.9.400"] ?? 0, 0); + assert.equal(await readDiskVersion(fixture), "0.9.400"); + } finally { + restore(); + ua._resetUpdateActionsForTest(); + } +}); + +test("web panel Check now defers to an active advisory without racing it (#4791/#1481)", async () => { + const fixture = makeFixture("0.9.300"); + const state: RegistryStubState = { latest: "0.9.400", tarballs: new Map([["0.9.400", makeNpmTgz("0.9.400")]]), hits: {} }; + const restore = stubRegistryFetch(state); + try { + ua._resetUpdateActionsForTest(); + ua.registerUpdateActions({ packageName: "billion-context", currentVersion: VERSION, autoUpdate: false, installDir: fixture, advisoryActive: () => true }); + const r = await ua.triggerManualCheck(); + assert.equal(r.ok, true); + assert.equal(r.status, "deferred-advisory"); + assert.equal(state.hits.latest ?? 0, 0, "deferral happens before any registry fetch"); + } finally { + restore(); + ua._resetUpdateActionsForTest(); + } +}); + +test("panel installs attribute manual-web; advisory callers keep the legacy label (#4791)", async () => { + const fixture = makeFixture("0.9.300"); + const state: RegistryStubState = { latest: "0.9.400", tarballs: new Map([["0.9.400", makeNpmTgz("0.9.400")]]), hits: {} }; + const restore = stubRegistryFetch(state); + await _resetLastInstallForTest(); + try { + const opts = { packageName: "billion-context", currentVersion: "0.9.300", autoUpdate: false, installDir: fixture }; + const panel = await forceInstallVersion("0.9.400", fixture, opts, "web-panel", "manual-web"); + assert.equal(panel.ok, true); + const rec = await getLastInstall(); + assert.equal(rec?.source, "manual-web", "a user-initiated panel install must not be misfiled under an advisory id"); + assert.equal(rec?.version, "0.9.400"); + assert.equal(await readDiskVersion(fixture), "0.9.400"); + await _resetLastInstallForTest(); + const fixture2 = makeFixture("0.9.300"); + const adv = await forceInstallVersion("0.9.400", fixture2, { ...opts, installDir: fixture2 }, "adv-test"); + assert.equal(adv.ok, true); + assert.equal((await getLastInstall())?.source, "advisory:adv-test", "advisory callers omitting the explicit source keep the legacy label"); + } finally { + restore(); + await _resetLastInstallForTest(); + } +}); + test("admin routes: state surfaces notices; install enforces charset/auth gates (#3719)", async () => { _setStoreForTest(new SessionStore({ enabled: false })); setRegistryForTest({});