Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 16 additions & 2 deletions src/agent/dsh-native-client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -511,6 +511,7 @@ const zh: Dict = {
"open": "打开 Web UI",
"hint": "查看压缩状态、会话与上下文窗口。",
"degraded": "当前 dsh 进程未绑定 bili 代理(未经 bili dsh 启动,或代理尚未就绪)——先运行 /acp,或改用 bili dsh 启动。",
"degraded_node22": "本机的 Node.js 版本低于 22,压缩代理无法启动——bili 压缩需要 Node.js 22 或更高(使用其内置 SQLite 引擎)。请把 Node.js 升级到 v22+ 后重启 dsh;升级前会话照常工作,只是暂时没有上下文压缩。",
"connecting": "正在连接 bili 代理…",
"stale": "运行中的 bili 代理比已安装的配置文件旧:本页面已加载新版界面,但代理进程仍在提供旧版服务,暂时无法打开内嵌页面。若本应用已运行新版本,启动一个新会话即会自动换上新代理(也可手动结束旧代理进程立即生效);若应用本身还是旧版本,请完全退出并重新启动 dsh。恢复前可点下方按钮直接打开 Web UI。",
"remote_blocked": "本页面通过远程地址访问,而 bili 面板运行在服务器本机的回环地址(127.0.0.1)上——你的浏览器无法直连它(直连会指向你自己的电脑)。要远程打开面板:在服务器上编辑 ~/.config/billion-context/billion-context.json,向顶层对象加入下方字段并保存——本页会在数秒内自动生效(无需重启 dsh,刷新页面同样可以);若你能直接访问该面板地址,也可点下方按钮在配置页开启。",
Expand Down Expand Up @@ -540,6 +541,7 @@ const en: Dict = {
"open": "Open Web UI",
"hint": "Inspect compression status, sessions and context windows.",
"degraded": "This dsh process is not bound to a bili proxy (not launched via bili dsh, or the proxy is not up yet) — run /acp first, or launch through bili dsh.",
"degraded_node22": "This machine's Node.js is older than 22, so the compression proxy cannot start — bili compression needs Node.js 22 or newer (it uses the built-in SQLite engine). Please upgrade Node.js to v22+ and restart dsh; until then your sessions keep working, just without context compression.",
"connecting": "Connecting to the bili proxy…",
"stale": "The running bili proxy is older than the installed profile: this page already runs the new face, but the proxy process still serves the old build, so the embedded page cannot be opened yet. If this app itself runs the new version, starting a new session swaps in the new proxy automatically (or kill the old proxy process manually for an immediate switch); if the app itself is still on the old version, fully quit and relaunch dsh. Until then, use the button below to open the Web UI directly.",
"remote_blocked": "This page is reached through a remote address, but the bili panel runs on the server's own loopback address (127.0.0.1) — your browser cannot reach it directly (it would point at your own machine). To open the panel remotely: edit ~/.config/billion-context/billion-context.json on the server and add the field below to the top-level object — this page picks it up within seconds (no dsh restart needed; reloading works too); if you CAN reach that panel address directly, use the button below to enable it from the config page.",
Expand All @@ -563,6 +565,18 @@ const en: Dict = {
"copied": "Copied",
};

// owner 2026-10-31: WHY no proxy is bound — published by the host half on the
// __BILI__ snapshot while origin-less. kind "no-engine" gets its own
// actionable page text (upgrade Node.js to v22+); anything else keeps today's
// generic degraded hint. Absent/garbage fields fail open (legacy hosts).
function readBootstrapFailureKind(): string | undefined {
const g = globalThis as { __BILI__?: { bootstrapFailure?: unknown } };
const bf = g.__BILI__?.bootstrapFailure;
if (bf === null || typeof bf !== "object") return undefined;
const kind = (bf as { kind?: unknown }).kind;
return typeof kind === "string" && kind.length > 0 ? kind : undefined;
}

function readOrigin(): string | undefined {
const g = globalThis as { __BILI__?: { origin?: unknown; relay?: unknown } };
const snap = g.__BILI__;
Expand Down Expand Up @@ -886,7 +900,7 @@ export function apply(ctx: ClientContext): void {
: renderProbeError(t, error, copied, () => startCopy(error));
let middle: unknown;
if (origin === undefined) {
middle = hintP("degraded");
middle = hintP(readBootstrapFailureKind() === "no-engine" ? "degraded_node22" : "degraded");
} else if (remoteBlocked) {
middle = renderRemoteBlock(t, origin, errorBox(liveEmbedError));
} else if (liveEmbed === "stale") {
Expand Down Expand Up @@ -1018,7 +1032,7 @@ export function apply(ctx: ClientContext): void {
: renderProbeError(t, error, copied, () => startCopy(error));
let middle: unknown;
if (origin === undefined) {
middle = createElement("p", { style: { margin: 0, opacity: 0.7, lineHeight: 1.6 } }, t("degraded"));
middle = createElement("p", { style: { margin: 0, opacity: 0.7, lineHeight: 1.6 } }, t(readBootstrapFailureKind() === "no-engine" ? "degraded_node22" : "degraded"));
} else if (remoteBlocked && origin !== undefined) {
// The jump button targets the panel's config page (#/config) in a
// fresh tab. For a purely remote browser that address is still
Expand Down
35 changes: 33 additions & 2 deletions src/agent/dsh-native.ts
Original file line number Diff line number Diff line change
Expand Up @@ -216,6 +216,21 @@ export function planNativeDsh(env: NodeJS.ProcessEnv): { mode: "off" | "attach"

const state: NativeInterceptState = { origin: undefined, ready: Promise.resolve(undefined) };

// owner 2026-10-31: the embedded DSH page must NAME a bootstrap failure
// instead of hiding behind the generic "run /acp first" hint. Recorded in
// bootstrap()'s catch and published through the __BILI__ snapshot (index-inject
// row + /bili/origin route); the client half renders an actionable message for
// "no-engine" (this Node.js has no usable SQLite — builtin needs v22+, the
// self-download is unavailable) and keeps the generic degraded hint otherwise.
export type BootstrapFailure = { kind: "no-engine" | "launch-failed"; detail: string };
let bootstrapFailure: BootstrapFailure | undefined;
export function classifyBootstrapFailure(err: unknown): BootstrapFailure["kind"] {
return /no SQLite engine available/i.test(err instanceof Error ? err.message : String(err)) ? "no-engine" : "launch-failed";
}
export function _bootstrapFailureForTest(): BootstrapFailure | undefined { return bootstrapFailure; }
export function _setBootstrapFailureForTest(value?: BootstrapFailure): void { bootstrapFailure = value; }


// Tool readiness belongs to one activation, including Cordis restarts that
// reuse their context. Proxy death only moves the live base read by execute
// closures (#3380); it does not invalidate surviving host registrations.
Expand Down Expand Up @@ -712,6 +727,10 @@ async function bootstrap(): Promise<string | undefined> {
{ scriptPath: nativeProxyScriptPath() },
);
if (gen !== originGen) return handle.origin;
// Success outranks an older recorded failure — a respawn after the
// user fixed the environment must not keep advertising it once a
// later unbind drops the origin plane again.
bootstrapFailure = undefined;
state.origin = handle.origin;
register.base = handle.origin;
// #983: do NOT write BILLION_CONTEXT_PROXY — dsh has no reader for it
Expand All @@ -723,6 +742,11 @@ async function bootstrap(): Promise<string | undefined> {
} catch (err) {
const msg = `proxy bootstrap failed — model traffic goes direct (uncompressed): ${errMessage(err)}`;
persistClientEvent(msg);
// owner 2026-10-31: name the failure on the DSH page (no-engine gets
// its own actionable message; everything else rides the generic
// degraded hint with this detail in bili.log). Every recovery-timer
// respawn re-runs bootstrap(), so the newest failure always wins.
bootstrapFailure = { kind: classifyBootstrapFailure(err), detail: errMessage(err) };
// #4811: a one-shot bootstrap failure must not become permanent. Plan-time
// arming normally covers this, but this is where the failure IS KNOWN —
// arm the recovery driver here so a base-less register always has a
Expand Down Expand Up @@ -2005,6 +2029,13 @@ export async function apply(ctx: PluginContext): Promise<void> {
if (label !== undefined) base.contextTabLabel = label;
return base;
};
// owner 2026-10-31: while no proxy is bound, publish WHY so the DSH page
// can show an actionable message (e.g. "upgrade Node.js to 22+") instead
// of the generic degraded hint. Once an origin exists the key stays absent.
const withBootstrapFailure = (originValue: string | undefined, base: Record<string, unknown>): Record<string, unknown> => {
if (originValue === undefined && bootstrapFailure !== undefined) base.bootstrapFailure = { ...bootstrapFailure };
return base;
};
ctx.on?.("webserver/index-inject", (table: Array<{ kind: string; name?: string; value?: unknown }>) => {
// #4846: DSH Desktop captures this table ONCE per app launch (one-shot
// boot snapshot), so a row dropped here is gone for the whole session —
Expand All @@ -2016,7 +2047,7 @@ export async function apply(ctx: PluginContext): Promise<void> {
// readCtxTabFace() only needs contextTab/contextTabLabel. Mirrors the
// /bili/origin route expression below so snapshot ≡ route at any instant.
const origin = currentOrigin();
table.push({ kind: "global", name: "__BILI__", value: withCtxTabFace(origin !== undefined && adminRelayEnabled() ? { origin: null, relay: true } : { origin: origin ?? null }) });
table.push({ kind: "global", name: "__BILI__", value: withBootstrapFailure(origin, withCtxTabFace(origin !== undefined && adminRelayEnabled() ? { origin: null, relay: true } : { origin: origin ?? null })) });
});

// #2604: follow the host session name (dsh-session-title service). Every
Expand Down Expand Up @@ -2053,7 +2084,7 @@ export async function apply(ctx: PluginContext): Promise<void> {
// response URL itself; the loopback origin is useless (and leaky)
// to a remote browser. #4237: same Context-tab face flags as the
// snapshot row.
const body = JSON.stringify(withCtxTabFace(origin !== undefined && adminRelayEnabled() ? { origin: null, relay: true } : { origin: origin ?? null }));
const body = JSON.stringify(withBootstrapFailure(origin, withCtxTabFace(origin !== undefined && adminRelayEnabled() ? { origin: null, relay: true } : { origin: origin ?? null })));
res.writeHead(200, { "content-type": "application/json" });
res.end(body);
},
Expand Down
14 changes: 13 additions & 1 deletion tests/dsh-native.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,21 @@ import os from "node:os";
import path from "node:path";
import http from "node:http";
import { pathToFileURL } from "node:url";
import { apply, installDshIntercepts, planNativeDsh, shouldBootstrapNativeDsh, persistClientEvent, mediaBytesOfWireBody, bodyOverWindowDetail, _attributionHealthForTest, _resetAttributionHealthForTest, _registerStateForTest, _resetRegisterForTest, _setModelInfoForTest, _nativeStateForTest, _setSpawnForTest, _setThrewRetryForTest, _settleNativeForTest, _stateHeadersForTest, _stateRespawnForTest, _stateTakeoverGateForTest, _stateToolsReadyForTest, _stateBeforeSendForTest, _stateOnResponseForTest, _noteRoutedForTest, _resetRoutedForTest, _resetWebProfileWarningForTest, _resetNonWebTraceForTest, _resetTitlesForTest, _resetBodyParseStatsForTest, _bodyParseStatsForTest, _parsedBodyOnceForTest, type PluginContext } from "../src/agent/dsh-native.ts";
import { apply, installDshIntercepts, planNativeDsh, shouldBootstrapNativeDsh, persistClientEvent, mediaBytesOfWireBody, bodyOverWindowDetail, _attributionHealthForTest, _resetAttributionHealthForTest, _registerStateForTest, _resetRegisterForTest, _setModelInfoForTest, _nativeStateForTest, _setSpawnForTest, _setThrewRetryForTest, _settleNativeForTest, _stateHeadersForTest, _stateRespawnForTest, _stateTakeoverGateForTest, _stateToolsReadyForTest, _stateBeforeSendForTest, _stateOnResponseForTest, _noteRoutedForTest, _resetRoutedForTest, _resetWebProfileWarningForTest, _resetNonWebTraceForTest, _resetTitlesForTest, _resetBodyParseStatsForTest, _bodyParseStatsForTest, _parsedBodyOnceForTest, classifyBootstrapFailure, type PluginContext } from "../src/agent/dsh-native.ts";
import { nativeInterceptInstalled, _resetForTest as _resetFetchInterceptForTest, type NativeInterceptState } from "../src/agent/native-intercept.ts";
import { nativeWebSocketInterceptInstalled, _resetForTest as _resetWsInterceptForTest } from "../src/agent/native-ws-intercept.ts";

// owner 2026-10-31: only a missing SQLite engine earns the "upgrade Node.js
// to v22+" page wording; every other bootstrap failure stays on the generic
// degraded hint (no false upgrade nudges).
test("classifyBootstrapFailure — no-engine vs generic launch failure", () => {
assert.equal(classifyBootstrapFailure(new Error("[storage:node:sqlite] no SQLite engine available (better-sqlite3 not installed)")), "no-engine");
assert.equal(classifyBootstrapFailure(new Error("no SQLite engine available (node:sqlite missing)")), "no-engine");
assert.equal(classifyBootstrapFailure("No sqlite engine available"), "no-engine"); // string rejects are classified too
assert.equal(classifyBootstrapFailure(new Error("connect ECONNREFUSED 127.0.0.1:8199")), "launch-failed");
assert.equal(classifyBootstrapFailure(new Error("attempt to write a readonly database")), "launch-failed");
assert.equal(classifyBootstrapFailure(undefined), "launch-failed");
});
import { __resetIncrementalClientForTests } from "../src/agent/incremental-client.ts";
import { isDshCompactionActive, _resetDshCompactionVerdictForTest } from "../src/agent/dsh-compaction-disable.ts";
import { once } from "node:events";
Expand Down
54 changes: 53 additions & 1 deletion tests/dsh-settings-ui.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import os from "node:os";
import path from "node:path";
import http from "node:http";
import vm from "node:vm";
import { apply, _resetRegisterForTest } from "../src/agent/dsh-native.ts";
import { apply, _resetRegisterForTest, _setBootstrapFailureForTest } from "../src/agent/dsh-native.ts";
import { rmrf } from "./tmp-rm.ts";

// The node:test runner sets NODE_TEST_CONTEXT itself (see tests/e2e/README.md);
Expand Down Expand Up @@ -116,6 +116,36 @@ test("#1590/#4846: index-inject still publishes __BILI__ when no origin is known
}
});

// owner 2026-10-31: while no proxy is bound, the snapshot names WHY, so the
// DSH page can tell the user to upgrade Node.js (v22+) instead of the generic
// "/acp first" degraded hint.
test("owner 2026-10-31: index-inject publishes bootstrapFailure while origin-less (node<22 page)", async () => {
const home = fs.mkdtempSync(path.join(os.tmpdir(), "bili-dsh-ui-"));
try {
await withEnv({ DSH_HOME: home, BILLION_CONTEXT_PROXY: undefined, BILI_CONFIG_FILE: emptyConfigFile(home) }, async () => {
_resetRegisterForTest(undefined);
const listeners: InjectListener[] = [];
apply(uiCtx(listeners) as Parameters<typeof apply>[0]);
// no failure recorded yet ⇒ payload byte-identical to today
let table: InjectRow[] = [];
listeners[0](table);
assert.deepEqual(table, [{ kind: "global", name: "__BILI__", value: { origin: null, contextTab: true } }]);
// a no-engine refusal recorded by the host half rides the same row
_setBootstrapFailureForTest({ kind: "no-engine", detail: "no SQLite engine available (node:sqlite missing, better-sqlite3 not installed)" });
table = [];
listeners[0](table);
assert.deepEqual(table[0].value, {
origin: null,
contextTab: true,
bootstrapFailure: { kind: "no-engine", detail: "no SQLite engine available (node:sqlite missing, better-sqlite3 not installed)" },
});
});
} finally {
_setBootstrapFailureForTest(undefined);
rmrf(home);
}
});

test("#4846: index-inject carries contextTab=false even before the origin is bound (desktop boot snapshot)", async () => {
const home = fs.mkdtempSync(path.join(os.tmpdir(), "bili-dsh-ui-"));
try {
Expand Down Expand Up @@ -792,6 +822,28 @@ test("#1590/#2125: client bundle registers the settings.section entry bili AND t
}
});

test("owner 2026-10-31: degraded page names the Node.js upgrade for a no-engine bootstrap failure and keeps the generic hint for any other kind (both slots)", async () => {
for (const slot of ["settings.section", "plugins.bundle.config"]) {
const nm = await mountClient({ open: (_url: string) => {}, fetch: async () => { throw new Error("no route"); }, setTimeout, clearTimeout, __BILI__: { origin: null, bootstrapFailure: { kind: "no-engine", detail: "no SQLite engine available" } } }, slot);
nm.resetHooks();
const ntree = nm.component() as ElementNode;
const nt: string[] = [];
collectText(ntree, nt);
assert.ok(nt.some((x) => x.includes("Node.js")), `${slot}: no-engine failure renders the Node.js upgrade hint: ${JSON.stringify(nt)}`);
assert.ok(!nt.some((x) => x.includes("/acp")), `${slot}: no-engine failure must not suggest the generic /acp remedy: ${JSON.stringify(nt)}`);
nm.runCleanups();

const lm = await mountClient({ open: (_url: string) => {}, fetch: async () => { throw new Error("no route"); }, setTimeout, clearTimeout, __BILI__: { origin: null, bootstrapFailure: { kind: "launch-failed", detail: "ECONNREFUSED" } } }, slot);
lm.resetHooks();
const ltree = lm.component() as ElementNode;
const lt: string[] = [];
collectText(ltree, lt);
assert.ok(lt.some((x) => x.includes("/acp")), `${slot}: launch-failed keeps the generic /acp hint: ${JSON.stringify(lt)}`);
assert.ok(!lt.some((x) => x.includes("Node.js")), `${slot}: launch-failed must not claim a Node.js problem: ${JSON.stringify(lt)}`);
lm.runCleanups();
}
});

test("#3373: relay mode — probe {origin:null,relay:true} binds same-origin; prefix gateways resolve through the base-relative fallback form", async () => {
{
// Root relay deployment: no response URL ⇒ base "" (same-origin paths).
Expand Down
Loading