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
@@ -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<string, number>();
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<string>();
/** Turns the server interrupted (bounded; late assistant text must not restore them). */
private readonly interruptedTurns = new Set<string>();
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<string>): 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,