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 fbc7f03df927c8bfb92bb85453845f76647b28e7 Mon Sep 17 00:00:00 2001 From: ranxianglei Date: Sun, 4 Oct 2026 21:15:09 +0800 Subject: [PATCH 4/4] fix(#2101): clear a stale toolsReady stamp on re-activation MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A re-activation after a HEALTHY registration used to leave the bili tools dead until dsh restarted — the same #2082 symptom reached from the success ordering. apply() reset register.dead and activeCtx, but not register.toolsReady: the tools registered into the deactivated context die with it, while every registerTools()/maybeRetry() early-returns on the stale stamp, so the new context never re-registers (and headersFor keeps stamping plugin mode for a lane whose dsh side has no tools). Clear toolsReady (and retryAt, per #1783's fresh-activation rule) when apply() sees a context change. Scoped to a context CHANGE: a same-context re-apply keeps its registration (the attach verify path already re-checks on its own). tests/issue2101-dsh-reactivation.test.ts: the success-ordering re-activation test times out on the unfixed tree (verified) and passes with the clear; a same-context re-apply stays healthy. --- release-notes/package.json | 2 +- src/agent/dsh-native.ts | 15 ++ tests/issue2101-dsh-reactivation.test.ts | 177 +++++++++++++++++++++++ 3 files changed, 193 insertions(+), 1 deletion(-) create mode 100644 tests/issue2101-dsh-reactivation.test.ts diff --git a/release-notes/package.json b/release-notes/package.json index f020c10120..040837ce2a 100644 --- a/release-notes/package.json +++ b/release-notes/package.json @@ -15,7 +15,7 @@ "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。" + "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; re-activating the plugin after a healthy boot also re-registers its tools (#2101); also fixes tool-call misrouting (#2072). Restart dsh once. 丨 桌面版修复:0.1.179 后升级会使 bili 工具消失(#2082),现已自愈;损坏的桌面更新自动回滚;健康运行后重激活插件也会重新注册工具(#2101);另修 #2072 调用错路由。升级后重启一次 dsh。" }, { "version": "0.1.182", diff --git a/src/agent/dsh-native.ts b/src/agent/dsh-native.ts index 28429ba428..b754fc264d 100644 --- a/src/agent/dsh-native.ts +++ b/src/agent/dsh-native.ts @@ -726,6 +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. + // #2101: a re-activation ALSO invalidates a SUCCESSFUL registration. + // Registrations die with their context: the tools registered into the + // previous activation are disposed when that context deactivates, but + // register.toolsReady keeps its stale stamp — and every + // registerTools()/maybeRetry() early-returns on it, so the new context + // never gets the bili tools (the #2082 symptom reached from the success + // ordering: a settings toggle, a profile switch or a plugin reload + // AFTER a healthy boot loses the tools until dsh restarts). Clear the + // stale stamp so the retry loop re-registers into the live context; + // retryAt goes with it (#1783: a fresh activation must not stand behind + // a stale back-off wall). + if (register.toolsReady && activeCtx !== undefined && activeCtx !== ctx) { + register.toolsReady = false; + register.retryAt = 0; + } register.dead = false; activeCtx = ctx; diff --git a/tests/issue2101-dsh-reactivation.test.ts b/tests/issue2101-dsh-reactivation.test.ts new file mode 100644 index 0000000000..2d966c990a --- /dev/null +++ b/tests/issue2101-dsh-reactivation.test.ts @@ -0,0 +1,177 @@ +// #2101: a re-activation after a HEALTHY registration must re-register the +// bili tools into the new context. +// +// #2082's fix (v0.1.184) covered the failure orderings: a registerTools +// rejection mid-teardown (dead poison), a base-less register with no respawn +// armed, and an in-flight fetch landing after a re-activation. But the +// success ordering was still open: tools registered successfully into ctx1 +// stamp register.toolsReady=true, and when dsh later deactivates ctx1 and +// re-activates the plugin with ctx2 (a settings toggle, a profile switch, a +// plugin reload), apply() reset register.dead but NOT toolsReady — and every +// registerTools()/maybeRetry() early-returns on it, so ctx2 never got the +// tools until dsh restarted. Same user-visible symptom as #2082. + +import test, { afterEach } from "node:test"; +import assert from "node:assert/strict"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import http from "node:http"; +import { apply, _resetRegisterForTest, _settleNativeForTest, _stateHeadersForTest } from "../src/agent/dsh-native.ts"; +import { rmrf } from "./tmp-rm.ts"; + +afterEach(() => { void _settleNativeForTest(); }); + +type MockTool = { name: string; description?: string; inputSchema: Record }; +type RegisteredTool = { + name: string; + description?: string; + parameters: unknown; + output: { schema: unknown; render: (args: unknown, value: unknown) => Array<{ type: string; text: string }> }; + execute: (args: Record, exec: { agent?: { session?: { id?: unknown } }; signal?: AbortSignal }) => Promise; +}; + +function mockBiliHandler(counters: { manifestRequests: number }): (req: http.IncomingMessage, res: http.ServerResponse) => void { + const manifestTools: MockTool[] = [ + { + name: "compress", + description: "Compress a range of messages", + inputSchema: { type: "object", properties: { summary: { type: "string" } }, required: ["summary"] }, + }, + ]; + return (req, res) => { + const url = req.url ?? ""; + if (url === "/__bili/plugin/manifest") { + counters.manifestRequests += 1; + 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 })) } })); + return; + } + res.writeHead(404); + res.end("{}"); + }; +} + +async function startMockProxy(): Promise<{ origin: string; close: () => void; manifestRequests: () => number }> { + const counters = { manifestRequests: 0 }; + const server = http.createServer(mockBiliHandler(counters)); + 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(), manifestRequests: () => counters.manifestRequests }); + }); + }); +} + +type HostCtx = Parameters[0]; + +function mockCtx() { + 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) => tools.push(t) }, + commands: { register: (c: { name: string; handler: () => Promise<{ kind: string; text: string }> }) => commands.push(c) }, + agents: { currentInitiator: () => initiator }, + setInitiator: (i: { session?: { id?: unknown } } | undefined) => (initiator = i), + registeredTools: tools, + registeredCommands: commands, + inject: (_deps: readonly string[], _cb: (sub: HostCtx) => void) => {}, + }; +} + +async function withEnv(env: Record, fn: () => Promise | T): Promise { + const saved: Record = {}; + for (const k of Object.keys(env)) { + saved[k] = process.env[k]; + const v = env[k]; + if (v === undefined) delete process.env[k]; + else process.env[k] = v; + } + try { + return await fn(); + } finally { + for (const [k, v] of Object.entries(saved)) { + if (v === undefined) delete process.env[k]; + else process.env[k] = v; + } + } +} + +async function waitFor(cond: () => boolean, what: string): Promise { + const deadline = Date.now() + 15000; + while (!cond()) { + if (Date.now() > deadline) throw new Error(`timeout waiting for ${what}`); + await new Promise((r) => setTimeout(r, 10)); + } +} + +test("#2101 a re-activation AFTER a healthy registration re-registers the tools into the new context", async () => { + const proxy = await startMockProxy(); + const home = fs.mkdtempSync(path.join(os.tmpdir(), "bili-dsh-2101-reactivation-")); + try { + await withEnv({ DSH_HOME: home, BILLION_CONTEXT_PROXY: proxy.origin }, async () => { + _resetRegisterForTest(proxy.origin); + + // phase 1: a healthy boot — the fetch lands while ctx1 is still + // active and the tool registers into ctx1 (the ordering #2082's + // fix did not cover: nothing ever threw, register.toolsReady is + // stamped, the plugin looks perfectly healthy). + const ctx1 = mockCtx(); + ctx1.setInitiator({ session: { id: "dsh-2101-session-1" } }); + apply(ctx1); + await waitFor(() => ctx1.registeredTools.length === 1, "initial registration into ctx1"); + assert.equal(ctx1.registeredTools[0].name, "compress"); + const fetchesAfterBoot = proxy.manifestRequests(); + + // phase 2: much later dsh deactivates ctx1 and re-activates the + // plugin with ctx2 (settings toggle / profile switch / reload). + // The tools died with ctx1, but toolsReady still carries the old + // stamp — without the #2101 clear, every registerTools()/ + // maybeRetry() early-returns and ctx2 never gets the bili tools + // until dsh restarts. + const ctx2 = mockCtx(); + ctx2.setInitiator({ session: { id: "dsh-2101-session-2" } }); + apply(ctx2); + await waitFor(() => ctx2.registeredTools.length === 1, "re-registration into the re-activated context"); + assert.equal(ctx2.registeredTools[0].name, "compress"); + assert.ok(proxy.manifestRequests() > fetchesAfterBoot, "the re-activation re-fetched the manifest instead of trusting the stale stamp"); + // plugin mode is live again for the new context + await waitFor(() => _stateHeadersForTest()?.("http://example.test/v1/messages") !== undefined, "headers stamped after re-activation"); + }); + } finally { + proxy.close(); + rmrf(home); + _resetRegisterForTest(undefined); + } +}); + +test("#2101 same-context re-apply keeps the lane healthy — the stale-stamp clear is scoped to a context CHANGE", async () => { + const proxy = await startMockProxy(); + const home = fs.mkdtempSync(path.join(os.tmpdir(), "bili-dsh-2101-same-ctx-")); + try { + await withEnv({ DSH_HOME: home, BILLION_CONTEXT_PROXY: proxy.origin }, async () => { + _resetRegisterForTest(proxy.origin); + + const ctx1 = mockCtx(); + ctx1.setInitiator({ session: { id: "dsh-2101-same-ctx" } }); + apply(ctx1); + await waitFor(() => ctx1.registeredTools.length === 1, "initial registration into ctx1"); + + // apply() running again with the SAME context (a benign re-entry + // — the attach verify path re-checks the proxy and may re-fetch + // the manifest, pre-existing behavior) must not tear the lane + // down: the tools stay live for ctx1 and headers keep stamping. + apply(ctx1); + await new Promise((r) => setTimeout(r, 150)); + assert.ok(ctx1.registeredTools.length >= 1, "tools stay registered for the same context"); + const tool = ctx1.registeredTools.find((t) => t.name === "compress"); + assert.ok(tool !== undefined, "the compress tool is still present after re-apply"); + assert.notEqual(_stateHeadersForTest()?.("http://example.test/v1/messages"), undefined, "headers still stamped"); + }); + } finally { + proxy.close(); + rmrf(home); + _resetRegisterForTest(undefined); + } +});