Skip to content

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

feat(dictation): Re-transcribe Orukeet dictations in unsupported languages (#2339)

Chad Piha9d9980ae9042
diff --git a/docs/orukeet-streaming-language.md b/docs/orukeet-streaming-language.md
index f00cdb770..dee05f915 100644
--- a/docs/orukeet-streaming-language.md
+++ b/docs/orukeet-streaming-language.md
@@ -30,4 +30,4 @@ Keep the original recording until routing is settled. Prefer the six-second esti
On 330 human-read FLEURS clips across 33 languages (all 25 supported languages and eight unsupported languages), exact language accuracy was 172/330 (52.1%) at two seconds and 256/330 (77.6%) at three seconds. Among the 315 clips containing a full six seconds, it was 293/315 (93.0%). These are classifier results on read speech, not ASR word accuracy or production calibration.
-At a score threshold of 0.90, the two-second estimate caught 28/80 unsupported-language clips and incorrectly flagged 6/250 supported-language clips. At six seconds those counts were 69/75 and 1/240. The deployed first/update windows therefore remain three and six seconds. A two-second guess is too unreliable to recommend for automatic provider routing. Clips without a sufficiently confident result should retain the user's configured provider or language policy.
+At a score threshold of 0.90, the two-second estimate caught 28/80 unsupported-language clips and incorrectly flagged 6/250 supported-language clips. At three seconds those counts were 50/80 (62.5%) and 3/250 (1.2%), and at six seconds 69/75 (92%) and 1/240 (0.4%). The deployed first/update windows therefore remain three and six seconds. A two-second guess is too unreliable to recommend for automatic provider routing. Clips without a sufficiently confident result should retain the user's configured provider or language policy.
diff --git a/docs/orukeet-streaming.md b/docs/orukeet-streaming.md
index 66844e490..2e2f83788 100644
--- a/docs/orukeet-streaming.md
+++ b/docs/orukeet-streaming.md
@@ -38,3 +38,17 @@ The rollout applies to dictation. Local Orukeet, meetings and existing BYOK prov
Automated tests cover real WebSocket transport, the registered Electron IPC handlers, startup buffering, token authentication, endpoint pinning, allowance and policy denials, account changes, cancellation, duplicate finals, silence, capture flush ordering, retry and timeout. [Streaming benchmark results](orukeet-benchmarks.md) report the deployed infrastructure measurements separately from desktop tests.
Before enabling the flag, accept the private backend route and metering, then verify microphone, hotkey, cleanup and single-paste behavior on signed macOS, Windows and Linux release builds. Automated Electron-boundary tests do not claim native OS acceptance. Roll back by restoring the previous `streamingProvider`; let active recordings finish. Track setup, stop-to-final, release-to-paste, queue time and fallback rate separately.
+
+## Routing policy (OpenWhispr)
+
+Orukeet transcribes 25 languages (`bg cs da de el en es et fi fr hr hu it lt lv mt nl pl pt ro ru sk sl sv uk`) and renders any other language as confident nonsense. Those dictations stay on the existing Cloud batch provider:
+
+- An explicitly selected language outside the 25 never starts an Orukeet stream. The dictation records in batch, tagged `language_unsupported`.
+- With the language set to "auto", the desktop reads the estimate in Orukeet's `final` message, never the early `language` events. An estimate outside the 25 with a score of at least 0.90 on at least 3 seconds of audio discards Orukeet's text. This applies to managed OpenWhispr Cloud dictation only.
+- The retained recording is then uploaded to `/api/transcribe`, tagged `language_detected_unsupported`. Like any "auto" dictation it sends no `language`, never the detected one, because `/api/transcribe` picks its model by declared language. Cleanup runs once, on the batch transcript.
+- Orukeet's text is never kept. If the upload fails, the dictation ends with a transcription error, as a batch recording would. If Cloud finds no speech or returns no text, it ends empty. Either way the recording is kept in History for a retry.
+- Every Orukeet dictation reports the final estimate as `sttDetectedLanguage`, `sttDetectedLanguageConfidence`, `sttDetectedLanguageAudioSeconds` and `sttDetectedLanguageStatus` on its usage, cleanup or batch request. A final without a `language` key (an older gateway) reports nothing.
+- The backend stores the estimate in `transcription_logs.metadata`. Once enough of a user's recent dictations are outside the 25, `/api/stt-config` stops offering Orukeet and `/api/stt/orukeet/session` refuses with 403 `FEATURE_NOT_ENABLED` and `reason: "language_unsupported"`. The desktop treats that refusal as its `feature_disabled` batch fallback. Allowlisted testers skip this gate. The rule lives in `openwhispr-api` (`lib/orukeet-language.ts`, applied in `lib/orukeet-rollout.ts`). Until that gate is deployed, the API ignores these fields and the `language_detected_unsupported` tag.
+- With cloud cleanup on, a re-transcribed wake-word command or selection edit writes no transcription log, so the gate never sees its estimate. The Cloud batch path decides whether to log before it knows the route, and only cleanup writes the combined log.
+
+The 0.90 threshold is Oruk's classifier score, not a calibrated probability. It caught 92% of unsupported FLEURS clips at 6 seconds and 62.5% at 3 seconds, while flagging 0.4% and 1.2% of supported ones. See [streaming language metadata](orukeet-streaming-language.md). The final carries the latest completed estimate, so the 3-second estimate decides only recordings shorter than 6 seconds. The desktop acts on it rather than waiting because a false flag costs one batch round trip and counts once toward the backend gate, while a miss pastes nonsense.
diff --git a/src/helpers/audioManager.js b/src/helpers/audioManager.js
index 7eca16a50..fbbffe533 100644
--- a/src/helpers/audioManager.js
+++ b/src/helpers/audioManager.js
@@ -136,9 +136,11 @@ import {
import {
REALTIME_MODELS,
defaultStreamingProviderName,
+ orukeetDetectedLanguageFields,
resolveManagedOrukeetRoute,
resolveStreamingProviderName,
buildStreamingSessionOptions,
+ shouldRetranscribeOrukeetLanguage,
} from "./dictationStreamingRouting";
const REASONING_CACHE_TTL = 30000; // 30 seconds
@@ -3366,13 +3368,24 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);
const streamingFallbackReason =
metadata.streamingFallbackReason ?? this.consumeStreamingFallbackReason(settings);
if (streamingFallbackReason) opts.streamingFallbackReason = streamingFallbackReason;
+ // Orukeet's audio estimate rides along for the backend's per-user gate
+ // only. It is never the declared `language`: /api/transcribe picks models
+ // by declared language, and the fallback must be the request the user
+ // would make without Orukeet.
+ const detectedLanguageFields = metadata.detectedLanguageFields || {};
+ Object.assign(opts, detectedLanguageFields);
if (analyticsSyncEnabled(settings)) {
opts.analyticsOccurredAt = analyticsOccurredAt.toISOString();
opts.localDate = localDateKey(analyticsOccurredAt);
}
const cleanupCloudMode = settings.cleanupCloudMode || "openwhispr";
// Only cloud cleanup writes a combined STT log; translation alone does not.
- if (settings.useCleanupModel && cleanupCloudMode === "openwhispr") {
+ // A voice assistant recording never runs cleanup, so this upload is its log.
+ if (
+ settings.useCleanupModel &&
+ cleanupCloudMode === "openwhispr" &&
+ !this.voiceAgentRequested
+ ) {
opts.sendLogs = "false";
}
@@ -3445,6 +3458,7 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);
language: this.getCleanupLanguage(settings),
locale: settings.uiLanguage || "en",
streamingFallbackReason,
+ ...detectedLanguageFields,
sttProvider: result.sttProvider,
sttModel: result.sttModel,
sttProcessingMs: result.sttProcessingMs,
@@ -3490,6 +3504,7 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);
mode: "cloudReason",
meta: {
streamingFallbackReason,
+ ...detectedLanguageFields,
sttProvider: result.sttProvider,
sttModel: result.sttModel,
sttProcessingMs: result.sttProcessingMs,
@@ -5130,6 +5145,7 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);
const provider = this.getStreamingProvider();
let acknowledgedFinal = null;
let finalAcknowledged = false;
+ let orukeetFinal = null;
// The worklet emits PCM followed by "flushed" on the same message port.
// IPC sends and the finalize invoke preserve that order in the main process.
if (this.streamingProcessor && provider.finalizeAcknowledged) {
@@ -5221,6 +5237,7 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);
if (provider.finalizeAcknowledged) {
const result = await (acknowledgedFinal || provider.finalize());
finalAcknowledged = result?.success === true;
+ if (finalAcknowledged) orukeetFinal = result;
if (finalAcknowledged && typeof result.text === "string") {
this.streamingFinalText = result.text;
}
@@ -5288,8 +5305,79 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);
// the batch path, which already keeps raw and processed text separate.
const rawStreamingText = finalText;
+ let usedBatchFallback = false;
+ let batchWarning = null;
+ let batchFallbackResult = null;
+ let failureReport = null;
+ const isOrukeetStream = this.getStreamingProviderName() === "orukeet";
+ const detectedLanguageFields = isOrukeetStream
+ ? orukeetDetectedLanguageFields(orukeetFinal)
+ : {};
+
+ // Orukeet renders speech outside its 25 languages as confident nonsense.
+ // With a confident final estimate, send the kept recording through Cloud
+ // as the same "auto" request the user makes without Orukeet, before any
+ // cleanup spends a call on the discarded text.
+ if (
+ isOrukeetStream &&
+ fallbackBlob?.size > 0 &&
+ resolveStreamingFallbackTarget(stSettings) === "cloud" &&
+ shouldRetranscribeOrukeetLanguage({ language: streamingSttLanguage, final: orukeetFinal })
+ ) {
+ logger.info(
+ "Orukeet detected an unsupported language, re-transcribing through Cloud",
+ detectedLanguageFields,
+ "streaming"
+ );
+ // Orukeet's text is the nonsense this path exists to catch, so it is
+ // never kept: a failed re-transcription ends as a batch recording's would.
+ const failLanguageFallback = (error) => {
+ logger.error(
+ "Language re-transcription failed, discarding the Orukeet transcript",
+ { error: error.message, code: error.code },
+ "streaming"
+ );
+ finalText = "";
+ const outcome = transcriptionFailureOutcome(error);
+ failureReport = outcome.report;
+ if (outcome.keepAudio) {
+ this.saveFailedTranscription(error.message, error.code || null, {
+ durationSeconds,
+ analyticsOccurredAt: analyticsOccurredAt.toISOString(),
+ });
+ }
+ };
+ try {
+ const batchResult = await this.processWithOpenWhisprCloud(
+ fallbackBlob,
+ {
+ durationSeconds,
+ analyticsOccurredAt: analyticsOccurredAt.toISOString(),
+ streamingFallbackReason: "language_detected_unsupported",
+ detectedLanguageFields,
+ },
+ wasCancelled
+ );
+ if (wasCancelled()) return true;
+ if (batchResult?.text) {
+ finalText = batchResult.text;
+ usedBatchFallback = true;
+ batchFallbackResult = batchResult;
+ batchWarning = batchResult.warning || null;
+ } else {
+ failLanguageFallback(
+ Object.assign(new Error("No speech detected in audio"), { code: "NO_SPEECH_DETECTED" })
+ );
+ }
+ } catch (languageFallbackErr) {
+ if (wasCancelled()) return true;
+ failLanguageFallback(languageFallbackErr);
+ }
+ }
+
let usedCloudReasoning = false;
- if (finalText) {
+ // The Cloud batch path already ran its own cleanup, agent or translation.
+ if (finalText && !usedBatchFallback) {
const reasoningStart = performance.now();
const agentName = getAgentName();
const screenContext = this.voiceAgentRequested ? await this.consumeScreenContext() : null;
@@ -5342,6 +5430,7 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);
sttProcessingMs: streamingSttProcessingMs,
sttWordCount: streamingSttWordCount,
sttLanguage: streamingSttLanguage,
+ ...detectedLanguageFields,
audioDurationMs: durationSeconds ? Math.round(durationSeconds * 1000) : undefined,
audioSizeBytes: streamingAudioBytesSent || undefined,
audioFormat: "linear16",
@@ -5400,6 +5489,7 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);
sttProcessingMs: streamingSttProcessingMs,
sttWordCount: streamingSttWordCount,
sttLanguage: streamingSttLanguage,
+ ...detectedLanguageFields,
audioDurationMs: durationSeconds
? Math.round(durationSeconds * 1000)
: undefined,
@@ -5446,10 +5536,6 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);
// If streaming produced no text, fall back to batch — routed so BYOK audio
// and cloud audio never cross over (see resolveStreamingFallbackTarget).
- let usedBatchFallback = false;
- let batchWarning = null;
- let batchFallbackResult = null;
- 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.
@@ -5506,7 +5592,7 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);
// 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"
+ ...(failoverReason || isOrukeetStream
? { streamingFallbackReason: failoverReason || "stream_no_final" }
: {}),
},
@@ -5583,6 +5669,7 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);
sttModel: streamingSttModel,
sttProcessingMs: streamingSttProcessingMs,
sttLanguage: streamingSttLanguage,
+ ...detectedLanguageFields,
audioSizeBytes: streamingAudioBytesSent || undefined,
audioFormat: "linear16",
clientTotalMs,
diff --git a/src/helpers/dictationStreamingRouting.js b/src/helpers/dictationStreamingRouting.js
index ee3216102..8421db5be 100644
--- a/src/helpers/dictationStreamingRouting.js
+++ b/src/helpers/dictationStreamingRouting.js
@@ -13,6 +13,51 @@ const ORUKEET_LANGUAGES = new Set(
modelRegistryData.parakeetModels[ORUKEET_MODEL].supportedLanguages
);
+// Oruk's audio classifier score (not a calibrated probability): 0.90 caught
+// 92% of unsupported FLEURS clips at 6 s and 62.5% at 3 s while flagging 0.4%
+// / 1.2% of supported ones. A false flag costs one batch round trip; a miss
+// pastes nonsense. See docs/orukeet-streaming-language.md.
+const ORUKEET_LANGUAGE_FALLBACK_MIN_CONFIDENCE = 0.9;
+const ORUKEET_LANGUAGE_FALLBACK_MIN_AUDIO_SECONDS = 3;
+
+export function isOrukeetLanguage(code) {
+ if (typeof code !== "string" || !code) return false;
+ return ORUKEET_LANGUAGES.has(code.split("-")[0].toLowerCase());
+}
+
+// Auto mode only: an explicit language outside the 25 never reaches Orukeet
+// (resolveManagedOrukeetRoute), and an explicit supported one is the user's
+// statement of what they speak. Only the final estimate counts; early
+// `language` events are provisional.
+export function shouldRetranscribeOrukeetLanguage({ language, final }) {
+ if (language && language !== "auto") return false;
+ if (!final || typeof final.language !== "string" || isOrukeetLanguage(final.language)) {
+ return false;
+ }
+ return (
+ Number.isFinite(final.languageConfidence) &&
+ final.languageConfidence >= ORUKEET_LANGUAGE_FALLBACK_MIN_CONFIDENCE &&
+ Number.isFinite(final.languageAudioSeconds) &&
+ final.languageAudioSeconds >= ORUKEET_LANGUAGE_FALLBACK_MIN_AUDIO_SECONDS
+ );
+}
+
+// Reported for every Orukeet dictation so the backend's per-user gate sees
+// what was spoken. No `language` key means an older gateway or no final:
+// nothing is reported, since "unknown" would misstate the detector.
+export function orukeetDetectedLanguageFields(final) {
+ if (!final || !("language" in final)) return {};
+ if (typeof final.language !== "string") return { sttDetectedLanguageStatus: "unknown" };
+ return {
+ sttDetectedLanguage: final.language,
+ sttDetectedLanguageConfidence: final.languageConfidence,
+ ...(Number.isFinite(final.languageAudioSeconds)
+ ? { sttDetectedLanguageAudioSeconds: final.languageAudioSeconds }
+ : {}),
+ sttDetectedLanguageStatus: "detected",
+ };
+}
+
export const REALTIME_MODELS = new Set(["gpt-4o-mini-transcribe", "gpt-4o-transcribe"]);
// REALTIME_MODELS is the OpenAI-only shortcut (it forces "openai-realtime"), so
@@ -38,8 +83,7 @@ export function resolveManagedOrukeetRoute({ settings, sttConfig, language }) {
return null;
}
if (!language || language === "auto") return "orukeet";
- const base = language.split("-")[0].toLowerCase();
- return ORUKEET_LANGUAGES.has(base) ? "orukeet" : "language_unsupported";
+ return isOrukeetLanguage(language) ? "orukeet" : "language_unsupported";
}
export function resolveStreamingProviderName({ settings, context, sttConfig, language }) {
diff --git a/src/helpers/ipcHandlers.js b/src/helpers/ipcHandlers.js
index 3321cecd1..45bc3d0d3 100644
--- a/src/helpers/ipcHandlers.js
+++ b/src/helpers/ipcHandlers.js
@@ -6187,6 +6187,10 @@ class IPCHandlers {
localDate: opts.localDate,
analyticsOccurredAt: opts.analyticsOccurredAt,
streamingFallbackReason: opts.streamingFallbackReason,
+ sttDetectedLanguage: opts.sttDetectedLanguage,
+ sttDetectedLanguageConfidence: opts.sttDetectedLanguageConfidence,
+ sttDetectedLanguageAudioSeconds: opts.sttDetectedLanguageAudioSeconds,
+ sttDetectedLanguageStatus: opts.sttDetectedLanguageStatus,
};
debugLogger.debug("Cloud transcribe request", { audioSize: audioData.length }, "cloud-api");
@@ -9403,6 +9407,10 @@ class IPCHandlers {
sttProcessingMs: opts.sttProcessingMs,
sttWordCount: opts.sttWordCount,
sttLanguage: opts.sttLanguage,
+ sttDetectedLanguage: opts.sttDetectedLanguage,
+ sttDetectedLanguageConfidence: opts.sttDetectedLanguageConfidence,
+ sttDetectedLanguageAudioSeconds: opts.sttDetectedLanguageAudioSeconds,
+ sttDetectedLanguageStatus: opts.sttDetectedLanguageStatus,
audioDurationMs: opts.audioDurationMs,
audioSizeBytes: opts.audioSizeBytes,
audioFormat: opts.audioFormat,
@@ -9646,6 +9654,10 @@ class IPCHandlers {
sttModel: opts.sttModel,
sttProcessingMs: opts.sttProcessingMs,
sttLanguage: opts.sttLanguage,
+ sttDetectedLanguage: opts.sttDetectedLanguage,
+ sttDetectedLanguageConfidence: opts.sttDetectedLanguageConfidence,
+ sttDetectedLanguageAudioSeconds: opts.sttDetectedLanguageAudioSeconds,
+ sttDetectedLanguageStatus: opts.sttDetectedLanguageStatus,
audioSizeBytes: opts.audioSizeBytes,
audioFormat: opts.audioFormat,
clientTotalMs: opts.clientTotalMs,
diff --git a/src/types/electron.ts b/src/types/electron.ts
index e7ae788a8..73ba5dc43 100644
--- a/src/types/electron.ts
+++ b/src/types/electron.ts
@@ -826,6 +826,14 @@ export interface ScreenRecordingAccessResult {
export type CloudReasonPurpose = "cleanup" | "assistant" | "translation" | "noteFormatting";
+// Orukeet's audio language estimate, reported for the backend's per-user gate.
+export interface SttDetectedLanguageFields {
+ sttDetectedLanguage?: string;
+ sttDetectedLanguageConfidence?: number;
+ sttDetectedLanguageAudioSeconds?: number;
+ sttDetectedLanguageStatus?: "detected" | "unknown";
+}
+
export interface ScreenContextImage {
mediaType: string;
/** Base64 image bytes, no data-URL prefix. */
@@ -2362,7 +2370,7 @@ declare global {
analyticsOccurredAt?: string;
// Why a managed-streaming user's dictation went batch (rollout metric).
streamingFallbackReason?: string;
- }
+ } & SttDetectedLanguageFields
) => Promise<
{
success: boolean;
@@ -2390,7 +2398,7 @@ declare global {
language?: string;
locale?: string;
streamingFallbackReason?: string;
- }
+ } & SttDetectedLanguageFields
) => Promise<{
success: boolean;
text?: string;
@@ -2420,7 +2428,7 @@ declare global {
analyticsOccurredAt?: string;
analyticsWordCount?: number;
analyticsCounterVersion?: number;
- }
+ } & SttDetectedLanguageFields
) => Promise<{
success: boolean;
wordsUsed?: number;
diff --git a/test/helpers/audioManagerStreamingFinalization.test.js b/test/helpers/audioManagerStreamingFinalization.test.js
index 1c42accd0..dc7954025 100644
--- a/test/helpers/audioManagerStreamingFinalization.test.js
+++ b/test/helpers/audioManagerStreamingFinalization.test.js
@@ -5,7 +5,7 @@ const { WebSocketServer } = require("ws");
const { OrukeetStreaming } = require("../../src/helpers/orukeetStreaming");
const { loadAudioManager } = require("./harness/audioManager");
-async function loadManagerClass(t) {
+async function loadManagerClass(t, mockModules) {
const { AudioManager } = await loadAudioManager(t, {
cachePrefix: "openwhispr-streaming-finalization-test-",
settingsKey: "__streamingFinalizationSettings",
@@ -15,6 +15,7 @@ async function loadManagerClass(t) {
cloudTranscriptionMode: "byok",
cloudTranscriptionProvider: "openai",
},
+ mockModules,
});
return AudioManager;
}
@@ -1248,3 +1249,428 @@ test("a managed Orukeet session fails over even if its route changes mid-recordi
assert.equal(manager._streamingStopPromise, null, "the recording is not cut off");
await manager.stopStreamingRecording();
});
+
+const JA_FINAL = {
+ success: true,
+ text: "ashita no kaigi",
+ model: "orukeet-v0.1.0",
+ language: "ja",
+ languageConfidence: 0.97,
+ languageAudioSeconds: 6,
+};
+
+const JA_DETECTION = {
+ sttDetectedLanguage: "ja",
+ sttDetectedLanguageConfidence: 0.97,
+ sttDetectedLanguageAudioSeconds: 6,
+ sttDetectedLanguageStatus: "detected",
+};
+
+const detectionFields = (opts) =>
+ Object.fromEntries(Object.entries(opts).filter(([key]) => key.startsWith("sttDetected")));
+
+function orukeetProvider(final) {
+ return {
+ finalizeAcknowledged: true,
+ finalize: async () => final,
+ stop: async () => ({ success: true, text: "" }),
+ };
+}
+
+// Stops a managed Cloud dictation whose provider acknowledged `final`, and
+// records what reached Cloud: batch uploads, cleanup requests, streaming usage
+// and the published result.
+async function stopManagedDictation(
+ AudioManager,
+ { final, providerName = "orukeet", language = "auto", upload, settings = {}, overrides = {} }
+) {
+ globalThis.__streamingFinalizationSettings = {
+ ...globalThis.__streamingFinalizationSettings,
+ cloudTranscriptionMode: "openwhispr",
+ isSignedIn: true,
+ ...settings,
+ };
+ const { manager } = createFinalizingManager(AudioManager);
+ manager.recordingStartTime = Date.now() - 8000;
+ manager.mergeRecordedSegments = async () => new Blob([new Uint8Array(100)]);
+ manager.getStreamingProvider = () => orukeetProvider(final);
+ manager.getStreamingProviderName = () => providerName;
+ manager.getEffectiveSttLanguage = () => language;
+ Object.assign(manager, overrides);
+ const uploads = [];
+ if (upload) {
+ manager.processWithOpenWhisprCloud = async (_blob, metadata) => {
+ uploads.push(metadata);
+ return upload(manager);
+ };
+ }
+ const reasonCalls = [];
+ globalThis.window.electronAPI.cloudReason = async (text, opts) => {
+ reasonCalls.push([text, opts]);
+ return { success: true, text: `${text}。` };
+ };
+ const usage = [];
+ globalThis.window.electronAPI.cloudStreamingUsage = async (_text, _seconds, opts) => {
+ usage.push(opts);
+ return { success: true };
+ };
+ let usageSettled;
+ const settled = new Promise((resolve) => {
+ usageSettled = resolve;
+ });
+ globalThis.window.dispatchEvent = () => usageSettled();
+ const published = [];
+ manager.onTranscriptionComplete = (result) => published.push(result);
+ const errors = [];
+ manager.onError = (error) => errors.push(error);
+ const stopResult = await manager.stopStreamingRecording();
+ // Usage settles only after a non-empty transcript is published.
+ if (published.some((result) => result.text)) await settled;
+ return { manager, uploads, reasonCalls, usage, published, errors, stopResult };
+}
+
+test("a confident unsupported estimate re-transcribes the kept recording through Cloud", async (t) => {
+ const AudioManager = await loadManagerClass(t);
+ const { uploads, usage, published } = await stopManagedDictation(AudioManager, {
+ final: JA_FINAL,
+ upload: async () => ({ text: "明日の会議", rawText: "明日の会議" }),
+ });
+ assert.equal(uploads.length, 1);
+ assert.equal(uploads[0].streamingFallbackReason, "language_detected_unsupported");
+ assert.deepEqual(uploads[0].detectedLanguageFields, JA_DETECTION);
+ assert.equal(Object.hasOwn(uploads[0], "language"), false);
+ assert.equal(published[0].text, "明日の会議");
+ assert.equal(published[0].rawText, "明日の会議");
+ // /api/transcribe metered the re-transcription; the stream is not metered too.
+ assert.equal(usage.length, 0);
+});
+
+test("language re-transcription skips streaming cleanup", async (t) => {
+ const AudioManager = await loadManagerClass(t, {
+ "/stores/settingsStore": `
+ export const getSettings = () => globalThis.__streamingFinalizationSettings;
+ export const getEffectiveCleanupModel = () => null;
+ export const selectResolvedLLMConfig = () => ({ model: null, provider: null });
+ export const isCloudCleanupMode = () => true;
+ export const isCloudDictationAgentMode = () => false;
+ export const isCloudTranslationMode = () => false;
+ `,
+ });
+ const originalNavigator = globalThis.navigator;
+ Object.defineProperty(globalThis, "navigator", { value: { onLine: true }, configurable: true });
+ t.after(() =>
+ Object.defineProperty(globalThis, "navigator", {
+ value: originalNavigator,
+ configurable: true,
+ })
+ );
+ const transcribeOpts = [];
+ globalThis.window.electronAPI.cloudTranscribe = async (_audio, opts) => {
+ transcribeOpts.push(opts);
+ return { success: true, text: "明日の会議", sttProvider: "openai" };
+ };
+ const { reasonCalls, usage, published } = await stopManagedDictation(AudioManager, {
+ final: JA_FINAL,
+ settings: { useCleanupModel: true, cleanupCloudMode: "openwhispr", customPrompts: {} },
+ overrides: {
+ isDictionaryEcho: () => false,
+ getWhisperPrompt: () => null,
+ finalizeChineseScript: async (text) => text,
+ },
+ });
+ // The real batch path ran: an "auto" upload that never declares the estimate.
+ assert.equal(transcribeOpts.length, 1);
+ assert.equal(Object.hasOwn(transcribeOpts[0], "language"), false);
+ assert.equal(transcribeOpts[0].streamingFallbackReason, "language_detected_unsupported");
+ assert.equal(transcribeOpts[0].sttDetectedLanguage, "ja");
+ // One cleanup, on the Cloud transcript; Orukeet's text never reaches /api/reason.
+ assert.deepEqual(
+ reasonCalls.map(([text]) => text),
+ ["明日の会議"]
+ );
+ assert.equal(reasonCalls[0][1].sttDetectedLanguage, "ja");
+ assert.equal(published[0].text, "明日の会議。");
+ assert.equal(usage.length, 0);
+});
+
+test("a low score, short window, supported or unknown estimate keeps the Orukeet text", async (t) => {
+ const AudioManager = await loadManagerClass(t);
+ for (const [final, expected] of [
+ [
+ { ...JA_FINAL, languageConfidence: 0.89 },
+ { ...JA_DETECTION, sttDetectedLanguageConfidence: 0.89 },
+ ],
+ [
+ { ...JA_FINAL, languageAudioSeconds: 2 },
+ { ...JA_DETECTION, sttDetectedLanguageAudioSeconds: 2 },
+ ],
+ [
+ { ...JA_FINAL, language: "de" },
+ { ...JA_DETECTION, sttDetectedLanguage: "de" },
+ ],
+ [
+ { ...JA_FINAL, language: null, languageConfidence: null },
+ { sttDetectedLanguageStatus: "unknown" },
+ ],
+ ]) {
+ const { uploads, usage, published } = await stopManagedDictation(AudioManager, {
+ final,
+ upload: async () => assert.fail("must not re-transcribe"),
+ });
+ assert.equal(uploads.length, 0);
+ assert.equal(published[0].text, "ashita no kaigi");
+ assert.equal(usage.length, 1);
+ assert.deepEqual(detectionFields(usage[0]), expected);
+ }
+});
+
+test("an explicit language setting never re-transcribes", async (t) => {
+ const AudioManager = await loadManagerClass(t);
+ const { uploads, usage, published } = await stopManagedDictation(AudioManager, {
+ final: JA_FINAL,
+ language: "en",
+ upload: async () => assert.fail("must not re-transcribe"),
+ });
+ assert.equal(uploads.length, 0);
+ assert.equal(published[0].text, "ashita no kaigi");
+ assert.deepEqual(detectionFields(usage[0]), JA_DETECTION);
+});
+
+test("an older gateway sends no detection fields", async (t) => {
+ const AudioManager = await loadManagerClass(t);
+ const { uploads, usage, published } = await stopManagedDictation(AudioManager, {
+ final: { success: true, text: "hello there" },
+ upload: async () => assert.fail("must not re-transcribe"),
+ });
+ assert.equal(uploads.length, 0);
+ assert.equal(published[0].text, "hello there");
+ assert.deepEqual(detectionFields(usage[0]), {});
+});
+
+test("a failed re-transcription is reported and kept for retry, never pasting Orukeet's text", async (t) => {
+ const AudioManager = await loadManagerClass(t);
+ const saved = [];
+ const { uploads, reasonCalls, usage, published, errors } = await stopManagedDictation(
+ AudioManager,
+ {
+ final: JA_FINAL,
+ upload: async () => {
+ throw new Error("Cloud transcription failed");
+ },
+ overrides: { saveFailedTranscription: (...args) => saved.push(args) },
+ }
+ );
+ assert.equal(uploads.length, 1);
+ assert.deepEqual(
+ errors.map(({ title, description }) => [title, description]),
+ [["Transcription Error", "Transcription failed: Cloud transcription failed"]]
+ );
+ assert.deepEqual(
+ saved.map(([message, code]) => [message, code]),
+ [["Cloud transcription failed", null]]
+ );
+ assert.deepEqual(published, []);
+ assert.deepEqual(reasonCalls, []);
+ assert.deepEqual(usage, []);
+});
+
+test("a re-transcription that returns no text ends empty and keeps the recording", async (t) => {
+ const AudioManager = await loadManagerClass(t);
+ const saved = [];
+ const { reasonCalls, usage, published, errors } = await stopManagedDictation(AudioManager, {
+ final: JA_FINAL,
+ upload: async () => ({ text: "" }),
+ overrides: { saveFailedTranscription: (...args) => saved.push(args) },
+ });
+ assert.deepEqual(published, [{ success: true, text: "" }]);
+ assert.deepEqual(
+ saved.map(([, code]) => code),
+ ["NO_SPEECH_DETECTED"]
+ );
+ assert.deepEqual(errors, []);
+ assert.deepEqual(reasonCalls, []);
+ assert.deepEqual(usage, []);
+});
+
+test("Cloud finding no speech ends the dictation empty and keeps the recording", async (t) => {
+ const AudioManager = await loadManagerClass(t);
+ const { dictionaryEchoError } = await import("../../src/utils/dictionaryEchoFilter.js");
+ for (const error of [
+ Object.assign(new Error("No speech detected in audio"), { code: "NO_SPEECH_DETECTED" }),
+ dictionaryEchoError(),
+ ]) {
+ const saved = [];
+ const { uploads, reasonCalls, usage, published } = await stopManagedDictation(AudioManager, {
+ final: JA_FINAL,
+ upload: async () => {
+ throw error;
+ },
+ overrides: { saveFailedTranscription: (...args) => saved.push(args) },
+ });
+ assert.equal(uploads.length, 1, error.code);
+ assert.deepEqual(published, [{ success: true, text: "" }], error.code);
+ // Neither Orukeet's text nor a second metering (an echo was already metered).
+ assert.deepEqual(reasonCalls, [], error.code);
+ assert.deepEqual(usage, [], error.code);
+ assert.deepEqual(
+ saved.map(([, code]) => code),
+ [error.code]
+ );
+ }
+});
+
+test("a re-transcription that reaches the word limit opens the upgrade prompt", async (t) => {
+ const AudioManager = await loadManagerClass(t);
+ const { published } = await stopManagedDictation(AudioManager, {
+ final: JA_FINAL,
+ upload: async () => ({
+ text: "明日の会議",
+ rawText: "明日の会議",
+ source: "openwhispr",
+ limitReached: true,
+ wordsUsed: 2000,
+ wordsRemaining: 0,
+ }),
+ });
+ assert.equal(published[0].source, "openwhispr");
+ assert.equal(published[0].limitReached, true);
+ assert.equal(published[0].wordsUsed, 2000);
+ assert.equal(published[0].wordsRemaining, 0);
+});
+
+test("only a signed-in OpenWhispr Cloud recording is re-transcribed", async (t) => {
+ const AudioManager = await loadManagerClass(t);
+ for (const settings of [{ cloudTranscriptionMode: "byok" }, { isSignedIn: false }]) {
+ const { uploads, published } = await stopManagedDictation(AudioManager, {
+ final: JA_FINAL,
+ settings,
+ upload: async () => assert.fail("must not upload to Cloud"),
+ });
+ assert.equal(uploads.length, 0, JSON.stringify(settings));
+ assert.equal(published[0].text, "ashita no kaigi");
+ }
+});
+
+test("kept Orukeet text carries the estimate into streaming cleanup and translation", async (t) => {
+ const AudioManager = await loadManagerClass(t, {
+ "/stores/settingsStore": `
+ export const getSettings = () => globalThis.__streamingFinalizationSettings;
+ export const getEffectiveCleanupModel = () => null;
+ export const selectResolvedLLMConfig = () => ({ model: null, provider: null });
+ export const isCloudCleanupMode = () => true;
+ export const isCloudDictationAgentMode = () => false;
+ export const isCloudTranslationMode = () => true;
+ `,
+ "/config/prompts": `
+ export const resolvePrompt = () => "translation prompt";
+ export const appendScreenContextSuffix = (prompt) => prompt;
+ `,
+ "/dictationAgentInference": `
+ export const resolveDictationAgentInference = () => ({ reachable: false, config: {} });
+ export const resolveDictationAgentVisionInference = () => ({ active: false, config: {} });
+ `,
+ "/dictationTranslationInference": `
+ export const resolveDictationTranslationInference = () => ({
+ reachable: true, model: "translation-model", config: { provider: "openwhispr" }
+ });
+ `,
+ });
+ for (const translationRequested of [false, true]) {
+ const { uploads, reasonCalls, usage, published } = await stopManagedDictation(AudioManager, {
+ final: { ...JA_FINAL, languageConfidence: 0.89 },
+ upload: async () => assert.fail("must not re-transcribe"),
+ settings: {
+ useCleanupModel: true,
+ cleanupCloudMode: "openwhispr",
+ customPrompts: {},
+ translationSourceLanguage: "en",
+ translationTargetLanguage: "es",
+ },
+ overrides: {
+ translationRequested,
+ processWithReasoningModel: async () => "translated transcript",
+ finalizeChineseScript: async (text) => text,
+ },
+ });
+ const label = translationRequested ? "translation" : "cleanup";
+ assert.equal(uploads.length, 0, label);
+ assert.equal(
+ published[0].text,
+ translationRequested ? "translated transcript" : "ashita no kaigi。",
+ label
+ );
+ // The cleanup call writes the combined log the backend's gate reads.
+ assert.equal(reasonCalls.length, 1, label);
+ assert.deepEqual(
+ detectionFields(reasonCalls[0][1]),
+ { ...JA_DETECTION, sttDetectedLanguageConfidence: 0.89 },
+ label
+ );
+ assert.equal(usage[0].sendLogs, false, label);
+ }
+});
+
+test("a non-Orukeet provider is untouched", async (t) => {
+ const AudioManager = await loadManagerClass(t);
+ const { uploads, usage, published } = await stopManagedDictation(AudioManager, {
+ final: JA_FINAL,
+ providerName: "deepgram",
+ upload: async () => assert.fail("must not re-transcribe"),
+ });
+ assert.equal(uploads.length, 0);
+ assert.equal(published[0].text, "ashita no kaigi");
+ assert.deepEqual(detectionFields(usage[0]), {});
+});
+
+test("an empty Orukeet final with a confident unsupported estimate still re-transcribes", async (t) => {
+ const AudioManager = await loadManagerClass(t);
+ const { uploads, usage, published } = await stopManagedDictation(AudioManager, {
+ final: { ...JA_FINAL, text: "" },
+ upload: async () => ({ text: "明日の会議", rawText: "明日の会議" }),
+ });
+ assert.equal(uploads.length, 1);
+ assert.equal(published[0].text, "明日の会議");
+ assert.equal(usage.length, 0);
+});
+
+test("a selection edit that fails during the language re-transcription surfaces its error", async (t) => {
+ const AudioManager = await loadManagerClass(t);
+ const selectionEditFailure = () =>
+ Object.assign(new Error("Selection edit failed"), {
+ selectionEditFatal: true,
+ code: "SELECTION_EDIT_REASONING_FAILED",
+ });
+ const saved = [];
+ const { reasonCalls, usage, published, errors } = await stopManagedDictation(AudioManager, {
+ final: JA_FINAL,
+ upload: async () => {
+ throw selectionEditFailure();
+ },
+ overrides: { saveFailedTranscription: (...args) => saved.push(args) },
+ });
+ // As a failed batch selection edit ends: its own title, recording kept.
+ assert.deepEqual(
+ errors.map(({ title, description, code }) => [title, description, code]),
+ [["Selection Edit Failed", "Selection edit failed", "SELECTION_EDIT_REASONING_FAILED"]]
+ );
+ assert.deepEqual(
+ saved.map(([, code]) => code),
+ ["SELECTION_EDIT_REASONING_FAILED"]
+ );
+ // Orukeet's discarded text is neither published nor edited with.
+ assert.deepEqual(published, []);
+ assert.deepEqual(reasonCalls, []);
+ assert.deepEqual(usage, []);
+
+ // A cancelled dictation ends quietly instead.
+ const cancelled = await stopManagedDictation(AudioManager, {
+ final: JA_FINAL,
+ upload: async (manager) => {
+ manager._requestStreamingCancellation();
+ throw selectionEditFailure();
+ },
+ });
+ assert.equal(cancelled.stopResult, true);
+ assert.deepEqual(cancelled.errors, []);
+ assert.deepEqual(cancelled.published, []);
+});
diff --git a/test/helpers/audioManagerStreamingRouting.test.js b/test/helpers/audioManagerStreamingRouting.test.js
index 9e023a6da..fb5dc59f1 100644
--- a/test/helpers/audioManagerStreamingRouting.test.js
+++ b/test/helpers/audioManagerStreamingRouting.test.js
@@ -385,6 +385,69 @@ test("a cloud upload reports why it was batch instead of the managed Orukeet str
]);
});
+// The Cloud batch pipeline end to end: upload, then cleanup or translation.
+async function loadCloudPipeline(
+ t,
+ { translationRequested, useCleanupModel, cleanupCloudMode, preferredLanguage = "en" }
+) {
+ const { createManager, window } = await loadAudioManager(t, {
+ cachePrefix: "openwhispr-fallback-cleanup-",
+ settingsKey: "__fallbackCleanupSettings",
+ settings: {
+ cloudTranscriptionMode: "openwhispr",
+ isSignedIn: true,
+ useCleanupModel,
+ cleanupCloudMode,
+ preferredLanguage,
+ translationSourceLanguage: "en",
+ translationTargetLanguage: "es",
+ customPrompts: {},
+ },
+ mockModules: {
+ "/stores/settingsStore": `
+ export const getSettings = () => globalThis.__fallbackCleanupSettings;
+ export const getEffectiveCleanupModel = () => "cleanup-model";
+ export const selectResolvedLLMConfig = () => ({ model: "cleanup-model", provider: "openwhispr" });
+ export const isCloudCleanupMode = () => globalThis.__fallbackCleanupSettings.cleanupCloudMode === "openwhispr";
+ export const isCloudDictationAgentMode = () => false;
+ export const isCloudTranslationMode = () => true;
+ `,
+ "/config/prompts": `
+ export const resolvePrompt = () => "translation prompt";
+ export const appendScreenContextSuffix = (prompt) => prompt;
+ `,
+ "/dictationAgentInference": `
+ export const resolveDictationAgentInference = () => ({ reachable: false, config: {} });
+ export const resolveDictationAgentVisionInference = () => ({ active: false, config: {} });
+ `,
+ "/dictationTranslationInference": `
+ export const resolveDictationTranslationInference = () => ({
+ reachable: true, model: "translation-model", config: { provider: "openwhispr" }
+ });
+ `,
+ },
+ });
+ const originalNavigator = globalThis.navigator;
+ Object.defineProperty(globalThis, "navigator", {
+ value: { onLine: true },
+ configurable: true,
+ });
+ t.after(() =>
+ Object.defineProperty(globalThis, "navigator", {
+ value: originalNavigator,
+ configurable: true,
+ })
+ );
+ const manager = createManager({
+ translationRequested,
+ isDictionaryEcho: () => false,
+ getWhisperPrompt: () => null,
+ finalizeChineseScript: async (text) => text,
+ processWithReasoningModel: async () => "translated transcript",
+ });
+ return { manager, window };
+}
+
for (const { name, translationRequested, useCleanupModel, cleanupCloudMode } of [
{
name: "cloud cleanup",
@@ -412,60 +475,10 @@ for (const { name, translationRequested, useCleanupModel, cleanupCloudMode } of
},
]) {
test(`batch fallback telemetry survives ${name}`, async (t) => {
- const { createManager, window } = await loadAudioManager(t, {
- cachePrefix: "openwhispr-fallback-cleanup-",
- settingsKey: "__fallbackCleanupSettings",
- settings: {
- cloudTranscriptionMode: "openwhispr",
- isSignedIn: true,
- useCleanupModel,
- cleanupCloudMode,
- preferredLanguage: "en",
- translationSourceLanguage: "en",
- translationTargetLanguage: "es",
- customPrompts: {},
- },
- mockModules: {
- "/stores/settingsStore": `
- export const getSettings = () => globalThis.__fallbackCleanupSettings;
- export const getEffectiveCleanupModel = () => "cleanup-model";
- export const selectResolvedLLMConfig = () => ({ model: "cleanup-model", provider: "openwhispr" });
- export const isCloudCleanupMode = () => globalThis.__fallbackCleanupSettings.cleanupCloudMode === "openwhispr";
- export const isCloudDictationAgentMode = () => false;
- export const isCloudTranslationMode = () => true;
- `,
- "/config/prompts": `
- export const resolvePrompt = () => "translation prompt";
- export const appendScreenContextSuffix = (prompt) => prompt;
- `,
- "/dictationAgentInference": `
- export const resolveDictationAgentInference = () => ({ reachable: false, config: {} });
- export const resolveDictationAgentVisionInference = () => ({ active: false, config: {} });
- `,
- "/dictationTranslationInference": `
- export const resolveDictationTranslationInference = () => ({
- reachable: true, model: "translation-model", config: { provider: "openwhispr" }
- });
- `,
- },
- });
- const originalNavigator = globalThis.navigator;
- Object.defineProperty(globalThis, "navigator", {
- value: { onLine: true },
- configurable: true,
- });
- t.after(() =>
- Object.defineProperty(globalThis, "navigator", {
- value: originalNavigator,
- configurable: true,
- })
- );
- const manager = createManager({
+ const { manager, window } = await loadCloudPipeline(t, {
translationRequested,
- isDictionaryEcho: () => false,
- getWhisperPrompt: () => null,
- finalizeChineseScript: async (text) => text,
- processWithReasoningModel: async () => "translated transcript",
+ useCleanupModel,
+ cleanupCloudMode,
});
const uploads = [];
const cleanupRequests = [];
@@ -501,3 +514,101 @@ for (const { name, translationRequested, useCleanupModel, cleanupCloudMode } of
assert.equal(cleanupRequests.length, combinedLog ? 6 : 0);
});
}
+
+const JA_DETECTION = {
+ sttDetectedLanguage: "ja",
+ sttDetectedLanguageConfidence: 0.97,
+ sttDetectedLanguageAudioSeconds: 6,
+ sttDetectedLanguageStatus: "detected",
+};
+
+test("the language fallback upload declares auto, never the detected language", async (t) => {
+ const { manager, window } = await loadCloudPipeline(t, {
+ translationRequested: false,
+ useCleanupModel: false,
+ cleanupCloudMode: "openwhispr",
+ preferredLanguage: "auto",
+ });
+ const captured = [];
+ window.electronAPI.cloudTranscribe = async (_buffer, opts) => {
+ captured.push(opts);
+ return { success: true, text: "日本語のテキスト", sttProvider: "openai" };
+ };
+ const result = await manager.processWithOpenWhisprCloud(new Blob([new Uint8Array(100)]), {
+ streamingFallbackReason: "language_detected_unsupported",
+ detectedLanguageFields: JA_DETECTION,
+ });
+ assert.equal(result.text, "日本語のテキスト");
+ assert.equal(Object.hasOwn(captured[0], "language"), false);
+ assert.equal(captured[0].streamingFallbackReason, "language_detected_unsupported");
+ assert.equal(captured[0].sttDetectedLanguage, "ja");
+ assert.equal(captured[0].sttDetectedLanguageConfidence, 0.97);
+ assert.equal(captured[0].sttDetectedLanguageAudioSeconds, 6);
+ assert.equal(captured[0].sttDetectedLanguageStatus, "detected");
+});
+
+test("a voice assistant upload writes its own log, since no cleanup call does", async (t) => {
+ const { manager, window } = await loadCloudPipeline(t, {
+ translationRequested: false,
+ useCleanupModel: true,
+ cleanupCloudMode: "openwhispr",
+ preferredLanguage: "auto",
+ });
+ const agentCommands = [];
+ Object.assign(manager, {
+ voiceAgentRequested: true,
+ consumeScreenContext: async () => null,
+ processAgentCommand: async (text) => {
+ agentCommands.push(text);
+ return text;
+ },
+ });
+ const uploads = [];
+ window.electronAPI.cloudTranscribe = async (_audio, opts) => {
+ uploads.push(opts);
+ return { success: true, text: "明日の会議", sttProvider: "openai" };
+ };
+ const reasonCalls = [];
+ window.electronAPI.cloudReason = async (...args) => {
+ reasonCalls.push(args);
+ return { success: true, text: "" };
+ };
+ await manager.processWithOpenWhisprCloud(new Blob([new Uint8Array(16)]), {
+ streamingFallbackReason: "language_detected_unsupported",
+ detectedLanguageFields: JA_DETECTION,
+ });
+ assert.deepEqual(agentCommands, ["明日の会議"]);
+ assert.equal(reasonCalls.length, 0);
+ assert.equal(Object.hasOwn(uploads[0], "sendLogs"), false);
+ assert.equal(uploads[0].sttDetectedLanguage, "ja");
+});
+
+for (const translationRequested of [false, true]) {
+ test(`with cloud ${translationRequested ? "translation " : ""}cleanup the combined log request carries the detection`, async (t) => {
+ const { manager, window } = await loadCloudPipeline(t, {
+ translationRequested,
+ useCleanupModel: true,
+ cleanupCloudMode: "openwhispr",
+ preferredLanguage: "auto",
+ });
+ const reasonOpts = [];
+ window.electronAPI.cloudTranscribe = async () => ({
+ success: true,
+ text: "日本語",
+ sttProvider: "openai",
+ });
+ window.electronAPI.cloudReason = async (_text, opts) => {
+ reasonOpts.push(opts);
+ return { success: true, text: "日本語。" };
+ };
+ await manager.processWithOpenWhisprCloud(new Blob([new Uint8Array(100)]), {
+ streamingFallbackReason: "language_detected_unsupported",
+ detectedLanguageFields: JA_DETECTION,
+ });
+ assert.equal(reasonOpts.length, 1);
+ assert.equal(reasonOpts[0].streamingFallbackReason, "language_detected_unsupported");
+ for (const [key, value] of Object.entries(JA_DETECTION)) {
+ assert.equal(reasonOpts[0][key], value, key);
+ }
+ });
+}
diff --git a/test/helpers/orukeetCloudSession.test.js b/test/helpers/orukeetCloudSession.test.js
index 8ddd55d9b..c41be0fea 100644
--- a/test/helpers/orukeetCloudSession.test.js
+++ b/test/helpers/orukeetCloudSession.test.js
@@ -137,6 +137,24 @@ for (const [status, code] of [
});
}
+test("a language exclusion keeps FEATURE_NOT_ENABLED for the batch fallback", async (t) => {
+ const f = await fixture(t, async () =>
+ Response.json(
+ {
+ error: "Orukeet dictation is not enabled for this account",
+ code: "FEATURE_NOT_ENABLED",
+ reason: "language_unsupported",
+ },
+ { status: 403 }
+ )
+ );
+ await assert.rejects(connectManagedOrukeet(f.options), {
+ code: "FEATURE_NOT_ENABLED",
+ status: 403,
+ });
+ assert.equal(f.sockets.length, 0);
+});
+
test("the weekly word quota surfaces as LIMIT_REACHED with its usage, not the mint cap", async (t) => {
const f = await fixture(t, async () =>
Response.json(
diff --git a/test/helpers/orukeetDictationIpc.test.js b/test/helpers/orukeetDictationIpc.test.js
index 9997b3c22..44bc24d8a 100644
--- a/test/helpers/orukeetDictationIpc.test.js
+++ b/test/helpers/orukeetDictationIpc.test.js
@@ -28,6 +28,7 @@ const cloudSession = {
const { once, EventEmitter } = require("node:events");
const { WebSocket, WebSocketServer } = require("ws");
const { OrukeetStreaming } = require("../../src/helpers/orukeetStreaming");
+const AgentStreamRequestRegistry = require("../../src/helpers/agentStreamRequestRegistry");
let server,
target,
opened = 0;
@@ -36,6 +37,19 @@ let commitCount = 0;
const messages = [];
const event = { sender: new EventEmitter() };
event.sender.send = (channel, text) => messages.push([channel, text]);
+event.sender.id = 1;
+const backendFetch = async (url, options) => {
+ assert.ok(
+ [
+ "https://api.openwhispr.test/api/stt/orukeet/session",
+ "https://api.openwhispr.test/api/reason",
+ "https://api.openwhispr.test/api/streaming-usage",
+ "https://api.openwhispr.test/api/transcribe",
+ ].includes(url)
+ );
+ assert.equal(options.headers.Authorization, "Bearer account-a");
+ return backendResponse(url, options);
+};
const managedOptions = {
provider: "orukeet",
mode: "openwhispr",
@@ -57,18 +71,7 @@ const electronStub = {
on: (channel, fn) => handlers.set(channel, fn),
removeHandler: () => {},
},
- net: {
- fetch: async (url, options) => {
- assert.ok(
- [
- "https://api.openwhispr.test/api/stt/orukeet/session",
- "https://api.openwhispr.test/api/reason",
- ].includes(url)
- );
- assert.equal(options.headers.Authorization, "Bearer account-a");
- return backendResponse(url, options);
- },
- },
+ net: { fetch: backendFetch },
BrowserWindow: class BrowserWindow {
static getAllWindows() {
return [];
@@ -81,7 +84,13 @@ const electronStub = {
dialog: {},
screen: { getPrimaryDisplay: () => ({ workAreaSize: { width: 0, height: 0 } }) },
systemPreferences: { getMediaAccessStatus: () => "granted" },
- session: { fromPartition: () => ({}) },
+ // Cloud uploads go through a dedicated session partition.
+ session: {
+ fromPartition: () => ({
+ webRequest: { onBeforeSendHeaders: () => {} },
+ fetch: backendFetch,
+ }),
+ },
clipboard: {},
nativeImage: {},
globalShortcut: {},
@@ -145,6 +154,7 @@ function buildFakeThis() {
_dictationStreaming: null,
_dictationConnectPromise: null,
_dictationIdleTimer: null,
+ _cloudTranscriptionRequests: new AgentStreamRequestRegistry(),
};
return new Proxy(target, {
get: (value, property) => (property in value ? value[property] : anything()),
@@ -340,6 +350,84 @@ test("cloud cleanup forwards fallback telemetry to its combined log request", as
assert.equal(Object.hasOwn(requests[1], "streamingFallbackReason"), false);
});
+const DETECTED = {
+ sttDetectedLanguage: "ja",
+ sttDetectedLanguageConfidence: 0.97,
+ sttDetectedLanguageAudioSeconds: 6,
+ sttDetectedLanguageStatus: "detected",
+};
+
+test("cloud cleanup forwards the detected language to its combined log request", async () => {
+ const requests = [];
+ backendResponse = async (url, options) => {
+ requests.push(JSON.parse(options.body));
+ return Response.json({ text: "clean transcript" });
+ };
+ await handlers.get("cloud-reason")(event, "raw", {
+ purpose: "cleanup",
+ sttProvider: "orukeet",
+ ...DETECTED,
+ });
+ await handlers.get("cloud-reason")(event, "raw", { purpose: "cleanup", sttProvider: "orukeet" });
+ assert.deepEqual(
+ Object.fromEntries(Object.keys(DETECTED).map((key) => [key, requests[0][key]])),
+ DETECTED
+ );
+ for (const key of Object.keys(DETECTED)) {
+ assert.equal(Object.hasOwn(requests[1], key), false, key);
+ }
+});
+
+test("streaming usage forwards the detected language", async () => {
+ const requests = [];
+ backendResponse = async (url, options) => {
+ assert.match(url, /\/api\/streaming-usage$/);
+ requests.push(JSON.parse(options.body));
+ return Response.json({
+ recorded: true,
+ wordCount: 1,
+ wordsUsed: 1,
+ wordsRemaining: 10,
+ limitReached: false,
+ });
+ };
+ await handlers.get("cloud-streaming-usage")(event, "hello", 4, {
+ sttProvider: "orukeet",
+ ...DETECTED,
+ });
+ await handlers.get("cloud-streaming-usage")(event, "hello", 4, {
+ sttProvider: "orukeet",
+ sttDetectedLanguageStatus: "unknown",
+ });
+ assert.deepEqual(
+ Object.fromEntries(Object.keys(DETECTED).map((key) => [key, requests[0][key]])),
+ DETECTED
+ );
+ assert.equal(requests[1].sttDetectedLanguageStatus, "unknown");
+ assert.equal(Object.hasOwn(requests[1], "sttDetectedLanguage"), false);
+});
+
+test("the language fallback upload carries the fallback reason and detection, and no language", async () => {
+ const bodies = [];
+ backendResponse = async (url, options) => {
+ assert.match(url, /\/api\/transcribe$/);
+ bodies.push(Buffer.from(options.body).toString("latin1"));
+ return Response.json({ text: "日本語", wordsUsed: 1, wordsRemaining: 10 });
+ };
+ const result = await handlers.get("cloud-transcribe")(event, new Uint8Array(64).buffer, {
+ streamingFallbackReason: "language_detected_unsupported",
+ ...DETECTED,
+ });
+ assert.equal(result.success, true);
+ const body = bodies[0];
+ assert.match(body, /name="streamingFallbackReason"\r\n\r\nlanguage_detected_unsupported\r\n/);
+ assert.match(body, /name="sttDetectedLanguage"\r\n\r\nja\r\n/);
+ assert.match(body, /name="sttDetectedLanguageConfidence"\r\n\r\n0\.97\r\n/);
+ assert.match(body, /name="sttDetectedLanguageAudioSeconds"\r\n\r\n6\r\n/);
+ assert.match(body, /name="sttDetectedLanguageStatus"\r\n\r\ndetected\r\n/);
+ assert.doesNotMatch(body, /name="language"/);
+});
+
test("warmups landing together mint one session and share its unused socket", async () => {
await handlers.get("dictation-realtime-stop")();
let mints = 0;
diff --git a/test/helpers/orukeetManagedRouting.test.js b/test/helpers/orukeetManagedRouting.test.js
index 012234652..9c1eb7f4e 100644
--- a/test/helpers/orukeetManagedRouting.test.js
+++ b/test/helpers/orukeetManagedRouting.test.js
@@ -102,3 +102,92 @@ test("a BYOK custom Orukeet endpoint is not language gated", async () => {
"orukeet"
);
});
+
+test("a confident unsupported estimate on 3 s or more in auto mode re-transcribes", async () => {
+ const { shouldRetranscribeOrukeetLanguage } = await loadRouting();
+ for (const language of ["auto", "", undefined]) {
+ assert.equal(
+ shouldRetranscribeOrukeetLanguage({
+ language,
+ final: {
+ success: true,
+ text: "x",
+ language: "ja",
+ languageConfidence: 0.9,
+ languageAudioSeconds: 3,
+ },
+ }),
+ true,
+ String(language)
+ );
+ }
+});
+
+test("everything else keeps the Orukeet transcript", async () => {
+ const { shouldRetranscribeOrukeetLanguage } = await loadRouting();
+ const final = {
+ success: true,
+ text: "x",
+ language: "ja",
+ languageConfidence: 0.97,
+ languageAudioSeconds: 6,
+ };
+ const cases = [
+ { language: "en", final }, // explicit setting
+ { language: "ja", final }, // explicit (never reaches Orukeet anyway)
+ { language: "auto", final: { ...final, language: "de" } }, // supported
+ { language: "auto", final: { ...final, languageConfidence: 0.89 } },
+ { language: "auto", final: { ...final, languageAudioSeconds: 2.9 } },
+ { language: "auto", final: { ...final, languageAudioSeconds: undefined } },
+ { language: "auto", final: { ...final, language: null, languageConfidence: null } }, // unknown
+ { language: "auto", final: { success: true, text: "x" } }, // older gateway
+ { language: "auto", final: null }, // finalize failed
+ ];
+ for (const input of cases) {
+ assert.equal(shouldRetranscribeOrukeetLanguage(input), false, JSON.stringify(input));
+ }
+});
+
+test("detected-language fields mirror the final estimate for the backend", async () => {
+ const { orukeetDetectedLanguageFields } = await loadRouting();
+ assert.deepEqual(
+ orukeetDetectedLanguageFields({
+ text: "x",
+ language: "hi",
+ languageConfidence: 0.93,
+ languageAudioSeconds: 3,
+ }),
+ {
+ sttDetectedLanguage: "hi",
+ sttDetectedLanguageConfidence: 0.93,
+ sttDetectedLanguageAudioSeconds: 3,
+ sttDetectedLanguageStatus: "detected",
+ }
+ );
+ assert.deepEqual(
+ orukeetDetectedLanguageFields({ text: "x", language: "en", languageConfidence: 0.5 }),
+ {
+ sttDetectedLanguage: "en",
+ sttDetectedLanguageConfidence: 0.5,
+ sttDetectedLanguageStatus: "detected",
+ }
+ );
+ assert.deepEqual(
+ orukeetDetectedLanguageFields({ text: "x", language: null, languageConfidence: null }),
+ { sttDetectedLanguageStatus: "unknown" }
+ );
+ // Older gateway (no key), failed finalize, and silence send nothing at all.
+ assert.deepEqual(orukeetDetectedLanguageFields({ text: "x" }), {});
+ assert.deepEqual(orukeetDetectedLanguageFields(null), {});
+ assert.deepEqual(orukeetDetectedLanguageFields(undefined), {});
+});
+
+test("isOrukeetLanguage accepts the 25 base codes and regional variants only", async () => {
+ const { isOrukeetLanguage } = await loadRouting();
+ for (const code of ["en", "en-US", "PT-br", "uk", "mt"]) {
+ assert.equal(isOrukeetLanguage(code), true, code);
+ }
+ for (const code of ["ja", "zh-CN", "auto", "", null, undefined, 5]) {
+ assert.equal(isOrukeetLanguage(code), false, String(code));
+ }
+});
diff --git a/test/helpers/transcriptionFallback.test.js b/test/helpers/transcriptionFallback.test.js
index 3b4e2c7dd..bce5120ca 100644
--- a/test/helpers/transcriptionFallback.test.js
+++ b/test/helpers/transcriptionFallback.test.js
@@ -1,5 +1,9 @@
const test = require("node:test");
const assert = require("node:assert/strict");
+const {
+ createPolicyResponseError,
+ toPolicyFailure,
+} = require("../../src/helpers/policyResponseError");
const load = () => import("../../src/helpers/transcriptionFallback.js");
@@ -58,6 +62,22 @@ test("a disabled Orukeet rollout falls back to batch as feature_disabled", async
);
});
+test("a language exclusion keeps the feature_disabled batch fallback", async () => {
+ // The start result the session route's 403 body becomes over IPC.
+ const result = toPolicyFailure(
+ createPolicyResponseError(
+ 403,
+ {
+ error: "Orukeet dictation is not enabled for this account",
+ code: "FEATURE_NOT_ENABLED",
+ reason: "language_unsupported",
+ },
+ "Orukeet session unavailable (403)"
+ )
+ );
+ assert.equal(await orukeetStart(result), "feature_disabled");
+});
+
test("an exhausted session mint window falls back to batch as rate_limited", async () => {
assert.equal(
await orukeetStart({ success: false, code: "RATE_LIMITED", status: 429 }),