import { readFileSync } from 'node:fs'; import path from 'node:path'; import { describe, expect, it } from 'vitest'; import { AssistantBudget, assistantBudgetFinalNote, resolveAssistantBudgetLimits, } from '../src/mcp/assistantBudget'; /** * P2a:用「预算 + 无进展」替代硬轮数上限(2026-09-22)。 * 改前 MAX_ROUNDS 默认 5/上限 8,且最后一轮 tools: [] → 需要 6+ 次工具的任务被硬截断。 */ describe('resolveAssistantBudgetLimits', () => { it('默认:保险丝 12 轮 / 40k token / 60s / 连续 2 轮无进展即停', () => { expect(resolveAssistantBudgetLimits({})).toEqual({ maxRounds: 12, tokenBudget: 40_000, wallclockMs: 60_000, noProgressRounds: 2, }); }); it('环境变量可调并夹取安全区间', () => { expect( resolveAssistantBudgetLimits({ ASSISTANT_MAX_ROUNDS: '20', ASSISTANT_TOKEN_BUDGET: '120000', ASSISTANT_WALLCLOCK_MS: '90000', ASSISTANT_NO_PROGRESS_ROUNDS: '3', }) ).toEqual({ maxRounds: 20, tokenBudget: 120_000, wallclockMs: 90_000, noProgressRounds: 3 }); expect(resolveAssistantBudgetLimits({ ASSISTANT_MAX_ROUNDS: '999' }).maxRounds).toBe(40); expect(resolveAssistantBudgetLimits({ ASSISTANT_TOKEN_BUDGET: '1' }).tokenBudget).toBe(2_000); }); }); describe('AssistantBudget', () => { const limits = resolveAssistantBudgetLimits({}); it('不再在第 5/8 轮就截断:默认要跑到保险丝 12 轮', () => { const b = new AssistantBudget(limits, 0, () => 0); const runRounds = (n: number) => { for (let i = 0; i < n; i += 1) { b.recordUsage({ promptTokens: 100, completionTokens: 50 }); b.noteProgress(true); } }; runRounds(5); expect(b.shouldStop().stop).toBe(false); // 改前:这里就被截断 runRounds(3); // 累计 8 轮 expect(b.shouldStop().stop).toBe(false); // 改前:上限 8 也被截断 runRounds(4); // 累计 12 轮 → 保险丝 expect(b.shouldStop()).toEqual({ stop: true, reason: 'max_rounds' }); }); it('token 预算耗尽即停(主控是预算,不是轮数)', () => { const b = new AssistantBudget({ ...limits, tokenBudget: 1_000 }, 0, () => 0); b.recordUsage({ promptTokens: 700, completionTokens: 400 }); expect(b.shouldStop()).toEqual({ stop: true, reason: 'token_budget' }); }); it('墙钟预算耗尽即停', () => { let now = 0; const b = new AssistantBudget({ ...limits, wallclockMs: 5_000 }, 0, () => now); now = 4_000; b.recordUsage({}); expect(b.shouldStop().stop).toBe(false); now = 5_000; expect(b.shouldStop()).toEqual({ stop: true, reason: 'wallclock_budget' }); }); it('无进展:连续 N 轮没有新执行即停;一旦有新进展重新计数', () => { const b = new AssistantBudget(limits, 0, () => 0); b.noteProgress(false); b.recordUsage({}); expect(b.shouldStop().stop).toBe(false); b.noteProgress(false); b.recordUsage({}); expect(b.shouldStop()).toEqual({ stop: true, reason: 'no_progress' }); const b2 = new AssistantBudget(limits, 0, () => 0); b2.noteProgress(false); b2.recordUsage({}); b2.noteProgress(true); // 有新进展 → 清零 b2.recordUsage({}); b2.noteProgress(false); b2.recordUsage({}); expect(b2.shouldStop().stop).toBe(false); }); it('snapshot 汇总轮数/token/耗时/停止原因', () => { const b = new AssistantBudget(limits, 1_000, () => 3_500); b.recordUsage({ promptTokens: 120, completionTokens: 30 }); b.recordUsage({ promptTokens: 80, completionTokens: 20 }); expect(b.snapshot()).toEqual({ rounds: 2, promptTokens: 200, completionTokens: 50, elapsedMs: 2_500, stop: { stop: false }, }); }); it('每种收尾原因都有可读的系统提示(不再"硬截断没解释")', () => { for (const key of ['token_budget', 'wallclock_budget', 'no_progress', 'max_rounds', 'aborted'] as const) { expect(assistantBudgetFinalNote[key].length).toBeGreaterThan(10); } }); }); describe('执行侧接线棘轮', () => { const read = (rel: string) => readFileSync(path.join(__dirname, '..', rel), 'utf8'); it('宿主用预算主控,循环不再以 MAX_ROUNDS 为条件', () => { const host = read('src/mcp/orderEntryAgentHost.ts'); expect(host).toContain('new AssistantBudget(resolveAssistantBudgetLimits())'); expect(host).not.toMatch(/for \(let round = 0; round < MAX_ROUNDS/); expect(host).toContain('budget.shouldStop()'); expect(host).toContain('budget.noteProgress(executedNew > 0)'); }); it('只读能力轮内并行(写能力仍串行)', () => { const host = read('src/mcp/orderEntryAgentHost.ts'); expect(host).toContain("getCapabilityEffect(task.name) === 'read'"); expect(host).toContain('await Promise.all(parallelReads.map((task) => runOne(task)))'); }); it('中止/超时不再抛 500,而是落成"半途收尾"', () => { const host = read('src/mcp/orderEntryAgentHost.ts'); expect(host).toContain("stopReason = aborted ? 'aborted' : 'wallclock_budget';"); expect(host).toContain("stats: {"); }); it('适配器解析 usage 并支持外部 signal(AbortSignal.any)', () => { const adapter = read('src/mcp/llmChatWithTools.ts'); expect(adapter).toContain('prompt_tokens?: number;'); expect(adapter).toContain('usage: { promptTokens, completionTokens, totalTokens }'); expect(adapter).toContain('AbortSignal.any([timeoutSignal, input.signal])'); }); it('路由透传断开信号并落库用量(失败不影响对话)', () => { const route = read('src/routes/orderEntryAgent.ts'); // 断开透传收敛到 attachClientAbort()(/chat 与 /chat/stream 共用),守卫不得去掉 expect(route).toContain('const controller = new AbortController();'); expect(route).toContain('if (!res.writableEnded) controller.abort();'); expect(route).toContain('signal: clientAbort.signal'); expect(route).toContain('attachClientAbort(res)'); // 流式进度也必须能中止与收尾(心跳定时器不得泄漏) expect(route).toContain("router.post('/chat/stream'"); expect(route).toContain('clearInterval(heartbeat)'); expect(route).toContain('await logAssistantTurn({'); const service = read('src/services/assistantTurnLogService.ts'); expect(service).toContain('INSERT INTO assistant_turns'); expect(service).toContain('不影响对话'); }); it('新表已登记进 tenant_business_tables(平台规则)', () => { const sql = readFileSync( path.join(__dirname, '..', '..', 'migrations', '20260922_assistant_turns.sql'), 'utf8' ); expect(sql).toContain("'assistant_turns'"); expect(sql).toContain('tenant_business_tables() 缺表'); }); });