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.
This commit is contained in:
PeymanHonarjoo
2026-10-12 16:51:04 +03:30
parent 0af55f52a3
commit 9e8dd33927
11 changed files with 1505 additions and 29 deletions
@@ -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
});
});
});