Skip to content
4 changes: 2 additions & 2 deletions portal/static/js/listener-event.js
Original file line number Diff line number Diff line change
Expand Up @@ -854,8 +854,8 @@ function finishSegmentWithDelay(seg, seqId) {
var isTranslationActive =
Boolean(translationLangSelect.value) && mode !== "original";

if (!isTranslationActive || seg.empty) {
// Nothing to read or hear (no translation wanted, or an empty one): advance immediately.
if (!isTranslationActive || seg.empty || (ttsSyncEnabled && seg.error)) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Medium · Captions advance before listeners can read

When the voice toggle remains enabled after selecting a language without synchronized TTS, and an errored or text-only segment arrives, finishSegmentWithDelay treats the saved ttsSyncEnabled flag and any seg.error as proof that speech failed, even when TTS is inactive or synthesis was not attempted. It skips the reading delay, so the next caption advances too soon.

Base immediate advancement on an actual failed speech attempt for the selected language, rather than the saved toggle and generic seg.error flag.

Prompt for AI agents
In `portal/static/js/listener-event.js` at line 857:

**Captions advance before listeners can read**

When the voice toggle remains enabled after selecting a language without synchronized TTS, and an errored or text-only segment arrives, `finishSegmentWithDelay` treats the saved `ttsSyncEnabled` flag and any `seg.error` as proof that speech failed, even when TTS is inactive or synthesis was not attempted. It skips the reading delay, so the next caption advances too soon.

Base immediate advancement on an actual failed speech attempt for the selected language, rather than the saved toggle and generic `seg.error` flag.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Medium · Playback failures still pause the queue

When an audio buffer is ready but the browser throws while scheduling or starting its playback, the audio-playback catch calls finishSegmentWithDelay without setting seg.error, so this guard falls through to the timed reading delay and holds the next buffered segment.

Route terminal playback failures through the same immediate-advance path as synthesis errors.

Prompt for AI agents
In `portal/static/js/listener-event.js` at line 857:

**Playback failures still pause the queue**

When an audio buffer is ready but the browser throws while scheduling or starting its playback, the audio-playback catch calls `finishSegmentWithDelay` without setting `seg.error`, so this guard falls through to the timed reading delay and holds the next buffered segment.

Route terminal playback failures through the same immediate-advance path as synthesis errors.

// Failed AI speech must not hold up the next sentence; its text stays in history.
isSegmentPlaying = false;
delete segmentStore[seqId];
expectedSeq++;
Expand Down
37 changes: 36 additions & 1 deletion tests/listener_channel_switch_browser.py
Original file line number Diff line number Diff line change
Expand Up @@ -402,7 +402,15 @@ async def caption(self, code: str, text: str, seq: int, delay_ms: int = 0) -> No
await listener_manager.broadcast(self.ch.booth(code), message)

async def translation(
self, code: str, target: str, text: str, seq: int, *, delay_ms: int = 0, speech_frames: int = 0
self,
code: str,
target: str,
text: str,
seq: int,
*,
delay_ms: int = 0,
speech_frames: int = 0,
error: str | None = None,
) -> None:
"""Send a TTS bundle; ``speech_frames`` of silent 24 kHz PCM make it a spoken segment."""
token = segment_timing.set(SegmentTiming(int(time.time() * 1000), delay_ms) if delay_ms else None)
Expand All @@ -415,6 +423,7 @@ async def translation(
segment_id=uuid.uuid4().hex,
seq=seq,
translation=text,
error=error,
audio_pending=False,
)
finally:
Expand Down Expand Up @@ -482,6 +491,22 @@ async def expect_routing(self, page: Page, code: str, target: str | None) -> Non
assert not repeated, f"live feed shown more than once: {repeated}"


async def expect_voice_recovery(page: Page, feeds: Feeds) -> float:
"""Ready AI speech bypasses a failed segment, while its captions remain readable."""
failed_seq = feeds.next_seq("floor")
started = time.monotonic()
await feeds.caption("floor", "A sentence whose voice failed", failed_seq)
await feeds.translation("floor", "fr", "Voix indisponible.", failed_seq, error="tts_error")
recovered_frames = 48000
await feeds.translation("floor", "fr", "La suite.", feeds.next_seq("floor"), speech_frames=recovered_frames)
await until(
lambda: speech_playing(page, recovered_frames), "ready speech skips a failed voice segment", timeout=1.5
)
await expect(page.locator("#caption-history")).to_contain_text("A sentence whose voice failed")
await expect(page.locator("#caption-history")).to_contain_text("Voix indisponible.")
return time.monotonic() - started


async def seed(run: int) -> tuple[Channels, int]:
"""An event with English and Spanish booths and floor audio, each translated to French and German."""
async with get_session() as s:
Expand Down Expand Up @@ -601,6 +626,16 @@ async def shot(name: str) -> None:
await expect_only_channel(page, media, ch, "es", "de")
await shot("2-spanish")

# A completed TTS failure must not impose the caption-reading delay on ready speech.
await choose(page, "Source Audio", SOURCES["floor"])
await choose(page, "Target Language", "French")
await expect_only_channel(page, media, ch, "floor", "fr")
await expect_voice_recovery(page, feeds)
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
await shot("2b-voice-recovered")
await choose(page, "Source Audio", "Spanish")
await choose(page, "Target Language", "German")
await expect_only_channel(page, media, ch, "es", "de")

# Leaving a channel whose WHEP is failing stops its back-off loop.
media.offline.add(ch.whep("floor"))
attempts = len(media.posts)
Expand Down
71 changes: 71 additions & 0 deletions tests/test_listener_event.js
Original file line number Diff line number Diff line change
Expand Up @@ -743,6 +743,77 @@ async function run() {
await waitFor(() => timeline.length >= 2);
assert(order() === '[31,32]', 'the feed plays its first two sentences in order, got ' + order());
assert(gapless(), 'back to back');

console.log('\n── AI voice continues after a failed segment (#415) ──');

useFakeTimers();
try {
for (const error of ['tts_error', 'tts_timeout', 'tts_unavailable', 'pipeline_failed', null]) {
timeline = [];
choose(translationLangSelect, 'fr');
sendFloorSegment(1, 'failed-1', 'Failed sentence', 'Phrase indisponible.', 'text');
for (const stage of ['text', 'audio']) sendFloorSegment(2, 'ready-2', 'Next sentence', 'Phrase suivante.', stage);
assert(order() === '[]', 'ready speech waits while the preceding segment is still pending');

ttsSocket().onmessage({
data: bundleFrame({ seq: 1, segment_id: 'failed-1', caption: 'Failed sentence',
translation: error === 'pipeline_failed' ? '' : 'Phrase indisponible.', error, audio_pending: false }),
});
const outcome = error || 'no_audio';
assert(order() === '[2]', outcome + ': ready speech is scheduled without a caption-reading pause, got ' + order());
assert(historyBox.textContent.includes('Failed sentence'), outcome + ': the failed sentence keeps its caption');
if (error !== 'pipeline_failed') {
assert(historyBox.textContent.includes('Phrase indisponible.'), outcome + ': translated text remains readable');

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Medium · Repeated captions hide later losses

When a later error type loses its segment’s history after an earlier iteration rendered the same text, when a later error-specific path drops that segment’s caption or translation, the repeated strings and uncleared historyBox let the assertions at lines 764 and 766 pass because an earlier iteration already rendered the same text; the loop therefore does not verify history retention for each failure case.

Use distinct caption and translation text for each error case, or assert against the history row for the current sequence.

Prompt for AI agents
In `tests/test_listener_event.js` at lines 764-766:

**Repeated captions hide later losses**

When a later error type loses its segment’s history after an earlier iteration rendered the same text, when a later error-specific path drops that segment’s caption or translation, the repeated strings and uncleared `historyBox` let the assertions at lines 764 and 766 pass because an earlier iteration already rendered the same text; the loop therefore does not verify history retention for each failure case.

Use distinct caption and translation text for each error case, or assert against the history row for the current sequence.

}
const beforeLateAudio = order();
sendFloorSegment(1, 'failed-1', 'Failed sentence', 'Phrase indisponible.', 'audio');
assert(order() === beforeLateAudio, outcome + ': late audio from the failed sentence is not replayed');
}

timeline = [];
choose(translationLangSelect, 'fr');
for (const seq of [1, 2]) {
ttsSocket().onmessage({
data: bundleFrame({ seq, segment_id: 'unavailable-' + seq, caption: 'Unavailable ' + seq,
translation: 'Indisponible.', error: 'tts_unavailable', audio_pending: false }),
});
}
sendFloorSegment(3, 'ready-3', 'Available', 'Disponible.', 'audio');
assert(order() === '[3]', 'consecutive synthesis failures do not accumulate reading pauses');

timeline = [];
choose(translationLangSelect, 'fr');
sendFloorSegment(1, 'pending-1', 'Pending', 'En attente.', 'text');
sendFloorSegment(2, 'ready-2', 'Ready', 'Prête.', 'audio');
assert(order() === '[]', 'a segment still awaiting audio is not skipped');
sendFloorSegment(1, 'pending-1', 'Pending', 'En attente.', 'audio');
runTimers(30);
assert(order() === '[1,2]', 'pending audio that succeeds still plays in sentence order');
assert(gapless(), 'successful recovery keeps the scheduled audio contiguous');

// Caption-only listeners keep their reading time even when voice synthesis failed.
ttsToggle.checked = false;
ttsToggle.dispatchEvent(new Event('change'));
choose(translationLangSelect, 'fr');
ttsSocket().onmessage({
data: bundleFrame({ seq: 1, segment_id: 'reading-1', caption: 'Reading control first',
translation: 'Première phrase.', error: 'tts_error', audio_pending: false }),
});
ttsSocket().onmessage({
data: bundleFrame({ seq: 2, segment_id: 'reading-2', caption: 'Reading control second',
translation: 'Deuxième phrase.', error: null, audio_pending: false }),
});
assert(!historyBox.textContent.includes('Reading control second'), 'text-only mode holds the next caption for reading');
runTimers(2500);
assert(historyBox.textContent.includes('Reading control second'), 'text-only mode advances after the normal reading delay');
} finally {
choose(translationLangSelect, 'fr');
fakeTimers.clear();
globalThis.setTimeout = realSetTimeout;
globalThis.clearTimeout = realClearTimeout;
ttsToggle.checked = true;
ttsToggle.dispatchEvent(new Event('change'));
}
window.AudioScheduler = stubScheduler;

console.log('\n── Empty translations (#1184) ──');
Expand Down
Loading