From 028bb2fa9710a25042f7f0ac6a44581d9f6ef275 Mon Sep 17 00:00:00 2001 From: ework-agent Date: Sun, 4 Oct 2026 20:43:56 +0800 Subject: [PATCH 1/4] =?UTF-8?q?fix(#2082):=20resolve=20the=20recovery=20co?= =?UTF-8?q?ntext=20at=20landing=20time=20=E2=80=94=20a=20re-activation=20m?= =?UTF-8?q?ust=20not=20be=20re-poisoned=20by=20a=20stale=20ctx=20capture?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The #2082 fix reset register.dead on re-activation and armed a detached recovery timer, but two async paths still resolved their PluginContext from a capture taken when the retry was armed or started: the timer tick (armRecoveryTimer captured the first ctx that saw the broken state) and an in-flight registration landing after a mid-fetch re-activation (registerTools captured ctx at call time). If dsh deactivated that context in between (profile switch / settings toggle / desktop copy swap), the stale path registered into it, cordis threw 'inactive context', and register.dead was re-poisoned until dsh restarted — exactly the failure this fix removes, in a narrow interleaving. Track the latest context in module state (apply() + maybeRetry update it; _resetRegisterForTest clears it). The timer tick and the single-flight registration landing now resolve activeCtx ?? ctx at landing time. Regression tests pin both facets: they fail on the pre-fix code and pass with the fix. --- src/agent/dsh-native.ts | 24 +++++- tests/issue2082-dsh-recovery.test.ts | 118 ++++++++++++++++++++++++--- 2 files changed, 127 insertions(+), 15 deletions(-) diff --git a/src/agent/dsh-native.ts b/src/agent/dsh-native.ts index f225522d99..28429ba428 100644 --- a/src/agent/dsh-native.ts +++ b/src/agent/dsh-native.ts @@ -455,7 +455,11 @@ async function registerTools(ctx: PluginContext): Promise { if (register.toolsReady || base === undefined) return; register.pending = (async () => { const tools = await fetchManifest(base, "anthropic"); - for (const tool of tools) ctx.tools.register(toolDefinition(tool)); + // #2082: land on the CURRENT context, not the one that started this + // flight — a re-activation mid-fetch must not register into (or die + // on) the deactivated context captured at call time. + const target = activeCtx ?? ctx; + for (const tool of tools) target.tools.register(toolDefinition(tool)); register.toolsReady = true; })() .catch((err: unknown) => { @@ -491,12 +495,20 @@ async function registerTools(ctx: PluginContext): Promise { // ops knob); absent it tracks RETRY_INTERVAL_MS. Tests that do not opt in // never start a timer at all (NODE_TEST_CONTEXT guard keeps suites quiet). let recoveryTimer: NodeJS.Timeout | undefined; +// #2082: the LATEST context seen by apply()/maybeRetry. Every async recovery +// path (the timer tick below, an in-flight registration landing after a +// re-activation) must resolve its context at landing time, not from a capture +// taken when the retry was armed — a captured context may already be +// deactivated by then (dsh reload / profile switch), and registering into it +// throws "inactive context" and would re-poison register.dead, exactly what +// this fix removes. +let activeCtx: PluginContext | undefined; function recoveryIntervalMs(): number { const raw = process.env.BILI_DSH_RECOVERY_INTERVAL_MS; const parsed = raw === undefined ? Number.NaN : Number(raw); return Number.isFinite(parsed) && parsed > 0 ? parsed : RETRY_INTERVAL_MS; } -function armRecoveryTimer(ctx: PluginContext): void { +function armRecoveryTimer(): void { if (recoveryTimer !== undefined) return; if (process.env.NODE_TEST_CONTEXT !== undefined && process.env.BILI_DSH_RECOVERY_INTERVAL_MS === undefined) return; recoveryTimer = setInterval(() => { @@ -505,13 +517,15 @@ function armRecoveryTimer(ctx: PluginContext): void { recoveryTimer = undefined; return; } - maybeRetry(ctx); + const ctx = activeCtx; + if (ctx !== undefined) maybeRetry(ctx); }, recoveryIntervalMs()); recoveryTimer.unref?.(); } function maybeRetry(ctx: PluginContext): void { - if (!register.dead && !register.toolsReady) armRecoveryTimer(ctx); + activeCtx = ctx; + if (!register.dead && !register.toolsReady) armRecoveryTimer(); if (register.dead || register.toolsReady) return; if (register.pending !== undefined) return; if (Date.now() < register.retryAt) return; @@ -713,6 +727,7 @@ export function apply(ctx: PluginContext): void { // lifetime: every later maybeRetry() returns immediately and the bili // tools never come back until dsh restarts. register.dead = false; + activeCtx = ctx; // #1590: the dsh web-profile settings panel shows a "bili设置" entry // (dsh-native-client.js) that opens this proxy's Web UI. The origin is @@ -1065,6 +1080,7 @@ export function _resetRegisterForTest(base: string | undefined): void { clearInterval(recoveryTimer); recoveryTimer = undefined; } + activeCtx = undefined; register.base = base; register.toolsReady = false; register.dead = false; diff --git a/tests/issue2082-dsh-recovery.test.ts b/tests/issue2082-dsh-recovery.test.ts index 56e1ba85ef..85ba672441 100644 --- a/tests/issue2082-dsh-recovery.test.ts +++ b/tests/issue2082-dsh-recovery.test.ts @@ -30,7 +30,7 @@ type RegisteredTool = { execute: (args: Record, exec: { agent?: { session?: { id?: unknown } }; signal?: AbortSignal }) => Promise; }; -function mockBiliHandler(): (req: http.IncomingMessage, res: http.ServerResponse) => void { +function mockBiliHandler(counters: { manifestRequests: number }, manifestDelayMs = 0): (req: http.IncomingMessage, res: http.ServerResponse) => void { const manifestTools: MockTool[] = [ { name: "compress", @@ -41,8 +41,15 @@ function mockBiliHandler(): (req: http.IncomingMessage, res: http.ServerResponse return (req, res) => { const url = req.url ?? ""; if (url === "/__bili/plugin/manifest") { - res.writeHead(200, { "content-type": "application/json" }); - res.end(JSON.stringify({ version: "0.1.119", tools: { anthropic: manifestTools.map((t) => ({ name: t.name, description: t.description, input_schema: t.inputSchema })) } })); + counters.manifestRequests += 1; + const respond = () => { + res.writeHead(200, { "content-type": "application/json" }); + res.end(JSON.stringify({ version: "0.1.119", tools: { anthropic: manifestTools.map((t) => ({ name: t.name, description: t.description, input_schema: t.inputSchema })) } })); + }; + // a slow manifest widens the fetch window so a re-activation can + // land while a registration is still in flight + if (manifestDelayMs > 0) setTimeout(respond, manifestDelayMs); + else respond(); return; } res.writeHead(404); @@ -50,28 +57,30 @@ function mockBiliHandler(): (req: http.IncomingMessage, res: http.ServerResponse }; } -async function startMockProxy(): Promise<{ origin: string; close: () => void }> { - const server = http.createServer(mockBiliHandler()); +async function startMockProxy(manifestDelayMs = 0): Promise<{ origin: string; close: () => void; manifestRequests: () => number }> { + const counters = { manifestRequests: 0 }; + const server = http.createServer(mockBiliHandler(counters, manifestDelayMs)); return new Promise((resolve) => { server.listen(0, "127.0.0.1", () => { const addr = server.address() as { port: number }; - resolve({ origin: `http://127.0.0.1:${addr.port}`, close: () => server.close() }); + resolve({ origin: `http://127.0.0.1:${addr.port}`, close: () => server.close(), manifestRequests: () => counters.manifestRequests }); }); }); } type HostCtx = Parameters[0]; -function mockCtx(opts: { registerThrows?: () => boolean } = {}) { +const INACTIVE_CONTEXT_ERROR = 'cannot get required service "tools" in inactive context'; + +function mockCtx(opts: { registerError?: () => Error | undefined } = {}) { const tools: RegisteredTool[] = []; const commands: Array<{ name: string; handler: () => Promise<{ kind: string; text: string }> }> = []; let initiator: { session?: { id?: unknown } } | undefined = undefined; return { tools: { register: (t: RegisteredTool) => { - if (opts.registerThrows?.()) { - throw new Error('cannot get required service "tools" in inactive context'); - } + const err = opts.registerError?.(); + if (err !== undefined) throw err; tools.push(t); }, }, @@ -163,7 +172,7 @@ test("#2082 apply() clears register.dead: a re-activated context recovers after // phase 1: the context is inactive during teardown — registration // throws cordis's inactive-context error and the register dies let tearing = true; - const ctx1 = mockCtx({ registerThrows: () => tearing }); + const ctx1 = mockCtx({ registerError: () => (tearing ? new Error(INACTIVE_CONTEXT_ERROR) : undefined) }); apply(ctx1); await new Promise((r) => setTimeout(r, 50)); assert.equal(ctx1.registeredTools.length, 0); @@ -185,3 +194,90 @@ test("#2082 apply() clears register.dead: a re-activated context recovers after _resetRegisterForTest(undefined); } }); + +test("#2082 recovery timer retries through the LATEST context after re-activation — a stale capture would re-poison dead", async () => { + const proxy = await startMockProxy(); + const home = fs.mkdtempSync(path.join(os.tmpdir(), "bili-dsh-2082-staletimer-")); + const savedInterval = process.env.BILI_DSH_RECOVERY_INTERVAL_MS; + const savedRetry = process.env.BILI_DSH_RETRY_INTERVAL_MS; + process.env.BILI_DSH_RECOVERY_INTERVAL_MS = "20"; + process.env.BILI_DSH_RETRY_INTERVAL_MS = "20"; + try { + await withEnv({ DSH_HOME: home, BILLION_CONTEXT_PROXY: proxy.origin }, async () => { + _resetRegisterForTest(proxy.origin); + + // phase 1: ctx1 fails with a TRANSIENT error (not inactive-context) + // — the register stays alive (!dead), tools stay down, and the + // recovery timer is armed while ctx1 is still the current context. + let mode1: "transient" | "inactive" = "transient"; + let attempts1 = 0; + const ctx1 = mockCtx({ + registerError: () => { + attempts1 += 1; + return mode1 === "transient" ? new Error("transient manifest registration failure") : new Error(INACTIVE_CONTEXT_ERROR); + }, + }); + apply(ctx1); + maybeRetryForTest(ctx1); + await waitFor(() => attempts1 >= 1, "first transient registration attempt"); + + // phase 2: dsh deactivates ctx1 and re-activates the plugin with + // ctx2. ctx2's own first attempt also fails transiently, so once + // its back-off expires the ONLY remaining driver is the recovery + // timer — it must retry through ctx2, not the stale ctx1 capture + // (registering into the deactivated ctx1 throws inactive-context + // and re-poisons dead, leaving the tools down until dsh restarts). + mode1 = "inactive"; + let attempts2 = 0; + const ctx2 = mockCtx({ + registerError: () => { + attempts2 += 1; + return attempts2 === 1 ? new Error("transient manifest registration failure") : undefined; + }, + }); + apply(ctx2); + await waitFor(() => ctx2.registeredTools.length === 1, "timer-driven registration through the LATEST context"); + assert.equal(ctx2.registeredTools[0].name, "compress"); + assert.ok(attempts2 >= 2, `expected ctx2's first attempt to fail and a retry to land (got ${attempts2} attempts)`); + assert.equal(ctx1.registeredTools.length, 0, "nothing registered into the deactivated context"); + }); + } finally { + for (const [k, v] of [["BILI_DSH_RECOVERY_INTERVAL_MS", savedInterval], ["BILI_DSH_RETRY_INTERVAL_MS", savedRetry]] as const) { + if (v === undefined) delete process.env[k]; + else process.env[k] = v; + } + proxy.close(); + rmrf(home); + _resetRegisterForTest(undefined); + } +}); + +test("#2082 an in-flight registration lands on the LATEST context after a mid-fetch re-activation", async () => { + const proxy = await startMockProxy(300); + const home = fs.mkdtempSync(path.join(os.tmpdir(), "bili-dsh-2082-inflight-")); + try { + await withEnv({ DSH_HOME: home, BILLION_CONTEXT_PROXY: proxy.origin }, async () => { + _resetRegisterForTest(proxy.origin); + + // ctx1 starts a registration whose manifest fetch is still in + // flight when dsh deactivates it and re-activates the plugin with + // ctx2 — the single-flight landing must target ctx2, not the stale + // ctx1 capture (which would die on inactive-context and poison + // dead before ctx2 ever gets its tools). + let deactivated1 = false; + const ctx1 = mockCtx({ registerError: () => (deactivated1 ? new Error(INACTIVE_CONTEXT_ERROR) : undefined) }); + apply(ctx1); + await waitFor(() => proxy.manifestRequests() >= 1, "manifest fetch in flight"); + deactivated1 = true; + const ctx2 = mockCtx(); + apply(ctx2); + await waitFor(() => ctx2.registeredTools.length === 1, "in-flight registration landing on the re-activated context"); + assert.equal(ctx2.registeredTools[0].name, "compress"); + assert.equal(ctx1.registeredTools.length, 0, "nothing registered into the deactivated context"); + }); + } finally { + proxy.close(); + rmrf(home); + _resetRegisterForTest(undefined); + } +}); From d32db9a3849c213b556e095ef4b6096206af375f Mon Sep 17 00:00:00 2001 From: ework-agent Date: Sun, 4 Oct 2026 20:49:05 +0800 Subject: [PATCH 2/4] docs(#2082): document BILI_DSH_RETRY_INTERVAL_MS / BILI_DSH_RECOVERY_INTERVAL_MS in CONFIGURATION.md en+zh MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The #2091 recovery knobs shipped without CONFIGURATION.md entries while every sibling dsh-plugin knob (incl. the adjacent BILI_MODEL_INFO_RETRY_MS) is documented — 'document or don't ship' (env-var discipline #2030, hard rule 4). Both are test/ops hooks with unchanged defaults; production behavior is untouched. --- CONFIGURATION.md | 2 ++ CONFIGURATION.zh-CN.md | 2 ++ 2 files changed, 4 insertions(+) diff --git a/CONFIGURATION.md b/CONFIGURATION.md index dcb30034a9..87bd3aa8dc 100644 --- a/CONFIGURATION.md +++ b/CONFIGURATION.md @@ -1009,6 +1009,8 @@ File keys resolve only when the matching env var is unset. Defaults in parenthes | `BILI_UPDATE_REGISTRY` | Base URL override for the npm registry used by the auto-updater and `bili update` (default `https://registry.npmjs.org`). Intended for hermetic testing against a loopback registry (the verdaccio instance in the `ACP_TEST_REGISTRY` e2e suite); leave unset in production (#1153). | | `BILI_UPDATE_CHECK_INTERVAL_MS` | Auto-update check period in milliseconds (default `180000`, i.e. 3 minutes; values ≤ 0 are ignored and the default applies). Shortened by the hermetic e2e suite so it never waits a full cycle (#1153). | | `BILI_MODEL_INFO_RETRY_MS` | Cooldown (ms) before the dsh native plugin re-resolves the current model's context window after a resolve that failed or returned no window (#1812/#1836): a cached entry without a window is not final — instead of latching headerless for the process lifetime, the next request after this cooldown triggers a retry. Default `30000`; non-numeric or negative values fall back to `30000`. Test hook — shortened by the dsh-native unit test so it never waits wall-clock; leave unset in production. | +| `BILI_DSH_RETRY_INTERVAL_MS` | Back-off (ms) between dsh native plugin tool-registration retries (#2082): after a manifest fetch or tool registration fails transiently, the next retry happens no sooner than this cooldown. Default `10000`; non-numeric or non-positive values fall back to `10000`. Test hook — shortened by the dsh-native unit tests so they never wait wall-clock; leave unset in production. | +| `BILI_DSH_RECOVERY_INTERVAL_MS` | Interval (ms) of the dsh native plugin's detached recovery timer (#2082): while the tools are down it keeps driving registration retries with zero model traffic — the case where the model already gave up on the missing tools and nothing else re-arms the loop. Defaults to following `BILI_DSH_RETRY_INTERVAL_MS` (`10000`). Test hook — under NODE_TEST_CONTEXT the timer never starts unless this var is set explicitly; leave unset in production. | | `BILI_ADVISORY_CHECK` | Set to `0` to disable the critical-defect advisory watcher (#1481). Default ON — it runs independently of `ACP_AUTO_UPDATE` so that installs with auto-update off still get force-updated out of a known-broken version range. Fail-open: an unreachable/malformed source only warns, never blocks model traffic. File-config key: `advisoryCheck`. | | `BILI_ADVISORY_URL` | Override for the advisory document URL. Default: the companion package `billion-context-advisories` on the configured registry (`BILI_UPDATE_REGISTRY` aware). File-config key: `advisoryUrl`. | | `BILI_RELEASE_NOTES_CHECK` | Set to `0` to disable the release-notes visibility watcher (#1870). Default ON — pure visibility, silent by default (#1977): fetches the companion release-notes doc and surfaces "CRITICAL update ready — restart to finish" (disk newer than running) or "critical update available" on `acp_status` and the `/acp` panel ONLY when the pending span contains a `critical`-tier entry; routine/recommended releases never surface. Never installs, never restarts; fail-open. File-config key: `releaseNotesCheck`. | diff --git a/CONFIGURATION.zh-CN.md b/CONFIGURATION.zh-CN.md index e66cf4b20b..ed93e65217 100644 --- a/CONFIGURATION.zh-CN.md +++ b/CONFIGURATION.zh-CN.md @@ -1013,6 +1013,8 @@ | `BILI_UPDATE_REGISTRY` | 自动更新与 `bili update` 使用的 npm registry base URL 覆盖(默认 `https://registry.npmjs.org`)。仅供 hermetic 测试指向回环 registry(`ACP_TEST_REGISTRY` e2e 套件自带的 verdaccio 实例);生产环境请勿设置(#1153)。 | | `BILI_UPDATE_CHECK_INTERVAL_MS` | 自动更新检查周期(毫秒,默认 `180000` 即 3 分钟;≤ 0 的值被忽略,回退默认)。hermetic e2e 套件用它缩短周期,避免等待完整间隔(#1153)。 | | `BILI_MODEL_INFO_RETRY_MS` | dsh 原生模型窗口解析失败(或解析结果不带窗口)后的重试冷却(毫秒,#1812/#1836):匹配的缓存条目没有 context window 时不视为最终结果 —— 不再让整个进程生命周期 latching 成无 header 状态,而是该冷却过期后由下一个请求触发重新解析。默认 `30000`;非数字或负值回退 `30000`。测试钩子 —— dsh-native 单元测试用它缩短冷却、避免真实等待;生产环境保持 unset。 | +| `BILI_DSH_RETRY_INTERVAL_MS` | dsh 原生插件工具注册重试的退避冷却(毫秒,#2082):manifest 拉取或工具注册瞬时失败后,下一次重试不早于该冷却发生。默认 `10000`;非数字或非正值回退 `10000`。测试钩子 —— dsh-native 单元测试用它缩短冷却、避免真实等待;生产环境保持 unset。 | +| `BILI_DSH_RECOVERY_INTERVAL_MS` | dsh 原生插件独立恢复定时器的间隔(毫秒,#2082):工具处于 down 状态时,即使零模型流量也持续驱动注册重试 —— 正是模型已放弃缺失工具、其他路径都不会再触发重试的场景。默认跟随 `BILI_DSH_RETRY_INTERVAL_MS`(`10000`)。测试钩子 —— NODE_TEST_CONTEXT 下除非显式设置本变量,否则定时器永不启动;生产环境保持 unset。 | | `BILI_ADVISORY_CHECK` | 设为 `0` 禁用严重缺陷公告监视器(#1481)。默认开启 —— 它独立于 `ACP_AUTO_UPDATE` 运行,确保关闭了自动更新的安装也能被强制移出已知缺陷版本范围。fail-open:公告源不可达/格式错误只告警,绝不阻断模型流量。文件配置键:`advisoryCheck`。 | | `BILI_ADVISORY_URL` | 公告文档 URL 覆盖。默认:已配置 registry(感知 `BILI_UPDATE_REGISTRY`)上的伴生包 `billion-context-advisories`。文件配置键:`advisoryUrl`。 | | `BILI_RELEASE_NOTES_CHECK` | 设为 `0` 禁用发版说明可见性监视器(#1870)。默认开启 —— 纯可见性,且默认静默(#1977):拉取伴生发版说明文档,仅当待更新跨度内含 `critical` 级条目时,才在 `acp_status` 与 `/acp` 面板提示「CRITICAL 更新已就绪待重启」(磁盘版本新于运行版本)或「存在 critical 更新」;routine/recommended 级发版永不上屏。绝不安装、绝不重启;fail-open。文件配置键:`releaseNotesCheck`。 | From 0bec76c864d2865f83b3214c1a49f2385a287349 Mon Sep 17 00:00:00 2001 From: ework-agent Date: Sun, 4 Oct 2026 20:49:05 +0800 Subject: [PATCH 3/4] release v0.1.184 --- package-lock.json | 4 ++-- package.json | 2 +- release-notes/package.json | 6 ++++++ 3 files changed, 9 insertions(+), 3 deletions(-) diff --git a/package-lock.json b/package-lock.json index bfe9b5789a..5780888bbf 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "billion-context", - "version": "0.1.183", + "version": "0.1.184", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "billion-context", - "version": "0.1.183", + "version": "0.1.184", "license": "MIT", "dependencies": { "zod": "4.1.8" diff --git a/package.json b/package.json index bfe531752d..a14cf69df4 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "billion-context", - "version": "0.1.183", + "version": "0.1.184", "description": "A context-compression plugin — small context windows (a 100K context is enough), 5x fewer tokens, month-long single sessions (billions of tokens), and compression quality — for all agents: pi, OpenCode, Codex, Claude Code, and more. billion-context is all you need.", "type": "module", "main": "dist/index.js", diff --git a/release-notes/package.json b/release-notes/package.json index 1f18ae311f..f020c10120 100644 --- a/release-notes/package.json +++ b/release-notes/package.json @@ -11,6 +11,12 @@ "schema": 1, "updated": "2026-10-04", "releases": [ + { + "version": "0.1.184", + "date": "2026-10-04", + "tier": "critical", + "summary": "Desktop (dsh): after 0.1.179, an update could make bili tools vanish until restart (#2082) — now self-healing, broken desktop updates roll back; also fixes tool-call misrouting (#2072). Restart dsh once. 丨 桌面版修复:0.1.179 后升级会使 bili 工具消失(#2082),现已自愈;损坏的桌面更新自动回滚;另修 #2072 调用错路由。升级后重启一次 dsh。" + }, { "version": "0.1.182", "date": "2026-10-04", From 1e7ee31ee0de266598ef5bb19259132ce6d80ef2 Mon Sep 17 00:00:00 2001 From: ework-agent Date: Sun, 4 Oct 2026 21:13:05 +0800 Subject: [PATCH 4/4] =?UTF-8?q?fix(#2101):=20clear=20the=20stale=20toolsRe?= =?UTF-8?q?ady=20latch=20on=20a=20fresh=20context=20=E2=80=94=20a=20succes?= =?UTF-8?q?sful=20registration=20into=20a=20dead=20context=20must=20not=20?= =?UTF-8?q?block=20re-registration?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit apply() reset register.dead but not register.toolsReady, so after a SUCCESSFUL registration into ctx1, a same-instance re-apply(ctx2) (profile switch / settings toggle / desktop copy swap) short-circuited registerTools for the new context while headersFor kept stamping x-bili-plugin — plugin mode suppresses wire tool injection, so the model lost the bili tools until dsh restarts (the #2082 symptom via a different route). The fix clears toolsReady only when the context identity genuinely changed (prevCtx !== ctx); same-context re-apply keeps the latch (no churn), and the state.toolsReady gate re-arms to hold the first request until the new registration lands. Regression test: red pre-fix on the no-stamp assertion, green post-fix. --- src/agent/dsh-native.ts | 13 ++++++++ tests/issue2082-dsh-recovery.test.ts | 46 ++++++++++++++++++++++++++++ 2 files changed, 59 insertions(+) diff --git a/src/agent/dsh-native.ts b/src/agent/dsh-native.ts index 28429ba428..5d46de1903 100644 --- a/src/agent/dsh-native.ts +++ b/src/agent/dsh-native.ts @@ -726,8 +726,21 @@ export function apply(ctx: PluginContext): void { // switch, a settings toggle) poisons register.dead for the whole process // lifetime: every later maybeRetry() returns immediately and the bili // tools never come back until dsh restarts. + const prevCtx = activeCtx; register.dead = false; activeCtx = ctx; + // #2101: a genuinely fresh context (dsh deactivated the prior one — profile + // switch / settings toggle / desktop copy swap — and re-applied on the SAME + // module instance) invalidates tools registered into the dead context. + // Keeping toolsReady would make registerTools short-circuit for the new + // context while headersFor keeps stamping x-bili-plugin, so the proxy + // suppresses wire tool injection and the model loses the bili tools until + // dsh restarts (the #2082 symptom via a different route). Clearing it lets + // the state.toolsReady gate below hold the first request until the new + // registration lands. Same-context re-apply must NOT clear it — no + // gratuitous re-registration churn. If the host re-imported the module + // instead, toolsReady is already false and this is a no-op. + if (prevCtx !== undefined && prevCtx !== ctx) register.toolsReady = false; // #1590: the dsh web-profile settings panel shows a "bili设置" entry // (dsh-native-client.js) that opens this proxy's Web UI. The origin is diff --git a/tests/issue2082-dsh-recovery.test.ts b/tests/issue2082-dsh-recovery.test.ts index 85ba672441..89b0b39366 100644 --- a/tests/issue2082-dsh-recovery.test.ts +++ b/tests/issue2082-dsh-recovery.test.ts @@ -9,6 +9,10 @@ // 3. A detached recovery timer keeps retrying while the tools are down even // with zero model traffic (the reported case: the model already gave up on // the missing tools, so nothing re-armed the loop). +// 4. apply() on a genuinely fresh context clears register.toolsReady (#2101) +// — a successful registration into a dead context must not block the new +// context from re-registering (stale latch + x-bili-plugin stamp = the +// model loses the bili tools until dsh restarts). import test, { afterEach } from "node:test"; import assert from "node:assert/strict"; @@ -281,3 +285,45 @@ test("#2082 an in-flight registration lands on the LATEST context after a mid-fe _resetRegisterForTest(undefined); } }); + +test("#2101 apply() on a fresh context clears the stale toolsReady latch — a successful registration into a dead context must not block re-registration (#2101)", async () => { + // slow manifest: widens the window between apply(ctx2) and the + // re-registration landing so the no-stamp assertion below is deterministic + const proxy = await startMockProxy(300); + const home = fs.mkdtempSync(path.join(os.tmpdir(), "bili-dsh-2101-")); + try { + await withEnv({ DSH_HOME: home, BILLION_CONTEXT_PROXY: proxy.origin }, async () => { + _resetRegisterForTest(proxy.origin); + + // phase 1: ctx1 registers successfully — register.toolsReady latches + const ctx1 = mockCtx(); + apply(ctx1); + await waitFor(() => ctx1.registeredTools.length === 1, "initial registration into ctx1"); + assert.equal(ctx1.registeredTools[0].name, "compress"); + + // phase 2: dsh deactivates ctx1 and re-applies on the SAME module + // instance (profile switch / settings toggle / desktop copy swap). + // Pre-fix: registerTools short-circuits on the stale toolsReady + // latch — ctx2 never gets tools.register while headersFor keeps + // stamping x-bili-plugin (plugin mode suppresses wire tool + // injection), so the model loses the bili tools until dsh restarts. + const ctx2 = mockCtx(); + ctx2.setInitiator({ session: { id: "dsh-2101-session" } }); + apply(ctx2); + + // while the re-registration is in flight, headersFor must NOT + // stamp: stamping flips the proxy into plugin mode, which + // suppresses wire injection — a live context without local tools + // would mean zero tools for the model. + assert.equal(_stateHeadersForTest()?.("http://example.test/v1/messages"), undefined, "no x-bili-plugin stamp while the fresh context lacks tools"); + + await waitFor(() => ctx2.registeredTools.length === 1, "re-registration into the fresh context"); + assert.equal(ctx2.registeredTools[0].name, "compress"); + await waitFor(() => _stateHeadersForTest()?.("http://example.test/v1/messages") !== undefined, "headers return after re-registration"); + }); + } finally { + proxy.close(); + rmrf(home); + _resetRegisterForTest(undefined); + } +});