Skip to content

🤖 Open-source, local-first alternative to Grok Bot, OpenAI dots and Claude Duet. Your own AI bots on any model: GPT, Claude, Gemini, Grok, DeepSeek, Kimi, GLM and 70+ more through one Modelflare key. Reach them in the app, WeChat or Feishu; they remember you, work in the background, run commands and use your computer. Pay per use.

fix(agent): a compaction that never reports back no longer holds up the conversation

Marla7c81aff1875d
diff --git a/src/agent/manager.ts b/src/agent/manager.ts
index 1bf3ad3..8434434 100644
--- a/src/agent/manager.ts
+++ b/src/agent/manager.ts
@@ -84,7 +84,8 @@ export class AgentManager {
private decisions = new Map<string, { promise: Promise<boolean>; resolve: (v: boolean) => void }>();
/** 会话 → 下一回合开始前要等的事(判定、压缩完成) */
private gates = new Map<string, Promise<unknown>>();
- private compactDone = new Map<string, (v: unknown) => void>();
+ /** DSH session → 进行中的原地压缩;插件回报、超时、会话被重置或换段、代理进程退出时结束 */
+ private compactDone = new Map<string, { botId: string; conv: string; resolve: (v: unknown) => void }>();
private judgedAt = new Map<string, number>();
private reviewTimers = new Map<string, NodeJS.Timeout>();
/** 会话 → 用户在生成确认里换了模型、代理要按新模型文档重写请求:重写后的那一次免确认 */
@@ -136,6 +137,10 @@ export class AgentManager {
media: !!this.o.media,
contextWindow: this.o.contextWindow,
});
+ // 代理进程退出(/stop、看门狗、换模型或设置、崩溃、重启、停止):进程里的压缩跟着没了,不再等它
+ h.on((e) => {
+ if (e.type === "exit") this.endCompaction((c) => c.botId === botId);
+ });
this.hosts.set(botId, h);
}
return h;
@@ -253,7 +258,7 @@ export class AgentManager {
return r;
} finally {
set.delete(conv);
- if (r) this.afterTurn(botId, conv, r.sessionId, input.model, r.usage, d.resolve);
+ if (r) this.afterTurn(botId, conv, r.sessionId, input.model, r.usage, d);
else d.resolve(false);
}
}
@@ -304,12 +309,12 @@ export class AgentManager {
}
/** 回合结束:上下文管家判定 + 安排记忆整理。不抛错。 */
- private afterTurn(botId: string, conv: string, sessionId: string, model: string, usage: TurnUsage, decide: (compact: boolean) => void): void {
+ private afterTurn(botId: string, conv: string, sessionId: string, model: string, usage: TurnUsage, d: { promise: Promise<boolean>; resolve: (v: boolean) => void }): void {
const st = this.settings(botId);
if (st.memory.enabled && st.memory.review && this.o.complete) this.scheduleReview(botId, conv, model);
const lines = linesFor(usage.window, usage.maxTokens);
if (!st.steward.enabled || !this.o.complete || !shouldJudge(usage.tokens, lines, this.judgedAt.get(sessionId))) {
- decide(false);
+ d.resolve(false);
return;
}
this.judgedAt.set(sessionId, usage.tokens);
@@ -324,16 +329,24 @@ export class AgentManager {
}
// 过了硬线还判不出来时换段(DS-Bot 的做法:判不出 = switch)
if (action === "compact") {
+ // 插件等判定已经超时(120 秒)走了:没人会去压缩,不设闸门,下一回合再判
+ if (this.decisions.get(conv) !== d) {
+ this.judgedAt.delete(sessionId);
+ this.note(conv, "compact-skipped", "判定太慢,插件没等到");
+ return;
+ }
const done = deferred<unknown>();
- this.compactDone.set(sessionId, done.resolve);
+ this.compactDone.set(sessionId, { botId, conv, resolve: done.resolve });
this.gates.set(conv, done.promise);
this.note(conv, "compact", `tokens=${usage.tokens}/${lines.usable}`);
- decide(true);
+ d.resolve(true);
+ // 插件迟迟不回报也只等 200 秒:闸门不能比这次压缩活得久
await withTimeout(done.promise, 200_000, undefined);
- this.compactDone.delete(sessionId);
+ this.endCompaction((_, sid) => sid === sessionId);
+ if (this.gates.get(conv) === done.promise) this.gates.delete(conv);
return;
}
- decide(false);
+ d.resolve(false);
if (action === undefined && usage.tokens < lines.hard) return;
await this.switchSegment(botId, conv, sessionId, model, action ?? "fallback");
})();
@@ -360,6 +373,17 @@ export class AgentManager {
this.o.store.setKV(`seed:${conv}`, handoff);
this.judgedAt.delete(sessionId);
this.note(conv, "switch", reason);
+ // 旧段上还没回报的压缩(/new 不等闸门)不用再等
+ this.endCompaction((c) => c.conv === conv);
+ }
+
+ /** 结束匹配的原地压缩:等着它的回合随即放行,闸门随之清掉 */
+ private endCompaction(match: (c: { botId: string; conv: string }, sessionId: string) => boolean): void {
+ for (const [sid, c] of this.compactDone) {
+ if (!match(c, sid)) continue;
+ this.compactDone.delete(sid);
+ c.resolve(true);
+ }
}
private scheduleReview(botId: string, conv: string, model: string): void {
@@ -547,13 +571,15 @@ export class AgentManager {
/** 插件 → 宿主:代理空闲时取管家判定(phase=idle),压缩完成后回报(phase=done)。 */
private async stewardCall(b: any): Promise<Record<string, unknown>> {
const sessionId = String(b?.sessionId ?? "");
- const conv = this.o.store.conversationForSession(sessionId);
- if (!conv || this.o.store.getAgentSession(conv) !== sessionId) return { compact: false };
if (b?.phase === "done") {
- this.note(conv, "compact-result", String(b?.result ?? ""));
- this.compactDone.get(sessionId)?.(true);
+ // 按 session 结束:会话可能已被 /reset、/new 换掉,闸门也得放开
+ const c = this.compactDone.get(sessionId)?.conv ?? this.o.store.conversationForSession(sessionId);
+ if (c) this.note(c, "compact-result", String(b?.result ?? ""));
+ this.endCompaction((_, sid) => sid === sessionId);
return { ok: true };
}
+ const conv = this.o.store.conversationForSession(sessionId);
+ if (!conv || this.o.store.getAgentSession(conv) !== sessionId) return { compact: false };
const d = this.decisions.get(conv);
if (!d) return { compact: false };
const compact = await withTimeout(d.promise, 120_000, false);
@@ -562,6 +588,8 @@ export class AgentManager {
}
resetConversation(conversationId: string): void {
+ // 会话换掉了:它上面还没回报的压缩不用再等
+ this.endCompaction((c) => c.conv === conversationId);
this.o.store.clearAgentSession(conversationId);
this.o.store.setKV(`seed:${conversationId}`, "");
this.mediaGrants.delete(conversationId);
diff --git a/test/agent-manager.unit.test.ts b/test/agent-manager.unit.test.ts
new file mode 100644
index 0000000..913074c
--- /dev/null
+++ b/test/agent-manager.unit.test.ts
@@ -0,0 +1,149 @@
+/** AgentManager 的回合调度:上下文管家的压缩闸门。代理进程用桩代替(不起 DSH)。 */
+import { EventEmitter } from "node:events";
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { Store } from "../src/store/db.js";
+import { AgentManager } from "../src/agent/manager.js";
+import type { TurnInput } from "../src/agent/host.js";
+import { STEWARD_SYSTEM } from "../src/agent/steward.js";
+
+const COMPACT = '{"action":"compact","reason":"still working"}';
+const CONV = "b:web:console";
+
+let dir: string;
+beforeEach(() => {
+ dir = fs.mkdtempSync(path.join(os.tmpdir(), "amb-mgr-"));
+});
+afterEach(() => {
+ vi.useRealTimers();
+ fs.rmSync(dir, { recursive: true, force: true });
+});
+
+/** 第一回合上下文很大(管家会判定),之后都很小;judge 是管家判定的回答 */
+function setup(judge: () => Promise<string> = async () => COMPACT) {
+ const store = new Store(":memory:");
+ store.createBot({ id: "b", name: "b" });
+ store.ensureConversation("b", "web", "console");
+ const mgr = new AgentManager({
+ store,
+ dataDir: dir,
+ runtimeDir: "/rt",
+ upstream: () => ({ baseUrl: "", apiKey: "" }),
+ enabled: true,
+ reviewDelayMs: 1e9,
+ complete: async (_bot, _model, system) => (system === STEWARD_SYSTEM ? judge() : "交接便条"),
+ });
+ const host = mgr.host("b");
+ let turns = 0;
+ host.runTurn = async (input: TurnInput) => {
+ turns++;
+ let sid = store.getAgentSession(input.conversationId);
+ if (!sid) store.setAgentSession(input.conversationId, "b", (sid = `S${turns}`));
+ return { text: "ok", sessionId: sid, files: [], usage: { tokens: turns === 1 ? 190_000 : 2_000, window: 200_000, maxTokens: 32_000 } };
+ };
+ return {
+ store,
+ mgr,
+ host,
+ turns: () => turns,
+ turn: () => mgr.runTurn("b", { conversationId: CONV, text: "hi", model: "m" }),
+ steward: (body: Record<string, unknown>) => (mgr as any).stewardCall({ botId: "b", ...body }) as Promise<Record<string, unknown>>,
+ };
+}
+
+/** 第一回合结束、管家判定"压缩"、插件来取判定:此后 DSH 在压缩 S1,下一回合要等它回报 */
+async function compacting(s: ReturnType<typeof setup>) {
+ await s.turn();
+ expect(await s.steward({ sessionId: "S1", phase: "idle" })).toEqual({ compact: true });
+}
+
+/** 发一条消息:1 秒内应该交给代理 */
+async function promptly(s: ReturnType<typeof setup>) {
+ const before = s.turns();
+ const p = s.turn();
+ await vi.advanceTimersByTimeAsync(1000);
+ expect(s.turns(), "the turn is still waiting for a compaction that will never report").toBe(before + 1);
+ await p;
+}
+
+describe("context steward: the compaction gate never outlives its compaction", () => {
+ beforeEach(() => {
+ vi.useFakeTimers();
+ });
+
+ it("waits for the plugin to report, then lets the next turn through", async () => {
+ const s = setup();
+ await compacting(s);
+ const p = s.turn();
+ await vi.advanceTimersByTimeAsync(5000);
+ expect(s.turns()).toBe(1);
+ expect(await s.steward({ sessionId: "S1", phase: "done", result: "compacted" })).toEqual({ ok: true });
+ await vi.advanceTimersByTimeAsync(0);
+ expect(s.turns()).toBe(2);
+ await p;
+ await promptly(s);
+ });
+
+ it("/reset while compacting: the next turns do not wait, and a late report for the old session is harmless", async () => {
+ const s = setup();
+ await compacting(s);
+ s.mgr.resetConversation(CONV);
+ await promptly(s);
+ expect(await s.steward({ sessionId: "S1", phase: "done", result: "compacted" })).toEqual({ ok: true });
+ await promptly(s);
+ await promptly(s);
+ });
+
+ it("/new while compacting: the new segment starts right away", async () => {
+ const s = setup();
+ await compacting(s);
+ await s.mgr.newSegment("b", CONV, "m");
+ expect(s.store.getAgentSession(CONV)).toBeUndefined();
+ await promptly(s);
+ });
+
+ it("the plugin's report counts even after the conversation moved to another session", async () => {
+ const s = setup();
+ await compacting(s);
+ s.store.setAgentSession(CONV, "b", "S9");
+ expect(await s.steward({ sessionId: "S1", phase: "done", result: "compacted" })).toEqual({ ok: true });
+ await promptly(s);
+ });
+
+ it("the agent process exits while compacting (/stop, idle watchdog, model change, crash): no more waiting", async () => {
+ const s = setup();
+ await compacting(s);
+ const child = new EventEmitter();
+ (s.host as any).watchChild(child);
+ child.emit("exit", null, "SIGTERM");
+ await promptly(s);
+ });
+
+ it("the plugin never reports: a turn waits at most until the 200 s cap, later turns not at all", async () => {
+ const s = setup();
+ await compacting(s);
+ await vi.advanceTimersByTimeAsync(100_000);
+ const p = s.turn();
+ await vi.advanceTimersByTimeAsync(100_001);
+ expect(s.turns()).toBe(2);
+ await p;
+ await promptly(s);
+ await vi.advanceTimersByTimeAsync(300_000);
+ await promptly(s);
+ });
+
+ it("a judgement the plugin gave up waiting for (120 s) sets no gate", async () => {
+ let decide!: (v: string) => void;
+ const s = setup(() => new Promise<string>((r) => (decide = r)));
+ await s.turn();
+ const idle = s.steward({ sessionId: "S1", phase: "idle" });
+ await vi.advanceTimersByTimeAsync(120_001);
+ expect(await idle).toEqual({ compact: false });
+ decide(COMPACT);
+ await vi.advanceTimersByTimeAsync(0);
+ await promptly(s);
+ expect(s.mgr.stewardLog.map((e) => e.action)).toEqual(["compact-skipped"]);
+ });
+});