diff --git a/apps/mobile/src/i18n/translations/de.json b/apps/mobile/src/i18n/translations/de.json index 5adf7cae2b1f0..218614ddf5a6f 100644 --- a/apps/mobile/src/i18n/translations/de.json +++ b/apps/mobile/src/i18n/translations/de.json @@ -872,6 +872,7 @@ "ade1c07a7b86bc75": "Versionskontrollaktion wird ausgeführt", "bd89398fa7d11169": "Die Versionskontrollaktion ist fehlgeschlagen.", "fac0a7eeb4021001": "{hook} wird ausgeführt...", + "fa6a84f05e3ec11c": "Diese Aufnahme konnte nicht transkribiert werden. Sie wurde für einen neuen Versuch behalten.", "8822e2c36699fc5d": "Für die Spracheingabe ist Mikrofonzugriff erforderlich. Erlaube den Zugriff in den Browser- oder Systemeinstellungen und versuche es erneut.", "124a9122bc3ecf5c": "Die Sprachtranskription wird noch abgeschlossen. Versuche es gleich noch einmal.", "a4727d05b33fe336": "Die Sprachtranskription ist für diese Sprache nicht verfügbar.", diff --git a/apps/mobile/src/i18n/translations/en.json b/apps/mobile/src/i18n/translations/en.json index 44804860b704d..d759359401f71 100644 --- a/apps/mobile/src/i18n/translations/en.json +++ b/apps/mobile/src/i18n/translations/en.json @@ -872,6 +872,7 @@ "ade1c07a7b86bc75": "Running source control action", "bd89398fa7d11169": "Source control action failed.", "fac0a7eeb4021001": "Running {hook}...", + "fa6a84f05e3ec11c": "Could not transcribe this recording. It was kept for a retry.", "8822e2c36699fc5d": "Microphone access is required for voice input. Allow access in your browser or system settings and try again.", "124a9122bc3ecf5c": "Voice transcription is still finishing. Try again shortly.", "a4727d05b33fe336": "Voice transcription is not available for this language.", diff --git a/apps/mobile/src/i18n/translations/es.json b/apps/mobile/src/i18n/translations/es.json index b89e4cd636b2e..dd13c12a2cf7d 100644 --- a/apps/mobile/src/i18n/translations/es.json +++ b/apps/mobile/src/i18n/translations/es.json @@ -872,6 +872,7 @@ "ade1c07a7b86bc75": "Ejecutando la acción de control de versiones", "bd89398fa7d11169": "Falló la acción de control de versiones.", "fac0a7eeb4021001": "Ejecutando {hook}...", + "fa6a84f05e3ec11c": "No se pudo transcribir esta grabación. Se ha conservado para volver a intentarlo.", "8822e2c36699fc5d": "La entrada de voz necesita acceso al micrófono. Permite el acceso en los ajustes del navegador o del sistema y vuelve a intentarlo.", "124a9122bc3ecf5c": "La transcripción de voz aún está terminando. Vuelve a intentarlo en breve.", "a4727d05b33fe336": "La transcripción de voz no está disponible para este idioma.", diff --git a/apps/mobile/src/i18n/translations/fr.json b/apps/mobile/src/i18n/translations/fr.json index 75e6c8ed3b83f..90889181796d0 100644 --- a/apps/mobile/src/i18n/translations/fr.json +++ b/apps/mobile/src/i18n/translations/fr.json @@ -872,6 +872,7 @@ "ade1c07a7b86bc75": "Exécution de l’action de gestion de versions", "bd89398fa7d11169": "Échec de l’action de gestion de versions.", "fac0a7eeb4021001": "Exécution de {hook}...", + "fa6a84f05e3ec11c": "Impossible de transcrire cet enregistrement. Il a été conservé pour une nouvelle tentative.", "8822e2c36699fc5d": "L’accès au micro est nécessaire pour la saisie vocale. Autorisez-le dans les paramètres de votre navigateur ou de votre système, puis réessayez.", "124a9122bc3ecf5c": "La transcription vocale n’est pas encore terminée. Réessayez dans un instant.", "a4727d05b33fe336": "La transcription vocale n’est pas disponible pour cette langue.", diff --git a/apps/mobile/src/i18n/translations/ja.json b/apps/mobile/src/i18n/translations/ja.json index ade01f9a68ae8..60a1abc5a6e44 100644 --- a/apps/mobile/src/i18n/translations/ja.json +++ b/apps/mobile/src/i18n/translations/ja.json @@ -872,6 +872,7 @@ "ade1c07a7b86bc75": "ソース管理の操作を実行しています", "bd89398fa7d11169": "ソース管理のアクションに失敗しました。", "fac0a7eeb4021001": "{hook} を実行しています...", + "fa6a84f05e3ec11c": "この録音を文字起こしできませんでした。再試行できるよう保持されています。", "8822e2c36699fc5d": "音声入力にはマイクへのアクセスが必要です。ブラウザーまたはシステムの設定でアクセスを許可してから、もう一度お試しください。", "124a9122bc3ecf5c": "音声の文字起こしがまだ終わっていません。しばらくしてからもう一度お試しください。", "a4727d05b33fe336": "この言語では音声の文字起こしを利用できません。", diff --git a/apps/mobile/src/i18n/translations/ko.json b/apps/mobile/src/i18n/translations/ko.json index e55249e7c76d5..a07b8caf9f534 100644 --- a/apps/mobile/src/i18n/translations/ko.json +++ b/apps/mobile/src/i18n/translations/ko.json @@ -872,6 +872,7 @@ "ade1c07a7b86bc75": "소스 제어 작업 실행 중", "bd89398fa7d11169": "소스 제어 작업에 실패했습니다.", "fac0a7eeb4021001": "{hook} 실행 중...", + "fa6a84f05e3ec11c": "이 녹음을 받아쓰지 못했습니다. 다시 시도할 수 있도록 보관했습니다.", "8822e2c36699fc5d": "음성 입력에는 마이크 액세스 권한이 필요합니다. 브라우저 또는 시스템 설정에서 액세스를 허용한 후 다시 시도하세요.", "124a9122bc3ecf5c": "음성 받아쓰기를 아직 마무리하는 중입니다. 잠시 후 다시 시도하세요.", "a4727d05b33fe336": "이 언어에서는 음성 받아쓰기를 사용할 수 없습니다.", diff --git a/apps/mobile/src/i18n/translations/pt-BR.json b/apps/mobile/src/i18n/translations/pt-BR.json index e373faf86a051..e3da041cac848 100644 --- a/apps/mobile/src/i18n/translations/pt-BR.json +++ b/apps/mobile/src/i18n/translations/pt-BR.json @@ -872,6 +872,7 @@ "ade1c07a7b86bc75": "Executando ação de controle de versão", "bd89398fa7d11169": "A ação de controle de versão falhou.", "fac0a7eeb4021001": "Executando {hook}...", + "fa6a84f05e3ec11c": "Não foi possível transcrever esta gravação. Ela foi mantida para uma nova tentativa.", "8822e2c36699fc5d": "É necessário acesso ao microfone para a entrada de voz. Permita o acesso nas configurações do navegador ou do sistema e tente novamente.", "124a9122bc3ecf5c": "A transcrição de voz ainda está terminando. Tente novamente em instantes.", "a4727d05b33fe336": "A transcrição de voz não está disponível para este idioma.", diff --git a/apps/mobile/src/i18n/translations/ru.json b/apps/mobile/src/i18n/translations/ru.json index c56ae7ca47388..32b4d96f575e4 100644 --- a/apps/mobile/src/i18n/translations/ru.json +++ b/apps/mobile/src/i18n/translations/ru.json @@ -872,6 +872,7 @@ "ade1c07a7b86bc75": "Выполнение действия контроля версий", "bd89398fa7d11169": "Ошибка действия контроля версий.", "fac0a7eeb4021001": "Выполняется {hook}...", + "fa6a84f05e3ec11c": "Не удалось расшифровать эту запись. Она сохранена для повторной попытки.", "8822e2c36699fc5d": "Для голосового ввода нужен доступ к микрофону. Разрешите доступ в настройках браузера или системы и повторите попытку.", "124a9122bc3ecf5c": "Расшифровка голоса ещё не завершена. Повторите чуть позже.", "a4727d05b33fe336": "Расшифровка голоса недоступна для этого языка.", diff --git a/apps/mobile/src/i18n/translations/sv.json b/apps/mobile/src/i18n/translations/sv.json index 7887ac576fc11..fce5214b3528f 100644 --- a/apps/mobile/src/i18n/translations/sv.json +++ b/apps/mobile/src/i18n/translations/sv.json @@ -872,6 +872,7 @@ "ade1c07a7b86bc75": "Kör versionshanteringsåtgärd", "bd89398fa7d11169": "Versionshanteringsåtgärden misslyckades.", "fac0a7eeb4021001": "Kör {hook}...", + "fa6a84f05e3ec11c": "Det gick inte att transkribera inspelningen. Den sparades så att du kan försöka igen.", "8822e2c36699fc5d": "Mikrofonåtkomst krävs för röstinmatning. Tillåt åtkomst i webbläsarens eller systemets inställningar och försök igen.", "124a9122bc3ecf5c": "Rösttranskriberingen håller fortfarande på att slutföras. Försök igen snart.", "a4727d05b33fe336": "Rösttranskribering är inte tillgänglig för det här språket.", diff --git a/apps/mobile/src/i18n/translations/zh.json b/apps/mobile/src/i18n/translations/zh.json index 5b3d7f7841bfd..84c8afdb94540 100644 --- a/apps/mobile/src/i18n/translations/zh.json +++ b/apps/mobile/src/i18n/translations/zh.json @@ -872,6 +872,7 @@ "ade1c07a7b86bc75": "正在运行版本控制操作", "bd89398fa7d11169": "版本控制操作失败。", "fac0a7eeb4021001": "正在运行 {hook}...", + "fa6a84f05e3ec11c": "无法转写此录音。录音已保留,可以重试。", "8822e2c36699fc5d": "语音输入需要麦克风权限。请在浏览器或系统设置中允许访问后重试。", "124a9122bc3ecf5c": "语音转写仍在收尾,请稍后重试。", "a4727d05b33fe336": "这种语言暂不支持语音转写。", diff --git a/apps/server/src/speech/SpeechService.test.ts b/apps/server/src/speech/SpeechService.test.ts index 7fb31140db4d0..2a30cb5313dfb 100644 --- a/apps/server/src/speech/SpeechService.test.ts +++ b/apps/server/src/speech/SpeechService.test.ts @@ -818,24 +818,36 @@ it.effect( }), ); -it.effect("reports a failure on a GPU the person chose instead of switching to CPU", () => - Effect.gen(function* () { - const failure = new Error("GPU failed"); - native.transcribe.mockRejectedValueOnce(failure); - const speech = yield* SpeechService.SpeechService; - const acceleration = 'gpu:["vulkan","gpu-1"]'; - yield* speech.updateAcceleration(acceleration); - const result = yield* Effect.result( - speech.transcribe(pcm(), DEFAULT_SPEECH_TRANSCRIPTION_OPTIONS), - ); - expect(Result.isFailure(result) && result.failure).toMatchObject({ - _tag: "SpeechOperationError", - operation: "inference", - cause: failure, - }); - expect(loadNative).toHaveBeenCalledTimes(1); - expect(loadNative.mock.calls[0]?.[3]).toBe(acceleration); - }).pipe(Effect.provide(layer)), +it.effect.each([ + ['gpu:["vulkan","gpu-1"]', "cpu"], + ["cpu", "auto"], +] as const)( + "retries a recording from a chosen %s on %s only when fallback is on", + ([acceleration, other]) => + Effect.gen(function* () { + const speech = yield* SpeechService.SpeechService; + for (const failing of ["model preparation", "inference"] as const) + for (const fallback of [false, true]) { + loadNative.mockClear(); + const failure = new Error("device failed"); + if (failing === "inference") native.transcribe.mockRejectedValueOnce(failure); + else loadNative.mockRejectedValueOnce(failure); + yield* speech.updateAcceleration(acceleration, fallback); + const result = yield* Effect.result( + speech.transcribe(pcm(), DEFAULT_SPEECH_TRANSCRIPTION_OPTIONS), + ); + if (fallback) expect(Result.isSuccess(result) && result.success).toBe("hello"); + else + expect(Result.isFailure(result) && result.failure).toMatchObject({ + _tag: "SpeechOperationError", + operation: failing, + cause: failure, + }); + expect(loadNative.mock.calls.map((call) => call[3])).toEqual( + fallback ? [acceleration, other] : [acceleration], + ); + } + }).pipe(Effect.provide(layer)), ); it.effect("replays streamed audio on CPU after an Auto-placed feed crashes, once", () => @@ -950,9 +962,15 @@ it.effect.each([false, true])( }).pipe(Effect.provide(layer)), ); -it.effect.each(["auto", 'gpu:["vulkan","gpu-1"]', "cpu"] as const)( - "reports finalization failure without repeated or explicit-backend fallback: %s", - (acceleration) => +it.effect.each([ + ["auto", false], + ['gpu:["vulkan","gpu-1"]', false], + ["cpu", false], + ['gpu:["vulkan","gpu-1"]', true], + ["cpu", true], +] as const)( + "reports finalization failure after at most one fallback: %s, fallback %s", + ([acceleration, fallback]) => Effect.gen(function* () { const failure = new Error("finish failed"); const worker = { @@ -962,15 +980,24 @@ it.effect.each(["auto", 'gpu:["vulkan","gpu-1"]', "cpu"] as const)( throw failure; }), }; - const cpu = { ...worker, backend: "CPU", dispose: vi.fn() }; + const other = { + ...worker, + backend: acceleration === "cpu" ? "Vulkan0" : "CPU", + dispose: vi.fn(), + }; + const retries = acceleration === "auto" || fallback; loadNative.mockResolvedValueOnce(worker); - if (acceleration === "auto") loadNative.mockResolvedValueOnce(cpu); + if (retries) loadNative.mockResolvedValueOnce(other); const speech = yield* SpeechService.SpeechService; - yield* speech.updateAcceleration(acceleration); + yield* speech.updateAcceleration(acceleration, fallback); const stream = yield* speech.startStream(DEFAULT_SPEECH_TRANSCRIPTION_OPTIONS); expect(Result.isFailure(yield* Effect.result(stream.finish))).toBe(true); - expect(worker.finish).toHaveBeenCalledTimes(acceleration === "auto" ? 2 : 1); - expect(loadNative).toHaveBeenCalledTimes(acceleration === "auto" ? 2 : 1); + // The failed stream frees the model before its socket closes, so a retry is not busy. + expect(yield* speech.status).toMatchObject({ state: "ready" }); + expect(worker.finish).toHaveBeenCalledTimes(retries ? 2 : 1); + expect(loadNative.mock.calls.map((call) => call[3])).toEqual( + retries ? [acceleration, acceleration === "cpu" ? "auto" : "cpu"] : [acceleration], + ); }).pipe(Effect.scoped, Effect.provide(layer)), ); diff --git a/apps/server/src/speech/SpeechService.ts b/apps/server/src/speech/SpeechService.ts index ba25233a32c7e..52926c4a9304d 100644 --- a/apps/server/src/speech/SpeechService.ts +++ b/apps/server/src/speech/SpeechService.ts @@ -157,6 +157,7 @@ export class SpeechService extends Context.Service< ) => Effect.Effect; readonly updateAcceleration: ( acceleration: SpeechAcceleration, + fallback?: boolean, ) => Effect.Effect; readonly updateModelUnloadTimeout: ( timeout: SpeechModelUnloadTimeout, @@ -245,9 +246,16 @@ const make = Effect.gen(function* () { }; // Auto placement may land on a GPU the native engine cannot actually run; one retry on - // this host's CPU recovers it. A GPU the person chose, and CPU itself, report the error. - const canRetryOnCpu = (acceleration: SpeechAcceleration, loaded: LoadedModel) => - acceleration === "auto" && loaded.backend.toLowerCase() !== "cpu"; + // this host's CPU recovers it. A device the person chose retries on the other only when allowed. + const fallbackFor = ( + settings: { speechAcceleration: SpeechAcceleration; speechAccelerationFallback: boolean }, + loaded: LoadedModel, + ) => { + const onCpu = loaded.backend.toLowerCase() === "cpu"; + if (settings.speechAcceleration === "auto") return onCpu ? undefined : "cpu"; + if (!settings.speechAccelerationFallback) return undefined; + return onCpu ? "auto" : "cpu"; + }; yield* Effect.addFinalizer(() => Effect.promise(async () => { @@ -404,6 +412,28 @@ const make = Effect.gen(function* () { } }; + // The loader already retries "auto" on the CPU; a chosen device needs the person's fallback. + const loadSelected = async ( + modelPath: string, + definition: SpeechModel, + signal: AbortSignal, + settings: { speechAcceleration: SpeechAcceleration; speechAccelerationFallback: boolean }, + ) => { + try { + return await loadModel(modelPath, definition, signal, settings.speechAcceleration); + } catch (cause) { + const { speechAcceleration, speechAccelerationFallback } = settings; + if (speechAcceleration === "auto" || !speechAccelerationFallback) throw cause; + if (signal.aborted || isSpeechError(cause)) throw cause; + return await loadModel( + modelPath, + definition, + signal, + speechAcceleration === "cpu" ? "auto" : "cpu", + ); + } + }; + const speechError = (operation: string, cause: unknown): SpeechError => isSpeechError(cause) ? cause : new SpeechOperationError({ operation, cause }); @@ -481,6 +511,7 @@ const make = Effect.gen(function* () { languages: definition.languages, supportsLanguageDetection: definition.supportsLanguageDetection, acceleration: settings.speechAcceleration, + accelerationFallback: settings.speechAccelerationFallback, benchmarkTier: settings.speechAcceleration === "cpu" || (settings.speechAcceleration === "auto" && autoUsesCpu) @@ -567,11 +598,11 @@ const make = Effect.gen(function* () { Effect.andThen(installedModelPath(selectedModel(settings))), Effect.flatMap((modelPath) => attempt("model preparation", (signal) => - loadModel( + loadSelected( modelPath, selectedModel(settings), AbortSignal.any([signal, lifetime.signal]), - settings.speechAcceleration, + settings, ), ).pipe( Effect.timeout("2 minutes"), @@ -619,11 +650,11 @@ const make = Effect.gen(function* () { const modelPath = yield* installedModelPath(definition); const loaded = yield* Effect.tryPromise({ try: (signal) => - loadModel( + loadSelected( modelPath, definition, AbortSignal.any([signal, lifetime.signal]), - settings.speechAcceleration, + settings, ), catch: (cause) => speechError("model preparation", cause), }); @@ -664,21 +695,22 @@ const make = Effect.gen(function* () { let inference = loaded; const result = yield* transcribeWith(loaded).pipe( Effect.catch((error) => { - if (!canRetryOnCpu(settings.speechAcceleration, loaded)) return Effect.fail(error); + const fallback = fallbackFor(settings, loaded); + if (!fallback) return Effect.fail(error); return Effect.tryPromise({ try: (signal) => loadModel( modelPath, definition, AbortSignal.any([signal, lifetime.signal]), - "cpu", + fallback, ), catch: (cause) => speechError("model preparation", cause), }).pipe( - Effect.flatMap((cpu) => { - autoCpuModel = definition.id; - inference = cpu; - return transcribeWith(cpu); + Effect.flatMap((other) => { + if (settings.speechAcceleration === "auto") autoCpuModel = definition.id; + inference = other; + return transcribeWith(other); }), ); }), @@ -764,7 +796,7 @@ const make = Effect.gen(function* () { let correct = makeSpeechTextCorrector(customWords, dictionary); const modelPath = yield* installedModelPath(definition); let streamModel = yield* attempt(operation, () => - loadModel(modelPath, definition, signal, settings.speechAcceleration), + loadSelected(modelPath, definition, signal, settings), ); loaded = streamModel; const vadPath = yield* silenceModelPath(streamModel, options, streamModel.supportsStreaming); @@ -793,19 +825,19 @@ const make = Effect.gen(function* () { correct = makeSpeechTextCorrector(vocabulary ? [] : customWords, dictionary); started = true; }; - // Audio already fed is kept so a CPU restart can replay it; the limit caps it at one recording. + // Audio already fed is kept so a fallback restart can replay it; the limit caps it at one recording. const received: Float32Array[] = []; - let retriedOnCpu = false; - const recoverOnCpu = async (cause: unknown) => { + let recovered = false; + const recover = async (cause: unknown) => { started = false; - if (closed || signal.aborted || retriedOnCpu) throw cause; - if (!canRetryOnCpu(settings.speechAcceleration, streamModel)) throw cause; - retriedOnCpu = true; + const fallback = fallbackFor(settings, streamModel); + if (closed || signal.aborted || recovered || !fallback) throw cause; + recovered = true; forgetModel(streamModel); await streamModel.dispose(); if (closed || signal.aborted) throw cause; - streamModel = await loadModel(modelPath, definition, signal, "cpu"); - autoCpuModel = definition.id; + streamModel = await loadModel(modelPath, definition, signal, fallback); + if (settings.speechAcceleration === "auto") autoCpuModel = definition.id; loaded = streamModel; await beginStream(); let update: Awaited> | undefined; @@ -819,7 +851,7 @@ const make = Effect.gen(function* () { try { await beginStream(); } catch (cause) { - await recoverOnCpu(cause); + await recover(cause); } }); let byteLength = 0; @@ -856,7 +888,7 @@ const make = Effect.gen(function* () { try { update = await streamModel.feed(pcm); } catch (cause) { - update = await recoverOnCpu(cause); + update = await recover(cause); revisionBase += lastNativeRevision; lastNativeRevision = 0; } @@ -875,7 +907,7 @@ const make = Effect.gen(function* () { let text: string; try { text = await streamModel.finish().catch(async (cause: unknown) => { - await recoverOnCpu(cause); + await recover(cause); if (closed || signal.aborted) throw cause; return streamModel.finish(); }); @@ -900,10 +932,14 @@ const make = Effect.gen(function* () { transcribe, startStream: Effect.fn("SpeechService.startStream")(function* (options) { const session = yield* Scope.fork(yield* Effect.scope); - return yield* openStream(options).pipe( - Scope.provide(session), - Effect.onError((cause) => Scope.close(session, Exit.failCause(cause))), - ); + const closeOnError = (effect: Effect.Effect) => + effect.pipe(Effect.onError((cause) => Scope.close(session, Exit.failCause(cause)))); + const stream = yield* closeOnError(openStream(options).pipe(Scope.provide(session))); + // A failed stream frees the model before the client hears of it, so its retry is not busy. + return { + feed: (pcm: Uint8Array) => closeOnError(stream.feed(pcm)), + finish: closeOnError(stream.finish), + }; }), downloadModel: Effect.fn("SpeechService.downloadModel")(function* (modelId) { yield* requireSupported; @@ -973,10 +1009,11 @@ const make = Effect.gen(function* () { yield* writeSettings("model linking", { speechModelId: first }); return yield* modelsEffect; }), - updateAcceleration: Effect.fn("SpeechService.updateAcceleration")((acceleration) => - writeSettings("acceleration update", { speechAcceleration: acceleration }).pipe( - Effect.andThen(freshStatus("acceleration update")), - ), + updateAcceleration: Effect.fn("SpeechService.updateAcceleration")((acceleration, fallback) => + writeSettings("acceleration update", { + speechAcceleration: acceleration, + ...(fallback === undefined ? {} : { speechAccelerationFallback: fallback }), + }).pipe(Effect.andThen(freshStatus("acceleration update"))), ), updateModelUnloadTimeout: Effect.fn("SpeechService.updateModelUnloadTimeout")((timeout) => writeSettings("model unload timeout update", { speechModelUnloadTimeout: timeout }).pipe( diff --git a/apps/server/src/speech/http.ts b/apps/server/src/speech/http.ts index 09c3d4dc23faa..2e771afc3f720 100644 --- a/apps/server/src/speech/http.ts +++ b/apps/server/src/speech/http.ts @@ -208,7 +208,9 @@ export const speechHttpApiLayer = HttpApiBuilder.group( "updateAcceleration", Effect.fn("environment.voice.updateAcceleration")(function* (args) { yield* guard(args.endpoint.name, AuthSettingsWriteScope); - return yield* speech.updateAcceleration(args.payload.acceleration).pipe(mapSpeechError); + return yield* speech + .updateAcceleration(args.payload.acceleration, args.payload.fallback) + .pipe(mapSpeechError); }), ) .handle( diff --git a/apps/server/src/speech/native.test.ts b/apps/server/src/speech/native.test.ts index cb7254891a51b..5341084b12b3a 100644 --- a/apps/server/src/speech/native.test.ts +++ b/apps/server/src/speech/native.test.ts @@ -55,6 +55,36 @@ it("returns transcription from an isolated process and disposes it", async () => } }); +it("splits a piece the engine could not finish instead of failing the recording", async () => { + for (const error of [ + "OutputTruncated", + "OutputRepetition", + "InputTooLong", + "OutOfMemory", + "BackendError", + ]) { + const model = await loadNativeSpeechModel( + "unused.gguf", + new AbortController().signal, + fixture(`async (pcm) => { + class OutputTruncated extends Error {} + const errors = { OutputTruncated, OutputRepetition: class OutputRepetition extends OutputTruncated {}, + InputTooLong: class InputTooLong extends Error {}, OutOfMemory: class OutOfMemory extends Error {}, + BackendError: class BackendError extends Error {} }; + if (pcm.length > 5000) throw new errors.${error}("too much"); + return { text: String(pcm.length) }; + }`), + ); + try { + expect( + await model.transcribe(new Float32Array(16000), { timestamps: "none" }, false), + ).toEqual({ text: "4000 4000 4000 4000" }); + } finally { + await model.dispose(); + } + } +}); + it("probes generic vocabulary support and delivers ordered terms to offline inference", async () => { for (const supported of [false, true]) { const model = await loadNativeSpeechModel( diff --git a/apps/server/src/speech/native.ts b/apps/server/src/speech/native.ts index 2bd2631c63fba..7c7a7510113dd 100644 --- a/apps/server/src/speech/native.ts +++ b/apps/server/src/speech/native.ts @@ -31,6 +31,13 @@ const newAudio = (filterSilence) => createSpeechAudio({ frameSamples: 512, filterSilence, nativeStreaming, longForm: model.supports("long_form"), maxAudioMs: model.capabilities.maxAudioMs, }); +// Matched by class name: OutputRepetition extends OutputTruncated, and smaller input needs less memory. +const splittable = new Set(["OutputTruncated", "InputTooLong", "OutOfMemory", "BackendError"]); +const canSplit = (error) => { + for (let proto = error && Object.getPrototypeOf(error); proto; proto = Object.getPrototypeOf(proto)) + if (splittable.has(proto.constructor?.name)) return true; + return false; +}; const openAsr = async () => { if (nativeStreaming) { session = model.createSession(); @@ -71,8 +78,7 @@ const transcribe = async (pcm) => { const result = await model.transcribe(pcm, options); texts.push(result.text); } catch (error) { - if ((error?.constructor?.name !== "OutputTruncated" && - error?.constructor?.name !== "InputTooLong") || pcm.length <= 4000) throw error; + if (!canSplit(error) || pcm.length <= 4000) throw error; const middle = Math.floor(pcm.length / 2); await transcribe(pcm.subarray(0, middle)); await transcribe(pcm.subarray(middle)); diff --git a/apps/web/src/components/settings/VoiceSettingsPanel.tsx b/apps/web/src/components/settings/VoiceSettingsPanel.tsx index 84a76f373c8be..6d9b142df03e3 100644 --- a/apps/web/src/components/settings/VoiceSettingsPanel.tsx +++ b/apps/web/src/components/settings/VoiceSettingsPanel.tsx @@ -869,6 +869,30 @@ function AdvancedSpeechSettings({ } /> + {supported.acceleration !== "auto" && supported.accelerationFallback !== undefined ? ( + + void run(gt("Could not change the hardware fallback"), () => + runEnvironmentSpeech( + updateEnvironmentSpeechAcceleration(prepared, supported.acceleration, checked), + ), + ) + } + /> + } + /> + ) : null} { stopped?.reject(new Error(m(msg("Microphone processing failed.")))); @@ -166,7 +167,7 @@ export function createBrowserPcmCapture( worklet.port.postMessage("stop"); try { await pending; - if (!feed && chunks.length) { + if (chunks.length) { const blob = new Blob(chunks, { type: "application/octet-stream" }); recordingUri = URL.createObjectURL(blob); } @@ -201,8 +202,8 @@ export function createBrowserPcmCapture( if (canStream() && prepared.streaming) { streaming = prepared.streaming; feed = prepared.streaming.feed; + // The opening audio stays in chunks: it belongs to the kept recording too. for (const chunk of chunks) feed(chunk); - chunks = []; } return prepared; }) diff --git a/apps/web/src/speech/browserVoiceInput.browser.test.ts b/apps/web/src/speech/browserVoiceInput.browser.test.ts index 5f3023a635240..446fb3ee5a0e5 100644 --- a/apps/web/src/speech/browserVoiceInput.browser.test.ts +++ b/apps/web/src/speech/browserVoiceInput.browser.test.ts @@ -198,6 +198,106 @@ it("retains all PCM until stop, retries batch audio, and captures preferences be expect(platform.recorder.uri).toBeNull(); }); +it("keeps recording when the environment refuses the live stream and transcribes the kept audio", async () => { + using microphone = capture(); + // What a busy or failing environment sends for a stream it cannot run (speech/stream.ts). + const refusal = "Live transcription failed. Please try recording again."; + const refused = Promise.withResolvers(); + using _socket = stubGlobal( + "WebSocket", + class extends EventTarget { + constructor() { + super(); + queueMicrotask(() => this.dispatchEvent(new Event("open"))); + } + send(data: unknown) { + if (typeof data !== "string" || !data.includes('"start"')) return; + queueMicrotask(() => { + this.dispatchEvent( + new MessageEvent("message", { + data: JSON.stringify({ type: "error", message: refusal }), + }), + ); + this.dispatchEvent(new Event("close")); + refused.resolve(); + }); + } + close() {} + }, + ); + const requests: Uint8Array[] = []; + const fetch = globalThis.fetch; + using _network = vi.spyOn(globalThis, "fetch").mockImplementation(async (input, init) => { + const request = new Request(input, init); + if (request.url === `${prepared.httpBaseUrl}/api/voice/status`) return Response.json(status); + if (request.url.includes("/api/auth/websocket-ticket/")) + return Response.json({ ticket: "stream-ticket", expiresAt: "2030-01-01T00:00:00.000Z" }); + if (request.url === `${prepared.httpBaseUrl}/api/voice/transcribe`) { + requests.push(decodeSpeechPcmRequest(new Uint8Array(await request.arrayBuffer())).pcm); + return requests.length === 1 + ? new Response(null, { status: 503 }) + : Response.json({ text: "hello" }); + } + return fetch(input, init); + }); + let controller!: VoiceInputController; + const platform = createBrowserVoiceInputPlatform({ + prepared, + hasAudioConsent: () => true, + getStreamingEnabled: () => true, + getTranscriptionOptions: () => DEFAULT_SPEECH_TRANSCRIPTION_OPTIONS, + getMicrophoneId: () => "", + onLevel() {}, + onDurationLimit() {}, + onText() {}, + // Wired as in voiceInputSession.ts. + onError: (message, code) => void controller.interruptRecording(message, null, code), + }); + const commitDraft = vi.fn(); + controller = new VoiceInputController({ + recorder: platform.recorder, + retryFailedRecording: true, + getTranscriber: () => platform.transcriber, + requestPermission: async () => ({ granted: true, canAskAgain: true }), + configureRecording: async () => {}, + releaseRecording: async () => platform.cancelRecording(), + deleteRecording: platform.deleteRecording, + readDraft: () => ({ + ownerKey: "draft", + text: "", + selection: { start: 0, end: 0 }, + revision: 0, + }), + commitDraft, + onStateChange() {}, + }); + using _controller = { [Symbol.dispose]: () => controller.dispose() }; + + await controller.start(); + expect(controller.currentState.phase).toBe("recording"); + microphone.feed(new Float32Array([0.1, 0.2])); + // The refusal arrives while the person is still speaking. + await refused.promise; + expect(controller.currentState).toMatchObject({ phase: "recording", error: null }); + microphone.feed(new Float32Array([0.3])); + + await controller.stop(); + expect(controller.currentState).toMatchObject({ + phase: "error", + errorCode: "transcription-failed", + }); + await controller.start(); + expect(commitDraft).toHaveBeenCalledWith("hello", { start: 5, end: 5 }); + expect(requests).toHaveLength(2); + for (const pcm of requests) + expect([...new Float32Array(pcm.slice().buffer)]).toEqual([ + Math.fround(0.1), + Math.fround(0.2), + Math.fround(0.3), + ]); + expect(platform.recorder.uri).toBeNull(); +}); + it.each([ ["fr", ["en-US"], "fr"], ["auto", ["nl-NL", "en-US"], "en-US"], @@ -289,7 +389,8 @@ it("streams the opening audio in order when the destination becomes ready during microphone.feed(continuing); await platform.recorder.stop(); expect(feed.mock.calls).toEqual([[opening], [continuing]]); - expect(platform.recorder.uri).toBeNull(); + // Streamed audio is kept too, so a failed stream can be transcribed from the recording. + expect(platform.recorder.uri).not.toBeNull(); await expect(transcription.streaming?.finish({ signal: abort.signal })).resolves.toBe("hello"); }); diff --git a/apps/web/src/speech/browserVoiceInput.ts b/apps/web/src/speech/browserVoiceInput.ts index 2d03019ce4ca8..25258372fa566 100644 --- a/apps/web/src/speech/browserVoiceInput.ts +++ b/apps/web/src/speech/browserVoiceInput.ts @@ -141,7 +141,10 @@ export function createBrowserVoiceInputPlatform(input: { options: recordingOptions, signal: options.signal, onText: input.onText, - onError: (error) => input.onError(error.message), + // Recording continues after a stream failure; finishing retries the retained audio. + onError: (error) => { + if (!input.hasAudioConsent()) input.onError(error.message); + }, }), }; }); diff --git a/packages/client-runtime/src/voice-input/controller.test.ts b/packages/client-runtime/src/voice-input/controller.test.ts index 15f5fea3aac76..a77cd670e294e 100644 --- a/packages/client-runtime/src/voice-input/controller.test.ts +++ b/packages/client-runtime/src/voice-input/controller.test.ts @@ -1,6 +1,7 @@ import { beforeEach, describe, expect, it, vi } from "vite-plus/test"; import { + RETAINED_RECORDING_ERROR, resetVoiceInputGlobalsForTests, resolveTranscriptCommit, VoiceInputController, @@ -112,6 +113,62 @@ describe("environment voice input", () => { expect(harness.deleted).toEqual(["file:///voice.m4a"]); }); + it("falls back to the retained recording when a live stream fails, and keeps it for retry", async () => { + const transcribe = vi + .fn() + .mockResolvedValueOnce("recovered text") + .mockRejectedValueOnce(new Error("inference failed")) + .mockResolvedValueOnce("retried text"); + const finish = vi.fn(async () => { + throw new Error("stream failed"); + }); + const harness = createHarness({ + retryFailedRecording: true, + getTranscriber: () => ({ + prepare: async () => ({ ...preparedTranscription(transcribe), streaming: { finish } }), + }), + }); + await harness.controller.start(); + await harness.controller.stop(); + expect(harness.commits.map(({ text }) => text)).toEqual(["hello recovered text"]); + expect(harness.deleted).toEqual(["file:///voice.m4a"]); + + harness.deleted.length = 0; + await harness.controller.start(); + await harness.controller.stop(); + expect(harness.controller.currentState).toMatchObject({ phase: "error", errorAction: "retry" }); + expect(harness.deleted).toEqual([]); + await harness.controller.start(); + expect(finish).toHaveBeenCalledTimes(2); + expect(transcribe).toHaveBeenCalledTimes(3); + expect(harness.recorder.record).toHaveBeenCalledTimes(2); + expect(harness.commits.map(({ text }) => text)).toEqual([ + "hello recovered text", + "hello retried text", + ]); + expect(harness.deleted).toEqual(["file:///voice.m4a"]); + }); + + it("offers a transcription retry only when the failed recording was kept", async () => { + for (const retryFailedRecording of [true, false]) { + resetVoiceInputGlobalsForTests(); + const fail = async () => { + throw new Error("failed"); + }; + const harness = createHarness({ + retryFailedRecording, + getTranscriber: () => ({ + prepare: async () => ({ ...preparedTranscription(fail), streaming: { finish: fail } }), + }), + }); + await harness.controller.start(); + await harness.controller.stop(); + expect(harness.controller.currentState.error === RETAINED_RECORDING_ERROR).toBe( + retryFailedRecording, + ); + } + }); + it("deletes retained failed audio when the user cancels instead of retrying", async () => { const harness = createHarness({ retryFailedRecording: true, diff --git a/packages/client-runtime/src/voice-input/controller.ts b/packages/client-runtime/src/voice-input/controller.ts index 372bfd2a9ad08..d77633536d421 100644 --- a/packages/client-runtime/src/voice-input/controller.ts +++ b/packages/client-runtime/src/voice-input/controller.ts @@ -14,6 +14,11 @@ const isVoiceTranscriptionError = Schema.is(VoiceTranscriptionError); export const VOICE_RECORDING_LIMIT_SECONDS = 5 * 60; +/** The recording is kept, so retrying transcribes it again without recording. */ +export const RETAINED_RECORDING_ERROR = msg( + "Could not transcribe this recording. It was kept for a retry.", +); + export const MICROPHONE_PERMISSION_ERROR = msg( "Microphone access is required for voice input. Allow access in your browser or system settings and try again.", ); @@ -598,32 +603,44 @@ export class VoiceInputController { const signal = this.transcriptionAbortController.signal; const capturedDraft = this.capturedDraft; let transcript: string; + const transcribeRecording = () => + runTranscriptionOperation(() => transcription.transcribe(recordingUri!, { signal })); try { const live = this.liveTranscription ? await this.liveTranscription : null; if (live && "error" in live) throw live.error; + const streaming = transcription.streaming; transcript = live?.text ?? - (await runTranscriptionOperation(() => - transcription.streaming - ? transcription.streaming.finish({ signal }) - : transcription.transcribe(recordingUri!, { signal }), - )); + (streaming + ? await runTranscriptionOperation(() => streaming.finish({ signal })).catch( + (error: unknown) => { + // A failed live stream gets one pass over the retained recording. + if (!recordingUri || signal.aborted || !this.isCurrent(operationToken)) + throw error; + return transcribeRecording(); + }, + ) + : await transcribeRecording()); } catch (error) { if (this.isCurrent(operationToken)) { - if ( + const retained = this.dependencies.retryFailedRecording && errorCode(error) !== "preparation-failed" && !this.liveTranscription && - !transcription.streaming && - recordingUri - ) { + recordingUri; + if (retained) { this.retryRecording = { uri: recordingUri, ownerKey: capturedDraft.ownerKey, - transcription, + transcription: { locale: transcription.locale, transcribe: transcription.transcribe }, }; } - this.setFailure(transcriptionFailure(error, this.resolve), "retry"); + this.setFailure( + retained + ? { message: this.text(RETAINED_RECORDING_ERROR), code: "transcription-failed" } + : transcriptionFailure(error, this.resolve), + "retry", + ); } return; } diff --git a/packages/client-runtime/src/voice-input/environment.ts b/packages/client-runtime/src/voice-input/environment.ts index 2aa18a7beb5a5..191728a0ffebd 100644 --- a/packages/client-runtime/src/voice-input/environment.ts +++ b/packages/client-runtime/src/voice-input/environment.ts @@ -290,13 +290,18 @@ export const postProcessEnvironmentTranscript = ( export const updateEnvironmentSpeechAcceleration = ( prepared: PreparedConnection, acceleration: SpeechAcceleration, + fallback?: boolean, ) => request({ group: "voice", prepared, method: "POST", path: (urls) => urls.updateAcceleration(), - run: ({ client, headers }) => client.updateAcceleration({ headers, payload: { acceleration } }), + run: ({ client, headers }) => + client.updateAcceleration({ + headers, + payload: { acceleration, ...(fallback === undefined ? {} : { fallback }) }, + }), }); export const updateEnvironmentSpeechModelUnloadTimeout = ( diff --git a/packages/contracts/src/settings.ts b/packages/contracts/src/settings.ts index b0726b07174c9..909264dd069e0 100644 --- a/packages/contracts/src/settings.ts +++ b/packages/contracts/src/settings.ts @@ -1415,6 +1415,10 @@ export const ServerSettings = Schema.Struct({ Schema.withDecodingDefault(Effect.succeed("handy-computer/parakeet-unified-en-0.6b-gguf")), ), speechAcceleration: SpeechAcceleration.pipe(Schema.withDecodingDefault(Effect.succeed("auto"))), + // A CPU or GPU the person chose may retry a failed recording on the other one. Auto always does. + speechAccelerationFallback: Schema.Boolean.pipe( + Schema.withDecodingDefault(Effect.succeed(false)), + ), speechModelUnloadTimeout: SpeechModelUnloadTimeout.pipe( Schema.withDecodingDefault(Effect.succeed("min_15")), ), @@ -1880,6 +1884,7 @@ export const ServerSettingsPatch = Schema.Struct({ ), speechModelId: Schema.optionalKey(Schema.String), speechAcceleration: Schema.optionalKey(SpeechAcceleration), + speechAccelerationFallback: Schema.optionalKey(Schema.Boolean), speechModelUnloadTimeout: Schema.optionalKey(SpeechModelUnloadTimeout), speechProjectCustomWords: Schema.optionalKey(SpeechCustomWords), speechPostProcessingModelSelection: Schema.optionalKey(Schema.NullOr(ModelSelection)), diff --git a/packages/contracts/src/speech.ts b/packages/contracts/src/speech.ts index 0784c92be4ab6..3a52df7201ffb 100644 --- a/packages/contracts/src/speech.ts +++ b/packages/contracts/src/speech.ts @@ -233,6 +233,7 @@ const SupportedSpeechStatus = Schema.Struct({ languages: Schema.optionalKey(Schema.Array(Schema.String)), supportsLanguageDetection: Schema.optionalKey(Schema.Boolean), acceleration: SpeechAcceleration, + accelerationFallback: Schema.optionalKey(Schema.Boolean), benchmarkTier: SpeechBenchmarkTier, modelUnloadTimeout: SpeechModelUnloadTimeout, gpuDevices: Schema.Array(SpeechGpuDevice), @@ -274,6 +275,7 @@ export const EnvironmentSpeechTranscriptionResult = Schema.Struct({ text: Schema export const EnvironmentSpeechAccelerationRequest = Schema.Struct({ acceleration: SpeechAcceleration, + fallback: Schema.optionalKey(Schema.Boolean), }); export const EnvironmentSpeechModelUnloadTimeoutRequest = Schema.Struct({ timeout: SpeechModelUnloadTimeout,