Files
SupplierSystem/src/copilot/assistantChatStream.test.ts
T
Ubuntu aa2db57b0f
CI / server typecheck + tests (push) Canceled after 0s
CI / web typecheck + tests + miniprogram syntax (push) Canceled after 0s
CI / eslint (观察项,C7 骨架) (push) Canceled after 0s
CI / npm audit (critical 硬拦) (push) Canceled after 0s
feat(main-system): 免入库单取货链路 + 实收数量「事实登记 + 事后同步」
免入库(主系统骑手上门取货):
- 50 展示「待取货」、副文案「待主系统骑手上门取货」、不建我方配送任务(守卫与开关解耦)
- 我方 50 即回写备货完成;两开关(SKIP_INBOUND_AWAIT_PICKUP / FULFILLMENT_EVENTS)改默认开

核货事实镜像(「核货完毕」标记):
- 按主系统 lookup 的 actual_qty 落台账,新增 GET/POST /orders/:orderCode/main-system-prep-facts[/refresh]
- 详情行内显示「核货完毕」(含核货量),分配对账兜底刷新

实收数量/单位口径变更(对方先改 + 我方事后同步):
- 台账加 applied_at;inbound 与 picking_check 同为事实登记(驳回不回滚)
- 同意才落我方值:免入库改装车核货量、送仓改验收实收(已入库走既有库存调整)、已结算/已结案只留痕
- 计划量与金额一起改,并同步结算投影(syncStatementsForOrderSafe)
- 审核页语义改「主系统实际值(已生效)/ 是否同步」+ 已处理历史(双方时间与落值结论)

台账对照与回写修复:
- 行级对照改整单一次性(同名商品不再重复认领)+ 存量纠正 healOrderPrepMapping
- 堵住客户绑定回填旁路(免入库单不再被派我方骑手)
- 回写触发函数改对象参数(修 branch/order 传反导致的静默不回写)

文档:设计文档 4 篇 +《给主系统 AI 的对接改造清单》§2.9(第六批契约)

回归:服务端全量与 HEAD 基线一致(24 个失败文件同集合);前端 140 文件 / 699 测试全绿;tsc 双端干净
2026-10-09 21:52:17 +08:00

224 lines
8.8 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { describe, expect, it, vi, beforeEach } from 'vitest';
import {
parseSseBuffer,
parseSseData,
postAssistantChat,
requestAssistantChat,
streamAssistantChat,
} from './assistantChatStream';
/**
* 助手流式进度(P2b-7,2026-09-23):SSE 客户端。
* 关键行为:半帧容错、注释/心跳忽略、`final` 载荷复用、失败一律回退 `/chat`、主动中止不回退。
*/
// 供应商系统(二次开发)本地 API 端口为 3022(主系统为 3001)
const apiUrl = (path: string) => `http://localhost:3022/api${path}`;
function sseResponse(frames: string[], options?: { contentType?: string; ok?: boolean; status?: number }) {
const encoder = new TextEncoder();
let i = 0;
const body = new ReadableStream<Uint8Array>({
pull(controller) {
if (i >= frames.length) {
controller.close();
return;
}
controller.enqueue(encoder.encode(frames[i]));
i += 1;
},
});
return {
ok: options?.ok ?? true,
status: options?.status ?? 200,
headers: { get: () => options?.contentType ?? 'text/event-stream; charset=utf-8' },
body,
json: async () => ({}),
} as unknown as Response;
}
beforeEach(() => {
vi.restoreAllMocks();
});
describe('parseSseBuffer', () => {
it('完整帧解析;半帧留在 rest 等下次', () => {
const first = parseSseBuffer('event: open\ndata: {"a":1}\n\nevent: tool_start\ndata: {"name":"lis');
expect(first.frames).toEqual([{ event: 'open', data: '{"a":1}' }]);
expect(first.rest).toBe('event: tool_start\ndata: {"name":"lis');
const second = parseSseBuffer(`${first.rest}t_orders"}\n\n`);
expect(second.frames).toEqual([{ event: 'tool_start', data: '{"name":"list_orders"}' }]);
expect(second.rest).toBe('');
});
it('同片多帧 + CRLF + 注释心跳全部处理', () => {
const { frames } = parseSseBuffer(
': ping\r\n\r\nevent: tool_end\r\ndata: {"ok":true}\r\n\r\nevent: final\r\ndata: {"reply":"hi"}\r\n\r\n'
);
expect(frames.map((row) => row.event)).toEqual(['tool_end', 'final']);
});
it('多行 data 按 \\n 拼接(SSE 规范)', () => {
const { frames } = parseSseBuffer('event: final\ndata: {"a":1,\ndata: "b":2}\n\n');
expect(frames[0].data).toBe('{"a":1,\n"b":2}');
});
it('没有 data 的帧直接丢弃;未知 event 不影响解析', () => {
const { frames } = parseSseBuffer('event: weird\n\nevent: x\ndata: 1\n\n');
expect(frames).toEqual([{ event: 'x', data: '1' }]);
});
it('parseSseData:JSON 优先,脏数据原样返回不抛错', () => {
expect(parseSseData('{"a":1}')).toEqual({ a: 1 });
expect(parseSseData('not json')).toBe('not json');
expect(parseSseData('')).toBeNull();
});
});
describe('streamAssistantChat', () => {
it('进度事件按到达顺序回调,final 作为返回值', async () => {
const frames = [
'event: open\ndata: {"session_id":null}\n\n',
'event: stage\ndata: {"type":"stage","modules":["customers"]}\n\n',
'event: tool_start\ndata: {"type":"tool_start","name":"list_customer',
'_directory"}\n\n',
'event: tool_end\ndata: {"type":"tool_end","name":"list_customer_directory","ok":true,"summary":"ok"}\n\n',
'event: final\ndata: {"reply":"共 8 个客户","stats":{"rounds":2}}\n\n',
];
const fetchMock = vi.fn().mockResolvedValue(sseResponse(frames));
vi.stubGlobal('fetch', fetchMock);
const seen: string[] = [];
const payload = await streamAssistantChat({
apiUrl,
headers: { Authorization: 'Bearer t' },
body: { text: '看一下客户' },
onProgress: (event) => seen.push(`${event.type}:${String(event.name || '')}`),
});
expect(payload.reply).toBe('共 8 个客户');
// 除 final/error 外的事件(含 open)都原样转给 onProgress,由调用方决定怎么用
expect(seen).toEqual([
'open:',
'stage:',
'tool_start:list_customer_directory',
'tool_end:list_customer_directory',
]);
expect(fetchMock.mock.calls[0][0]).toContain('/mcp/order-entry/chat/stream');
});
it('error 事件抛错(带上后端 error_description)', async () => {
vi.stubGlobal(
'fetch',
vi.fn().mockResolvedValue(
sseResponse([
'event: open\ndata: {}\n\n',
'event: error\ndata: {"error":"branch_required","error_description":"请先在顶部选择操作分公司"}\n\n',
])
)
);
await expect(streamAssistantChat({ apiUrl, headers: {}, body: {} })).rejects.toThrow(
'请先在顶部选择操作分公司'
);
});
it('非 SSE 响应 / 没有 final → 抛错供调用方回退', async () => {
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(sseResponse([], { contentType: 'application/json' })));
await expect(streamAssistantChat({ apiUrl, headers: {}, body: {} })).rejects.toThrow(/stream_unavailable/);
vi.stubGlobal(
'fetch',
vi.fn().mockResolvedValue(sseResponse(['event: tool_end\ndata: {"ok":true}\n\n']))
);
await expect(streamAssistantChat({ apiUrl, headers: {}, body: {} })).rejects.toThrow('stream_incomplete');
});
});
describe('requestAssistantChat(流式优先 + 自动回退)', () => {
it('SSE 成功 → streamed=true,不调 /chat', async () => {
const fetchMock = vi
.fn()
.mockResolvedValue(sseResponse(['event: final\ndata: {"reply":"ok"}\n\n']));
vi.stubGlobal('fetch', fetchMock);
const result = await requestAssistantChat({ apiUrl, headers: {}, body: { text: 'x' } });
expect(result.streamed).toBe(true);
expect(result.payload.reply).toBe('ok');
expect(fetchMock).toHaveBeenCalledTimes(1);
});
it('SSE 失败 → 回退 /chat,行为与改前一致', async () => {
const fetchMock = vi
.fn()
.mockResolvedValueOnce(sseResponse([], { contentType: 'application/json' }))
.mockResolvedValueOnce({
ok: true,
status: 200,
json: async () => ({ reply: '回退答复', session_id: 's1' }),
} as unknown as Response);
vi.stubGlobal('fetch', fetchMock);
const result = await requestAssistantChat({ apiUrl, headers: {}, body: { text: 'x' } });
expect(result.streamed).toBe(false);
expect(result.payload.reply).toBe('回退答复');
expect(String(fetchMock.mock.calls[1][0])).toContain('/mcp/order-entry/chat');
expect(String(fetchMock.mock.calls[1][0])).not.toContain('/chat/stream');
});
it('服务端用 error 事件报出的失败**不回退重跑**(避免白烧两次模型)', async () => {
const fetchMock = vi.fn().mockResolvedValue(
sseResponse([
'event: open\ndata: {}\n\n',
'event: error\ndata: {"error":"branch_required","error_description":"请先选分公司"}\n\n',
])
);
vi.stubGlobal('fetch', fetchMock);
await expect(requestAssistantChat({ apiUrl, headers: {}, body: { text: 'x' } })).rejects.toThrow(
'请先选分公司'
);
expect(fetchMock).toHaveBeenCalledTimes(1); // 关键:没有第二次请求
});
it('传输层失败(非 SSE)才回退 —— 一次流式 + 一次 /chat', async () => {
const fetchMock = vi
.fn()
.mockResolvedValueOnce(sseResponse([], { contentType: 'application/json' }))
.mockResolvedValueOnce({ ok: true, status: 200, json: async () => ({ reply: 'ok' }) } as unknown as Response);
vi.stubGlobal('fetch', fetchMock);
const result = await requestAssistantChat({ apiUrl, headers: {}, body: { text: 'x' } });
expect(result.streamed).toBe(false);
expect(fetchMock).toHaveBeenCalledTimes(2);
});
it('主动中止(AbortError)不回退,直接抛出', async () => {
const abortError = Object.assign(new Error('aborted'), { name: 'AbortError' });
const fetchMock = vi.fn().mockRejectedValue(abortError);
vi.stubGlobal('fetch', fetchMock);
await expect(requestAssistantChat({ apiUrl, headers: {}, body: {} })).rejects.toThrow('aborted');
expect(fetchMock).toHaveBeenCalledTimes(1);
});
it('回退也失败时,抛出后端说明(不再吞掉)', async () => {
const fetchMock = vi
.fn()
.mockResolvedValueOnce(sseResponse([], { contentType: 'application/json' }))
.mockResolvedValueOnce({
ok: false,
status: 400,
json: async () => ({ error: 'branch_required', error_description: '请先选分公司' }),
} as unknown as Response);
vi.stubGlobal('fetch', fetchMock);
await expect(requestAssistantChat({ apiUrl, headers: {}, body: {} })).rejects.toThrow('请先选分公司');
});
});
describe('postAssistantChat', () => {
it('非 2xx 抛错', async () => {
vi.stubGlobal(
'fetch',
vi.fn().mockResolvedValue({
ok: false,
status: 500,
json: async () => ({ error_description: '助手失败' }),
} as unknown as Response)
);
await expect(postAssistantChat({ apiUrl, headers: {}, body: {} })).rejects.toThrow('助手失败');
});
});