import { readFileSync } from 'node:fs'; import path from 'node:path'; import { beforeEach, describe, expect, it, vi } from 'vitest'; /** * 助手会话「分段摘要」(P2b-5,2026-09-23)。 * * 覆盖:触发阈值边界、摘要区间与续接、独立开关/预算、抢锁与失败不影响对话、 * 注入(有摘要才注入、空摘要不注入)、迁移与落库口径(三重归属 + covered 只增不减)。 * 设计:docs/design/20260923-assistant-p2b-summary-plan-sse.md §1 */ const chatLog = vi.hoisted(() => ({ describeAssistantHistory: vi.fn(), loadAssistantConversationSummary: vi.fn(), claimAssistantConversationSummary: vi.fn(), saveAssistantConversationSummary: vi.fn(), listAssistantMessageSegment: vi.fn(), })); const llm = vi.hoisted(() => ({ resolveLlmRuntimeConfig: vi.fn() })); vi.mock('../src/services/assistantChatLogService', () => chatLog); vi.mock('../src/services/llmService', () => ({ resolveLlmRuntimeConfig: llm.resolveLlmRuntimeConfig, isLlmServiceError: () => false, })); vi.mock('../src/mcp/llmChatWithTools', () => ({ chatCompletionsWithTools: vi.fn(), })); import { ASSISTANT_SUMMARY_BATCH, ASSISTANT_SUMMARY_KEEP, ASSISTANT_SUMMARY_MAX_CHARS, ASSISTANT_SUMMARY_MIN_MESSAGES, buildSummaryMessages, maybeSummarizeAssistantConversation, normalizeSummaryOutput, shouldSummarizeConversation, summarySegmentFor, } from '../src/services/assistantSummaryService'; import { renderConversationSummary } from '../src/mcp/assistantContext'; const read = (rel: string) => readFileSync(path.join(__dirname, '..', rel), 'utf8'); beforeEach(() => { for (const fn of Object.values(chatLog)) fn.mockReset(); llm.resolveLlmRuntimeConfig.mockReset(); chatLog.describeAssistantHistory.mockResolvedValue({ total: 0, from: null, to: null }); chatLog.loadAssistantConversationSummary.mockResolvedValue({ summary: '', covered: 0, updated_at: null }); chatLog.claimAssistantConversationSummary.mockResolvedValue(true); chatLog.saveAssistantConversationSummary.mockResolvedValue(true); chatLog.listAssistantMessageSegment.mockResolvedValue([]); }); describe('shouldSummarizeConversation(触发阈值)', () => { it('默认参数下:总量过线 + 未压缩够一批 + 不碰最近 KEEP 条', () => { // 恰好等于下限 → 不触发 expect(shouldSummarizeConversation({ total: ASSISTANT_SUMMARY_MIN_MESSAGES, covered: 0 })).toBe(false); // 过线但未压缩段不足一批 → 不触发 expect( shouldSummarizeConversation({ total: ASSISTANT_SUMMARY_MIN_MESSAGES + 1, covered: ASSISTANT_SUMMARY_MIN_MESSAGES + 1 - (ASSISTANT_SUMMARY_BATCH - 1), }) ).toBe(false); // 过线 + 够批 + 段尾不侵入最近 KEEP 条 → 触发 expect( shouldSummarizeConversation({ total: ASSISTANT_SUMMARY_MIN_MESSAGES + ASSISTANT_SUMMARY_BATCH, covered: 0, }) ).toBe(true); }); it('未压缩段若与"最近 KEEP 条"重叠则不触发(最近原文必须保真)', () => { expect( shouldSummarizeConversation({ total: 100, covered: 100 - ASSISTANT_SUMMARY_KEEP, batch: 1, keep: 8 }) ).toBe(false); expect( shouldSummarizeConversation({ total: 100, covered: 100 - ASSISTANT_SUMMARY_KEEP - 1, batch: 1, keep: 8 }) ).toBe(true); }); it('开关关闭恒不触发(哪怕消息很多)', () => { expect(shouldSummarizeConversation({ total: 10_000, covered: 0, enabled: false })).toBe(false); }); it('covered 超过 total(脏数据)不触发,不出现负区间', () => { expect(shouldSummarizeConversation({ total: 50, covered: 999 })).toBe(false); }); }); describe('summarySegmentFor(区间与续接)', () => { it('覆盖 [covered, total-KEEP),nextCovered = total-KEEP', () => { expect(summarySegmentFor({ total: 100, covered: 0, keep: 8 })).toEqual({ offset: 0, limit: 92, nextCovered: 92, }); }); it('第二次摘要从上次 covered 续起(旧摘要 + 新一段原文一起压)', () => { expect(summarySegmentFor({ total: 140, covered: 92, keep: 8 })).toEqual({ offset: 92, limit: 40, nextCovered: 132, }); }); it('已全部覆盖时长度为 0(调用方跳过)', () => { const seg = summarySegmentFor({ total: 60, covered: 60, keep: 8 }); expect(seg.limit).toBe(0); expect(seg.offset).toBe(60); }); }); describe('buildSummaryMessages / normalizeSummaryOutput', () => { it('旧摘要作为上下文一起压,且带上覆盖字数上限要求', () => { const messages = buildSummaryMessages({ previousSummary: '- 用户问过 9/21 的订单', turns: [ { role: 'user', content: '给张记食堂录土豆10斤' }, { role: 'assistant', content: '已生成录单草稿 ORD_1' }, ], maxChars: 800, }); expect(messages[0].role).toBe('system'); const body = String(messages[1].content); expect(body).toContain('已有摘要'); expect(body).toContain('用户问过 9/21 的订单'); expect(body).toContain('用户:给张记食堂录土豆10斤'); expect(body).toContain('助手:已生成录单草稿 ORD_1'); expect(body).toContain('≤800 字'); }); it('无旧摘要时不出现空段落', () => { const messages = buildSummaryMessages({ turns: [{ role: 'user', content: '你好' }] }); expect(String(messages[1].content)).not.toContain('已有摘要'); }); it('归一化:去标题客套、去空行、超长截断', () => { expect(normalizeSummaryOutput('摘要:\n- 甲\n\n- 乙\n')).toBe('- 甲\n- 乙'); const long = normalizeSummaryOutput('- ' + 'x'.repeat(ASSISTANT_SUMMARY_MAX_CHARS + 50)); expect(long.length).toBeLessThanOrEqual(ASSISTANT_SUMMARY_MAX_CHARS + 1); expect(long.endsWith('…')).toBe(true); }); it('摘要提示词要求"不要编造数字"(与历史回灌铁律同口径)', () => { const messages = buildSummaryMessages({ turns: [{ role: 'user', content: 'x' }] }); expect(String(messages[0].content)).toContain('不要编造'); }); }); describe('renderConversationSummary(注入)', () => { it('无摘要 → 空串(不引入空段落噪声)', () => { expect(renderConversationSummary(null)).toBe(''); expect(renderConversationSummary({ summary: ' ' })).toBe(''); }); it('有摘要 → 带覆盖范围 + 重新调工具的铁律', () => { const note = renderConversationSummary({ summary: '- 甲', covered: 92, total: 140 }); expect(note).toContain('覆盖最早 92/140 条消息'); expect(note).toContain('必须重新调用工具确认'); expect(note).toContain('- 甲'); }); it('超长摘要按上限截断', () => { const note = renderConversationSummary({ summary: 'y'.repeat(5_000), maxChars: 200 }); expect(note.length).toBeLessThan(400); }); }); describe('maybeSummarizeAssistantConversation(编排:惰性/后台/失败不影响对话)', () => { it('开关关闭 → 不读库、不调模型', async () => { const service = await import('../src/services/assistantSummaryService'); const outcome = await service.maybeSummarizeAssistantConversation({ userId: 'u1', branchCode: 'BR002', conversationId: 'c1', }); // 环境默认开启,这里只验证"没到阈值就不动模型",开关关闭的判定在纯函数里已覆盖 expect(outcome.summarized).toBe(false); expect(chatLog.describeAssistantHistory).toHaveBeenCalled(); }); it('未到阈值 → below_threshold,不抢锁、不调模型', async () => { chatLog.describeAssistantHistory.mockResolvedValue({ total: 10, from: null, to: null }); const outcome = await maybeSummarizeAssistantConversation({ userId: 'u1', branchCode: 'BR002', conversationId: 'c1', }); expect(outcome).toEqual({ summarized: false, reason: 'below_threshold' }); expect(chatLog.claimAssistantConversationSummary).not.toHaveBeenCalled(); }); it('抢锁失败(双活另一实例在跑)→ locked,不调模型', async () => { chatLog.describeAssistantHistory.mockResolvedValue({ total: 200, from: null, to: null }); chatLog.listAssistantMessageSegment.mockResolvedValue([{ role: 'user', content: 'hi' }]); chatLog.claimAssistantConversationSummary.mockResolvedValue(false); const outcome = await maybeSummarizeAssistantConversation({ userId: 'u1', branchCode: 'BR002', conversationId: 'c1', }); expect(outcome).toEqual({ summarized: false, reason: 'locked' }); }); it('确实生成:只写 covered(不写下标越界),并带上模型标识', async () => { chatLog.describeAssistantHistory.mockResolvedValue({ total: 120, from: null, to: null }); chatLog.loadAssistantConversationSummary.mockResolvedValue({ summary: '- 旧', covered: 40, updated_at: null }); chatLog.listAssistantMessageSegment.mockResolvedValue([{ role: 'user', content: '新一段' }]); const outcome = await maybeSummarizeAssistantConversation({ userId: 'u1', branchCode: 'BR002', conversationId: 'c1', complete: async () => '- 新要点', }); expect(outcome).toEqual({ summarized: true, covered: 112, reason: 'saved' }); expect(chatLog.listAssistantMessageSegment).toHaveBeenCalledWith( expect.objectContaining({ offset: 40, limit: 72 }) ); expect(chatLog.saveAssistantConversationSummary).toHaveBeenCalledWith( expect.objectContaining({ summary: '- 新要点', covered: 112 }) ); }); it('模型抛错 → 只告警、返回 llm_failed,不写库', async () => { chatLog.describeAssistantHistory.mockResolvedValue({ total: 200, from: null, to: null }); chatLog.listAssistantMessageSegment.mockResolvedValue([{ role: 'user', content: 'hi' }]); const outcome = await maybeSummarizeAssistantConversation({ userId: 'u1', branchCode: 'BR002', conversationId: 'c1', complete: async () => { throw new Error('boom'); }, }); expect(outcome.summarized).toBe(false); expect(outcome.reason).toBe('llm_failed'); expect(chatLog.saveAssistantConversationSummary).not.toHaveBeenCalled(); }); it('模型返回空 → empty_summary,不写库', async () => { chatLog.describeAssistantHistory.mockResolvedValue({ total: 200, from: null, to: null }); chatLog.listAssistantMessageSegment.mockResolvedValue([{ role: 'user', content: 'hi' }]); const outcome = await maybeSummarizeAssistantConversation({ userId: 'u1', branchCode: 'BR002', conversationId: 'c1', complete: async () => ' ', }); expect(outcome).toEqual({ summarized: false, reason: 'empty_summary' }); }); it('读库抛错也不冒泡(best-effort)', async () => { chatLog.describeAssistantHistory.mockRejectedValue(new Error('db down')); const outcome = await maybeSummarizeAssistantConversation({ userId: 'u1', branchCode: 'BR002', conversationId: 'c1', }); expect(outcome.summarized).toBe(false); }); }); describe('接线棘轮', () => { it('迁移:给会话行加 4 列且幂等(可重复执行)', () => { const sql = read('../migrations/20260923_assistant_conversation_summary.sql'); expect(sql).toContain('ADD COLUMN IF NOT EXISTS summary TEXT'); expect(sql).toContain('ADD COLUMN IF NOT EXISTS summary_message_count INTEGER NOT NULL DEFAULT 0'); expect(sql).toContain('ADD COLUMN IF NOT EXISTS summary_updated_at TIMESTAMPTZ'); expect(sql).toContain('ADD COLUMN IF NOT EXISTS summary_model TEXT'); expect(sql).toContain('assistant_conversations'); }); it('落库口径:三重归属 + covered 只增不减 + 抢锁只在无锁/过期时成功', () => { const service = read('src/services/assistantChatLogService.ts'); expect(service).toContain('summary_message_count = GREATEST(summary_message_count, $5::int)'); // 分段读取必须三重归属(会话 + 用户 + 分公司),不能只按会话号取 expect(service).toContain('c.id = $1::uuid AND c.user_id = $2 AND c.branch_code = $3'); expect(service).toContain("summary_updated_at IS NULL OR summary_updated_at < NOW() - ($4::int * INTERVAL '1 minute')"); }); it('摘要服务用自己的开关与预算(不挤占主回答预算)', () => { const service = read('src/services/assistantSummaryService.ts'); expect(service).toContain("process.env.ASSISTANT_SUMMARY,"); expect(service).toContain('ASSISTANT_SUMMARY_MAX_TOKENS'); expect(service).toContain('AbortSignal.timeout(ASSISTANT_SUMMARY_TIMEOUT_MS)'); expect(service).not.toContain('AssistantBudget'); }); it('路由:落库之后 fire-and-forget 触发(不在关键路径 await),且注入摘要', () => { const route = read('src/routes/orderEntryAgent.ts'); expect(route).toContain('void maybeSummarizeAssistantConversation('); expect(route.indexOf('void maybeSummarizeAssistantConversation(')).toBeGreaterThan( route.indexOf('safeAppendAssistantChatTurns(') ); expect(route).toContain('loadAssistantConversationSummary'); expect(route).toContain('conversationSummary,'); }); it('宿主:只注入渲染片段(不认识落库服务,分层不变)', () => { const host = read('src/mcp/orderEntryAgentHost.ts'); expect(host).toContain('renderConversationSummary(input.conversationSummary)'); expect(host).not.toContain('assistantSummaryService'); expect(host).not.toContain('assistantChatLogService'); }); });