From 9e8dd339272d06f2085c58913e0155f43f7789af Mon Sep 17 00:00:00 2001 From: PeymanHonarjoo Date: Mon, 12 Oct 2026 16:51:04 +0330 Subject: [PATCH] feat: implement answer-limited state handling in voice stream service - Introduced handling for 'answer_limited' events from the server, allowing the UI to reflect when an assistant's answer has reached the output-token limit. - Updated the VoiceStreamService to manage limited and interrupted turns with bounded memory. - Enhanced the transcript component to display appropriate messages for limited answers, including a fallback for unavailable text. - Added styles to visually indicate limited answers in the UI. - Created unit tests for the new functionality, ensuring correct behavior for limited answers and their presentation. --- .../voice-event.validator.spec.ts | 172 +++++++ .../voice-stream/voice-event.validator.ts | 180 +++++++ .../voice-stream/voice-stream.service.spec.ts | 452 ++++++++++++++++++ .../voice-stream/voice-stream.service.ts | 176 ++++++- .../voice-stream/voice-stream.types.ts | 35 +- .../voice-stream/voice-transport.spec.ts | 177 +++++++ .../services/voice-stream/voice-transport.ts | 17 +- .../voice-transcript.component.css | 44 +- .../voice-transcript.component.html | 12 +- .../voice-transcript.component.spec.ts | 234 +++++++++ .../voice-transcript.component.ts | 35 +- 11 files changed, 1505 insertions(+), 29 deletions(-) create mode 100644 src/app/services/voice-stream/voice-event.validator.spec.ts create mode 100644 src/app/services/voice-stream/voice-event.validator.ts create mode 100644 src/app/services/voice-stream/voice-transport.spec.ts create mode 100644 src/app/shared/ui/voice-transcript/voice-transcript.component.spec.ts diff --git a/src/app/services/voice-stream/voice-event.validator.spec.ts b/src/app/services/voice-stream/voice-event.validator.spec.ts new file mode 100644 index 0000000..466cd0e --- /dev/null +++ b/src/app/services/voice-stream/voice-event.validator.spec.ts @@ -0,0 +1,172 @@ +import { describe, expect, it } from 'vitest'; +import { + ANSWER_LIMITED_REASONS, + TRANSCRIPT_STATUSES, + VOICE_SERVER_EVENT_TYPES, + isApplicationReference, + parseVoiceServerEvent, +} from './voice-event.validator'; +import { VoiceServerEvent } from './voice-stream.types'; + +const ANSWER_LIMITED: VoiceServerEvent = { + type: 'answer_limited', + turn_ref: 'live-turn-1', + reason: 'output_token_limit', +}; + +describe('voice-event.validator', () => { + describe('application references', () => { + it('accepts a non-empty bounded string reference', () => { + expect(isApplicationReference('live-turn-1')).toBe(true); + expect(isApplicationReference('a'.repeat(256))).toBe(true); + }); + + it('rejects missing, empty, wrong-typed or oversized references', () => { + expect(isApplicationReference('')).toBe(false); + expect(isApplicationReference(null)).toBe(false); + expect(isApplicationReference(undefined)).toBe(false); + expect(isApplicationReference(42)).toBe(false); + expect(isApplicationReference({})).toBe(false); + expect(isApplicationReference('a'.repeat(257))).toBe(false); + }); + }); + + describe('answer_limited frames', () => { + it('parses a valid answer_limited frame and reaches the dispatcher shape', () => { + expect(parseVoiceServerEvent(JSON.stringify(ANSWER_LIMITED))).toEqual(ANSWER_LIMITED); + }); + + it('rejects an unknown reason (exactly output_token_limit is accepted)', () => { + expect( + parseVoiceServerEvent(JSON.stringify({ ...ANSWER_LIMITED, reason: 'output_length_limit' })), + ).toBeNull(); + expect(parseVoiceServerEvent(JSON.stringify({ ...ANSWER_LIMITED, reason: 'token_limit' }))).toBeNull(); + expect(parseVoiceServerEvent(JSON.stringify({ type: 'answer_limited', turn_ref: 't1' }))).toBeNull(); + }); + + it('rejects answer_limited without a valid turn_ref', () => { + expect(parseVoiceServerEvent(JSON.stringify({ ...ANSWER_LIMITED, turn_ref: '' }))).toBeNull(); + expect(parseVoiceServerEvent(JSON.stringify({ ...ANSWER_LIMITED, turn_ref: 7 }))).toBeNull(); + expect(parseVoiceServerEvent('{"type":"answer_limited","reason":"output_token_limit"}')).toBeNull(); + }); + + it('only advertises the contract reason and statuses', () => { + expect(ANSWER_LIMITED_REASONS).toEqual(['output_token_limit']); + expect(TRANSCRIPT_STATUSES).toEqual(['partial', 'completed', 'interrupted', 'limited']); + }); + }); + + describe('transcript frames', () => { + it('accepts a limited assistant transcript', () => { + const frame = { type: 'transcript', turn_ref: 't1', role: 'assistant', text: 'پاسخ', status: 'limited' }; + expect(parseVoiceServerEvent(JSON.stringify(frame))).toEqual(frame); + }); + + it('rejects a limited USER transcript (limited is assistant-only)', () => { + const frame = { type: 'transcript', turn_ref: 't1', role: 'user', text: 'ادامه بده', status: 'limited' }; + expect(parseVoiceServerEvent(JSON.stringify(frame))).toBeNull(); + }); + + it('accepts the existing (older backend) transcript statuses for both roles', () => { + for (const status of ['partial', 'completed', 'interrupted'] as const) { + for (const role of ['user', 'assistant'] as const) { + const frame = { type: 'transcript', turn_ref: 't1', role, text: 'متن', status }; + expect(parseVoiceServerEvent(JSON.stringify(frame))).toEqual(frame); + } + } + }); + + it('rejects unknown statuses and malformed transcript fields', () => { + const base = { type: 'transcript', turn_ref: 't1', role: 'assistant', text: 'متن' }; + expect(parseVoiceServerEvent(JSON.stringify({ ...base, status: 'capped' }))).toBeNull(); + expect(parseVoiceServerEvent(JSON.stringify({ ...base, status: 5 }))).toBeNull(); + expect(parseVoiceServerEvent(JSON.stringify({ ...base, status: 'limited', text: 3 }))).toBeNull(); + expect(parseVoiceServerEvent(JSON.stringify({ ...base, status: 'limited', role: 'system' }))).toBeNull(); + expect(parseVoiceServerEvent(JSON.stringify({ ...base, status: 'limited', turn_ref: '' }))).toBeNull(); + }); + }); + + describe('existing events keep passing (older backends)', () => { + it('accepts every known event type with a valid payload', () => { + const frames: VoiceServerEvent[] = [ + { + type: 'session_ready', + session_id: 'ses-1', + input_audio: { encoding: 'pcm_s16le', sample_rate: 24000, channels: 1 }, + output_audio: { encoding: 'pcm_s16le', sample_rate: 24000, channels: 1 }, + }, + { type: 'user_speech_started', turn_ref: 'turn-1' }, + { type: 'transcript', turn_ref: 'turn-1', role: 'user', text: 'سلام', status: 'completed' }, + { + type: 'sources', + turn_ref: 'turn-1', + sources: [ + { source_ref: 'src-1', document_id: 'doc-1', chunk_id: 'chunk-1', title: 'سند' }, + ], + }, + { type: 'audio_started', audio_ref: 'aud-1', turn_ref: 'turn-1' }, + { type: 'audio_ended', audio_ref: 'aud-1', turn_ref: 'turn-1' }, + { type: 'turn_interrupted', turn_ref: 'turn-1', cancelled_tool_call_ids: [] }, + { + type: 'error', + turn_ref: 'turn-1', + error: { code: 'SEARCH_TIMEOUT', message: 'دیر شد', retryable: true }, + }, + ]; + for (const frame of frames) { + expect(parseVoiceServerEvent(JSON.stringify(frame))).toEqual(frame); + } + // The enforced allowlist: every type the transport accepts, and nothing else. + expect(VOICE_SERVER_EVENT_TYPES).toEqual([ + 'session_ready', + 'user_speech_started', + 'transcript', + 'sources', + 'audio_started', + 'audio_ended', + 'turn_interrupted', + 'answer_limited', + 'error', + ]); + }); + + it('defaults a missing error retryable flag to false instead of dropping the frame', () => { + const parsed = parseVoiceServerEvent( + '{"type":"error","error":{"code":"X","message":"y"}}', + ); + expect(parsed).toEqual({ + type: 'error', + error: { code: 'X', message: 'y', retryable: false }, + }); + }); + }); + + describe('allowlist and malformed input', () => { + it('drops unknown event types instead of forwarding them', () => { + expect(parseVoiceServerEvent('{"type":"response.create"}')).toBeNull(); + expect(parseVoiceServerEvent('{"type":"continue"}')).toBeNull(); + expect(parseVoiceServerEvent('{"type":"answer_limited2","turn_ref":"t1","reason":"output_token_limit"}')).toBeNull(); + expect(parseVoiceServerEvent('{"type":42}')).toBeNull(); + }); + + it('drops malformed JSON and non-object payloads', () => { + expect(parseVoiceServerEvent('not json')).toBeNull(); + expect(parseVoiceServerEvent('')).toBeNull(); + expect(parseVoiceServerEvent('null')).toBeNull(); + expect(parseVoiceServerEvent('[]')).toBeNull(); + expect(parseVoiceServerEvent('"transcript"')).toBeNull(); + }); + + it('drops frames with a broken audio/session/interruption payload', () => { + expect(parseVoiceServerEvent('{"type":"audio_started"}')).toBeNull(); + expect(parseVoiceServerEvent('{"type":"audio_started","audio_ref":""}')).toBeNull(); + expect(parseVoiceServerEvent('{"type":"turn_interrupted","turn_ref":"t1","cancelled_tool_call_ids":[1]}')).toBeNull(); + expect( + parseVoiceServerEvent( + '{"type":"session_ready","session_id":"s","input_audio":{"encoding":"pcm_s16le","sample_rate":24000,"channels":1}}', + ), + ).toBeNull(); + expect(parseVoiceServerEvent('{"type":"sources","turn_ref":"t1","sources":"none"}')).toBeNull(); + }); + }); +}); diff --git a/src/app/services/voice-stream/voice-event.validator.ts b/src/app/services/voice-stream/voice-event.validator.ts new file mode 100644 index 0000000..d06ed3e --- /dev/null +++ b/src/app/services/voice-stream/voice-event.validator.ts @@ -0,0 +1,180 @@ +import { + AnswerLimitedReason, + TranscriptStatus, + VoiceServerEvent, + VoiceServerEventType, +} from './voice-stream.types'; + +/** + * Runtime guards for the JSON frames that arrive on the voice stream. + * + * The transport used to hand every parsed object straight to the service. A frame with + * an unknown `type` then fell through the dispatcher silently, and a frame with a + * broken payload reached a handler that reads its fields. Every JSON frame now passes + * this explicit allowlist first: known types are checked field by field, unknown types + * and malformed payloads are DROPPED — never thrown, never re-interpreted, and never + * able to end a call. Dropping matches how malformed JSON was already treated, so no + * malformed frame can enter an error path or trigger cleanup. + * + * The guards mirror the contract in `VoiceServerEvent`; they do not invent protocol. + */ +export const VOICE_SERVER_EVENT_TYPES = [ + 'session_ready', + 'user_speech_started', + 'transcript', + 'sources', + 'audio_started', + 'audio_ended', + 'turn_interrupted', + 'answer_limited', + 'error', +] as const; + +export const ANSWER_LIMITED_REASONS = ['output_token_limit'] as const; + +export const TRANSCRIPT_STATUSES = ['partial', 'completed', 'interrupted', 'limited'] as const; + +/** + * Compile-time alignment between the allowlists above and the wire unions in + * `voice-stream.types.ts`: a union member missing from an allowlist (or an allowlisted + * value with no union member) fails to compile here, so the transport can never + * silently start dropping a valid frame after a contract change. + */ +type Exactly = T; +export type AllowlistsAligned = [ + Exactly, + Exactly<(typeof VOICE_SERVER_EVENT_TYPES)[number] extends VoiceServerEventType ? true : false>, + Exactly, + Exactly<(typeof TRANSCRIPT_STATUSES)[number] extends TranscriptStatus ? true : false>, + Exactly, + Exactly<(typeof ANSWER_LIMITED_REASONS)[number] extends AnswerLimitedReason ? true : false>, +]; + +/** Longest application reference accepted on the wire (session/turn/audio ids). */ +const MAX_REFERENCE_LENGTH = 256; + +/** + * An application reference issued by the backend (`session_id`, `turn_ref`, `audio_ref`, + * `source_ref`, …): a non-empty, length-bounded string. Anything else (number, null, + * empty string, oversized string) is not a reference and cannot correlate a frame. + */ +export function isApplicationReference(value: unknown): value is string { + return typeof value === 'string' && value.length > 0 && value.length <= MAX_REFERENCE_LENGTH; +} + +function isRecord(value: unknown): value is Record { + return typeof value === 'object' && value !== null && !Array.isArray(value); +} + +function isAudioFormat(value: unknown): boolean { + return ( + isRecord(value) && + typeof value['encoding'] === 'string' && + typeof value['sample_rate'] === 'number' && + typeof value['channels'] === 'number' + ); +} + +/** Only the fields the client actually reads are required; presentation is tolerant. */ +function isVoiceSource(value: unknown): boolean { + return ( + isRecord(value) && + isApplicationReference(value['source_ref']) && + isApplicationReference(value['chunk_id']) + ); +} + +function isVoiceServerEvent(value: unknown): value is VoiceServerEvent { + if (!isRecord(value)) return false; + // Allowlist: an unknown event type is dropped, never forwarded. + if (!VOICE_SERVER_EVENT_TYPES.includes(value['type'] as VoiceServerEventType)) return false; + switch (value['type']) { + case 'session_ready': + return ( + isApplicationReference(value['session_id']) && + isAudioFormat(value['input_audio']) && + isAudioFormat(value['output_audio']) + ); + + case 'user_speech_started': + return isApplicationReference(value['turn_ref']); + + case 'transcript': + return ( + isApplicationReference(value['turn_ref']) && + (value['role'] === 'user' || value['role'] === 'assistant') && + typeof value['text'] === 'string' && + TRANSCRIPT_STATUSES.includes(value['status'] as TranscriptStatus) && + // `limited` is valid only for assistant transcripts. + (value['status'] !== 'limited' || value['role'] === 'assistant') + ); + + case 'sources': + return ( + isApplicationReference(value['turn_ref']) && + Array.isArray(value['sources']) && + value['sources'].every(isVoiceSource) + ); + + case 'audio_started': + case 'audio_ended': + return ( + isApplicationReference(value['audio_ref']) && + (value['turn_ref'] === undefined || isApplicationReference(value['turn_ref'])) + ); + + case 'turn_interrupted': + return ( + isApplicationReference(value['turn_ref']) && + (value['cancelled_tool_call_ids'] === undefined || + (Array.isArray(value['cancelled_tool_call_ids']) && + value['cancelled_tool_call_ids'].every(isApplicationReference))) + ); + + case 'answer_limited': + return ( + isApplicationReference(value['turn_ref']) && + ANSWER_LIMITED_REASONS.includes(value['reason'] as AnswerLimitedReason) + ); + + case 'error': + return ( + isRecord(value['error']) && + typeof value['error']['code'] === 'string' && + typeof value['error']['message'] === 'string' && + (value['error']['retryable'] === undefined || + typeof value['error']['retryable'] === 'boolean') && + (value['turn_ref'] === undefined || isApplicationReference(value['turn_ref'])) && + (value['audio_ref'] === undefined || isApplicationReference(value['audio_ref'])) + ); + + default: + // Defense in depth: unreachable while the allowlist above matches this switch, + // and it keeps a newly modeled-but-unhandled type from reaching the service. + return false; + } +} + +/** + * Parse one JSON control frame from the wire. + * + * Returns the validated event, or `null` when the frame is malformed JSON, an unknown + * event type, or a known type with an invalid payload. A `null` result is dropped by + * the transport exactly like malformed JSON always was — it is not an error state. + */ +export function parseVoiceServerEvent(raw: string): VoiceServerEvent | null { + let parsed: unknown; + try { + parsed = JSON.parse(raw); + } catch { + return null; + } + if (!isVoiceServerEvent(parsed)) return null; + + if (parsed.type === 'error' && parsed.error.retryable === undefined) { + // A frame without the flag behaves like a non-retryable error, which is what the + // service's boolean read produced before validation existed. + return { ...parsed, error: { ...parsed.error, retryable: false } }; + } + return parsed; +} diff --git a/src/app/services/voice-stream/voice-stream.service.spec.ts b/src/app/services/voice-stream/voice-stream.service.spec.ts index 90c4b3e..0a69d50 100644 --- a/src/app/services/voice-stream/voice-stream.service.spec.ts +++ b/src/app/services/voice-stream/voice-stream.service.spec.ts @@ -460,4 +460,456 @@ describe('VoiceStreamService (backend handoff contract)', () => { expect(sessionStorage.getItem('voice_creation_attempt')).toBeNull(); expect(service.connection()).toBe('disconnected'); }); + + describe('bounded answers (answer_limited)', () => { + const MARKER: VoiceServerEvent = { + type: 'answer_limited', + turn_ref: 'turn-1', + reason: 'output_token_limit', + }; + + it('keeps the marker as bounded metadata when it arrives before any transcript text', async () => { + await startConnected(); + + transportHandlers?.onEvent(MARKER); + + // No transcript text is invented for the answer. + expect(service.messages()).toEqual([]); + expect(service.connection()).toBe('connected'); + expect(service.state()).toBe('LISTENING'); + }); + + it('attaches the marker to the row when the first transcript lands after it', async () => { + await startConnected(); + + transportHandlers?.onEvent(MARKER); // marker first, no text yet + transportHandlers?.onEvent({ + type: 'transcript', + turn_ref: 'turn-1', + role: 'assistant', + text: 'پاسخ ', + status: 'partial', + }); + transportHandlers?.onEvent({ + type: 'transcript', + turn_ref: 'turn-1', + role: 'assistant', + text: 'پاسخ نهایی', + status: 'limited', + }); + + const assistant = service.messages().find((m) => m.id === 'turn-1:assistant'); + expect(assistant?.text).toBe('پاسخ نهایی'); // final snapshot replaces the partial text + expect(assistant?.limited).toBe(true); + expect(assistant?.final).toBe(true); + }); + + it('keeps exact text and limited status when the limited transcript arrives before the marker', async () => { + await startConnected(); + + transportHandlers?.onEvent({ + type: 'transcript', + turn_ref: 'turn-1', + role: 'assistant', + text: 'پاسخ کامل', + status: 'limited', + }); + expect(service.messages()[0].limited).toBe(true); // the transcript alone marks the answer + + transportHandlers?.onEvent(MARKER); + + const assistant = service.messages().find((m) => m.id === 'turn-1:assistant'); + expect(assistant?.text).toBe('پاسخ کامل'); + expect(assistant?.limited).toBe(true); + }); + + it('treats repeated answer_limited markers as idempotent (no duplicate rows or notices)', async () => { + await startConnected(); + + transportHandlers?.onEvent({ + type: 'transcript', + turn_ref: 'turn-1', + role: 'assistant', + text: 'پاسخ', + status: 'limited', + }); + const before = service.messages(); + + transportHandlers?.onEvent(MARKER); + transportHandlers?.onEvent(MARKER); + transportHandlers?.onEvent(MARKER); + + expect(service.messages()).toHaveLength(1); + expect(service.messages()).toBe(before); // no state write at all → no re-announcement + expect(service.messages()[0].text).toBe('پاسخ'); + expect(service.streamError()).toBeNull(); // informational, never an error banner + expect(service.connection()).toBe('connected'); + }); + + it('preserves repeated legitimate partial words (no content-based dedup)', async () => { + await startConnected(); + + transportHandlers?.onEvent({ type: 'transcript', turn_ref: 't1', role: 'assistant', text: 'بله', status: 'partial' }); + transportHandlers?.onEvent({ type: 'transcript', turn_ref: 't1', role: 'assistant', text: ' بله', status: 'partial' }); + transportHandlers?.onEvent({ type: 'transcript', turn_ref: 't1', role: 'assistant', text: ' بله', status: 'partial' }); + + expect(service.messages()[0].text).toBe('بله بله بله'); + }); + + it('does not downgrade a limited answer on delayed completed/partial events', async () => { + await startConnected(); + + transportHandlers?.onEvent({ + type: 'transcript', + turn_ref: 't1', + role: 'assistant', + text: 'پاسخ محدود', + status: 'limited', + }); + + // Delayed frames for the same turn arrive after the final snapshot. + transportHandlers?.onEvent({ + type: 'transcript', + turn_ref: 't1', + role: 'assistant', + text: 'پاسخ کامل‌تر', + status: 'completed', + }); + transportHandlers?.onEvent({ + type: 'transcript', + turn_ref: 't1', + role: 'assistant', + text: ' ادامه', + status: 'partial', + }); + + const assistant = service.messages().find((m) => m.id === 't1:assistant'); + expect(assistant?.limited).toBe(true); // never reverts to completed/partial + expect(assistant?.final).toBe(true); + expect(assistant?.text).toBe('پاسخ کامل‌تر'); // the late partial did not extend it + }); + + it('lets turn_interrupted take precedence over limited and blocks late text', async () => { + await startConnected(); + + transportHandlers?.onEvent({ + type: 'transcript', + turn_ref: 'turn-1', + role: 'assistant', + text: 'پاسخ ', + status: 'partial', + }); + transportHandlers?.onEvent({ + type: 'transcript', + turn_ref: 'turn-1', + role: 'assistant', + text: 'پاسخ نهایی', + status: 'limited', + }); + transportHandlers?.onEvent(MARKER); + engineClear.mockClear(); + + transportHandlers?.onEvent({ type: 'turn_interrupted', turn_ref: 'turn-1' }); + + const assistant = service.messages().find((m) => m.id === 'turn-1:assistant'); + expect(assistant?.interrupted).toBe(true); // interruption wins over the limited state + expect(engineClear).toHaveBeenCalledTimes(1); // the existing barge-in flush still runs + + // Late assistant text cannot restore the interrupted answer. + transportHandlers?.onEvent({ + type: 'transcript', + turn_ref: 'turn-1', + role: 'assistant', + text: 'متن دیرکرده', + status: 'limited', + }); + transportHandlers?.onEvent({ + type: 'transcript', + turn_ref: 'turn-1', + role: 'assistant', + text: 'ادامه', + status: 'partial', + }); + + const after = service.messages().find((m) => m.id === 'turn-1:assistant'); + expect(after?.text).toBe('پاسخ نهایی'); + expect(after?.interrupted).toBe(true); + }); + + it('does not mark an already interrupted answer as limited', async () => { + await startConnected(); + + transportHandlers?.onEvent({ + type: 'transcript', + turn_ref: 'turn-1', + role: 'assistant', + text: 'پاسخ', + status: 'partial', + }); + transportHandlers?.onEvent({ type: 'turn_interrupted', turn_ref: 'turn-1' }); + transportHandlers?.onEvent(MARKER); + + const assistant = service.messages().find((m) => m.id === 'turn-1:assistant'); + expect(assistant?.interrupted).toBe(true); + expect(assistant?.limited).toBeFalsy(); + }); + + it('does not mark a sources-only row of an interrupted turn as limited', async () => { + await startConnected(); + + // The turn is capped, then cut off before any transcript row exists, then its + // sources arrive: the row must not be presented as a limited answer. + transportHandlers?.onEvent(MARKER); + transportHandlers?.onEvent({ type: 'turn_interrupted', turn_ref: 'turn-1' }); + transportHandlers?.onEvent({ + type: 'sources', + turn_ref: 'turn-1', + sources: [{ source_ref: 'src-1', document_id: 'doc-1', chunk_id: 'chunk-1', title: 'سند' }], + }); + + const assistant = service.messages().find((m) => m.id === 'turn-1:assistant'); + expect(assistant?.limited).toBeFalsy(); + expect(assistant?.sources).toHaveLength(1); + }); + + it('keeps a delayed user transcript attached to its own turn, independent of assistant status', async () => { + await startConnected(); + + transportHandlers?.onEvent({ type: 'user_speech_started', turn_ref: 'turn-1' }); + transportHandlers?.onEvent({ + type: 'transcript', + turn_ref: 'turn-1', + role: 'assistant', + text: 'پاسخ اول', + status: 'limited', + }); + // Turn 2 starts before turn 1's user transcript is finalized. + transportHandlers?.onEvent({ type: 'user_speech_started', turn_ref: 'turn-2' }); + transportHandlers?.onEvent({ + type: 'transcript', + turn_ref: 'turn-2', + role: 'assistant', + text: 'پاسخ دوم', + status: 'partial', + }); + transportHandlers?.onEvent({ + type: 'transcript', + turn_ref: 'turn-1', + role: 'user', + text: 'سوال اول', + status: 'completed', + }); + + const list = service.messages(); + expect(list.map((m) => m.id)).toEqual(['turn-1:user', 'turn-1:assistant', 'turn-2:assistant']); + expect(list.find((m) => m.id === 'turn-1:user')?.text).toBe('سوال اول'); + expect(list.find((m) => m.id === 'turn-1:user')?.limited).toBeFalsy(); + expect(list.find((m) => m.id === 'turn-1:assistant')?.limited).toBe(true); + expect(list.find((m) => m.id === 'turn-2:assistant')?.limited).toBeFalsy(); + }); + + it('cannot let an old session marker contaminate a new session', async () => { + await startConnected(); // session A + transportHandlers?.onEvent({ type: 'answer_limited', turn_ref: 'shared-turn', reason: 'output_token_limit' }); + await service.close(); + + await startConnected(); // session B + + transportHandlers?.onEvent({ + type: 'transcript', + turn_ref: 'shared-turn', + role: 'assistant', + text: 'پاسخ تازه', + status: 'partial', + }); + + const assistant = service.messages().find((m) => m.id === 'shared-turn:assistant'); + expect(assistant?.text).toBe('پاسخ تازه'); + expect(assistant?.limited).toBeFalsy(); // session A's metadata did not leak + }); + + it('does not stop capture, close the socket, flush audio or reset playback progress', async () => { + await startConnected(); + transportHandlers?.onEvent({ type: 'audio_started', audio_ref: 'aud-1' }); + engineHandlers?.onPlaybackProgress('aud-1', 120); + controls = []; + engineFlush.mockClear(); + engineClear.mockClear(); + engineStop.mockClear(); + transportMock.close.mockClear(); + + transportHandlers?.onEvent(MARKER); + transportHandlers?.onEvent({ + type: 'transcript', + turn_ref: 'turn-1', + role: 'assistant', + text: 'پاسخ', + status: 'limited', + }); + + expect(engineFlush).not.toHaveBeenCalled(); // no flush/mute of playback + expect(engineClear).not.toHaveBeenCalled(); + expect(engineStop).not.toHaveBeenCalled(); // microphone keeps capturing + expect(transportMock.close).not.toHaveBeenCalled(); // socket stays open + expect(api.closeVoiceSession).not.toHaveBeenCalled(); // no backend close request + expect(service.connection()).toBe('connected'); + expect(service.state()).toBe('LISTENING'); + + // Capture keeps flowing and playback progress keeps being reported. + engineHandlers?.onFrame(new ArrayBuffer(9600), 0.5); + expect(transportMock.sendAudio).toHaveBeenCalledTimes(1); + engineHandlers?.onPlaybackProgress('aud-1', 300); + expect(controls).toEqual([{ type: 'playback_progress', audio_ref: 'aud-1', played_ms: 300 }]); + }); + + it('keeps buffered audio playing after the marker; audio_ended only seals generation', async () => { + await startConnected(); + transportHandlers?.onEvent({ type: 'audio_started', audio_ref: 'aud-1' }); + transportHandlers?.onAudio(new ArrayBuffer(9600)); // real binary audio + expect(service.state()).toBe('SPEAKING'); + + engineHandlers?.onPlaybackProgress('aud-1', 100); + controls = []; + engineFlush.mockClear(); + + transportHandlers?.onEvent(MARKER); + + // Still playing: state unchanged, no flush, no clear, audio keeps arriving. + expect(service.state()).toBe('SPEAKING'); + expect(engineFlush).not.toHaveBeenCalled(); + expect(engineClear).not.toHaveBeenCalled(); + transportHandlers?.onAudio(new ArrayBuffer(9600)); + expect(engineStop).not.toHaveBeenCalled(); + + // audio_ended seals GENERATION (drain) — it is not actual playback completion: + // progress keeps being reported from what the worklet really plays. + transportHandlers?.onEvent({ type: 'audio_ended', audio_ref: 'aud-1' }); + expect(engineFlush).toHaveBeenCalledTimes(1); + expect(service.state()).toBe('SPEAKING'); + + engineHandlers?.onPlaybackProgress('aud-1', 400); + expect(controls).toEqual([{ type: 'playback_progress', audio_ref: 'aud-1', played_ms: 400 }]); + + // The turn only finishes when playback actually drains. + vi.useFakeTimers(); + try { + engineHandlers?.onPlaybackIdle(); + vi.advanceTimersByTime(900); // no completed transcript for this limited turn → settle + } finally { + vi.useRealTimers(); + } + expect(service.state()).toBe('LISTENING'); + }); + + it('does not leave the UI thinking when a limited answer produces no audio', async () => { + await startConnected(); + transportHandlers?.onEvent({ + type: 'transcript', + turn_ref: 'turn-1', + role: 'user', + text: 'سوال', + status: 'completed', + }); + expect(service.state()).toBe('PROCESSING'); + + // The marker lands while no audio is outstanding at all. + vi.useFakeTimers(); + try { + transportHandlers?.onEvent(MARKER); + vi.advanceTimersByTime(900); // the bounded settle fallback + } finally { + vi.useRealTimers(); + } + expect(service.state()).toBe('LISTENING'); // usable again, session alive + expect(service.connection()).toBe('connected'); + + // The user can immediately speak a genuine continuation ("ادامه بده"). + engineHandlers?.onFrame(new ArrayBuffer(9600), 0.5); + expect(transportMock.sendAudio).toHaveBeenCalledTimes(1); + }); + + it('reports the real final played progress when a limited answer is interrupted', async () => { + await startConnected(); + transportHandlers?.onEvent({ + type: 'transcript', + turn_ref: 'turn-1', + role: 'assistant', + text: 'پاسخ', + status: 'limited', + }); + transportHandlers?.onEvent({ type: 'audio_started', audio_ref: 'aud-2' }); + engineHandlers?.onPlaybackProgress('aud-2', 300); + controls = []; + + transportHandlers?.onEvent({ type: 'turn_interrupted', turn_ref: 'turn-1' }); + // The worklet answers `clear` with its final cumulative report for the ref. + engineHandlers?.onPlaybackProgress('aud-2', 780); + + expect(controls).toEqual([ + { type: 'playback_progress', audio_ref: 'aud-2', played_ms: 780 }, + ]); + }); + + it('never auto-continues, fabricates a control message or recreates the session', async () => { + await startConnected(); + controls = []; + + transportHandlers?.onEvent(MARKER); + + expect(controls).toEqual([]); // no continue/resume/response.create text command + expect(api.createVoiceSession).toHaveBeenCalledTimes(1); // no second reservation + expect(transportMock.connect).toHaveBeenCalledTimes(1); // no second socket + expect(api.closeVoiceSession).not.toHaveBeenCalled(); // no close request either + expect(service.connection()).toBe('connected'); // the session stays usable + }); + + it('still fails safely on a genuine error frame after a limited answer', async () => { + await startConnected(); + const ended = firstEndedError(); + + transportHandlers?.onEvent(MARKER); + transportHandlers?.onEvent({ + type: 'error', + error: { code: 'LIVE_BUFFER_OVERFLOW', message: 'overflow', retryable: false }, + }); + + expect(await ended).toBe('overflow'); // a fatal error is NOT reinterpreted as limited + expect(api.closeVoiceSession).toHaveBeenCalledTimes(1); + expect(service.connection()).toBe('disconnected'); + }); + + it('still fails safely on a real playback overflow after a limited answer', async () => { + await startConnected(); + const ended = firstEndedError(); + + transportHandlers?.onEvent(MARKER); + engineHandlers?.onPlaybackOverflow(); + + expect(await ended).toBe(OVERFLOW_MESSAGE); + expect(service.connection()).toBe('disconnected'); + }); + + it('keeps the ordinary completed-answer flow of an older backend intact', async () => { + await startConnected(); + transportHandlers?.onEvent({ type: 'audio_started', audio_ref: 'aud-1' }); + transportHandlers?.onAudio(new ArrayBuffer(9600)); + transportHandlers?.onEvent({ + type: 'transcript', + turn_ref: 'turn-1', + role: 'assistant', + text: 'پاسخ کامل', + status: 'completed', + }); + transportHandlers?.onEvent({ type: 'audio_ended', audio_ref: 'aud-1' }); + + const assistant = service.messages().find((m) => m.id === 'turn-1:assistant'); + expect(assistant?.text).toBe('پاسخ کامل'); + expect(assistant?.limited).toBeFalsy(); + expect(assistant?.final).toBe(true); + expect(engineFlush).toHaveBeenCalledTimes(1); + + engineHandlers?.onPlaybackIdle(); + expect(service.state()).toBe('LISTENING'); // completed turns finish immediately + }); + }); }); diff --git a/src/app/services/voice-stream/voice-stream.service.ts b/src/app/services/voice-stream/voice-stream.service.ts index a53e73e..c498bd6 100644 --- a/src/app/services/voice-stream/voice-stream.service.ts +++ b/src/app/services/voice-stream/voice-stream.service.ts @@ -1,6 +1,7 @@ import { Injectable, NgZone, computed, inject, signal } from '@angular/core'; import { Subject } from 'rxjs'; import { MicrophoneError } from '../microphone/microphone.service'; +import { uuid } from '../../shared/utils/uuid'; import { VoiceApiError, VoiceApiService, VoiceSessionResponse } from './voice-api.service'; import { VoiceAudioEngine, VoiceEngineError } from './voice-audio-engine.service'; import { VOICE_TRANSPORT_FACTORY, VoiceTransport } from './voice-transport'; @@ -87,13 +88,21 @@ const ERROR_BANNER_MS = 6000; const FINAL_PROGRESS_WAIT_MS = 300; /** Longest wait for V04 /close before releasing local resources anyway (the POST keeps running). */ const CLOSE_WAIT_MS = 3000; +/** + * Bounded per-turn answer-state memory (turns the server marked `answer_limited`, and + * turns it interrupted). A marker can arrive before its transcript row exists, so the + * record must survive until the row lands — but a long call must not grow it forever, + * so the oldest entries are dropped past this cap. + */ +const TURN_STATE_MEMORY = 50; /** * One live voice call against the backend handoff contract (§7–§9): * * mic ─▶ engine ─▶ PCM16 24 kHz frames ─▶ WSS ─▶ server * server ─▶ session_ready / user_speech_started / transcript / sources / - * audio_started / audio_ended / turn_interrupted / error (JSON) + * audio_started / audio_ended / turn_interrupted / answer_limited / + * error (JSON) * ─▶ PCM16 24 kHz audio (binary) ─▶ engine playback * client ─▶ playback_progress (the only JSON control message, cumulative played_ms) * @@ -156,6 +165,10 @@ export class VoiceStreamService { private readonly playedMsByRef = new Map(); private currentAudioRef: string | null = null; private progressWaiters: Array<() => void> = []; + /** Turns whose answer the server marked limited (bounded; marker may precede its row). */ + private readonly limitedTurns = new Set(); + /** Turns the server interrupted (bounded; late assistant text must not restore them). */ + private readonly interruptedTurns = new Set(); constructor() { this.attempt = loadPersistedAttempt(); @@ -182,6 +195,10 @@ export class VoiceStreamService { this.clearError(); this.cleanupPromise = null; this.resetTurnFlags(); + // Per-session answer state: a new session can never inherit the previous one's + // limited/interrupted turn markers. + this.limitedTurns.clear(); + this.interruptedTurns.clear(); this.lastConversationId = null; this.currentAudioRef = null; this.playedMsByRef.clear(); @@ -511,6 +528,12 @@ export class VoiceStreamService { this.onTurnInterrupted(event.turn_ref); break; + case 'answer_limited': + // Answer state only — see onAnswerLimited: no cleanup, no socket/mic/playback + // side effects, no automatic continuation. + this.onAnswerLimited(event.turn_ref); + break; + case 'error': this.onServerError(event, session); break; @@ -538,7 +561,46 @@ export class VoiceStreamService { // (audio_ended); otherwise the tail would be finalized while audio is still streamed. this.turnEnded = true; if (this.audioGenerationDone) this.engine.flushPlayback(); + return; } + + if (event.status === 'limited') { + // An answer state, not a playback or session event: the limited transcript does + // NOT seal the audio reference, so generated audio keeps playing until audio_ended + // and the real queue drain finish it. Only the "thinking" state needs a bounded + // fallback, for a limited answer that produced no audio to drain. + this.scheduleLimitedSettle(); + } + } + + /** + * `answer_limited`: the assistant answer reached the backend's output-token limit. + * + * This is an ANSWER state — not an error and not a session-lifecycle event. It must + * not close or reconnect the socket, stop the microphone, flush or mute playback, + * reset `audio_ref`/`played_ms`, mark the session failed, mark playback finished, ask + * the backend to close, or request another answer automatically. The audio already + * generated keeps playing; the user asks for more ("ادامه بده") as a genuine new + * microphone turn. + */ + private onAnswerLimited(turnRef: string): void { + this.rememberLimitedTurn(turnRef); + this.markLimited(turnRef); + this.scheduleLimitedSettle(); + } + + /** + * Never leave the UI permanently "thinking" after a limited answer: when audio is + * queued the state is SPEAKING and the normal drain path returns to LISTENING, but a + * limited answer can arrive with no outstanding audio at all — then schedule the same + * bounded settle the drain path uses. + */ + private scheduleLimitedSettle(): void { + if (this.state() !== 'PROCESSING' || this.settleTimer) return; + this.settleTimer = setTimeout(() => { + this.settleTimer = null; + if (this.state() === 'PROCESSING') this.finishTurn(); + }, this.config.settleMs); } /** Server-side barge-in: the user spoke over the assistant. */ @@ -622,11 +684,28 @@ export class VoiceStreamService { const id = `${event.turn_ref}:${event.role}`; const final = event.status !== 'partial'; const interrupted = event.status === 'interrupted'; + const limited = event.status === 'limited'; + // `limited` is valid only for assistant rows (the transport rejects the rest), and a + // user transcript of a limited turn stays a plain user row. + const attachLimited = + event.role === 'assistant' && + !interrupted && + (limited || this.isLimitedTurn(event.turn_ref)); + + // A turn the server already interrupted cannot be restored by late assistant text + // (partial, completed or limited). The interrupted transcript itself still passes: + // it carries the final text of the cut-off answer. + if (event.role === 'assistant' && !interrupted && this.interruptedTurns.has(event.turn_ref)) { + return; + } this.messages.update((list) => { const index = list.findIndex((m) => m.id === id); if (index === -1) { - if (!event.text.trim()) return list; + // A `limited` transcript is kept even with empty text: the row carries the + // answer state and the UI shows the unavailable-text presentation for it — + // spoken text is never manufactured. + if (!event.text.trim() && !limited) return list; return this.insertTranscript(list, { id, turnRef: event.turn_ref, @@ -634,35 +713,41 @@ export class VoiceStreamService { text: event.text, final, interrupted: interrupted || undefined, + limited: attachLimited || undefined, }); } const current = list[index]; if (current.interrupted && !interrupted) return list; // late partial for a cut-off message + // A late `partial` must not extend an answer that is already final (completed or + // limited): the answer would silently revert to growing partial text. + if (current.final && event.status === 'partial' && event.role === 'assistant') return list; const copy = [...list]; copy[index] = { ...current, text: this.mergeTranscriptText(current.text, event), final: current.final || final, interrupted: current.interrupted || interrupted || undefined, + // Monotonic: once an answer is limited, a delayed completed/partial transcript + // cannot downgrade it back. + limited: current.limited || attachLimited || undefined, }; return copy; }); } /** - * The contract does not say whether a `partial` carries the full text so far or only the new fragment, - * so both are handled: - * - `completed` with text → the final full text replaces whatever was accumulated - * - text that starts with what we already have → cumulative, replace - * - anything else → a fragment, append as-is (fragments carry their own spacing) + * Transcript text semantics (contract): + * - `partial` is a DELTA: it is appended as-is, with its own spacing. Identical + * deltas are legitimately repeated words and are never deduplicated by content. + * - `completed` and `limited` are FINAL SNAPSHOTS: they replace the accumulated + * text exactly, so the last partial accumulation is never kept alongside them. */ private mergeTranscriptText(previous: string, event: TranscriptEvent): string { const next = event.text; if (!next) return previous; - if (!previous || event.status === 'completed') return next; - if (next.startsWith(previous)) return next; - return previous + next; + if (event.status === 'partial') return previous + next; + return next; } private upsertSources(event: SourcesEvent): void { @@ -671,7 +756,17 @@ export class VoiceStreamService { const index = list.findIndex((m) => m.id === id); const current: VoiceMessage = index === -1 - ? { id, turnRef: event.turn_ref, role: 'assistant', text: '', final: false } + ? { + id, + turnRef: event.turn_ref, + role: 'assistant', + text: '', + final: false, + // A sources row for a turn the server already marked limited shows the + // limited indication with the unavailable-text presentation — unless the + // turn was interrupted, which takes precedence. + limited: this.isLimitedTurn(event.turn_ref) || undefined, + } : list[index]; const sources = [...(current.sources ?? [])]; @@ -720,16 +815,67 @@ export class VoiceStreamService { } private markInterrupted(turnRef: string): void { + this.rememberInterruptedTurn(turnRef); const id = `${turnRef}:assistant`; this.messages.update((list) => { const index = list.findIndex((m) => m.id === id); if (index === -1 || list[index].interrupted) return list; const copy = [...list]; + // Interruption takes precedence over a limited marker on the same answer: the row + // is presented as cut off, not as a completed-capped answer. copy[index] = { ...copy[index], final: true, interrupted: true }; return copy; }); } + /** + * Flag the assistant answer of `turnRef` as limited. When the row does not exist yet + * (the marker arrived before any transcript text) the bounded `limitedTurns` record + * carries the state until the row is created — no text is ever invented here. + */ + private markLimited(turnRef: string): void { + const id = `${turnRef}:assistant`; + this.messages.update((list) => { + const index = list.findIndex((m) => m.id === id); + // No row yet (the bounded record carries the state), already limited, or + // interrupted (interruption takes precedence): nothing to change. + if (index === -1 || list[index].limited || list[index].interrupted) return list; + const copy = [...list]; + copy[index] = { ...copy[index], limited: true }; + return copy; + }); + } + + /** + * Whether the server marked `turnRef`'s answer limited. Interrupted turns answer + * `false`: the interruption takes precedence over the limited state everywhere this + * predicate is used (transcript rows, sources rows and the marker application), so + * the answer is always presented as cut off rather than capped. + */ + private isLimitedTurn(turnRef: string): boolean { + return this.limitedTurns.has(turnRef) && !this.interruptedTurns.has(turnRef); + } + + /** Bounded memory of limited turns; repeated markers are idempotent. */ + private rememberLimitedTurn(turnRef: string): void { + this.limitedTurns.add(turnRef); + this.evictOldest(this.limitedTurns); + } + + /** Bounded memory of interrupted turns, so late assistant text cannot restore them. */ + private rememberInterruptedTurn(turnRef: string): void { + this.interruptedTurns.add(turnRef); + this.evictOldest(this.interruptedTurns); + } + + private evictOldest(turns: Set): void { + while (turns.size > TURN_STATE_MEMORY) { + const oldest = turns.values().next().value; + if (oldest === undefined) break; + turns.delete(oldest); + } + } + private finalizeAssistant(): void { this.messages.update((list) => list.some((m) => m.role === 'assistant' && !m.final) @@ -834,6 +980,10 @@ export class VoiceStreamService { this.interruptTimer = null; } this.currentAudioRef = null; + // The markers describe this session's turns only: drop them so a later session + // starts clean even if a late frame slipped through. + this.limitedTurns.clear(); + this.interruptedTurns.clear(); }; if (options.ordered) { @@ -1132,8 +1282,8 @@ const ATTEMPT_STORAGE_KEY = 'voice_creation_attempt'; function newCreationAttempt(): VoiceCreationAttempt { return { - conversationRequestId: crypto.randomUUID(), - sessionRequestId: crypto.randomUUID(), + conversationRequestId: uuid(), + sessionRequestId: uuid(), conversationId: null, sessionId: null, streamPath: null, diff --git a/src/app/services/voice-stream/voice-stream.types.ts b/src/app/services/voice-stream/voice-stream.types.ts index 679f538..3ece35e 100644 --- a/src/app/services/voice-stream/voice-stream.types.ts +++ b/src/app/services/voice-stream/voice-stream.types.ts @@ -23,7 +23,11 @@ export interface VoiceSource { chunk_id: string; title: string; excerpt?: string; - location?: { page?: number; section?: string } | null; + /** + * Where the chunk lives in its document. `page` is `null` when the backend cannot + * attribute a page (it serializes the absence as JSON `null`, not as an omission). + */ + location?: { page?: number | null; section?: string } | null; /** `false` = the excerpt is no longer valid and must be hidden, not kept on screen. */ available?: boolean; } @@ -34,7 +38,14 @@ export interface VoiceAudioFormat { channels: number; } -export type TranscriptStatus = 'partial' | 'completed' | 'interrupted'; +export type TranscriptStatus = 'partial' | 'completed' | 'interrupted' | 'limited'; + +/** + * Why an assistant answer was marked limited. The backend applies a conservative + * output-token budget (tool calls included); reaching it ends the GENERATION of the + * answer, not the session and not the playback of the audio already produced. + */ +export type AnswerLimitedReason = 'output_token_limit'; export type VoiceServerEvent = | { @@ -52,8 +63,9 @@ export type VoiceServerEvent = turn_ref: string; role: 'user' | 'assistant'; /** - * Full text so far OR a new fragment: the contract does not say which, so - * `VoiceStreamService.mergeTranscriptText` accepts both (`completed` always carries the final text). + * `partial` is a delta (append it); `completed` and `limited` are final + * snapshots (they replace the accumulated text). See + * `VoiceStreamService.mergeTranscriptText`. */ text: string; status: TranscriptStatus; @@ -62,6 +74,13 @@ export type VoiceServerEvent = | { type: 'audio_started'; audio_ref: string; turn_ref?: string } | { type: 'audio_ended'; audio_ref: string; turn_ref?: string } | { type: 'turn_interrupted'; turn_ref: string; cancelled_tool_call_ids?: string[] } + /** + * The assistant answer hit the backend's output-token limit. This is an ANSWER + * state, not an error and not a session-lifecycle event: it does not stop or seal + * audio playback, does not close the session or the microphone, and does not ask + * for an automatic continuation — a genuine new user turn is required for more. + */ + | { type: 'answer_limited'; turn_ref: string; reason: AnswerLimitedReason } | { type: 'error'; turn_ref?: string; @@ -69,6 +88,9 @@ export type VoiceServerEvent = error: { code: string; message: string; request_id?: string; retryable: boolean }; }; +/** Every `type` discriminator of `VoiceServerEvent`. */ +export type VoiceServerEventType = VoiceServerEvent['type']; + /** * The only client→server JSON control message. `played_ms` is the cumulative real * playback time of `audio_ref` (computed from samples actually consumed by the @@ -91,6 +113,11 @@ export interface VoiceMessage { final: boolean; /** assistant message cut short by the user speaking over it */ interrupted?: boolean; + /** + * Assistant answer the server capped (output-token limit). The session and the + * playback of the produced audio stay usable; only the answer is limited. + */ + limited?: boolean; /** retrieved documents that back this answer */ sources?: VoiceSource[]; } diff --git a/src/app/services/voice-stream/voice-transport.spec.ts b/src/app/services/voice-stream/voice-transport.spec.ts new file mode 100644 index 0000000..2af7a52 --- /dev/null +++ b/src/app/services/voice-stream/voice-transport.spec.ts @@ -0,0 +1,177 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { WebSocketVoiceTransport } from './voice-transport'; +import { VoiceServerEvent } from './voice-stream.types'; + +/** + * Minimal fake WebSocket: captures the handlers the transport installs and lets the test + * deliver string control frames / binary audio frames exactly like a server would. + */ +class FakeWebSocket { + static readonly CONNECTING = 0; + static readonly OPEN = 1; + static readonly CLOSING = 2; + static readonly CLOSED = 3; + static instances: FakeWebSocket[] = []; + + readyState = FakeWebSocket.OPEN; + binaryType: 'blob' | 'arraybuffer' = 'blob'; + sent: unknown[] = []; + onopen: (() => void) | null = null; + onmessage: ((event: { data: unknown }) => void) | null = null; + onerror: (() => void) | null = null; + onclose: ((event: { code: number; reason: string; wasClean: boolean }) => void) | null = null; + + constructor(public readonly url: string) { + FakeWebSocket.instances.push(this); + } + + send(data: unknown): void { + this.sent.push(data); + } + + close(): void { + this.readyState = FakeWebSocket.CLOSED; + } + + // ---- test helpers --------------------------------------------------------- + + /** The transport attaches its handlers inside connect(); simulate the open handshake. */ + static async connectTransport(transport: WebSocketVoiceTransport): Promise { + const connected = transport.connect({ + onEvent: vi.fn(), + onAudio: vi.fn(), + onClose: vi.fn(), + onOverflow: vi.fn(), + }); + const ws = FakeWebSocket.instances.at(-1)!; + ws.onopen?.(); + await connected; + return ws; + } + + deliverText(payload: string): void { + this.onmessage?.({ data: payload }); + } + + deliverJson(payload: unknown): void { + this.deliverText(JSON.stringify(payload)); + } + + deliverAudio(bytes: ArrayBuffer): void { + this.onmessage?.({ data: bytes }); + } +} + +describe('WebSocketVoiceTransport (JSON frame parsing)', () => { + beforeEach(() => { + FakeWebSocket.instances = []; + vi.stubGlobal('WebSocket', FakeWebSocket); + }); + + const ANSWER_LIMITED_FRAME = { + type: 'answer_limited', + turn_ref: 'live-turn-1', + reason: 'output_token_limit', + }; + + it('parses a valid answer_limited frame and forwards it to the handlers', async () => { + const events: VoiceServerEvent[] = []; + const transport = new WebSocketVoiceTransport('wss://ui.local/stream', 1000); + const connected = transport.connect({ + onEvent: (event) => events.push(event), + onAudio: vi.fn(), + onClose: vi.fn(), + onOverflow: vi.fn(), + }); + const ws = FakeWebSocket.instances.at(-1)!; + ws.onopen?.(); + await connected; + + ws.deliverJson(ANSWER_LIMITED_FRAME); + + expect(events).toEqual([ANSWER_LIMITED_FRAME]); + }); + + it('keeps forwarding the existing event types (older backends unaffected)', async () => { + const events: VoiceServerEvent[] = []; + const transport = new WebSocketVoiceTransport('wss://ui.local/stream', 1000); + const connected = transport.connect({ + onEvent: (event) => events.push(event), + onAudio: vi.fn(), + onClose: vi.fn(), + onOverflow: vi.fn(), + }); + const ws = FakeWebSocket.instances.at(-1)!; + ws.onopen?.(); + await connected; + + ws.deliverJson({ type: 'user_speech_started', turn_ref: 'live-turn-2' }); + ws.deliverJson({ type: 'audio_started', audio_ref: 'live-audio-1' }); + ws.deliverJson({ + type: 'transcript', + turn_ref: 'live-turn-2', + role: 'assistant', + text: 'سلام', + status: 'partial', + }); + + expect(events.map((e) => e.type)).toEqual(['user_speech_started', 'audio_started', 'transcript']); + }); + + it('drops unknown and malformed frames without an error path or cleanup', async () => { + const events: VoiceServerEvent[] = []; + const onClose = vi.fn(); + const onOverflow = vi.fn(); + const transport = new WebSocketVoiceTransport('wss://ui.local/stream', 1000); + const connected = transport.connect({ + onEvent: (event) => events.push(event), + onAudio: vi.fn(), + onClose, + onOverflow, + }); + const ws = FakeWebSocket.instances.at(-1)!; + ws.onopen?.(); + await connected; + + ws.deliverText('not json'); + ws.deliverJson({ type: 'response.create' }); + ws.deliverJson({ type: 'answer_limited', turn_ref: 'live-turn-1', reason: 'other_limit' }); + ws.deliverJson({ type: 'transcript', turn_ref: 't1', role: 'user', text: 'x', status: 'limited' }); + ws.deliverJson({ type: 'audio_started', audio_ref: '' }); + + expect(events).toEqual([]); // nothing entered the service + expect(onClose).not.toHaveBeenCalled(); + expect(onOverflow).not.toHaveBeenCalled(); + expect(ws.readyState).toBe(FakeWebSocket.OPEN); // socket untouched + }); + + it('delivers binary audio frames as ArrayBuffers to onAudio', async () => { + const onAudio = vi.fn(); + const transport = new WebSocketVoiceTransport('wss://ui.local/stream', 1000); + const connected = transport.connect({ + onEvent: vi.fn(), + onAudio, + onClose: vi.fn(), + onOverflow: vi.fn(), + }); + const ws = FakeWebSocket.instances.at(-1)!; + ws.onopen?.(); + await connected; + + const pcm = new ArrayBuffer(9600); + ws.deliverAudio(pcm); + + expect(onAudio).toHaveBeenCalledWith(pcm); + }); + + it('sendControl only emits playback_progress (no fabricated continue/resume command)', async () => { + const transport = new WebSocketVoiceTransport('wss://ui.local/stream', 1000); + const ws = await FakeWebSocket.connectTransport(transport); + + transport.sendControl({ type: 'playback_progress', audio_ref: 'live-audio-1', played_ms: 120 }); + + expect(ws.sent).toEqual([ + JSON.stringify({ type: 'playback_progress', audio_ref: 'live-audio-1', played_ms: 120 }), + ]); + }); +}); diff --git a/src/app/services/voice-stream/voice-transport.ts b/src/app/services/voice-stream/voice-transport.ts index 23638be..8b30ab0 100644 --- a/src/app/services/voice-stream/voice-transport.ts +++ b/src/app/services/voice-stream/voice-transport.ts @@ -1,5 +1,6 @@ import { InjectionToken, inject } from '@angular/core'; import { PlaybackProgressMessage, VOICE_STREAM_CONFIG, VoiceServerEvent } from './voice-stream.types'; +import { parseVoiceServerEvent } from './voice-event.validator'; export interface VoiceTransportHandlers { onEvent(event: VoiceServerEvent): void; @@ -79,13 +80,11 @@ export class WebSocketVoiceTransport implements VoiceTransport { ws.onmessage = (event: MessageEvent) => { if (typeof event.data === 'string') { - let parsed: VoiceServerEvent | null = null; - try { - parsed = JSON.parse(event.data) as VoiceServerEvent; - } catch { - /* ignore malformed control frames */ - return; - } + // Allowlist + field guards: an unknown type or a malformed payload is dropped + // here, exactly like malformed JSON always was — it never reaches the service, + // never enters an error path and never triggers cleanup. + const parsed = parseVoiceServerEvent(event.data); + if (!parsed) return; this.traceFrame(parsed); handlers.onEvent(parsed); } else if (event.data instanceof ArrayBuffer) { @@ -208,6 +207,10 @@ export class WebSocketVoiceTransport implements VoiceTransport { const t = event as { status?: string; text?: string }; return `transcript[${t.status ?? '?'}] ${(t.text ?? '').slice(0, 80)}`; } + if (type === 'answer_limited') { + const a = event as { turn_ref?: string; reason?: string }; + return `answer_limited ${a.turn_ref ?? ''} reason=${a.reason ?? ''}`.trim(); + } if (type === 'audio_started' || type === 'audio_ended') { return `${type} ${(event as { audio_ref?: string }).audio_ref ?? ''}`.trim(); } diff --git a/src/app/shared/ui/voice-transcript/voice-transcript.component.css b/src/app/shared/ui/voice-transcript/voice-transcript.component.css index 71ee665..d71a95e 100644 --- a/src/app/shared/ui/voice-transcript/voice-transcript.component.css +++ b/src/app/shared/ui/voice-transcript/voice-transcript.component.css @@ -48,12 +48,43 @@ opacity: 0.8; } +.bubble.is-limited { + /* informational answer state: a quiet accent, never an error treatment */ + border-inline-start: 2px solid var(--color-primary); + padding-inline-start: 0.5rem; +} + .bubble-tag { margin-inline-start: 0.375rem; font-size: 0.75rem; opacity: 0.7; } +.bubble-tag.is-limited { + color: var(--color-primary); + font-weight: 600; + opacity: 1; +} + +.bubble-footer { + display: flex; + flex-direction: column; + align-items: flex-start; + gap: 0.125rem; + margin-top: 0.25rem; +} + +.bubble-help { + font-size: 0.75rem; + line-height: 1.6; + color: var(--muted); +} + +.bubble-text.is-missing { + color: var(--muted); + font-style: italic; +} + @keyframes bubbleIn { from { opacity: 0; @@ -77,7 +108,7 @@ .source-chip { display: flex; - align-items: baseline; + align-items: flex-start; gap: 0.375rem; padding: 0.25rem 0.5rem; border: 1px solid var(--surface-border); @@ -85,7 +116,7 @@ background: var(--surface-bg); color: var(--text-secondary); font-size: 0.75rem; - line-height: 1.5; + line-height: 1.6; } .source-chip.is-unavailable { @@ -103,6 +134,15 @@ font-weight: 600; } +/* The excerpt is the chip's content, shown complete with the provider's own line + breaks — it is the retrieved answer text the user asked to see as the source. */ +.source-label { + flex: 1 1 auto; + min-width: 0; + white-space: pre-wrap; + overflow-wrap: anywhere; +} + .transcript-empty { margin: auto; margin-bottom:10px; diff --git a/src/app/shared/ui/voice-transcript/voice-transcript.component.html b/src/app/shared/ui/voice-transcript/voice-transcript.component.html index accc25f..4ae35d4 100644 --- a/src/app/shared/ui/voice-transcript/voice-transcript.component.html +++ b/src/app/shared/ui/voice-transcript/voice-transcript.component.html @@ -5,13 +5,23 @@ [class.is-user]="message.role === 'user'" [class.is-partial]="!message.final" [class.is-interrupted]="message.interrupted" + [class.is-limited]="message.limited && !message.interrupted" dir="rtl" > @if (message.text) { {{ message.text }} + } @else if (message.limited && !message.interrupted) { + + متن این پاسخ در دسترس نیست } @if (message.interrupted) { (قطع شد) + } @else if (message.limited) { + + + پاسخ محدود شده + برای توضیح بیشتر بگویید «ادامه بده». + } @if (message.sources?.length) {
    @@ -19,7 +29,7 @@
  • {{ source.source_ref }} {{ sourceLabel(source) }} diff --git a/src/app/shared/ui/voice-transcript/voice-transcript.component.spec.ts b/src/app/shared/ui/voice-transcript/voice-transcript.component.spec.ts new file mode 100644 index 0000000..a677696 --- /dev/null +++ b/src/app/shared/ui/voice-transcript/voice-transcript.component.spec.ts @@ -0,0 +1,234 @@ +import { provideZonelessChangeDetection } from '@angular/core'; +import { TestBed } from '@angular/core/testing'; +import { VoiceTranscriptComponent } from './voice-transcript.component'; +import { VoiceMessage, VoiceSource } from '../../../services/voice-stream/voice-stream.types'; + +const LIMITED_LABEL = 'پاسخ محدود شده'; +const LIMITED_HELP = 'برای توضیح بیشتر بگویید «ادامه بده».'; +const UNAVAILABLE_TEXT = 'متن این پاسخ در دسترس نیست'; + +function message(overrides: Partial): VoiceMessage { + return { + id: 'turn-1:assistant', + turnRef: 'turn-1', + role: 'assistant', + text: 'پاسخ', + final: true, + ...overrides, + }; +} + +async function render(messages: VoiceMessage[]): Promise { + const fixture = TestBed.createComponent(VoiceTranscriptComponent); + fixture.componentRef.setInput('messages', messages); + fixture.detectChanges(); + await fixture.whenStable(); + return fixture.nativeElement as HTMLElement; +} + +describe('VoiceTranscriptComponent', () => { + beforeEach(async () => { + await TestBed.configureTestingModule({ + imports: [VoiceTranscriptComponent], + providers: [provideZonelessChangeDetection()], + }).compileComponents(); + }); + + it('shows the limited indication with the continuation help next to the transcript text', async () => { + const element = await render([message({ limited: true })]); + + expect(element.textContent).toContain('پاسخ'); // the available transcript stays visible + expect(element.textContent).toContain(LIMITED_LABEL); + expect(element.textContent).toContain(LIMITED_HELP); + // The help text is a separate indication, never appended to the provider transcript. + const text = element.querySelector('.bubble-text')?.textContent ?? ''; + expect(text).toBe('پاسخ'); + expect(text).not.toContain(LIMITED_HELP); + }); + + it('shows the unavailable-text presentation when a limited answer has no transcript text', async () => { + const element = await render([message({ text: '', limited: true })]); + + expect(element.textContent).toContain(UNAVAILABLE_TEXT); + expect(element.textContent).toContain(LIMITED_LABEL); + expect(element.textContent).toContain(LIMITED_HELP); + }); + + it('keeps the sources of a limited answer visible', async () => { + const element = await render([ + message({ + limited: true, + sources: [ + { + source_ref: 'S1', + document_id: 'doc-1', + chunk_id: 'chunk-1', + title: 'سند آزمون', + excerpt: 'بانک سؤالات و پاسخ‌های سامانه هوش مصنوعی تلفنی', + location: { page: null, section: 'docx/paragraph/1 | docx/table/1/row/1/cell/1' }, + }, + ], + }), + ]); + + expect(element.querySelectorAll('.source-chip')).toHaveLength(1); + expect(element.textContent).toContain(LIMITED_LABEL); + }); + + it('shows the excerpt instead of the document section path', async () => { + const source: VoiceSource = { + source_ref: 'S1', + document_id: 'doc-1', + chunk_id: 'chunk-1', + title: 'document.docx', + excerpt: 'ساعت کاری شرکت از شنبه تا چهارشنبه است', + location: { page: null, section: 'docx/paragraph/1 | docx/table/1/row/1/cell/1' }, + }; + const element = await render([message({ sources: [source] })]); + + const label = element.querySelector('.source-label')?.textContent ?? ''; + expect(label).toContain('ساعت کاری شرکت از شنبه تا چهارشنبه است'); + expect(label).not.toContain('docx/table/1/row/1/cell/1'); + expect(label).not.toContain('document.docx'); // the filename is not the chip label + }); + + it('keeps the full excerpt and the document details in the hover tooltip', async () => { + const source: VoiceSource = { + source_ref: 'S1', + document_id: 'doc-1', + chunk_id: 'chunk-1', + title: 'document.docx', + excerpt: 'سؤال: ساعت کاری؟\nپاسخ: ۸ تا ۱۳', + location: { page: 3, section: 'docx/paragraph/1' }, + }; + const element = await render([message({ sources: [source] })]); + + const tooltip = element.querySelector('.source-chip')?.getAttribute('title') ?? ''; + expect(tooltip).toContain('document.docx'); + expect(tooltip).toContain('docx/paragraph/1'); + expect(tooltip).toContain('صفحه 3'); + expect(tooltip).toContain('سؤال: ساعت کاری؟\nپاسخ: ۸ تا ۱۳'); + }); + + it('shows a single-paragraph excerpt completely with its line breaks', async () => { + const excerpt = + 'بانک سؤالات و پاسخ‌های سامانه هوش مصنوعی تلفنی: ساعت کاری شرکت از شنبه تا چهارشنبه است'; + const source: VoiceSource = { + source_ref: 'S1', + document_id: 'doc-1', + chunk_id: 'chunk-1', + title: 'document.docx', + excerpt, + }; + const element = await render([message({ sources: [source] })]); + + const label = element.querySelector('.source-label'); + // a single paragraph is not summarized: the full text is rendered… + expect(label?.textContent).toBe(excerpt); + // …and wraps instead of being clipped to one line + const style = getComputedStyle(label!); + expect(style.whiteSpace).toBe('pre-wrap'); + expect(style.textOverflow).not.toBe('ellipsis'); + }); + + it('summarizes a multi-paragraph excerpt to its first paragraph with an ellipsis', async () => { + const source: VoiceSource = { + source_ref: 'S1', + document_id: 'doc-1', + chunk_id: 'chunk-1', + title: 'document.docx', + excerpt: + 'بانک سؤالات و پاسخ‌های سامانه هوش مصنوعی تلفنی\nسؤال: ساعت کاری شرکت چنده؟\nپاسخ: ۸ تا ۱۳', + }; + const element = await render([message({ sources: [source] })]); + + const label = element.querySelector('.source-label')?.textContent ?? ''; + expect(label).toBe('بانک سؤالات و پاسخ‌های سامانه هوش مصنوعی تلفنی …'); + expect(label).not.toContain('سؤال: ساعت کاری'); + expect(label).not.toContain('پاسخ: ۸ تا ۱۳'); + // the complete excerpt stays available in the hover tooltip + expect(element.querySelector('.source-chip')?.getAttribute('title')).toContain('پاسخ: ۸ تا ۱۳'); + }); + + it('treats blank-line-separated paragraphs as multiple paragraphs', async () => { + const source: VoiceSource = { + source_ref: 'S1', + document_id: 'doc-1', + chunk_id: 'chunk-1', + title: 'document.docx', + excerpt: 'پاراگراف اول\n\nپاراگراف دوم', + }; + const element = await render([message({ sources: [source] })]); + + const label = element.querySelector('.source-label')?.textContent ?? ''; + expect(label).toBe('پاراگراف اول …'); + expect(label).not.toContain('پاراگراف دوم'); + }); + + it('trims the excerpt so trailing wire newlines do not add empty lines', async () => { + const source: VoiceSource = { + source_ref: 'S1', + document_id: 'doc-1', + chunk_id: 'chunk-1', + title: 'document.docx', + excerpt: 'پاسخ: ۸ تا ۱۳\n', + }; + const element = await render([message({ sources: [source] })]); + + expect(element.querySelector('.source-label')?.textContent).toBe('پاسخ: ۸ تا ۱۳'); + }); + + it('falls back to the document title for sources the server marks unavailable', async () => { + const element = await render([ + message({ + sources: [ + { + source_ref: 'S1', + document_id: 'doc-1', + chunk_id: 'chunk-1', + title: 'document.docx', + excerpt: 'متن منقضی‌شده', + available: false, + }, + ], + }), + ]); + + const chip = element.querySelector('.source-chip'); + expect(chip?.classList.contains('is-unavailable')).toBe(true); + expect(chip?.querySelector('.source-label')?.textContent).toBe('document.docx'); + expect(chip?.querySelector('.source-label')?.textContent).not.toContain('متن منقضی‌شده'); + // The revoked excerpt stays hidden in the tooltip too. + expect(chip?.getAttribute('title')).not.toContain('متن منقضی‌شده'); + expect(chip?.getAttribute('title')).toContain('document.docx'); + }); + + it('presents an interrupted answer as interrupted, not as limited', async () => { + const element = await render([ + message({ limited: true, interrupted: true, text: 'پاسخ قطع‌شده' }), + ]); + + expect(element.textContent).toContain('(قطع شد)'); + expect(element.textContent).not.toContain(LIMITED_LABEL); + expect(element.textContent).not.toContain(LIMITED_HELP); + }); + + it('never applies the limited indication to user rows or ordinary answers', async () => { + const element = await render([ + message({ id: 'turn-1:user', turnRef: 'turn-1', role: 'user', text: 'ادامه بده' }), + message({ id: 'turn-2:assistant', turnRef: 'turn-2', text: 'پاسخ عادی' }), + ]); + + expect(element.textContent).not.toContain(LIMITED_LABEL); + expect(element.textContent).toContain('ادامه بده'); + expect(element.textContent).toContain('پاسخ عادی'); + }); + + it('renders the limited indication in an RTL bubble', async () => { + const element = await render([message({ limited: true })]); + const bubble = element.querySelector('.bubble'); + + expect(bubble?.getAttribute('dir')).toBe('rtl'); + expect(bubble?.classList.contains('is-limited')).toBe(true); + }); +}); diff --git a/src/app/shared/ui/voice-transcript/voice-transcript.component.ts b/src/app/shared/ui/voice-transcript/voice-transcript.component.ts index 378134f..a810456 100644 --- a/src/app/shared/ui/voice-transcript/voice-transcript.component.ts +++ b/src/app/shared/ui/voice-transcript/voice-transcript.component.ts @@ -12,11 +12,42 @@ import { VoiceMessage, VoiceSource } from '../../../services/voice-stream/voice- export class VoiceTranscriptComponent { readonly messages = input.required(); - /** "عنوان — صفحه ۱، بند ۲" */ + /** + * Compact chip label: the excerpt's first paragraph, followed by an ellipsis when the + * chunk holds more paragraphs. The document's internal `location.section` path (e.g. + * "docx/table/1/row/1/cell/1") is document structure, not content, so it is not shown + * in the chip (it stays in the hover tooltip, along with the complete excerpt). Sources + * the server marks unavailable keep their excerpt hidden and fall back to the title. + */ sourceLabel(source: VoiceSource): string { + if (source.available !== false) { + const excerpt = source.excerpt?.trim(); + if (excerpt) { + // Paragraph breaks (single or repeated newlines) separate the excerpt into + // paragraphs; only the first one is summarized into the chip. + const paragraphs = excerpt + .split(/\r?\n+/) + .map((paragraph) => paragraph.trim()) + .filter(Boolean); + const first = paragraphs[0]; + if (first) return paragraphs.length > 1 ? `${first} …` : first; + } + } + return source.title || source.document_id; + } + + /** Hover tooltip: document, location and the complete, untruncated excerpt. */ + sourceTooltip(source: VoiceSource): string { const parts: string[] = []; + if (source.title) parts.push(source.title); if (source.location?.page != null) parts.push(`صفحه ${source.location.page}`); if (source.location?.section) parts.push(source.location.section); - return parts.length ? `${source.title} — ${parts.join('، ')}` : source.title; + // Same hidden-excerpt rule as the chip label: a source the server marks unavailable + // has revoked text, so it is not surfaced here either. + if (source.available !== false) { + const excerpt = source.excerpt?.trim(); + if (excerpt) parts.push(excerpt); + } + return parts.join('\n'); } }