Skip to content

Voice-to-text dictation app with local (Nvidia Parakeet/Whisper) and cloud models (BYOK). Privacy-first and available cross-platform.

fix(dictation): Keep the capture when managed Orukeet refuses a recording (#2341)

Chad Pihabc46aaf6c70f
diff --git a/src/helpers/audioManager.js b/src/helpers/audioManager.js
index eff2b99ad..7eca16a50 100644
--- a/src/helpers/audioManager.js
+++ b/src/helpers/audioManager.js
@@ -15,6 +15,7 @@ import {
createLocalSpeechGateState,
getLocalSpeechGateDecision,
recordLocalSpeechWindow,
+ recordPcm16SpeechWindow,
} from "./localSpeechGate";
import { reacquireIfDead } from "./micTrackHealth";
import { isMicWarm, WARMUP_ACQUIRE_TIMEOUT_MS } from "./micWarmState";
@@ -83,9 +84,11 @@ import {
resolveSelfHostedTranscriptionModel,
} from "./selfHostedTranscription";
import {
+ isManagedOrukeetStream,
resolveStreamingFallbackTarget,
resolveStreamingStartFallback,
} from "./transcriptionFallback";
+import { transcriptionFailureOutcome } from "./transcriptionFailureOutcome";
import {
executeTranslationChain,
hasTextContent,
@@ -110,7 +113,6 @@ import { evaluateFinishedRecording, withSalvageWarning } from "./recordingValida
import { isEmptyRecording } from "./recordingGuard";
import {
analyzeDictionaryPromptFragment,
- DICTIONARY_ECHO_CODE,
dictionaryEchoError,
matchesDictionaryPrompt,
payloadSendsDictionaryBias,
@@ -160,6 +162,15 @@ const cleanupFailureFromError = (error) => ({
...(error?.technicalDetails ? { technicalDetails: error.technicalDetails } : {}),
});
+const cloudSignInRequiredError = () => {
+ const err = new Error(
+ "OpenWhispr Cloud requires sign-in. Please sign in again or switch to BYOK mode."
+ );
+ err.code = "AUTH_REQUIRED";
+ err.messageKey = "hooks.audioRecording.errorDescriptions.sessionExpired";
+ return err;
+};
+
const micDeviceKey = (settings) =>
`${settings.microphoneSelectionMode}|${settings.selectedMicDeviceId}`;
@@ -639,6 +650,8 @@ class AudioManager {
this.sttConfig = null;
this.sttConfigFetchedAt = null;
this.streamingFallbackReason = null;
+ this._streamingFailoverReason = null;
+ this._streamingSpeechGateState = null;
this.warmupFailureStreak = 0;
this.lastAudioBlob = null;
this.lastAudioMetadata = null;
@@ -2055,14 +2068,7 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);
);
}
} else if (isOpenWhisprCloudMode) {
- if (!isSignedIn) {
- const err = new Error(
- "OpenWhispr Cloud requires sign-in. Please sign in again or switch to BYOK mode."
- );
- err.code = "AUTH_REQUIRED";
- err.messageKey = "hooks.audioRecording.errorDescriptions.sessionExpired";
- throw err;
- }
+ if (!isSignedIn) throw cloudSignInRequiredError();
activeModel = "openwhispr-cloud";
result = await this.processWithOpenWhisprCloud(audioBlob, metadata, wasCancelled);
} else {
@@ -2140,31 +2146,11 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);
"performance"
);
- if (error.code === DICTIONARY_ECHO_CODE) {
- // The transcript was discarded as an echo of the dictionary prompt.
- // Surface the shared soft no-audio outcome and keep the recording for
- // a manual retry — otherwise the whole utterance disappears with no
- // feedback (#1547).
- noAudioDetected = true;
- if (this.lastAudioBlob) {
- this.saveFailedTranscription(error.message, error.code, metadata);
- }
- } else if (error.message === "No audio detected") {
- noAudioDetected = true;
- } else {
- this.onError?.({
- title: error.selectionEditFatal ? "Selection Edit Failed" : "Transcription Error",
- description: error.selectionEditFatal
- ? error.message
- : `Transcription failed: ${error.message}`,
- code: error.code,
- messageKey: error.messageKey,
- });
-
- // Save failed transcription with audio so the user can retry later
- if (this.lastAudioBlob) {
- this.saveFailedTranscription(error.message, error.code || null, metadata);
- }
+ const outcome = transcriptionFailureOutcome(error);
+ noAudioDetected = outcome.noAudio;
+ if (outcome.report) this.onError?.(outcome.report);
+ if (outcome.keepAudio && this.lastAudioBlob) {
+ this.saveFailedTranscription(error.message, error.code || null, metadata);
}
} finally {
const shouldNotifyNoAudio =
@@ -4621,6 +4607,8 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);
sessionId = (this._streamingSessionGeneration || 0) + 1;
this._streamingSessionGeneration = sessionId;
this.streamingFallbackReason = null;
+ this._streamingFailoverReason = null;
+ this._streamingSpeechGateState = createLocalSpeechGateState();
this._activeStreamingSessionId = sessionId;
const ownsSession = () => this._activeStreamingSessionId === sessionId;
const cancellationGeneration = this._streamingCancellationGeneration;
@@ -4685,6 +4673,16 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);
this.streamingProcessor = new AudioWorkletNode(audioContext, "pcm-streaming-processor");
const provider = this.getStreamingProvider();
+ // Decided once, with the provider, so a config refresh mid-recording
+ // cannot change how this session's stream errors are handled. Only a
+ // session whose fallback recorder started has a capture to fail over
+ // to; stop finishes that recorder before a refused commit can arrive.
+ const failsOver =
+ Boolean(this.streamingFallbackRecorder) &&
+ isManagedOrukeetStream({
+ providerName: this.getStreamingProviderName(),
+ cloudTranscriptionMode: getSettings().cloudTranscriptionMode,
+ });
this.streamingProcessor.port.onmessage = (event) => {
// The worklet posts its remaining PCM followed by a "flushed" sentinel
@@ -4695,7 +4693,10 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);
this._streamingFlushResolve?.();
return;
}
- provider.send(event.data);
+ // Measured from the first chunk: a recording that fails over later
+ // still has its opening words in the gate.
+ recordPcm16SpeechWindow(this._streamingSpeechGateState, event.data);
+ if (!this._streamingFailoverReason) provider.send(event.data);
};
this.isStreaming = true;
@@ -4734,6 +4735,14 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);
const errorCleanup = provider.onError((error) => {
if (!ownsSession()) return;
logger.error("Streaming provider error", { error }, "streaming");
+ // Managed Orukeet refuses a second concurrent recording on the account
+ // and can drop a socket mid-recording. The fallback recorder has the
+ // whole capture, so keep recording and let stop upload it to Cloud
+ // rather than cutting the user off behind an error.
+ if (failsOver) {
+ this._streamingFailoverReason ??= "stream_no_final";
+ return;
+ }
this.onError?.({
title: "Streaming Error",
description: error,
@@ -4795,6 +4804,24 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);
this._settleStreamingStart();
if (startWasCancelled()) return false;
+ // A managed Orukeet start failure (refused socket, account cap, outage)
+ // keeps this capture: the fallback recorder has held the audio since the
+ // mic opened, and reopening the mic for a batch recording would lose it.
+ if (result.needsFallback && this.streamingFallbackReason && this.streamingFallbackRecorder) {
+ this._streamingFailoverReason = this.streamingFallbackReason;
+ this.streamingFallbackReason = null;
+ logger.info(
+ "Managed Orukeet unavailable, recording for the Cloud upload",
+ { reason: this._streamingFailoverReason },
+ "streaming"
+ );
+ if (this.stopRequestedDuringStreamingStart) {
+ this.stopRequestedDuringStreamingStart = false;
+ return this.stopStreamingRecording();
+ }
+ return true;
+ }
+
if (result.needsFallback) {
this.isRecording = false;
this.recordingStartTime = null;
@@ -5422,7 +5449,36 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);
let usedBatchFallback = false;
let batchWarning = null;
let batchFallbackResult = null;
- if (!finalText && !finalAcknowledged && durationSeconds > 2 && fallbackBlob?.size > 0) {
+ let failureReport = null;
+ const failoverReason = this._streamingFailoverReason;
+ // No stream will transcribe a failed-over recording, so it uploads at any
+ // length, unless it was the silence the batch speech gate skips.
+ const failoverSilent =
+ Boolean(failoverReason) &&
+ getLocalSpeechGateDecision(this._streamingSpeechGateState).reason === "silence";
+ if (failoverSilent) {
+ logger.info("Speech gate skipped the failed-over upload", { failoverReason }, "streaming");
+ }
+ // A failed-over recording has no other transcript, so a failure to
+ // transcribe it ends as a batch recording's would. A stream that produced
+ // no text still ends quietly on a real failure, but keeps a recording that
+ // reads as silence for a retry, as batch does.
+ const failBatchFallback = (error) => {
+ const outcome = transcriptionFailureOutcome(error);
+ if (!failoverReason && outcome.report) return;
+ failureReport = outcome.report;
+ if (outcome.keepAudio) {
+ this.saveFailedTranscription(error.message, error.code || null, {
+ durationSeconds,
+ analyticsOccurredAt: analyticsOccurredAt.toISOString(),
+ });
+ }
+ };
+ if (
+ !finalText &&
+ (failoverReason ? !failoverSilent : !finalAcknowledged && durationSeconds > 2) &&
+ fallbackBlob?.size > 0
+ ) {
const target = resolveStreamingFallbackTarget(getSettings());
if (target === "skip") {
logger.warn(
@@ -5430,6 +5486,7 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);
{},
"streaming"
);
+ failBatchFallback(cloudSignInRequiredError());
} else {
logger.info(
"Streaming produced no text, falling back to batch transcription",
@@ -5446,9 +5503,11 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);
durationSeconds,
analyticsOccurredAt: analyticsOccurredAt.toISOString(),
// The tag feeds the Orukeet rollout's fallback rate; other
- // providers still fall back, just untagged.
- ...(this.getStreamingProviderName() === "orukeet"
- ? { streamingFallbackReason: "stream_no_final" }
+ // providers still fall back, just untagged. Only managed
+ // Orukeet fails over, and its reason outlives the cached
+ // config a refused start drops.
+ ...(failoverReason || this.getStreamingProviderName() === "orukeet"
+ ? { streamingFallbackReason: failoverReason || "stream_no_final" }
: {}),
},
wasCancelled
@@ -5463,7 +5522,10 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);
logger.info("Batch fallback succeeded", { textLength: finalText.length }, "streaming");
}
} catch (fallbackErr) {
+ // The cancelled upload's rejection is the expected outcome.
+ if (wasCancelled()) return true;
logger.error("Batch fallback failed", { error: fallbackErr.message }, "streaming");
+ failBatchFallback(fallbackErr);
}
}
}
@@ -5496,6 +5558,14 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);
source: batchFallbackResult?.source || `${this.getStreamingProviderName()}-streaming`,
clientTranscriptionId,
analyticsOccurredAt: resultAnalyticsOccurredAt,
+ // The upgrade prompt opens on these, as after a batch recording.
+ ...(batchFallbackResult?.limitReached
+ ? {
+ limitReached: true,
+ wordsUsed: batchFallbackResult.wordsUsed,
+ wordsRemaining: batchFallbackResult.wordsRemaining,
+ }
+ : {}),
...this._takePendingResultExtras(),
...(batchWarning ? { warning: batchWarning } : {}),
});
@@ -5569,7 +5639,9 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);
if (wasCancelled()) return true;
- if (!finalText) {
+ if (failureReport) {
+ this.onError?.(failureReport);
+ } else if (!finalText) {
// Match the batch pipeline: settle processing first, then publish the
// empty outcome so the warning cannot interrupt the thinking transition.
this.onTranscriptionComplete?.({ success: true, text: "" });
diff --git a/src/helpers/localSpeechGate.js b/src/helpers/localSpeechGate.js
index d9bd2f067..805d69bcc 100644
--- a/src/helpers/localSpeechGate.js
+++ b/src/helpers/localSpeechGate.js
@@ -36,6 +36,24 @@ export const recordLocalSpeechWindow = (state, rms, peak) => {
return state;
};
+// The streaming worklet's PCM16 chunks, quantized to the batch analyser's
+// getByteTimeDomainData bytes (floor(128·(1 + x))) so a failed-over recording
+// is skipped exactly when batch would skip it. At full resolution a quiet mic
+// reads as silence that batch never sees.
+export const recordPcm16SpeechWindow = (state, buffer) => {
+ const samples = new Int16Array(buffer);
+ if (!samples.length) return state;
+ let sum = 0;
+ let peak = 0;
+ for (const sample of samples) {
+ const byte = Math.floor(128 * (1 + sample / 0x8000));
+ const value = (byte - 128) / 128;
+ sum += value * value;
+ peak = Math.max(peak, Math.abs(value));
+ }
+ return recordLocalSpeechWindow(state, Math.sqrt(sum / samples.length), peak);
+};
+
export const getLocalSpeechGateDecision = (state) => {
if (!state?.windowCount) {
return { skip: false, reason: "unavailable" };
diff --git a/src/helpers/orukeetStreaming.js b/src/helpers/orukeetStreaming.js
index 1d9c2864e..a5761c5af 100644
--- a/src/helpers/orukeetStreaming.js
+++ b/src/helpers/orukeetStreaming.js
@@ -255,13 +255,22 @@ class OrukeetStreaming {
fail(error) {
if (this.failure) return;
+ // The final already completed this recording. Orukeet closes a finished
+ // socket when the account holds another warm one, so a later close or
+ // error only ends the connection.
+ if (this.result) return this.close();
this.failure = error;
+ // Before `ready` (including while main mints the session token, before
+ // connect() runs), the failed start is the report and falls back on it;
+ // onError is for an established stream, so a refused socket does not also
+ // surface as a streaming error.
+ const connecting = this.connecting || Boolean(this.connectReject);
this.connectReject?.(error);
this.connectResolve = this.connectReject = null;
this.finalReject?.(error);
this.clearFinal();
this.close();
- this.onError?.(error);
+ if (!connecting) this.onError?.(error);
}
close() {
diff --git a/src/helpers/transcriptionFailureOutcome.js b/src/helpers/transcriptionFailureOutcome.js
new file mode 100644
index 000000000..652a6b83f
--- /dev/null
+++ b/src/helpers/transcriptionFailureOutcome.js
@@ -0,0 +1,27 @@
+import { DICTIONARY_ECHO_CODE } from "../utils/dictionaryEchoFilter.js";
+
+// How a transcription failure ends, for batch recordings and re-uploaded
+// streaming ones alike. Silence is not reported. A transcript discarded as an
+// echo of the dictionary prompt, or audio Cloud found no speech in, reads as
+// silence, but its recording is kept for a manual retry like any real
+// failure's, or the utterance vanishes (#1547).
+export const transcriptionFailureOutcome = (error) => {
+ if (error.code === DICTIONARY_ECHO_CODE || error.code === "NO_SPEECH_DETECTED") {
+ return { noAudio: true, keepAudio: true, report: null };
+ }
+ if (error.message === "No audio detected") {
+ return { noAudio: true, keepAudio: false, report: null };
+ }
+ return {
+ noAudio: false,
+ keepAudio: true,
+ report: {
+ title: error.selectionEditFatal ? "Selection Edit Failed" : "Transcription Error",
+ description: error.selectionEditFatal
+ ? error.message
+ : `Transcription failed: ${error.message}`,
+ code: error.code,
+ messageKey: error.messageKey,
+ },
+ };
+};
diff --git a/src/helpers/transcriptionFallback.js b/src/helpers/transcriptionFallback.js
index c6dc582f4..caca7a65f 100644
--- a/src/helpers/transcriptionFallback.js
+++ b/src/helpers/transcriptionFallback.js
@@ -22,13 +22,18 @@ const USER_ACTIONABLE_START_FAILURES = new Set([
"LIMIT_REACHED",
]);
+// Orukeet over OpenWhispr Cloud sessions, as opposed to a self-hosted server.
+export function isManagedOrukeetStream({ providerName, cloudTranscriptionMode }) {
+ return providerName === "orukeet" && cloudTranscriptionMode === "openwhispr";
+}
+
// Every other managed Orukeet start failure goes to batch rather than losing
// the dictation: the rollout was turned off for this account, its mint window
// is exhausted, or the session service, the network, the WebSocket or the
// session response failed. Scoped to the managed Orukeet route so no other
// provider's start-failure behavior changes.
export function resolveStreamingStartFallback({ providerName, cloudTranscriptionMode, result }) {
- if (providerName !== "orukeet" || cloudTranscriptionMode !== "openwhispr") return null;
+ if (!isManagedOrukeetStream({ providerName, cloudTranscriptionMode })) return null;
if (USER_ACTIONABLE_START_FAILURES.has(result.code) || result.code?.startsWith("POLICY_")) {
return null;
}
diff --git a/test/helpers/audioManagerNoAudioLifecycle.test.js b/test/helpers/audioManagerNoAudioLifecycle.test.js
index 040ce0f72..f1b5c8916 100644
--- a/test/helpers/audioManagerNoAudioLifecycle.test.js
+++ b/test/helpers/audioManagerNoAudioLifecycle.test.js
@@ -2,17 +2,19 @@ const test = require("node:test");
const assert = require("node:assert/strict");
const { loadAudioManager } = require("./harness/audioManager");
-async function loadManagerClass(t) {
+const LOCAL_WHISPER_SETTINGS = {
+ useLocalWhisper: true,
+ localTranscriptionProvider: "whisper",
+ whisperModel: "base",
+ cloudTranscriptionMode: "byok",
+ isSignedIn: false,
+};
+
+async function loadManagerClass(t, settings = LOCAL_WHISPER_SETTINGS) {
const { AudioManager } = await loadAudioManager(t, {
cachePrefix: "openwhispr-no-audio-lifecycle-test-",
settingsKey: "__noAudioLifecycleSettings",
- settings: {
- useLocalWhisper: true,
- localTranscriptionProvider: "whisper",
- whisperModel: "base",
- cloudTranscriptionMode: "byok",
- isSignedIn: false,
- },
+ settings,
});
return AudioManager;
}
@@ -29,6 +31,9 @@ function createManager(AudioManager, failure) {
processWithLocalWhisper: async () => {
throw failure;
},
+ processWithOpenWhisprCloud: async () => {
+ throw failure;
+ },
onStateChange: (state) => order.push(state.isProcessing ? "processing" : "idle"),
onNoAudio: () => order.push("no-audio"),
onError: () => order.push("error"),
@@ -60,3 +65,21 @@ test("dictionary-echo silence keeps the recording but shares the settled outcome
assert.deepEqual(order, ["idle", "no-audio"]);
assert.deepEqual(saved, [{ message: "No audio detected", code: DICTIONARY_ECHO_CODE }]);
});
+
+test("Cloud finding no speech is the no-audio outcome and keeps the recording", async (t) => {
+ const AudioManager = await loadManagerClass(t, {
+ useLocalWhisper: false,
+ cloudTranscriptionMode: "openwhispr",
+ isSignedIn: true,
+ });
+ // cloud-transcribe's shape for the API's 422 (ipcHandlers.js).
+ const failure = Object.assign(new Error("No speech detected in audio"), {
+ code: "NO_SPEECH_DETECTED",
+ });
+ const { manager, order, saved } = createManager(AudioManager, failure);
+
+ await manager.processAudio({ size: 256, type: "audio/webm" });
+
+ assert.deepEqual(order, ["idle", "no-audio"]);
+ assert.deepEqual(saved, [{ message: "No speech detected in audio", code: "NO_SPEECH_DETECTED" }]);
+});
diff --git a/test/helpers/audioManagerStreamingFinalization.test.js b/test/helpers/audioManagerStreamingFinalization.test.js
index 2ba7847db..06152720b 100644
--- a/test/helpers/audioManagerStreamingFinalization.test.js
+++ b/test/helpers/audioManagerStreamingFinalization.test.js
@@ -488,6 +488,33 @@ test("a stream without a final falls back to batch for every provider, tagged on
]);
});
+test("a no-final stream whose Cloud upload finds no speech keeps the recording quietly", async (t) => {
+ const AudioManager = await loadManagerClass(t);
+ globalThis.__streamingFinalizationSettings = {
+ ...globalThis.__streamingFinalizationSettings,
+ cloudTranscriptionMode: "openwhispr",
+ isSignedIn: true,
+ };
+ const { manager } = createFinalizingManager(AudioManager);
+ manager.recordingStartTime = Date.now() - 5000;
+ manager.mergeRecordedSegments = async () => new Blob([new Uint8Array(100)]);
+ const saved = [];
+ const errors = [];
+ const completions = [];
+ manager.saveFailedTranscription = (message, code) => saved.push({ message, code });
+ manager.onError = (error) => errors.push(error);
+ manager.onTranscriptionComplete = (result) => completions.push(result);
+ manager.processWithOpenWhisprCloud = async () => {
+ throw Object.assign(new Error("No speech detected in audio"), { code: "NO_SPEECH_DETECTED" });
+ };
+
+ await manager.stopStreamingRecording();
+
+ assert.deepEqual(saved, [{ message: "No speech detected in audio", code: "NO_SPEECH_DETECTED" }]);
+ assert.deepEqual(errors, []);
+ assert.deepEqual(completions, [{ success: true, text: "" }]);
+});
+
test("Orukeet uses the acknowledged final even if the transcript event is delayed", async (t) => {
const AudioManager = await loadManagerClass(t);
const { manager } = createFinalizingManager(AudioManager);
@@ -530,3 +557,615 @@ test("missing Orukeet capture flush never commits a partial recording", async (t
assert.equal(stopped, true);
assert.equal(manager.streamingProcessor, null);
});
+
+function useManagedOrukeetSettings() {
+ globalThis.__streamingFinalizationSettings = {
+ ...globalThis.__streamingFinalizationSettings,
+ cloudTranscriptionMode: "openwhispr",
+ isSignedIn: true,
+ };
+}
+
+// A capture pipeline whose fallback recorder holds "opening words" from the
+// moment it starts, before any streaming session exists, and whose worklet
+// answers "stop" with the flush sentinel like the real one.
+function installCapture(t) {
+ const previous = {
+ AudioWorkletNode: globalThis.AudioWorkletNode,
+ MediaRecorder: globalThis.MediaRecorder,
+ };
+ globalThis.AudioWorkletNode = class {
+ constructor() {
+ this.port = {
+ postMessage: (message) => {
+ if (message === "stop") queueMicrotask(() => this.port.onmessage?.({ data: "flushed" }));
+ },
+ };
+ }
+
+ connect() {}
+ disconnect() {}
+ };
+ globalThis.MediaRecorder = class {
+ constructor() {
+ this.state = "inactive";
+ this.mimeType = "audio/webm";
+ }
+
+ start() {
+ this.state = "recording";
+ this.ondataavailable({ data: new Blob(["opening words"]) });
+ }
+
+ stop() {
+ this.state = "inactive";
+ queueMicrotask(() => this.onstop?.());
+ }
+ };
+ t.after(() => {
+ for (const [name, value] of Object.entries(previous)) {
+ if (value === undefined) delete globalThis[name];
+ else globalThis[name] = value;
+ }
+ });
+}
+
+function createStartingManager(AudioManager, { providerName, provider }) {
+ const errors = [];
+ const uploads = [];
+ const completions = [];
+ const stream = { getAudioTracks: () => [], getTracks: () => [{ stop() {} }] };
+ const source = { connect() {}, disconnect() {} };
+ const manager = Object.assign(Object.create(AudioManager.prototype), {
+ isRecording: false,
+ isProcessing: false,
+ isStreaming: false,
+ streamingStartInProgress: false,
+ _streamingStartSettlementWaiters: [],
+ stopRequestedDuringStreamingStart: false,
+ _streamingStopPromise: null,
+ _streamingStopMode: null,
+ _streamingCancellationGeneration: 0,
+ _activeTranscriptionAbortController: null,
+ _streamingSessionGeneration: 0,
+ _activeStreamingSessionId: null,
+ _streamingMicSwapPromise: null,
+ streamingCleanupFns: [],
+ streamingFallbackRecorder: null,
+ streamingFallbackChunks: [],
+ _streamingFallbackSegments: [],
+ streamingTextDebounce: null,
+ pendingAssistantConversation: null,
+ pendingSelectionEdit: null,
+ preparedMicCapture: { take: async () => null },
+ micRecovery: { stop() {} },
+ isRecordingAllowedByPolicy: () => true,
+ getAudioConstraints: async () => ({}),
+ _acquireCaptureStream: async () => stream,
+ getOrCreateAudioContext: async () => ({
+ createMediaStreamSource: () => source,
+ createAnalyser: () => ({}),
+ audioWorklet: { addModule: async () => {} },
+ }),
+ getWorkletBlobUrl: () => "",
+ getStreamingProvider: () => provider,
+ getStreamingProviderName: () => providerName,
+ getEffectiveSttLanguage: () => "auto",
+ getKeyterms: () => [],
+ beginMicRecovery: async () => {},
+ mergeRecordedSegments: async (segments) => segments[0] ?? null,
+ getLargestRecordedSegment: () => null,
+ awaitStreamingTextSettled: async () => {},
+ shouldUseStreaming: () => false,
+ _markCaptureStreamReleased() {},
+ onStateChange() {},
+ startRecording: async () => assert.fail("the microphone must not be reopened"),
+ processWithOpenWhisprCloud: async (blob, metadata) => {
+ uploads.push({ audio: await blob.text(), reason: metadata.streamingFallbackReason });
+ return { text: "" };
+ },
+ onError: (error) => errors.push(error),
+ onTranscriptionComplete: (result) => completions.push(result),
+ });
+ return { manager, errors, uploads, completions };
+}
+
+function startingOrukeetProvider(overrides = {}) {
+ const sent = [];
+ return {
+ sent,
+ onPartial: () => () => {},
+ onFinal: () => () => {},
+ onError: () => () => {},
+ onSessionEnd: () => () => {},
+ send: (pcm) => sent.push(pcm),
+ start: async () => ({ success: true }),
+ finalizeAcknowledged: true,
+ // What main answers once the adapter is gone or failed.
+ finalize: async () => ({ success: false, error: "No Orukeet recording is active" }),
+ stop: async () => ({ success: true, text: "" }),
+ ...overrides,
+ };
+}
+
+// One 50 ms worklet chunk (800 PCM16 samples at 16 kHz).
+const speechPcm = () => new Int16Array(800).fill(8000).buffer;
+const silentPcm = () => new Int16Array(800).buffer;
+
+function refusedStartProvider() {
+ return startingOrukeetProvider({
+ start: async () => ({ success: false, error: "Orukeet connection closed" }),
+ });
+}
+
+test("a refused managed Orukeet start keeps its capture and uploads the opening words", async (t) => {
+ const AudioManager = await loadManagerClass(t);
+ useManagedOrukeetSettings();
+ installCapture(t);
+ const provider = startingOrukeetProvider({
+ start: async () => ({ success: false, error: "Orukeet connection closed" }),
+ });
+ const { manager, errors, uploads } = createStartingManager(AudioManager, {
+ providerName: "orukeet",
+ provider,
+ });
+
+ assert.equal(await manager.startStreamingRecording(), true);
+ assert.equal(manager.isRecording, true);
+ manager.streamingProcessor.port.onmessage({ data: speechPcm() });
+ assert.deepEqual(provider.sent, [], "a failed-over recording feeds no socket");
+
+ // Stopped well under the 2 s floor a streamed recording needs to fall back.
+ await manager.stopStreamingRecording();
+
+ assert.deepEqual(uploads, [{ audio: "opening words", reason: "session_unavailable" }]);
+ assert.deepEqual(errors, []);
+});
+
+test("a managed Orukeet stream refused mid-recording keeps recording and uploads it", async (t) => {
+ const AudioManager = await loadManagerClass(t);
+ useManagedOrukeetSettings();
+ installCapture(t);
+ let raise;
+ const provider = startingOrukeetProvider({
+ onError: (listener) => {
+ raise = listener;
+ return () => {};
+ },
+ });
+ const { manager, errors, uploads } = createStartingManager(AudioManager, {
+ providerName: "orukeet",
+ provider,
+ });
+
+ assert.equal(await manager.startStreamingRecording(), true);
+ raise("Account already has an active recording");
+
+ assert.equal(manager.isStreaming, true, "the recording is not cut off");
+ assert.equal(manager._streamingStopPromise, null);
+ await manager.stopStreamingRecording();
+ assert.deepEqual(uploads, [{ audio: "opening words", reason: "stream_no_final" }]);
+ assert.deepEqual(errors, []);
+});
+
+test("a managed Orukeet error while stop awaits the final still uploads a short capture", async (t) => {
+ const AudioManager = await loadManagerClass(t);
+ useManagedOrukeetSettings();
+ installCapture(t);
+ let raise;
+ const provider = startingOrukeetProvider({
+ onError: (listener) => {
+ raise = listener;
+ return () => {};
+ },
+ // The refusal (commit capacity, a dropped socket or a final timeout)
+ // lands a round trip after the commit, once stop has finished the
+ // fallback recorder.
+ finalize: async () => {
+ while (manager.streamingFallbackRecorder) await new Promise(setImmediate);
+ raise("Orukeet transcription failed: capacity");
+ return { success: false, error: "Orukeet transcription failed: capacity" };
+ },
+ });
+ const { manager, errors, uploads } = createStartingManager(AudioManager, {
+ providerName: "orukeet",
+ provider,
+ });
+
+ assert.equal(await manager.startStreamingRecording(), true);
+ await manager.stopStreamingRecording();
+
+ assert.deepEqual(uploads, [{ audio: "opening words", reason: "stream_no_final" }]);
+ assert.deepEqual(errors, []);
+});
+
+test("a managed Orukeet drop without a fallback recorder surfaces and auto-stops", async (t) => {
+ const AudioManager = await loadManagerClass(t);
+ useManagedOrukeetSettings();
+ installCapture(t);
+ globalThis.MediaRecorder = class {
+ constructor() {
+ throw new Error("MediaRecorder unavailable");
+ }
+ };
+ let raise;
+ const provider = startingOrukeetProvider({
+ onError: (listener) => {
+ raise = listener;
+ return () => {};
+ },
+ });
+ const { manager, errors } = createStartingManager(AudioManager, {
+ providerName: "orukeet",
+ provider,
+ });
+
+ assert.equal(await manager.startStreamingRecording(), true);
+ raise("Account already has an active recording");
+
+ // Nothing holds the capture, so there is nothing to fail over to.
+ assert.equal(errors[0]?.title, "Streaming Error");
+ assert.ok(manager._streamingStopPromise, "the recording auto-stops");
+ await manager._streamingStopPromise;
+});
+
+test("a refused managed Orukeet start without a fallback recorder records in batch instead", async (t) => {
+ const AudioManager = await loadManagerClass(t);
+ useManagedOrukeetSettings();
+ installCapture(t);
+ globalThis.MediaRecorder = class {
+ constructor() {
+ throw new Error("MediaRecorder unavailable");
+ }
+ };
+ const { manager, uploads } = createStartingManager(AudioManager, {
+ providerName: "orukeet",
+ provider: refusedStartProvider(),
+ });
+ let batchStarts = 0;
+ manager.startRecording = async () => {
+ batchStarts += 1;
+ return true;
+ };
+ manager.cleanupStreaming = async () => {};
+
+ assert.equal(await manager.startStreamingRecording(), true);
+
+ // Nothing captured the opening words, so only a fresh recording can.
+ assert.equal(batchStarts, 1);
+ assert.equal(manager._streamingFailoverReason, null);
+ assert.deepEqual(uploads, []);
+});
+
+test("a stop pressed while a refused managed Orukeet start settles uploads once", async (t) => {
+ const AudioManager = await loadManagerClass(t);
+ useManagedOrukeetSettings();
+ installCapture(t);
+ let refuse;
+ const provider = startingOrukeetProvider({
+ start: () =>
+ new Promise((resolve) => {
+ refuse = () => resolve({ success: false, error: "Orukeet connection closed" });
+ }),
+ });
+ const { manager, errors, uploads } = createStartingManager(AudioManager, {
+ providerName: "orukeet",
+ provider,
+ });
+
+ const starting = manager.startStreamingRecording();
+ while (!refuse) await new Promise((resolve) => setImmediate(resolve));
+ await manager.stopStreamingRecording();
+ refuse();
+ await starting;
+
+ assert.equal(manager.isRecording, false, "the deferred stop ends the recording");
+ assert.deepEqual(uploads, [{ audio: "opening words", reason: "session_unavailable" }]);
+ assert.deepEqual(errors, []);
+});
+
+test("the recording after a failed-over one streams to its socket again", async (t) => {
+ const AudioManager = await loadManagerClass(t);
+ useManagedOrukeetSettings();
+ installCapture(t);
+ let starts = 0;
+ const provider = startingOrukeetProvider({
+ start: async () => {
+ starts += 1;
+ return starts === 1
+ ? { success: false, error: "Orukeet connection closed" }
+ : { success: true };
+ },
+ });
+ const { manager } = createStartingManager(AudioManager, { providerName: "orukeet", provider });
+
+ assert.equal(await manager.startStreamingRecording(), true);
+ await manager.stopStreamingRecording();
+ assert.equal(await manager.startStreamingRecording(), true);
+ const pcm = speechPcm();
+ manager.streamingProcessor.port.onmessage({ data: pcm });
+
+ assert.deepEqual(provider.sent, [pcm]);
+});
+
+test("opening words streamed before a mid-recording drop still count as speech", async (t) => {
+ const AudioManager = await loadManagerClass(t);
+ useManagedOrukeetSettings();
+ installCapture(t);
+ let raise;
+ const provider = startingOrukeetProvider({
+ onError: (listener) => {
+ raise = listener;
+ return () => {};
+ },
+ });
+ const { manager, uploads } = createStartingManager(AudioManager, {
+ providerName: "orukeet",
+ provider,
+ });
+
+ assert.equal(await manager.startStreamingRecording(), true);
+ manager.streamingProcessor.port.onmessage({ data: speechPcm() });
+ raise("Orukeet connection closed");
+ manager.streamingProcessor.port.onmessage({ data: silentPcm() });
+ await manager.stopStreamingRecording();
+
+ assert.deepEqual(uploads, [{ audio: "opening words", reason: "stream_no_final" }]);
+});
+
+test("other streaming providers still surface a dropped stream and auto-stop", async (t) => {
+ const AudioManager = await loadManagerClass(t);
+ useManagedOrukeetSettings();
+ installCapture(t);
+ let raise;
+ const provider = startingOrukeetProvider({
+ onError: (listener) => {
+ raise = listener;
+ return () => {};
+ },
+ finalizeAcknowledged: false,
+ });
+ const { manager, errors } = createStartingManager(AudioManager, {
+ providerName: "openai-realtime",
+ provider,
+ });
+
+ assert.equal(await manager.startStreamingRecording(), true);
+ raise("Connection lost");
+
+ assert.equal(errors[0].title, "Streaming Error");
+ assert.ok(manager._streamingStopPromise, "the recording auto-stops");
+ await manager._streamingStopPromise;
+});
+
+test("a failed-over upload error is reported and kept for retry, not shown as silence", async (t) => {
+ const AudioManager = await loadManagerClass(t);
+ useManagedOrukeetSettings();
+ installCapture(t);
+ const provider = startingOrukeetProvider({
+ start: async () => ({ success: false, error: "Orukeet connection closed" }),
+ });
+ const { manager, errors, completions } = createStartingManager(AudioManager, {
+ providerName: "orukeet",
+ provider,
+ });
+ const saved = [];
+ manager.saveFailedTranscription = async (message, code) => saved.push([message, code]);
+ manager.processWithOpenWhisprCloud = async () => {
+ const error = new Error("You're offline.");
+ error.code = "OFFLINE";
+ throw error;
+ };
+
+ await manager.startStreamingRecording();
+ await manager.stopStreamingRecording();
+
+ assert.equal(errors.length, 1);
+ assert.equal(errors[0].code, "OFFLINE");
+ assert.deepEqual(saved, [["You're offline.", "OFFLINE"]]);
+ assert.deepEqual(completions, []);
+});
+
+test("cancelling a failed-over upload does not keep it as a failed transcription", async (t) => {
+ const AudioManager = await loadManagerClass(t);
+ useManagedOrukeetSettings();
+ installCapture(t);
+ const { manager, errors } = createStartingManager(AudioManager, {
+ providerName: "orukeet",
+ provider: refusedStartProvider(),
+ });
+ const saved = [];
+ manager.saveFailedTranscription = async (message, code) => saved.push([message, code]);
+ // Main answers an upload cancelled mid-flight with TRANSCRIPTION_CANCELLED.
+ let cancelUpload;
+ let uploadStarted;
+ const uploading = new Promise((resolve) => {
+ uploadStarted = resolve;
+ });
+ globalThis.window.electronAPI.cancelCloudTranscription = () => cancelUpload();
+ manager.processWithOpenWhisprCloud = () =>
+ new Promise((_resolve, reject) => {
+ cancelUpload = () =>
+ reject(Object.assign(new Error("Cancelled"), { code: "TRANSCRIPTION_CANCELLED" }));
+ uploadStarted();
+ });
+
+ await manager.startStreamingRecording();
+ const stopping = manager.stopStreamingRecording();
+ await uploading;
+ await manager.cancelStreamingRecording();
+ await stopping;
+
+ assert.deepEqual(saved, []);
+ assert.deepEqual(errors, []);
+});
+
+test("a failed-over upload that echoes the dictionary reads as silence and keeps the audio", async (t) => {
+ const AudioManager = await loadManagerClass(t);
+ useManagedOrukeetSettings();
+ installCapture(t);
+ const { manager, errors, completions } = createStartingManager(AudioManager, {
+ providerName: "orukeet",
+ provider: refusedStartProvider(),
+ });
+ const saved = [];
+ manager.saveFailedTranscription = async (message, code) => saved.push([message, code]);
+ manager.processWithOpenWhisprCloud = async () => {
+ throw Object.assign(new Error("No audio detected"), { code: "DICTIONARY_ECHO" });
+ };
+
+ await manager.startStreamingRecording();
+ await manager.stopStreamingRecording();
+
+ assert.deepEqual(saved, [["No audio detected", "DICTIONARY_ECHO"]]);
+ assert.deepEqual(errors, []);
+ assert.deepEqual(completions, [{ success: true, text: "" }]);
+});
+
+test("a start refused as disabled keeps its tag after the cached config is dropped", async (t) => {
+ const AudioManager = await loadManagerClass(t);
+ useManagedOrukeetSettings();
+ installCapture(t);
+ const { manager, uploads } = createStartingManager(AudioManager, {
+ providerName: "orukeet",
+ provider: startingOrukeetProvider({
+ start: async () => ({ success: false, code: "FEATURE_NOT_ENABLED", error: "Disabled" }),
+ }),
+ });
+ // Resolve the provider from the cached config, as the real manager does.
+ delete manager.getStreamingProviderName;
+ manager.sttConfig = { dictation: { mode: "streaming" }, streamingProvider: "orukeet" };
+
+ await manager.startStreamingRecording();
+ await manager.stopStreamingRecording();
+
+ assert.deepEqual(uploads, [{ audio: "opening words", reason: "feature_disabled" }]);
+});
+
+test("signing out during a failed-over recording reports it and keeps the audio", async (t) => {
+ const AudioManager = await loadManagerClass(t);
+ useManagedOrukeetSettings();
+ installCapture(t);
+ const { manager, errors, uploads, completions } = createStartingManager(AudioManager, {
+ providerName: "orukeet",
+ provider: refusedStartProvider(),
+ });
+ const saved = [];
+ manager.saveFailedTranscription = async (message, code) => saved.push(code);
+
+ await manager.startStreamingRecording();
+ globalThis.__streamingFinalizationSettings = {
+ ...globalThis.__streamingFinalizationSettings,
+ isSignedIn: false,
+ };
+ await manager.stopStreamingRecording();
+
+ assert.deepEqual(uploads, []);
+ assert.deepEqual(
+ errors.map(({ code, messageKey }) => ({ code, messageKey })),
+ [{ code: "AUTH_REQUIRED", messageKey: "hooks.audioRecording.errorDescriptions.sessionExpired" }]
+ );
+ assert.deepEqual(saved, ["AUTH_REQUIRED"]);
+ assert.deepEqual(completions, []);
+});
+
+test("a failed-over upload that reaches the word limit carries it to the upgrade prompt", async (t) => {
+ const AudioManager = await loadManagerClass(t);
+ useManagedOrukeetSettings();
+ installCapture(t);
+ const { manager, completions } = createStartingManager(AudioManager, {
+ providerName: "orukeet",
+ provider: refusedStartProvider(),
+ });
+ globalThis.window.dispatchEvent = () => true;
+ manager.processWithOpenWhisprCloud = async () => ({
+ text: "Last words of the day.",
+ source: "openwhispr",
+ limitReached: true,
+ wordsUsed: 2000,
+ wordsRemaining: 0,
+ });
+
+ await manager.startStreamingRecording();
+ await manager.stopStreamingRecording();
+
+ assert.equal(completions.length, 1);
+ const { text, limitReached, wordsUsed, wordsRemaining } = completions[0];
+ assert.deepEqual(
+ { text, limitReached, wordsUsed, wordsRemaining },
+ { text: "Last words of the day.", limitReached: true, wordsUsed: 2000, wordsRemaining: 0 }
+ );
+});
+
+test("a silent failed-over tap is not uploaded", async (t) => {
+ const AudioManager = await loadManagerClass(t);
+ useManagedOrukeetSettings();
+ installCapture(t);
+ const { manager, errors, uploads, completions } = createStartingManager(AudioManager, {
+ providerName: "orukeet",
+ provider: refusedStartProvider(),
+ });
+
+ await manager.startStreamingRecording();
+ manager.streamingProcessor.port.onmessage({ data: silentPcm() });
+ await manager.stopStreamingRecording();
+
+ assert.deepEqual(uploads, []);
+ assert.deepEqual(errors, []);
+ assert.deepEqual(completions, [{ success: true, text: "" }]);
+});
+
+test("a failed-over selection edit that fails is reported as a selection edit failure", async (t) => {
+ const AudioManager = await loadManagerClass(t);
+ useManagedOrukeetSettings();
+ installCapture(t);
+ const { manager, errors } = createStartingManager(AudioManager, {
+ providerName: "orukeet",
+ provider: refusedStartProvider(),
+ });
+ manager.saveFailedTranscription = async () => {};
+ manager.processWithOpenWhisprCloud = async () => {
+ throw Object.assign(new Error("Selection edit could not safely read the selection: gone"), {
+ code: "SELECTION_EDIT_CAPTURE_FAILED",
+ messageKey: "hooks.audioRecording.selectionEditing.unavailable",
+ selectionEditFatal: true,
+ });
+ };
+
+ await manager.startStreamingRecording();
+ await manager.stopStreamingRecording();
+
+ assert.deepEqual(errors, [
+ {
+ title: "Selection Edit Failed",
+ description: "Selection edit could not safely read the selection: gone",
+ code: "SELECTION_EDIT_CAPTURE_FAILED",
+ messageKey: "hooks.audioRecording.selectionEditing.unavailable",
+ },
+ ]);
+});
+
+test("a managed Orukeet session fails over even if its route changes mid-recording", async (t) => {
+ const AudioManager = await loadManagerClass(t);
+ useManagedOrukeetSettings();
+ installCapture(t);
+ let raise;
+ const { manager, errors } = createStartingManager(AudioManager, {
+ providerName: "orukeet",
+ provider: startingOrukeetProvider({
+ onError: (listener) => {
+ raise = listener;
+ return () => {};
+ },
+ }),
+ });
+
+ assert.equal(await manager.startStreamingRecording(), true);
+ // A background stt-config refresh rolled the account off the Orukeet route.
+ manager.getStreamingProviderName = () => "deepgram";
+ raise("Account already has an active recording");
+
+ assert.deepEqual(errors, []);
+ assert.equal(manager._streamingStopPromise, null, "the recording is not cut off");
+ await manager.stopStreamingRecording();
+});
diff --git a/test/helpers/localSpeechGate.test.js b/test/helpers/localSpeechGate.test.js
index 6abc92039..fdb546888 100644
--- a/test/helpers/localSpeechGate.test.js
+++ b/test/helpers/localSpeechGate.test.js
@@ -72,3 +72,40 @@ test("allows sustained speech-like energy through", async () => {
maxConsecutiveSpeechWindows: 3,
});
});
+
+test("measures a PCM16 chunk as one window", async () => {
+ const { createLocalSpeechGateState, recordPcm16SpeechWindow, getLocalSpeechGateDecision } =
+ await import("../../src/helpers/localSpeechGate.js");
+
+ const silent = createLocalSpeechGateState();
+ recordPcm16SpeechWindow(silent, new Int16Array(800).buffer);
+ assert.equal(getLocalSpeechGateDecision(silent).reason, "silence");
+
+ const speech = createLocalSpeechGateState();
+ recordPcm16SpeechWindow(speech, new Int16Array([16384, -16384, 16384, -16384]).buffer);
+ assert.deepEqual(getLocalSpeechGateDecision(speech), {
+ skip: false,
+ reason: "speech_detected",
+ peakRms: 0.5,
+ peakAmplitude: 0.5,
+ windowCount: 1,
+ speechWindowCount: 1,
+ maxConsecutiveSpeechWindows: 1,
+ });
+});
+
+test("reads a quiet PCM16 chunk at the batch analyser's 8-bit resolution", async () => {
+ const { createLocalSpeechGateState, recordPcm16SpeechWindow, getLocalSpeechGateDecision } =
+ await import("../../src/helpers/localSpeechGate.js");
+
+ // ±40 is about -58 dBFS. The analyser's byte samples floor every negative
+ // sample to -1/128 and every small positive one to 0, so batch measures
+ // (1/128)·√½ and never calls this silence.
+ const state = createLocalSpeechGateState();
+ recordPcm16SpeechWindow(state, new Int16Array([40, -40, 40, -40]).buffer);
+ const decision = getLocalSpeechGateDecision(state);
+
+ assert.equal(decision.reason, "insufficient_speech");
+ assert.ok(Math.abs(decision.peakRms - 0.0055243) < 1e-6, `peakRms ${decision.peakRms}`);
+ assert.equal(decision.peakAmplitude, 0.0078125);
+});
diff --git a/test/helpers/orukeetStreaming.test.js b/test/helpers/orukeetStreaming.test.js
index 1086d8a35..85e3cbf19 100644
--- a/test/helpers/orukeetStreaming.test.js
+++ b/test/helpers/orukeetStreaming.test.js
@@ -234,3 +234,80 @@ test("oversized capacity backoff cannot overflow the timer into a retry loop", a
await assert.rejects(adapter.finalize(), /timed out/);
assert.equal(commits, 1);
});
+
+async function gateway(t, options = {}) {
+ const server = new WebSocketServer({ port: 0, host: "127.0.0.1", ...options });
+ await once(server, "listening");
+ t.after(async () => {
+ for (const socket of server.clients) socket.terminate();
+ await new Promise((resolve) => server.close(resolve));
+ });
+ return { server, baseUrl: `http://127.0.0.1:${server.address().port}` };
+}
+
+test("a socket refused before ready rejects connect without raising a stream error", async (t) => {
+ // The gateway can refuse the upgrade itself, or accept it and answer with an
+ // error instead of `ready` (the per-account cap does either).
+ const refusedUpgrade = await gateway(t, { verifyClient: (_info, done) => done(false, 429) });
+ const refusedSession = await gateway(t);
+ refusedSession.server.on("connection", (socket) => {
+ socket.send(JSON.stringify({ type: "error", code: "account_limit", message: "Busy" }));
+ socket.close();
+ });
+
+ for (const { baseUrl } of [refusedUpgrade, refusedSession]) {
+ const adapter = new OrukeetStreaming({ timeoutMs: 300 });
+ const errors = [];
+ adapter.onError = (error) => errors.push(error);
+ await assert.rejects(adapter.connect({ baseUrl, apiKey: "test-key" }));
+ assert.deepEqual(errors, [], baseUrl);
+ }
+});
+
+test("a refusal after ready still raises a stream error", async (t) => {
+ const { adapter, options } = await fixture(t, (socket) =>
+ socket.send(JSON.stringify({ type: "error", code: "account_limit", message: "Busy" }))
+ );
+ const raised = new Promise((resolve) => {
+ adapter.onError = resolve;
+ });
+ await adapter.connect(options);
+ adapter.sendAudio(Buffer.from([1, 0]));
+ assert.equal((await raised).message, "Busy");
+});
+
+test("a server closing a completed socket raises no stream error", async (t) => {
+ // Orukeet closes a finished socket right after its final when the account
+ // already holds a warm one.
+ const { adapter, options } = await fixture(t, (socket, event) => {
+ if (event.type === "commit") {
+ socket.send(JSON.stringify({ type: "final", text: "" }));
+ socket.close();
+ }
+ });
+ const errors = [];
+ adapter.onError = (error) => errors.push(error);
+ await adapter.connect(options);
+ const closed = once(adapter.ws, "close");
+ adapter.sendAudio(Buffer.from([1, 0]));
+
+ assert.equal((await adapter.finalize()).text, "");
+ await closed;
+ assert.deepEqual(errors, []);
+});
+
+test("a failure while the session token is minted raises no stream error", async () => {
+ // Main creates the adapter before minting the managed token, so it is
+ // connecting before connect() runs; the failed start reports this failure.
+ const adapter = new OrukeetStreaming({ timeoutMs: 300 });
+ const errors = [];
+ adapter.onError = (error) => errors.push(error);
+ adapter.beginConnecting();
+ adapter.sendAudio(Buffer.alloc(2 * 1024 * 1024 + 2));
+
+ await assert.rejects(
+ adapter.connect({ baseUrl: "http://127.0.0.1:9", apiKey: "test-key" }),
+ /new Orukeet adapter/
+ );
+ assert.deepEqual(errors, []);
+});