import { describe, expect, it, beforeEach } from 'vitest'; import { compactToolResultForModel, replyFromToolTrace, snapshotHintForSystem, chinaClockSystemNote, SYSTEM_PROMPT, collectCopilotUi, showQueryFromList, uiActionsFromCapabilityResult, finalizeAssistantReply, resolveAssistantUiLocale, assistantLanguageSystemNote, } from '../src/mcp/orderEntryAgentHost'; import { sanitizeAssistantReply, extractToolCallsFromContent } from '../src/mcp/llmChatWithTools'; import { addCalendarDaysYmd, formatAssistantChinaClock } from '../src/utils/chinaDate'; import { formatSessionIndex, readAssistantSession, resetAssistantSessionsForTests, resolveAssistantHintModule, writeAssistantSession, } from '../src/services/assistantSessionStore'; describe('assistant clock', () => { it('exposes today yesterday tomorrow as YYYY-MM-DD', () => { const clock = formatAssistantChinaClock(new Date('2026-09-04T04:00:00+08:00')); expect(clock.today).toBe('2026-09-04'); expect(clock.yesterday).toBe('2026-09-03'); expect(clock.tomorrow).toBe('2026-09-05'); expect(addCalendarDaysYmd('2026-01-01', -1)).toBe('2025-12-31'); expect(chinaClockSystemNote(new Date('2026-09-04T04:00:00+08:00'))).toContain('今天 2026-09-04'); expect(SYSTEM_PROMPT).toMatch(/不要调 get_current_time/); expect(SYSTEM_PROMPT).toMatch(/要数字或列表:直接调当前模块 list/); expect(SYSTEM_PROMPT).toMatch(/问功能 \/ 在哪/); expect(SYSTEM_PROMPT).toMatch(/search/); expect(SYSTEM_PROMPT).toMatch(/不要逢问必跳页/); expect(SYSTEM_PROMPT).toMatch(/口头说「确认」不算数/); expect(SYSTEM_PROMPT).toMatch(/弹出确认单/); expect(SYSTEM_PROMPT).toMatch(/prepare_order_edit/); expect(SYSTEM_PROMPT).toMatch(/不要把全部行改成同一数量/); expect(SYSTEM_PROMPT).toMatch(/open_order/); expect(SYSTEM_PROMPT).toMatch(/不要 prepare_order_edit 假装做完/); expect(SYSTEM_PROMPT).toMatch(/禁止用本工具改供应商、加工、单位、成本价、新建商品档案/); expect(SYSTEM_PROMPT).not.toMatch(/禁止改价格/); }); it('locks reply language to zh-CN when locale is missing or invalid', () => { expect(resolveAssistantUiLocale(undefined)).toBe('zh-CN'); expect(resolveAssistantUiLocale('foo')).toBe('zh-CN'); expect(resolveAssistantUiLocale('en')).toBe('en'); expect(assistantLanguageSystemNote('zh-CN')).toMatch(/简体中文/); expect(assistantLanguageSystemNote('en')).toMatch(/English/); expect(assistantLanguageSystemNote('id')).toMatch(/Bahasa Indonesia/); }); }); describe('compactToolResultForModel', () => { it('keeps list summary and at most 8 orders without ui', () => { const orders = Array.from({ length: 20 }, (_, i) => ({ order_code: `O${i}`, customer_name: '食堂', })); const compact = compactToolResultForModel('list_orders', { ok: true, data: { count: 20, total_amount: 100, date_from: '2026-09-03', date_to: '2026-09-03', date_field: 'delivery_date', search: '土豆', orders, ui: [{ type: 'navigate', path: '/orders' }], }, }) as Record; expect(compact.ok).toBe(true); expect(compact.ui).toBeUndefined(); expect(compact.search).toBe('土豆'); expect(String(compact.summary)).toContain('订单 20 个'); expect(Array.isArray(compact.orders) && compact.orders).toHaveLength(8); expect(JSON.stringify(compact).length).toBeLessThan(JSON.stringify({ orders, ui: compact.ui }).length); }); it('keeps sku name and quantity on order detail', () => { const compact = compactToolResultForModel('get_order_detail', { ok: true, data: { order: { order_code: 'O1', customer_name: '一食堂', delivery_date: '2026-09-03' }, items: [{ sku_code: 'S1', item_name: '土豆', quantity: 10, unit: '斤', unit_cost: 3 }], }, }) as { items: Array<{ item_name: string; quantity: number; unit_cost?: number }> }; expect(compact.items[0]).toMatchObject({ item_name: '土豆', quantity: 10 }); expect(compact.items[0].unit_cost).toBeUndefined(); }); it('collectCopilotUi still reads full handler data including ui', () => { const actions = collectCopilotUi({ ui: [ { type: 'navigate', path: '/orders', web: { path: '/orders' } }, { type: 'set_fields', patches: [{ name: 'search', value: '白菜' }] }, ], }); expect(actions).toHaveLength(2); }); it('showQueryFromList does not navigate and hides unit_cost', () => { const action = showQueryFromList('list_orders', { count: 1, total_amount: 100, date_from: '2026-09-02', date_to: '2026-09-02', orders: [{ order_code: 'ORD1', customer_name: '食堂', unit_cost: 3 }], }); expect(action?.type).toBe('show_query'); if (action?.type === 'show_query') { expect(action.payload.rows[0].unit_cost).toBeUndefined(); expect(action.payload.rows[0].order_code).toBe('ORD1'); expect(action.payload.count).toBe(1); } }); it('list_orders query card pages 20 rows and drops photo urls', () => { const orders = Array.from({ length: 25 }, (_, i) => ({ order_code: `ORD${i}`, customer_name: '食堂', photo_url: 'https://cdn.example/a.jpg', unit_cost: 3, })); const action = showQueryFromList('list_orders', { count: 37, orders }, { date_from: '2026-09-17', date_to: '2026-09-23' }); expect(action?.type).toBe('show_query'); if (action?.type === 'show_query') { expect(action.payload.rows).toHaveLength(20); expect(action.payload.count).toBe(37); expect(action.payload.browse_id).toBeTruthy(); expect(action.payload.has_date).toBe(true); expect(action.payload.has_search).toBe(true); expect(action.payload.rows[0].photo_url).toBeUndefined(); expect(action.payload.rows[0].unit_cost).toBeUndefined(); expect(JSON.stringify(action.payload.rows)).not.toContain('https://'); } }); it('list_customers emits request_pick without branch_code and without show_query', () => { const actions = uiActionsFromCapabilityResult('list_customers', { ok: true, data: { count: 2, customers: [ { customer_code: 'C1', company_name: '一食堂', branch_code: 'BR002' }, { customer_code: 'C2', company_name: '二食堂', branch_code: 'BR002' }, ], }, }); expect(actions).toHaveLength(1); expect(actions[0]?.type).toBe('request_pick'); if (actions[0]?.type === 'request_pick') { expect(actions[0].payload.slot).toBe('customer_code'); expect(actions[0].payload.options).toEqual([ { id: 'C1', label: '一食堂' }, { id: 'C2', label: '二食堂' }, ]); expect(JSON.stringify(actions[0])).not.toContain('branch_code'); } }); it('uiActionsFromCapabilityResult emits preview_change from need_confirm preview', () => { const actions = uiActionsFromCapabilityResult('create_after_sale', { ok: false, code: 'need_confirm', action_id: 'create_after_sale', message: '确认', preview: { action_type: 'create', capability: 'create_after_sale', target_type: 'after_sale', summary: '新建售后', diff: [{ field: '订单', after: 'ORD1' }], }, }); expect(actions).toEqual([ { type: 'preview_change', payload: expect.objectContaining({ capability: 'create_after_sale' }), }, ]); }); }); describe('replyFromToolTrace', () => { it('synthesizes a business reply and prefers need_input', () => { expect( replyFromToolTrace([ { name: 'list_self_purchases', ok: true, summary: '自采 23 条(日期 2026-09-03)' }, ]) ).toContain('自采 23 条'); expect( replyFromToolTrace([{ name: 'list_orders', ok: false, summary: '还缺少:date_from。请向用户询问后再调用。' }]) ).toContain('还缺少:date_from'); }); }); describe('finalizeAssistantReply', () => { it('strips leaked DSML and falls back to tool trace', () => { const leaked = `< | | DSML | | tool_calls> < | | DSML | | invoke name="list"> < | | DSML | | parameter name="search" string="true">土豆 `; expect(sanitizeAssistantReply(leaked)).not.toMatch(/DSML|invoke name=/); expect( finalizeAssistantReply(leaked, [{ name: 'list_pages', ok: true, summary: '页面 37 个' }]) ).toContain('页面 37 个'); const parsed = extractToolCallsFromContent(leaked, ['list_orders', 'list_pages']); expect(parsed[0]?.function.name).toBe('list_orders'); expect(JSON.parse(parsed[0]?.function.arguments || '{}')).toMatchObject({ search: '土豆' }); }); }); describe('snapshotHintForSystem', () => { it('only writes pageId and path for non-order pages', () => { const hint = snapshotHintForSystem({ pageId: 'purchase-list', path: '/purchase', values: { date_from: '2026-09-03' }, rows: [{ a: 1 }], }); expect(hint).toContain('pageId=purchase-list'); expect(hint).toContain('path=/purchase'); expect(hint).not.toContain('date_from'); }); it('tells model to search then open_order on /orders', () => { const hint = snapshotHintForSystem({ pageId: 'order-management', path: '/orders', values: { search: 'ORD1' }, }); expect(hint).toMatch(/open_order/); expect(hint).toMatch(/抽屉/); expect(hint).not.toContain('ORD1'); }); it('skips extra navigate when order drawer is already open', () => { const hint = snapshotHintForSystem({ pageId: 'order-management', path: '/orders', values: { selected_order_code: 'ORD9' }, }); expect(hint).toContain('ORD9'); expect(hint).toMatch(/不要再 open_page/); expect(hint).toMatch(/prepare_order_edit/); }); }); describe('assistant session store', () => { beforeEach(() => { resetAssistantSessionsForTests(); }); it('prefers session lastModule over request hint', () => { expect(resolveAssistantHintModule('self-purchase', 'order-entry')).toBe('self-purchase'); expect(resolveAssistantHintModule(null, 'order-entry')).toBe('order-entry'); }); it('roundtrips memory session and formats index as non-fact', async () => { await writeAssistantSession('u1', 's1', { lastModule: 'self-purchase', lastUser: '昨天自采多少条', lastReply: '23条', traces: [{ name: 'list_self_purchases', ok: true, summary: '自采 23 条(日期 2026-09-03)' }], }); const session = await readAssistantSession('u1', 's1'); expect(session?.lastModule).toBe('self-purchase'); const index = formatSessionIndex(session); expect(index).toContain('不是当前事实'); expect(index).toContain('必须再调工具'); expect(index).toContain('list_self_purchases'); expect(index).not.toContain('pendingWrite'); }); });