fix(frontend): keep voice mode listening for the full no-speech window

Chrome raises its own no-speech error after a few seconds of silence and sometimes ends a recognition session by itself. While voice mode is endpointing, restart recognition transparently against one fixed no-speech deadline, send captured words when Chrome ends a session after speech, and bound restarts so a failing recognizer surfaces an error instead of leaving the bar on Listening.
This commit is contained in:
Chris Scott committed 2026-10-22 21:31:47 -04:00
1 parent 73af7aec89
commit 95cd276e37
2 files changed
+445 -17

No files matched your search

+312 -3
View File
@@ -318,23 +318,332 @@ describe('WebSpeechRecognizer', () => {
vi.useRealTimers()
})
it('reports no-speech instead of an error when the browser raises no-speech during endpointing', async () => {
it('reports no-speech instead of an error when Chrome raises no-speech after the deadline', async () => {
const rec = new WebSpeechRecognizer()
const onEndOfSpeech = vi.fn()
const onError = vi.fn()
const onEnd = vi.fn()
rec.onError(onError)
await rec.start({ endpointing: { pauseMs: 800, noSpeechTimeoutMs: 5000 }, onEndOfSpeech })
rec.onEnd(onEnd)
vi.useFakeTimers()
const startPromise = rec.start({ endpointing: { pauseMs: 800, noSpeechTimeoutMs: 5000 }, onEndOfSpeech })
await vi.advanceTimersByTimeAsync(0)
await startPromise
vi.setSystemTime(Date.now() + 5000)
fakeRec.onerror!({ error: 'no-speech' })
expect(onEndOfSpeech).toHaveBeenCalledTimes(1)
expect(onEndOfSpeech).toHaveBeenCalledWith('no-speech', '')
expect(onError).not.toHaveBeenCalled()
expect(rec.getState()).toBe('error')
expect(fakeRec.start).toHaveBeenCalledTimes(1)
fakeRec.onend!(new Event('end'))
expect(onEndOfSpeech).toHaveBeenCalledTimes(1)
expect(onEnd).toHaveBeenCalledTimes(1)
expect(rec.getState()).toBe('idle')
vi.useRealTimers()
})
it('restarts transparently when Chrome raises no-speech before the deadline', async () => {
const rec = new WebSpeechRecognizer()
const onEndOfSpeech = vi.fn()
const onError = vi.fn()
const onEnd = vi.fn()
const onStart = vi.fn()
rec.onError(onError)
rec.onEnd(onEnd)
rec.onStart(onStart)
vi.useFakeTimers()
const startPromise = rec.start({
endpointing: { pauseMs: 2000, noSpeechTimeoutMs: 10000 },
onEndOfSpeech,
})
await vi.advanceTimersByTimeAsync(0)
await startPromise
expect(onStart).toHaveBeenCalledTimes(1)
vi.advanceTimersByTime(6000)
fakeRec.onerror!({ error: 'no-speech' })
expect(onEndOfSpeech).not.toHaveBeenCalled()
expect(onError).not.toHaveBeenCalled()
fakeRec.onend!(new Event('end'))
await vi.advanceTimersByTimeAsync(0)
expect(fakeRec.start).toHaveBeenCalledTimes(2)
expect(onStart).toHaveBeenCalledTimes(1)
expect(onEnd).not.toHaveBeenCalled()
expect(rec.isCurrentlyListening()).toBe(true)
vi.advanceTimersByTime(3999)
expect(onEndOfSpeech).not.toHaveBeenCalled()
vi.advanceTimersByTime(1)
expect(onEndOfSpeech).toHaveBeenCalledTimes(1)
expect(onEndOfSpeech).toHaveBeenCalledWith('no-speech', '')
fakeRec.onend!(new Event('end'))
expect(onEnd).toHaveBeenCalledTimes(1)
vi.useRealTimers()
})
it('restarts when recognition ends unexpectedly before the deadline without speech', async () => {
const rec = new WebSpeechRecognizer()
const onEndOfSpeech = vi.fn()
const onError = vi.fn()
const onEnd = vi.fn()
const onStart = vi.fn()
rec.onError(onError)
rec.onEnd(onEnd)
rec.onStart(onStart)
vi.useFakeTimers()
const startPromise = rec.start({
endpointing: { pauseMs: 2000, noSpeechTimeoutMs: 10000 },
onEndOfSpeech,
})
await vi.advanceTimersByTimeAsync(0)
await startPromise
vi.advanceTimersByTime(3000)
fakeRec.onend!(new Event('end'))
await vi.advanceTimersByTimeAsync(0)
expect(fakeRec.start).toHaveBeenCalledTimes(2)
expect(onStart).toHaveBeenCalledTimes(1)
expect(onEnd).not.toHaveBeenCalled()
expect(onError).not.toHaveBeenCalled()
expect(onEndOfSpeech).not.toHaveBeenCalled()
expect(rec.isCurrentlyListening()).toBe(true)
vi.useRealTimers()
})
it('reports a pause with the final transcript when recognition ends unexpectedly', async () => {
const rec = new WebSpeechRecognizer()
const onEndOfSpeech = vi.fn()
const onEnd = vi.fn()
rec.onEnd(onEnd)
vi.useFakeTimers()
const startPromise = rec.start({
endpointing: { pauseMs: 2000, noSpeechTimeoutMs: 10000 },
onEndOfSpeech,
})
await vi.advanceTimersByTimeAsync(0)
await startPromise
fakeRec.onresult!(makeResultEvent(0, 1, [
{ isFinal: true, transcript: 'hello world', confidence: 1.0 },
]))
fakeRec.onend!(new Event('end'))
expect(fakeRec.start).toHaveBeenCalledTimes(1)
expect(onEndOfSpeech).toHaveBeenCalledTimes(1)
expect(onEndOfSpeech).toHaveBeenCalledWith('pause', 'hello world')
expect(onEnd).toHaveBeenCalledTimes(1)
vi.useRealTimers()
})
it('keeps the accumulated transcript across transparent restarts', async () => {
const rec = new WebSpeechRecognizer()
const onEndOfSpeech = vi.fn()
vi.useFakeTimers()
const startPromise = rec.start({
endpointing: { pauseMs: 5000, noSpeechTimeoutMs: 10000 },
onEndOfSpeech,
})
await vi.advanceTimersByTimeAsync(0)
await startPromise
fakeRec.onresult!(makeResultEvent(0, 1, [
{ isFinal: true, transcript: 'hello', confidence: 1.0 },
]))
vi.advanceTimersByTime(1000)
fakeRec.onerror!({ error: 'no-speech' })
fakeRec.onend!(new Event('end'))
await vi.advanceTimersByTimeAsync(0)
expect(rec.getFinalTranscript()).toBe('hello')
fakeRec.onresult!(makeResultEvent(0, 1, [
{ isFinal: true, transcript: 'world', confidence: 1.0 },
]))
fakeRec.onend!(new Event('end'))
expect(onEndOfSpeech).toHaveBeenCalledTimes(1)
expect(onEndOfSpeech).toHaveBeenCalledWith('pause', 'hello world')
vi.useRealTimers()
})
it('reports a pause with the interim transcript when recognition ends unexpectedly before a final result', async () => {
const rec = new WebSpeechRecognizer()
const onEndOfSpeech = vi.fn()
vi.useFakeTimers()
const startPromise = rec.start({
endpointing: { pauseMs: 2000, noSpeechTimeoutMs: 10000 },
onEndOfSpeech,
})
await vi.advanceTimersByTimeAsync(0)
await startPromise
fakeRec.onresult!(makeResultEvent(0, 1, [
{ isFinal: false, transcript: 'hello there', confidence: 0.0 },
]))
fakeRec.onend!(new Event('end'))
expect(onEndOfSpeech).toHaveBeenCalledTimes(1)
expect(onEndOfSpeech).toHaveBeenCalledWith('pause', 'hello there')
vi.useRealTimers()
})
it('cancels a pending restart when stop() is called', async () => {
const rec = new WebSpeechRecognizer()
const onEndOfSpeech = vi.fn()
const onEnd = vi.fn()
rec.onEnd(onEnd)
vi.useFakeTimers()
const startPromise = rec.start({
endpointing: { pauseMs: 2000, noSpeechTimeoutMs: 10000 },
onEndOfSpeech,
})
await vi.advanceTimersByTimeAsync(0)
await startPromise
vi.advanceTimersByTime(3000)
fakeRec.onerror!({ error: 'no-speech' })
rec.stop()
fakeRec.onend!(new Event('end'))
await vi.advanceTimersByTimeAsync(0)
expect(fakeRec.start).toHaveBeenCalledTimes(1)
expect(onEndOfSpeech).not.toHaveBeenCalled()
expect(onEnd).toHaveBeenCalledTimes(1)
vi.useRealTimers()
})
it('surfaces an error when a transparent restart throws', async () => {
const rec = new WebSpeechRecognizer()
const onEndOfSpeech = vi.fn()
const onError = vi.fn()
const onEnd = vi.fn()
rec.onError(onError)
rec.onEnd(onEnd)
vi.useFakeTimers()
const startPromise = rec.start({
endpointing: { pauseMs: 2000, noSpeechTimeoutMs: 10000 },
onEndOfSpeech,
})
await vi.advanceTimersByTimeAsync(0)
await startPromise
fakeRec.start.mockImplementationOnce(() => {
throw new Error('InvalidStateError')
})
vi.advanceTimersByTime(3000)
fakeRec.onend!(new Event('end'))
expect(fakeRec.start).toHaveBeenCalledTimes(2)
expect(onError).toHaveBeenCalledTimes(1)
expect(onError).toHaveBeenCalledWith('Speech recognition stopped unexpectedly. Please try again.')
expect(onEndOfSpeech).not.toHaveBeenCalled()
expect(onEnd).toHaveBeenCalledTimes(1)
expect(rec.getState()).toBe('idle')
vi.useRealTimers()
})
it('stops restarting after the transparent restart cap', async () => {
const rec = new WebSpeechRecognizer()
const onEndOfSpeech = vi.fn()
const onEnd = vi.fn()
rec.onEnd(onEnd)
vi.useFakeTimers()
const startPromise = rec.start({
endpointing: { pauseMs: 2000, noSpeechTimeoutMs: 20000 },
onEndOfSpeech,
})
await vi.advanceTimersByTimeAsync(0)
await startPromise
for (let i = 0; i < 6; i++) {
vi.advanceTimersByTime(500)
fakeRec.onerror!({ error: 'no-speech' })
fakeRec.onend!(new Event('end'))
await vi.advanceTimersByTimeAsync(0)
}
expect(fakeRec.start).toHaveBeenCalledTimes(6)
expect(onEndOfSpeech).toHaveBeenCalledTimes(1)
expect(onEndOfSpeech).toHaveBeenCalledWith('no-speech', '')
expect(onEnd).toHaveBeenCalledTimes(1)
vi.useRealTimers()
})
it('stops restarting when a restarted session ends immediately without audio', async () => {
const rec = new WebSpeechRecognizer()
const onEndOfSpeech = vi.fn()
vi.useFakeTimers()
const startPromise = rec.start({
endpointing: { pauseMs: 2000, noSpeechTimeoutMs: 10000 },
onEndOfSpeech,
})
await vi.advanceTimersByTimeAsync(0)
await startPromise
vi.advanceTimersByTime(3000)
fakeRec.onend!(new Event('end'))
await vi.advanceTimersByTimeAsync(0)
vi.advanceTimersByTime(100)
fakeRec.onend!(new Event('end'))
expect(fakeRec.start).toHaveBeenCalledTimes(2)
expect(onEndOfSpeech).toHaveBeenCalledTimes(1)
expect(onEndOfSpeech).toHaveBeenCalledWith('no-speech', '')
vi.useRealTimers()
})
it('surfaces Chrome no-speech as an error when endpointing is off', async () => {
const rec = new WebSpeechRecognizer()
const onError = vi.fn()
const onEnd = vi.fn()
rec.onError(onError)
rec.onEnd(onEnd)
await rec.start()
fakeRec.onerror!({ error: 'no-speech' })
expect(onError).toHaveBeenCalledTimes(1)
expect(onError).toHaveBeenCalledWith('No speech detected. Please try again.')
expect(fakeRec.start).toHaveBeenCalledTimes(1)
fakeRec.onend!(new Event('end'))
expect(onEnd).toHaveBeenCalledTimes(1)
})
it('does not report end of speech for a manual stop', async () => {
+133 -14
View File
@@ -91,6 +91,9 @@ declare global {
}
const WEB_SPEECH_INACTIVITY_TIMEOUT_MS = 2000;
const MAX_TRANSPARENT_RESTARTS = 5;
const MIN_RESTART_SESSION_MS = 250;
const RESTART_FAILED_MESSAGE = 'Speech recognition stopped unexpectedly. Please try again.';
export function appendTranscriptSegment(current: string, segment: string): string {
const trimmedCurrent = current.trim();
@@ -108,13 +111,22 @@ export class WebSpeechRecognizer {
private onEndCallbacks: (() => void)[] = [];
private onStartCallbacks: (() => void)[] = [];
private finalTranscript = '';
private interimTranscript = '';
private inactivityTimeoutRef: ReturnType<typeof setTimeout> | null = null;
private noSpeechTimeoutRef: ReturnType<typeof setTimeout> | null = null;
private noSpeechDeadlineAt: number | null = null;
private inactivityTimeoutMs = WEB_SPEECH_INACTIVITY_TIMEOUT_MS;
private endpointing: SttEndpointingOptions | null = null;
private endOfSpeechHandler: ((reason: SttEndOfSpeechReason, finalText: string) => void) | null = null;
private pendingEndOfSpeechReason: SttEndOfSpeechReason | null = null;
private endOfSpeechEmitted = false;
private restartCount = 0;
private restartStartedAt = 0;
private sessionHadSpeech = false;
private awaitingRestart = false;
private stopRequested = false;
private fatalErrorRaised = false;
private suppressStartCallbacks = false;
private clearInactivityTimeout(): void {
if (this.inactivityTimeoutRef !== null) {
@@ -130,24 +142,74 @@ export class WebSpeechRecognizer {
}
}
private accumulatedTranscript(): string {
const interim = this.interimTranscript.trim();
return interim ? appendTranscriptSegment(this.finalTranscript, interim) : this.finalTranscript;
}
private emitEndOfSpeech(reason: SttEndOfSpeechReason): void {
if (this.endOfSpeechEmitted) return;
this.endOfSpeechEmitted = true;
this.endOfSpeechHandler?.(reason, this.finalTranscript);
this.endOfSpeechHandler?.(reason, this.accumulatedTranscript());
}
private hasNoSpeechBudgetRemaining(): boolean {
return this.noSpeechDeadlineAt !== null && Date.now() < this.noSpeechDeadlineAt;
}
private scheduleNoSpeechTimeout(): void {
this.clearNoSpeechTimeout();
const noSpeechTimeoutMs = this.endpointing?.noSpeechTimeoutMs;
if (!noSpeechTimeoutMs || noSpeechTimeoutMs <= 0) return;
if (this.noSpeechDeadlineAt === null) return;
const remainingMs = Math.max(0, this.noSpeechDeadlineAt - Date.now());
this.noSpeechTimeoutRef = setTimeout(() => {
this.noSpeechTimeoutRef = null;
if (!this.isListening || this.finalTranscript) return;
if (this.endOfSpeechEmitted || this.finalTranscript) return;
if (!this.isListening && !this.awaitingRestart) return;
this.emitEndOfSpeech('no-speech');
this.stop();
}, noSpeechTimeoutMs);
}, remainingMs);
}
private canRestartCapture(): boolean {
if (this.endOfSpeechEmitted) return false;
if (this.restartCount >= MAX_TRANSPARENT_RESTARTS) return false;
const endedTooSoon =
this.restartCount > 0 &&
!this.sessionHadSpeech &&
Date.now() - this.restartStartedAt < MIN_RESTART_SESSION_MS;
return !endedTooSoon;
}
private restartCapture(): 'restarted' | 'blocked' | 'failed' {
if (!this.recognition || !this.canRestartCapture()) return 'blocked';
this.restartCount += 1;
this.restartStartedAt = Date.now();
this.isListening = true;
this.state = 'listening';
this.awaitingRestart = false;
this.stopRequested = false;
this.fatalErrorRaised = false;
this.sessionHadSpeech = false;
this.suppressStartCallbacks = true;
try {
this.recognition.start();
return 'restarted';
} catch {
this.suppressStartCallbacks = false;
this.isListening = false;
this.endpointing = null;
this.endOfSpeechHandler = null;
this.endOfSpeechEmitted = true;
this.onErrorCallbacks.forEach((cb) => cb(RESTART_FAILED_MESSAGE));
return 'failed';
}
}
private resetInactivityTimeout(): void {
@@ -178,12 +240,20 @@ export class WebSpeechRecognizer {
this.recognition.onstart = () => {
this.isListening = true;
this.state = 'listening';
this.sessionHadSpeech = false;
this.scheduleNoSpeechTimeout();
if (this.suppressStartCallbacks) {
this.suppressStartCallbacks = false;
return;
}
this.onStartCallbacks.forEach((cb) => cb());
};
this.recognition.onresult = (event: SpeechRecognitionEvent) => {
this.clearNoSpeechTimeout();
this.sessionHadSpeech = true;
let interimTranscript = '';
for (let i = event.resultIndex; i < event.results.length; i++) {
@@ -205,6 +275,8 @@ export class WebSpeechRecognizer {
}
}
this.interimTranscript = interimTranscript;
if (interimTranscript) {
this.onInterimResultCallbacks.forEach((cb) => cb(this.finalTranscript + ' ' + interimTranscript));
}
@@ -214,18 +286,31 @@ export class WebSpeechRecognizer {
this.recognition.onerror = (event: SpeechRecognitionErrorEvent) => {
this.clearInactivityTimeout();
this.clearNoSpeechTimeout();
this.state = 'error';
this.isListening = false;
this.pendingEndOfSpeechReason = null;
if (this.endpointing && event.error === 'no-speech') {
if (this.hasNoSpeechBudgetRemaining() && !this.endOfSpeechEmitted) {
this.awaitingRestart = true;
this.isListening = false;
return;
}
this.fatalErrorRaised = true;
this.clearNoSpeechTimeout();
this.state = 'error';
this.isListening = false;
this.pendingEndOfSpeechReason = null;
this.emitEndOfSpeech('no-speech');
this.endpointing = null;
this.endOfSpeechHandler = null;
return;
}
this.clearNoSpeechTimeout();
this.state = 'error';
this.isListening = false;
this.pendingEndOfSpeechReason = null;
this.fatalErrorRaised = true;
let errorMsg = event.error || 'Unknown error';
switch (event.error) {
@@ -251,19 +336,34 @@ export class WebSpeechRecognizer {
this.recognition.onend = () => {
this.clearInactivityTimeout();
this.clearNoSpeechTimeout();
this.isListening = false;
this.state = 'idle';
const reason = this.pendingEndOfSpeechReason;
this.pendingEndOfSpeechReason = null;
this.endpointing = null;
if (reason) {
this.emitEndOfSpeech(reason);
} else if (this.endpointing && !this.stopRequested && !this.fatalErrorRaised) {
if (this.awaitingRestart) {
const outcome = this.hasNoSpeechBudgetRemaining() ? this.restartCapture() : 'blocked';
if (outcome === 'restarted') return;
if (outcome === 'blocked') this.emitEndOfSpeech('no-speech');
} else if (this.accumulatedTranscript()) {
this.emitEndOfSpeech('pause');
} else if (this.hasNoSpeechBudgetRemaining()) {
const outcome = this.restartCapture();
if (outcome === 'restarted') return;
if (outcome === 'blocked') this.emitEndOfSpeech('no-speech');
} else {
this.emitEndOfSpeech('no-speech');
}
}
this.endOfSpeechHandler = null;
this.clearNoSpeechTimeout();
this.isListening = false;
this.state = 'idle';
this.endpointing = null;
this.endOfSpeechHandler = null;
this.awaitingRestart = false;
this.onEndCallbacks.forEach((cb) => cb());
};
}
@@ -292,6 +392,7 @@ export class WebSpeechRecognizer {
}
this.finalTranscript = '';
this.interimTranscript = '';
this.state = 'listening';
this.clearInactivityTimeout();
this.clearNoSpeechTimeout();
@@ -301,6 +402,16 @@ export class WebSpeechRecognizer {
this.endOfSpeechHandler = options.onEndOfSpeech ?? null;
this.pendingEndOfSpeechReason = null;
this.endOfSpeechEmitted = false;
this.restartCount = 0;
this.restartStartedAt = 0;
this.sessionHadSpeech = false;
this.awaitingRestart = false;
this.stopRequested = false;
this.fatalErrorRaised = false;
this.suppressStartCallbacks = false;
const noSpeechTimeoutMs = this.endpointing?.noSpeechTimeoutMs ?? 0;
this.noSpeechDeadlineAt = noSpeechTimeoutMs > 0 ? Date.now() + noSpeechTimeoutMs : null;
if (options.language) {
this.recognition.lang = options.language;
@@ -349,6 +460,8 @@ export class WebSpeechRecognizer {
}
stop(): void {
this.stopRequested = true;
this.awaitingRestart = false;
this.clearInactivityTimeout();
this.clearNoSpeechTimeout();
if (this.recognition) {
@@ -362,6 +475,8 @@ export class WebSpeechRecognizer {
}
abort(): void {
this.stopRequested = true;
this.awaitingRestart = false;
this.clearInactivityTimeout();
this.clearNoSpeechTimeout();
if (this.recognition) {
@@ -375,6 +490,7 @@ export class WebSpeechRecognizer {
this.state = 'idle';
this.isListening = false;
this.finalTranscript = '';
this.interimTranscript = '';
this.endpointing = null;
this.endOfSpeechHandler = null;
this.pendingEndOfSpeechReason = null;
@@ -416,6 +532,9 @@ export class WebSpeechRecognizer {
this.endOfSpeechHandler = null;
this.pendingEndOfSpeechReason = null;
this.endOfSpeechEmitted = true;
this.noSpeechDeadlineAt = null;
this.awaitingRestart = false;
this.suppressStartCallbacks = false;
this.onResultCallbacks = [];
this.onInterimResultCallbacks = [];
this.onErrorCallbacks = [];