33 lines
2.6 KiB
TypeScript
33 lines
2.6 KiB
TypeScript
import { afterEach, describe, expect, it, vi } from 'vitest';
|
|
import { RealChatAdapter, readEvents } from '../src/adapters/real';
|
|
import { TurnGate } from '../src/adapters/demo';
|
|
import type { ServerEvent } from '../src/domain/model';
|
|
const event = (t: string, payload: object = {}) => ({ t, epoch: 2, turn_id: 'turn', ...payload });
|
|
const frame = (e: object) => `data: ${JSON.stringify(e)}\r\n\r\n`;
|
|
function body(text: string) {
|
|
const bytes = new TextEncoder().encode(text);
|
|
return new ReadableStream<Uint8Array>({ start(controller) { for (const byte of bytes) controller.enqueue(Uint8Array.of(byte)); controller.close(); } });
|
|
}
|
|
afterEach(() => vi.unstubAllGlobals());
|
|
describe('real SSE transport', () => {
|
|
it('decodes fragmented Chinese, CRLF, comment and multiple events without losing bytes', async () => {
|
|
const output: ServerEvent[] = [];
|
|
await readEvents(body(': ping\r\n\r\n' + frame(event('chat.delta', { delta: '你好🌙' })) + frame(event('chat.final', { utterance: { text: '你好🌙', speech_tags: [] } }))), e => output.push(e));
|
|
expect(output).toHaveLength(2); expect(output[0]).toHaveProperty('delta', '你好🌙');
|
|
});
|
|
it('fails closed on missing final, invalid JSON and SSE errors', async () => {
|
|
await expect(readEvents(body(frame(event('chat.delta', { delta: '半句' }))), () => {})).rejects.toThrow('连接中断');
|
|
await expect(readEvents(body('data: {oops}\n\n'), () => {})).rejects.toThrow();
|
|
await expect(readEvents(body(frame(event('chat.error', { phi: '暂时没连上', retryable: true }))), e => { if (e.t === 'chat.error') throw new Error(e.phi); })).rejects.toThrow('暂时没连上');
|
|
});
|
|
it('synchronizes a restarted server epoch and rejects foreign/late turns', async () => {
|
|
const gate = new TurnGate(), signal = gate.begin('turn'), emit = vi.fn();
|
|
const fetch = vi.fn().mockResolvedValueOnce(new Response(JSON.stringify({ epoch: 2, llm: { ok: true } }))).mockResolvedValueOnce(new Response(body(frame({ ...event('chat.delta', { delta: '旧' }), epoch: 1 }) + frame({ ...event('chat.delta', { delta: '他轮' }), turn_id: 'other' }) + frame(event('chat.final', { utterance: { text: '新', speech_tags: [] } })))));
|
|
vi.stubGlobal('fetch', fetch);
|
|
await new RealChatAdapter(e => { gate.epoch = e; }).send('你好', 'turn', 1, signal, e => { if (gate.accepts(e)) emit(e); });
|
|
expect(emit).toHaveBeenCalledTimes(1); expect(gate.epoch).toBe(2);
|
|
expect(JSON.parse(fetch.mock.calls[1][1].body).epoch).toBe(2);
|
|
expect(fetch.mock.calls[1][1].signal).toBe(signal);
|
|
});
|
|
});
|