import { DataStream_Chunk, Encryption_Type, type Transcription } from '@livekit/protocol'; import { describe, expect, it } from 'vitest'; import { TextStreamReader } from '../data-stream/incoming/StreamReader'; import type { TextStreamInfo } from '../types'; import TranscriptionStreamConverter from './TranscriptionStreamConverter'; /** Lets pending microtasks (the reader's async iteration) run to completion. */ const flush = () => new Promise((resolve) => setTimeout(resolve, 0)); /** * Builds a `TextStreamReader` fed by an explicit controller, so a test can interleave writes, * assertions, and a close that merges trailer attributes the way the real manager does. */ function transcriptionStream(id: string, attributes: Record = {}) { const info: TextStreamInfo = { id, mimeType: 'text/plain', topic: 'lk.transcription', timestamp: 0, attributes, encryptionType: Encryption_Type.NONE, }; let controller!: ReadableStreamDefaultController; const stream = new ReadableStream({ start: (c) => { controller = c; }, }); let chunkIndex = 0; return { reader: new TextStreamReader(info, stream), write(text: string) { controller.enqueue( new DataStream_Chunk({ streamId: id, chunkIndex: BigInt(chunkIndex++), content: new TextEncoder().encode(text), }), ); }, close(closeAttributes?: Record) { if (closeAttributes) { info.attributes = { ...info.attributes, ...closeAttributes }; } controller.close(); }, error(err: Error) { controller.error(err); }, }; } /** Flattens emitted `Transcription`s to `[text, final]` pairs for terse assertions. */ function emissions(emitted: Array) { return emitted.map((t) => [t.segments[0].text, t.segments[0].final]); } function setup( overrides: { getMicrophoneTrackSid?: (identity: string) => string | undefined; getDelegatingPublisherIdentity?: (identity: string) => string | undefined; } = {}, ) { const emitted: Array = []; const converter = new TranscriptionStreamConverter({ onTranscription: (transcription) => emitted.push(transcription), getMicrophoneTrackSid: overrides.getMicrophoneTrackSid ?? (() => undefined), getDelegatingPublisherIdentity: overrides.getDelegatingPublisherIdentity ?? (() => undefined), }); return { converter, emitted }; } describe('TranscriptionStreamConverter', () => { it('appends deltas within one stream and marks final on the closing attribute', async () => { const { converter, emitted } = setup(); const stream = transcriptionStream('ST_1', { 'lk.segment_id': 'SG_1', 'lk.transcription_final': 'false', }); const done = converter.handleTextStream(stream.reader, 'agent-1'); stream.write('Hello'); await flush(); stream.write(' world'); await flush(); stream.close({ 'lk.transcription_final': 'true' }); await done; expect(emissions(emitted)).toEqual([ ['Hello', false], ['Hello world', false], ['Hello world', true], ]); expect(emitted[0].segments[0].id).toBe('SG_1'); }); it('replaces the text when a new stream re-uses a segment id', async () => { const { converter, emitted } = setup(); const interim = transcriptionStream('ST_1', { 'lk.segment_id': 'SG_1', 'lk.transcription_final': 'false', }); const interimDone = converter.handleTextStream(interim.reader, 'user-1'); interim.write('Hello'); await flush(); interim.close(); await interimDone; const final = transcriptionStream('ST_2', { 'lk.segment_id': 'SG_1', 'lk.transcription_final': 'true', }); const finalDone = converter.handleTextStream(final.reader, 'user-1'); final.write('Hello world!'); await flush(); final.close(); await finalDone; // Not 'HelloHello world!' - the second stream replaces rather than appends. expect(emissions(emitted)).toEqual([ ['Hello', false], ['Hello world!', true], ]); expect(emitted.every((t) => t.segments[0].id === 'SG_1')).toBe(true); }); it('does not re-emit on close when the attribute already matched the last emission', async () => { const { converter, emitted } = setup(); const stream = transcriptionStream('ST_1', { 'lk.segment_id': 'SG_1', 'lk.transcription_final': 'false', }); const done = converter.handleTextStream(stream.reader, 'user-1'); stream.write('Hello'); await flush(); stream.close(); await done; expect(emissions(emitted)).toEqual([['Hello', false]]); }); it('treats a close with no finality attribute as final', async () => { const { converter, emitted } = setup(); const stream = transcriptionStream('ST_1', { 'lk.segment_id': 'SG_1' }); const done = converter.handleTextStream(stream.reader, 'agent-1'); stream.write('Hello'); await flush(); stream.close(); await done; expect(emissions(emitted)).toEqual([ ['Hello', false], ['Hello', true], ]); }); it('accepts every form of the finality attribute agents send', async () => { for (const raw of ['true', '1']) { const { converter, emitted } = setup(); const stream = transcriptionStream('ST_1', { 'lk.segment_id': 'SG_1', 'lk.transcription_final': raw, }); const done = converter.handleTextStream(stream.reader, 'agent-1'); stream.write('Hello'); await flush(); stream.close(); await done; expect(emissions(emitted)).toEqual([['Hello', true]]); } }); it('falls back to the stream id when lk.segment_id is absent', async () => { const { converter, emitted } = setup(); const stream = transcriptionStream('ST_1'); const done = converter.handleTextStream(stream.reader, 'agent-1'); stream.write('Hello'); await flush(); stream.close(); await done; expect(emitted[0].segments[0].id).toBe('ST_1'); }); it('keys partial state per sender so two speakers do not interleave', async () => { const { converter, emitted } = setup(); const alice = transcriptionStream('ST_A', { 'lk.segment_id': 'SG_1', 'lk.transcription_final': 'false', }); const bob = transcriptionStream('ST_B', { 'lk.segment_id': 'SG_1', 'lk.transcription_final': 'false', }); const aliceDone = converter.handleTextStream(alice.reader, 'alice'); const bobDone = converter.handleTextStream(bob.reader, 'bob'); alice.write('from alice'); bob.write('from bob'); await flush(); alice.close({ 'lk.transcription_final': 'true' }); bob.close({ 'lk.transcription_final': 'true' }); await Promise.all([aliceDone, bobDone]); const byIdentity = emitted.reduce>>((acc, t) => { const identity = t.transcribedParticipantIdentity; acc[identity] = [...(acc[identity] ?? []), t.segments[0].text]; return acc; }, {}); expect(byIdentity.alice).toEqual(['from alice', 'from alice']); expect(byIdentity.bob).toEqual(['from bob', 'from bob']); }); it('emits nothing for a stream that closes without any content', async () => { const { converter, emitted } = setup(); const stream = transcriptionStream('ST_1', { 'lk.segment_id': 'SG_1' }); const done = converter.handleTextStream(stream.reader, 'agent-1'); stream.close(); await done; expect(emitted).toHaveLength(0); }); it('closes a segment out as final when the stream errors mid-segment', async () => { const { converter, emitted } = setup(); const info: TextStreamInfo = { id: 'ST_1', mimeType: 'text/plain', topic: 'lk.transcription', timestamp: 0, attributes: { 'lk.segment_id': 'SG_1', 'lk.transcription_final': 'false' }, encryptionType: Encryption_Type.NONE, }; let controller!: ReadableStreamDefaultController; const stream = new ReadableStream({ start: (c) => { controller = c; }, }); const done = converter.handleTextStream(new TextStreamReader(info, stream), 'agent-1'); controller.enqueue( new DataStream_Chunk({ streamId: 'ST_1', chunkIndex: 0n, content: new TextEncoder().encode('Hel'), }), ); await flush(); controller.error(new Error('sender disconnected')); await done; expect(emissions(emitted)).toEqual([ ['Hel', false], ['Hel', true], ]); }); it('drops in-flight segment state on reset', async () => { const { converter, emitted } = setup(); const first = transcriptionStream('ST_1', { 'lk.segment_id': 'SG_1', 'lk.transcription_final': 'false', }); const firstDone = converter.handleTextStream(first.reader, 'agent-1'); first.write('Hello'); await flush(); first.close(); await firstDone; converter.reset(); // Same stream id as the first stream, deliberately: replace-on-new-stream-id would produce // 'Fresh' on its own, so re-using 'ST_1' is what makes this assertion discriminate. Without // reset() the partial for (agent-1, SG_1) is still open on stream 'ST_1', so the write would // append and the text would be 'HelloFresh'. const second = transcriptionStream('ST_1', { 'lk.segment_id': 'SG_1', 'lk.transcription_final': 'false', }); const secondDone = converter.handleTextStream(second.reader, 'agent-1'); second.write('Fresh'); await flush(); second.close(); await secondDone; expect(emissions(emitted)).toEqual([ ['Hello', false], ['Fresh', false], ]); }); describe('json_format payloads', () => { it('unwraps JSON TimedString chunks into plain text', async () => { const { converter, emitted } = setup(); const stream = transcriptionStream('ST_1', { 'lk.segment_id': 'SG_1', 'lk.transcription_final': 'false', }); const done = converter.handleTextStream(stream.reader, 'agent-1'); stream.write('{"text": "Hello", "start_time": 1.5}\n'); await flush(); stream.write('{"text": " world", "start_time": 2.0}\n'); await flush(); stream.close({ 'lk.transcription_final': 'true' }); await done; expect(emissions(emitted)).toEqual([ ['Hello', false], ['Hello world', false], ['Hello world', true], ]); // Timings stay zeroed, exactly as the legacy channel always reported them. expect(emitted[0].segments[0].startTime).toBe(0n); expect(emitted[0].segments[0].endTime).toBe(0n); }); it('reassembles a TimedString split across chunks instead of leaking raw JSON', async () => { // A write larger than one packet is split by the transport, so a single TimedString can // arrive in pieces that are not valid JSON on their own. const { converter, emitted } = setup(); const stream = transcriptionStream('ST_1', { 'lk.segment_id': 'SG_1', 'lk.transcription_final': 'false', }); const done = converter.handleTextStream(stream.reader, 'agent-1'); stream.write('{"text": "Hel'); await flush(); stream.write('lo", "start_time": 1.5}\n{"text": " wor'); await flush(); stream.write('ld"}\n'); await flush(); stream.close({ 'lk.transcription_final': 'true' }); await done; expect(emissions(emitted)).toEqual([ ['Hello', false], ['Hello world', false], ['Hello world', true], ]); }); it('unwraps several TimedStrings that arrive in one chunk', async () => { const { converter, emitted } = setup(); const stream = transcriptionStream('ST_1', { 'lk.segment_id': 'SG_1' }); const done = converter.handleTextStream(stream.reader, 'agent-1'); stream.write('{"text": "Hello"}\n{"text": " there"}\n{"text": " world"}\n'); await flush(); stream.close({ 'lk.transcription_final': 'true' }); await done; expect(emitted[emitted.length - 1].segments[0].text).toBe('Hello there world'); }); it('appends an unterminated plain-text tail when the stream closes', async () => { // Agents write the final markup-stripped remainder of a segment without JSON encoding. const { converter, emitted } = setup(); const stream = transcriptionStream('ST_1', { 'lk.segment_id': 'SG_1', 'lk.transcription_final': 'false', }); const done = converter.handleTextStream(stream.reader, 'agent-1'); stream.write('{"text": "Hello"}\n'); await flush(); stream.write(' world'); await flush(); stream.close({ 'lk.transcription_final': 'true' }); await done; expect(emissions(emitted)).toEqual([ ['Hello', false], ['Hello world', true], ]); }); it('decodes a buffered TimedString when the stream ends abnormally', async () => { const { converter, emitted } = setup(); const stream = transcriptionStream('ST_1', { 'lk.segment_id': 'SG_1', 'lk.transcription_final': 'false', }); const done = converter.handleTextStream(stream.reader, 'agent-1'); stream.write('{"text": "Hello"}'); await flush(); stream.error(new Error('sender disconnected')); await done; expect(emissions(emitted)).toEqual([['Hello', true]]); }); it('leaves plain text chunks untouched, including ones that look JSON-ish', async () => { const { converter, emitted } = setup(); const stream = transcriptionStream('ST_1', { 'lk.segment_id': 'SG_1' }); const done = converter.handleTextStream(stream.reader, 'agent-1'); stream.write('{not json at all'); await flush(); stream.write(' {"no_text_field": 1}'); await flush(); stream.close({ 'lk.transcription_final': 'true' }); await done; expect(emitted[emitted.length - 1].segments[0].text).toBe( '{not json at all {"no_text_field": 1}', ); }); }); describe('speaker and track resolution', () => { /** Drives one complete single-chunk segment and returns the last emission. */ async function emitOne( converter: TranscriptionStreamConverter, emitted: Array, senderIdentity: string, attributes: Record, ) { const stream = transcriptionStream('ST_1', attributes); const done = converter.handleTextStream(stream.reader, senderIdentity); stream.write('Hello'); await flush(); stream.close({ 'lk.transcription_final': 'true' }); await done; return emitted[emitted.length - 1]; } it('prefers the lk.transcribed_track_id attribute', async () => { const { converter, emitted } = setup({ getMicrophoneTrackSid: () => 'TR_fallback', }); const transcription = await emitOne(converter, emitted, 'agent-1', { 'lk.segment_id': 'SG_1', 'lk.transcribed_track_id': 'TR_attribute', }); expect(transcription.trackId).toBe('TR_attribute'); expect(transcription.transcribedParticipantIdentity).toBe('agent-1'); }); it("falls back to the speaker's microphone track when the attribute is absent", async () => { const { converter, emitted } = setup({ getMicrophoneTrackSid: (identity) => (identity === 'user-1' ? 'TR_mic' : undefined), }); const transcription = await emitOne(converter, emitted, 'user-1', { 'lk.segment_id': 'SG_1', }); expect(transcription.trackId).toBe('TR_mic'); }); it('attributes an avatar-delegated stream to the delegating publisher and its track', async () => { const { converter, emitted } = setup({ getDelegatingPublisherIdentity: (identity) => identity === 'agent-1' ? 'avatar-worker' : undefined, getMicrophoneTrackSid: (identity) => identity === 'avatar-worker' ? 'TR_avatar' : undefined, }); const transcription = await emitOne(converter, emitted, 'agent-1', { 'lk.segment_id': 'SG_1', }); // Legacy named the avatar worker, and it is the participant publishing the audio track. expect(transcription.transcribedParticipantIdentity).toBe('avatar-worker'); expect(transcription.trackId).toBe('TR_avatar'); }); it("falls back to the sender's own microphone track when the delegate has none", async () => { const { converter, emitted } = setup({ getDelegatingPublisherIdentity: () => 'avatar-worker', getMicrophoneTrackSid: (identity) => (identity === 'agent-1' ? 'TR_agent' : undefined), }); const transcription = await emitOne(converter, emitted, 'agent-1', { 'lk.segment_id': 'SG_1', }); expect(transcription.trackId).toBe('TR_agent'); }); it('leaves trackId empty when nothing resolves', async () => { const { converter, emitted } = setup(); const transcription = await emitOne(converter, emitted, 'agent-1', { 'lk.segment_id': 'SG_1', }); expect(transcription.trackId).toBe(''); }); it('treats an empty string from a resolver as "not found"', async () => { // A resolver reporting "nothing found" as '' rather than undefined must not pin the result: // an empty identity resolves no participant and an empty sid resolves no publication, so // either would silently stop transcription events reaching track-bound consumers. const { converter, emitted } = setup({ getDelegatingPublisherIdentity: () => '', getMicrophoneTrackSid: (identity) => (identity === 'agent-1' ? 'TR_agent' : ''), }); const transcription = await emitOne(converter, emitted, 'agent-1', { 'lk.segment_id': 'SG_1', }); expect(transcription.transcribedParticipantIdentity).toBe('agent-1'); expect(transcription.trackId).toBe('TR_agent'); }); }); });