Skip to content

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

Integrate combined Orukeet cleanup and supported-language routing (#2436)

Nathan Roll1044d0095262
diff --git a/docs/orukeet-streaming-language.md b/docs/orukeet-streaming-language.md
index dee05f915..cd00f641e 100644
--- a/docs/orukeet-streaming-language.md
+++ b/docs/orukeet-streaming-language.md
@@ -8,6 +8,7 @@ Orukeet's optional audio-language detector runs independently while audio is arr
"text": "Example transcript.",
"language": "en",
"language_confidence": 0.99,
+ "language_supported_score": 0.995,
"language_audio_seconds": 6,
"language_source": "audio_lid",
"language_status": "detected"
@@ -18,7 +19,7 @@ The same language fields appear on early messages with `type: "language"`. This
The gateway does not wait for language detection before returning a transcript. Recordings shorter than three seconds, silent audio, detector overload/failure, or a result that is not ready at commit can return `language: null`, `language_confidence: null`, and `language_status: "unknown"`. Older gateways may omit these fields. Unknown must not be interpreted as English or as proof that the language is supported. This detector is not a voice-activity or code-switching detector.
-The desktop adapter preserves the optional final metadata as `language`, `languageConfidence`, and `languageAudioSeconds` in `dictationRealtimeFinalize()`. The renderer can subscribe to `onDictationRealtimeLanguage(callback)`; like other preload subscriptions, it returns an unsubscribe function. Hints never trigger a transcript or paste. The final estimate is authoritative for that recording. Routing policy remains with the caller; receiving metadata does not itself switch providers.
+The desktop adapter preserves the optional final metadata as `language`, `languageConfidence`, `languageSupportedScore`, and `languageAudioSeconds` in `dictationRealtimeFinalize()`. The renderer can subscribe to `onDictationRealtimeLanguage(callback)`; like other preload subscriptions, it returns an unsubscribe function. Hints never trigger a transcript or paste. The final estimate is authoritative for that recording. Routing policy remains with the caller; receiving metadata does not itself switch providers.
Orukeet supports these 25 language codes:
@@ -31,3 +32,74 @@ 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 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.
+
+## Combined supported-language score and opt-in rollout
+
+The preview adds `language_supported_score` to both language hints and the final result. It sums the detector's normalized scores for the 25 languages above; it is not a calibrated probability. The desktop exposes it as `languageSupportedScore`. Zero is valid. Null, absent, non-finite and out-of-range values are unavailable, not evidence of an unsupported language. A group score can still be valid if the top language has no two-letter ISO code.
+
+If no detector pass completed successfully, the preview final contains `language_supported_score: null`; the desktop omits the camelCase field. If the three-second pass completed but the six-second pass did not, the final retains that valid three-second result and reports `language_audio_seconds: 3`.
+
+On an expanded 950-clip FLEURS read-speech panel (38 languages, including Bengali, Urdu, Tamil, Telugu and Marathi), 908 clips had a full six-second window:
+
+| Rule | Unsupported caught | Supported wrongly diverted |
+| --------------------------- | -----------------: | -------------------------: |
+| Top unsupported score ≥0.30 | 311/312 | 26/596 |
+| Top unsupported score ≥0.50 | 305/312 | 19/596 |
+| Top unsupported score ≥0.70 | 276/312 | 14/596 |
+| Top unsupported score ≥0.90 | 248/312 | 4/596 |
+| Supported total ≤0.30 | 312/312 | 19/596 |
+| Supported total ≤0.10 | 310/312 | 6/596 |
+
+These are diagnostic results on read speech, not production error rates. The group rule is independent of the top label. Both proposed group cutoffs caught all 121 eligible clips in the five added languages. Those languages are included in the detector's 107-label vocabulary; this does not validate languages outside that vocabulary or code-switching.
+
+The supported-total ≤0.30 rule wrongly diverted **19 of 596 supported-language test clips (3.2%)**, not 3.2% of all traffic. The earlier 0.4% was 1 of 240 supported clips on a smaller panel using the stricter top-score ≥0.90 rule. On this expanded six-second panel, that same strict rule diverted 4/596 (0.7%). Both the panel and the routing rule changed; the two headline percentages are not a like-for-like model regression.
+
+For the expanded panel's three-second windows (325 unsupported and 625 supported clips):
+
+| Rule | Unsupported caught | Supported wrongly diverted |
+| --------------------------- | -----------------: | -------------------------: |
+| Top unsupported score ≥0.30 | 300/325 | 72/625 |
+| Top unsupported score ≥0.50 | 277/325 | 40/625 |
+| Top unsupported score ≥0.70 | 238/325 | 24/625 |
+| Top unsupported score ≥0.90 | 174/325 | 8/625 |
+| Supported total ≤0.30 | 317/325 | 76/625 |
+| Supported total ≤0.10 | 294/325 | 26/625 |
+
+The six-second group cutoffs produce too many false fallbacks at three seconds. The implementation leaves that window on the existing rule.
+
+The new routing policy is off by default. The authenticated `/api/stt-config` response can set `orukeetLanguageRouting` for a test cohort:
+
+| Value | Behavior |
+| -------------------------------- | ---------------------------------------------------- |
+| Absent, `"off"`, or unrecognized | Existing top-label rule; no comparison event |
+| `"shadow"` | Existing routing; log both group-score decisions |
+| `"supported-0.30"` | Existing rule OR supported total ≤0.30 when eligible |
+| `"supported-0.10"` | Existing rule OR supported total ≤0.10 when eligible |
+
+Eligibility requires Auto language, a valid final supported score, and `languageAudioSeconds >= 6`. Explicit language choices and BYOK behavior stay unchanged. Missing scores or shorter analyzed windows use the existing rule. The retained recording and existing Cloud fallback handle the actual re-transcription; failure never pastes the rejected Orukeet transcript or performs cleanup twice.
+
+A recording lasting six seconds does not guarantee a completed six-second detector pass. For example, a paced 6.1-second recording finalized with the three-second estimate during validation. Never substitute recording duration for `languageAudioSeconds`, or wait for detection to complete before finalizing.
+
+### Session compatibility
+
+The desktop declares the `orukeet-language-routing` capability. The backend only returns a preview URL or language-routing flag to clients carrying that capability; older clients keep their production URL and normal streaming behavior. The adapter accepts only exact approved HTTPS/WSS URL pairs, including `https://orukeet.gizmovoice.ai/preview/language-routing`; lookalike hosts, arbitrary paths and query parameters are rejected. Session credentials stay in the main process. Operator setup and direct replay instructions are in the private deployment handoff.
+
+### Comparison logs and validation
+
+Opt-in managed dictations carry `orukeetLanguageRouting` on the existing authenticated streaming-usage request, or on the batch/cleanup request when a fallback or cleanup owns the log. The server persists the allowlisted decision independently of renderer debug logging. It contains mode, supported score, analyzed duration and the compared rule decisions; it contains no transcript, audio or credential. BYOK sends no comparison. A group-score-only fallback uses `language_supported_score_low`; a legacy-rule fallback retains `language_detected_unsupported`.
+
+Export comparison events as JSONL and run:
+
+```sh
+node scripts/summarize-orukeet-language-routing.cjs comparison-events.jsonl
+```
+
+The script accepts exported server records with `metadata.orukeetLanguageRouting`, records with `meta`, or the comparison object itself. It reports eligible counts and disagreements. Accuracy needs a reference: a reviewer may add `expectedSupported: true` or `false` to the outer JSON object after checking the actual recording/language. Without reference labels, the script does not calculate a false-fallback rate or recall from the detector's own guess. Do not include recordings or transcripts in the exported comparison file.
+
+Start with `shadow` for internal testers and collect real dictation, including the reported failure, noise, short recordings and language switching. Review cases where the rules disagree, and supported-language examples even when they agree. Then choose a cutoff and enable it for the test cohort before expanding it.
+
+### Rollback
+
+Set `orukeetLanguageRouting` to `"off"` or remove it from `/api/stt-config`, and restore the production URL pair in the session endpoint. While an experiment is enabled, config expires after 30 seconds and refreshes at the next normal config check; restarting the app refreshes it immediately. Normal config retains its existing 15-minute TTL. No client rebuild is needed to roll back this flag.
+
+Provider, routing mode and cleanup options are captured at recording start, so a config refresh or rollback never switches an in-progress recording to a different provider. Operator admission and deployment commands live in the private handoff.
diff --git a/docs/orukeet-streaming.md b/docs/orukeet-streaming.md
index 2e2f83788..d62469863 100644
--- a/docs/orukeet-streaming.md
+++ b/docs/orukeet-streaming.md
@@ -15,19 +15,19 @@ The desktop supports this server-controlled `/api/stt-config` response for dicta
Keep the flag off until the private Cloud backend implements `POST /api/stt/orukeet/session`. That backend is maintained separately from this desktop repository. Before issuing a session, it must apply the existing account authentication, workspace policy, entitlement, allowance, rate and concurrency checks. Return the existing structured error format for denials; the desktop preserves auth refresh, policy and upgrade metadata.
-The backend-only [issue-session.cjs](integrations/orukeet/issue-session.cjs) calls the deployed token service and validates its response. Inject `ORUKEET_SERVICE_KEY` from the backend secret manager and return `await issueSession({ serviceKey, accountId: authenticatedUser.id })` with `Cache-Control: no-store`. Use the same opaque account ID across devices, derived from verified authentication, never a desktop-supplied ID. IDs must contain 8–128 letters, digits, underscores or hyphens; do not use an email address. The helper is outside the packaged Electron file allowlist. No service credential belongs in the app, renderer, repository, logs or response. No unauthenticated route is included here.
+Session minting, service credentials and operational deployment commands belong in the private Cloud backend and deployment handoff. The desktop receives only the authenticated session response.
-The response contains `baseUrl`, `websocketUrl`, `clientToken`, `protocol`, `expiresIn`, `singleUse`, and `model`. The main process validates all fields, pins the destination to `https://orukeet.gizmovoice.ai`, and connects using `orukeet.pcm.v1` and `auth.<clientToken>` WebSocket subprotocols. A renderer-selected URL cannot redirect managed credentials. Token issuance and connection are bound to the current account; cancellation or credential changes cannot reopen a stale session.
+The response contains `baseUrl`, `websocketUrl`, `clientToken`, `protocol`, `expiresIn`, `singleUse`, and `model`. The main process validates all fields, pins the destination to exact approved paths at `https://orukeet.gizmovoice.ai`, and connects using `orukeet.pcm.v1` and `auth.<clientToken>` WebSocket subprotocols. A renderer-selected URL cannot redirect managed credentials. Token issuance and connection are bound to the current account; cancellation or credential changes cannot reopen a stale session.
**Usage enforcement:** current GPU tokens are single-use connection credentials with a 60-second connection expiry, not per-user billing grants. An established socket can last longer. Token issuance checks alone do not enforce paid audio duration. Before a paid rollout, the private backend and gateway must provide trusted user/session metering or proxy sessions through an authenticated metered backend. Client duration telemetry is not a trusted billing receipt. Rebenchmark if a proxy hop is introduced.
-**Account concurrency:** account-bound sessions share one active recording and one idle/warm socket across the three regions. The default role is `warm`; receiving audio promotes it to `active`. A second concurrent recording is rejected before transcription, and the desktop retains its audio for the existing authorized fallback. Finishing or clearing returns the connection to `warm`; if another warm socket already exists, the completed connection closes after delivering its final result. A coordinator outage rejects new sessions and closes existing sessions after their lease expires. This bounds concurrency, not billable usage. Calls without `accountId` remain legacy-compatible and do not enforce a per-account cap. The private backend must supply the ID to enable this protection; the desktop PR alone cannot do that.
+**Account concurrency:** account-bound sessions share one active recording and one idle/warm socket across the three regions. The default role is `warm`; receiving audio promotes it to `active`. A second concurrent recording is rejected before transcription, and the desktop retains its audio for the existing authorized fallback. Account-bound sockets accept one finalized utterance, then close after delivering it; clearing cannot refund the cumulative audio budget. A coordinator outage rejects new sessions and closes existing sessions after their lease expires. This bounds concurrency, not billable usage. Calls without `accountId` remain legacy-compatible and do not enforce a per-account cap. The private backend must supply the ID to enable this protection; the desktop PR alone cannot do that.
## Recording lifecycle
The main process creates the adapter before requesting the session so initial PCM is buffered. The existing AudioWorklet emits mono PCM16 at 16 kHz. On release it sends its final PCM and a flush acknowledgement; only then does the desktop commit. Final acknowledgement replaces fixed settling delays. Successful silence is accepted without a second transcription. A flush failure closes the incomplete stream and preserves the existing recording fallback.
-The server can accept another recording on a surviving socket after a final resets its audio and language state. The desktop currently closes the used adapter after each recording and creates a new warm connection; it only reuses a socket that has carried no audio. An unused Orukeet connection closes after 60 seconds; recording startup cancels that timer. Cancellation closes without commit. Pending audio is bounded to 2 MiB; setup and final waits are bounded. Application heartbeats run every 15 seconds. The server allows at most 600 seconds of audio and uses overlapped windows above 60 seconds; an individual socket has a 20-minute lifetime.
+The desktop closes the used adapter after each recording and creates a new warm connection; it only reuses a socket that has carried no audio. An unused Orukeet connection closes after 60 seconds; recording startup cancels that timer. Cancellation closes without commit. Pending audio is bounded to 2 MiB; setup and final waits are bounded. Application heartbeats run every 15 seconds. The server allows at most 600 seconds of audio and uses overlapped windows above 60 seconds; an individual socket has a 20-minute lifetime.
A `capacity` response means the server retained the audio. Managed Cloud closes that attempt immediately and uploads the complete retained capture through the existing authorized batch fallback, including recordings under two seconds; it does not keep the active socket retrying until the final deadline. A self-hosted BYOK connection still retries only the commit after `retry_after_ms`, within the original final deadline. Connection loss closes the adapter and uses the existing retained-audio fallback. Duplicate final responses are ignored. The fallback does not replace the configured batch model or bypass its account checks.
@@ -45,10 +45,47 @@ Orukeet transcribes 25 languages (`bg cs da de el en es et fi fr hr hu it lt lv
- 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.
+- Opt-in supported-score modes add a fallback when the six-second supported total is at or below the configured cutoff; they never remove a fallback selected by the existing rule. Shadow mode keeps the existing decision and records both candidates.
+- The retained recording is then uploaded to `/api/transcribe`, tagged `language_detected_unsupported` for the legacy rule or `language_supported_score_low` for a group-only decision. 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.
+- 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`). The private API owns rollout and telemetry persistence.
- 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.
+The default 0.90 threshold and opt-in supported-total scores are classifier scores, not calibrated probabilities. See the separate three/six-second panels and sample counts in [streaming language metadata](orukeet-streaming-language.md). The final carries the latest completed estimate, so a longer recording can still use a three-second estimate if the later pass is not ready. 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.
+
+## Combined cloud cleanup
+
+An updated backend can return `orukeetPipeline: "gemma12"` with the normal
+Orukeet streaming configuration. This desktop declares `orukeet-pipeline-v2`
+and uses it only for ordinary managed cloud cleanup. Local/BYOK, voice-agent,
+translation and the separate supported-language-score cohort keep their paths.
+
+The main process calls `POST /api/stt/orukeet/pipeline-session` with cleanup
+options (dictionary, custom prompt, language, locale and agent name). The backend
+builds the same prompt as `/api/reason`, applies account/policy/usage checks, and
+returns a single-use, 60-second grant. The desktop accepts only the fixed
+`orukeet.gizmovoice.ai` hostname and the documented Gemma 12B regional paths. Both the grant
+and WebSocket `ready` must confirm account limits.
+
+Audio streams while recording. The one final result carries raw ASR and cleaned
+text separately; ordinary cleanup reuses the latter only if it completed and the
+captured cleanup options match. Otherwise it uses the existing cleanup call. Language
+fallback keeps its own transcript and cleanup. Duplicate finals cannot paste or
+submit usage twice, and a canceled recording cannot return a final.
+
+Completed GPU cleanup includes a signed, account-bound token-usage receipt.
+The main process relays it to `/api/stt/orukeet/pipeline-usage`, making at most three attempts (two retries) for transient
+failures without holding up paste. The backend verifies the signature
+and deduplicates its UUID. This is token telemetry, not an extra word charge or a
+durable offline billing channel; when the combined cleanup is the pasted text,
+its raw ASR words go through the existing idempotent `/api/streaming-usage`
+request. A dictation cleaned any other way meters its processed text.
+
+Ordinary non-pipeline streaming continues metering its processed text. Pipeline logs carry `orukeetCleanup` status, model, token counts and timings, with ASR latency measured separately when the raw transcript arrives. A request whose text isn't the combined cleanup (a language fallback, a cleanup redone through `/api/reason`, an agent command) omits a completed status, so Gemma is never credited with cleanup it didn't deliver.
+
+The final deadline allows the ASR budget plus 15 seconds for cleanup/queueing and a 2-second margin, capped at 30 seconds. If cleanup misses that deadline, the gateway errors or the socket drops after the raw transcript arrived, that transcript is pasted without cleanup and the usual "Cleanup failed" notice appears, as for any failed cleanup; the recording isn't transcribed again. A pipeline-only policy refusal or invalid cleanup options retries the authorized plain-ASR session; transcription policy and quota refusals still stop the request. When only the Gemma side fails, the backend answers the pipeline request with a plain `orukeet.pcm.v1` session itself, and the desktop connects to it as ordinary streaming with the normal cleanup route, reporting the cleanup as `fallback` so `/api/reason` doesn't retry Gemma. Warmup may send the eligible cleanup prompt and dictionary before a recording begins; this enables prompt-cache reuse and respects the same local policy guard as recording.
+
+The combined configuration refreshes after 30 seconds. Disabling the backend
+pipeline flag refuses new grants immediately; the desktop retains captured audio
+and uses its existing authorized fallback. Active recordings retain their original provider, routing policy and cleanup options. Already active recordings can finish.
diff --git a/scripts/summarize-orukeet-language-routing.cjs b/scripts/summarize-orukeet-language-routing.cjs
new file mode 100644
index 000000000..0f382b764
--- /dev/null
+++ b/scripts/summarize-orukeet-language-routing.cjs
@@ -0,0 +1,78 @@
+#!/usr/bin/env node
+// Accept exported comparison events as JSONL; output counts, never recordings or text.
+const fs = require("node:fs");
+function summarize(records) {
+ const result = { events: 0, eligible: 0, skipped: 0, labeled: 0, rules: {} };
+ for (const name of ["legacyFallback", "top05Fallback", "candidate030", "candidate010"])
+ result.rules[name] = {
+ fallback: 0,
+ disagreesWithLegacy: 0,
+ unsupportedCaught: 0,
+ unsupportedTotal: 0,
+ supportedDiverted: 0,
+ supportedTotal: 0,
+ };
+ for (const record of records) {
+ const row =
+ record?.metadata?.orukeetLanguageRouting ??
+ record?.orukeetLanguageRouting ??
+ record?.meta ??
+ record?.comparison ??
+ record;
+ if (
+ row?.version !== 1 ||
+ typeof row.eligible !== "boolean" ||
+ typeof row.legacyFallback !== "boolean"
+ ) {
+ result.skipped++;
+ continue;
+ }
+ result.events++;
+ if (!row.eligible) continue;
+ if (
+ ![row.top05Fallback, row.candidate030, row.candidate010].every((v) => typeof v === "boolean")
+ ) {
+ result.skipped++;
+ continue;
+ }
+ result.eligible++;
+ // Ground truth must come from a human/reference label, never the detector's top guess.
+ const expected = record.expectedSupported;
+ if (typeof expected === "boolean") result.labeled++;
+ for (const [name, counts] of Object.entries(result.rules)) {
+ const fallback = row[name];
+ counts.fallback += Number(fallback);
+ counts.disagreesWithLegacy += Number(fallback !== row.legacyFallback);
+ if (expected === false) {
+ counts.unsupportedTotal++;
+ counts.unsupportedCaught += Number(fallback);
+ }
+ if (expected === true) {
+ counts.supportedTotal++;
+ counts.supportedDiverted += Number(fallback);
+ }
+ }
+ }
+ return result;
+}
+if (require.main === module) {
+ if (process.argv.length !== 3) {
+ console.error(
+ "Usage: node scripts/summarize-orukeet-language-routing.cjs comparison-events.jsonl"
+ );
+ process.exitCode = 2;
+ } else {
+ try {
+ const rows = fs
+ .readFileSync(process.argv[2], "utf8")
+ .split(/\r?\n/)
+ .filter((s) => s.trim())
+ .map(JSON.parse);
+ console.log(JSON.stringify(summarize(rows), null, 2));
+ } catch {
+ console.error("Unable to read comparison events as JSONL");
+ process.exitCode = 1;
+ }
+ }
+}
+module.exports = { summarize };
diff --git a/src/helpers/audioManager.js b/src/helpers/audioManager.js
index e5dcd6392..d517b4f08 100644
--- a/src/helpers/audioManager.js
+++ b/src/helpers/audioManager.js
@@ -57,6 +57,7 @@ import {
effectiveLocalHistoryEnabled,
isAgentAllowed,
isCloudBackupAllowed,
+ isLlmSelectionAllowed,
isTranscriptionContextAllowed,
isTranscriptionSelectionAllowed,
} from "../stores/policyRules";
@@ -156,7 +157,9 @@ import {
resolveManagedOrukeetRoute,
resolveStreamingProviderName,
buildStreamingSessionOptions,
- shouldRetranscribeOrukeetLanguage,
+ evaluateOrukeetLanguageRouting,
+ hasOrukeetExperiment,
+ ORUKEET_EXPERIMENT_CONFIG_TTL_MS,
} from "./dictationStreamingRouting";
const REASONING_CACHE_TTL = 30000; // 30 seconds
@@ -673,6 +676,8 @@ class AudioManager {
this._activeTranscriptionAbortController = null;
this._activeStreamingSessionId = null;
this._activeStreamingProviderName = null;
+ this._activeStreamingConfig = null;
+ this._activePipelineOptions = undefined;
this.streamingFallbackRecorder = null;
this.streamingFallbackChunks = [];
this._recordingSpool = null;
@@ -1063,11 +1068,12 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);
}
isSttConfigStale(now = Date.now()) {
- return (
- !this.sttConfig ||
- !this.sttConfigFetchedAt ||
- now - this.sttConfigFetchedAt > STT_CONFIG_TTL_MS
- );
+ // Re-check opt-in language experiments frequently so a server rollback
+ // takes effect on the next recording after at most 30 s of cached config.
+ const ttl = hasOrukeetExperiment(this.sttConfig)
+ ? ORUKEET_EXPERIMENT_CONFIG_TTL_MS
+ : STT_CONFIG_TTL_MS;
+ return !this.sttConfig || !this.sttConfigFetchedAt || now - this.sttConfigFetchedAt > ttl;
}
invalidateSttConfig() {
@@ -1092,6 +1098,8 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);
if (this._activeStreamingSessionId !== sessionId) return;
this._activeStreamingSessionId = null;
this._activeStreamingProviderName = null;
+ this._activeStreamingConfig = null;
+ this._activePipelineOptions = undefined;
}
getStreamingProviderName() {
@@ -3520,6 +3528,9 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);
const streamingFallbackReason =
metadata.streamingFallbackReason ?? this.consumeStreamingFallbackReason(settings);
if (streamingFallbackReason) opts.streamingFallbackReason = streamingFallbackReason;
+ if (metadata.orukeetLanguageRouting)
+ opts.orukeetLanguageRouting = metadata.orukeetLanguageRouting;
+ if (metadata.orukeetCleanup) opts.orukeetCleanup = metadata.orukeetCleanup;
// 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
@@ -3610,6 +3621,8 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);
language: this.getCleanupLanguage(settings),
locale: settings.uiLanguage || "en",
streamingFallbackReason,
+ orukeetLanguageRouting: metadata.orukeetLanguageRouting,
+ orukeetCleanup: metadata.orukeetCleanup,
...detectedLanguageFields,
sttProvider: result.sttProvider,
sttModel: result.sttModel,
@@ -3656,6 +3669,8 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);
mode: "cloudReason",
meta: {
streamingFallbackReason,
+ orukeetLanguageRouting: metadata.orukeetLanguageRouting,
+ orukeetCleanup: metadata.orukeetCleanup,
...detectedLanguageFields,
sttProvider: result.sttProvider,
sttModel: result.sttModel,
@@ -4636,6 +4651,34 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);
return this.sttConfig.dictation?.mode === "streaming";
}
+ getPipelineCleanupOptions(
+ settings,
+ {
+ voiceAgentRequested = this.voiceAgentRequested,
+ translationRequested = this.translationRequested,
+ } = {}
+ ) {
+ if (
+ this.sttConfig?.orukeetPipeline !== "gemma12" ||
+ settings.useLocalWhisper ||
+ settings.cloudTranscriptionMode !== "openwhispr" ||
+ !settings.useCleanupModel ||
+ !isCloudCleanupMode() ||
+ !isLlmSelectionAllowed(usePolicyStore.getState(), { mode: "openwhispr" }) ||
+ (settings.cleanupCloudMode || "openwhispr") !== "openwhispr" ||
+ voiceAgentRequested ||
+ translationRequested
+ )
+ return undefined;
+ return {
+ agentName: getAgentName() || "",
+ customDictionary: getDictionaryHintWords(settings),
+ customPrompt: this.getCustomPrompt(),
+ language: this.getCleanupLanguage(settings) || undefined,
+ locale: settings.uiLanguage || "en",
+ };
+ }
+
async warmupStreamingConnection({ isSignedIn: isSignedInOverride, warmMic = true } = {}) {
if (!this.isRecordingAllowedByPolicy()) {
logger.debug("Streaming warmup skipped by workspace policy", {}, "streaming");
@@ -4660,6 +4703,11 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);
language: settings.preferredLanguage,
keyterms: this.getKeyterms(),
voiceAgentRequested: this.voiceAgentRequested,
+ // Warmup runs while idle, so the socket is for an ordinary dictation.
+ pipelineOptions: this.getPipelineCleanupOptions(settings, {
+ voiceAgentRequested: false,
+ translationRequested: false,
+ }),
})
);
// Throw error to trigger retry if AUTH_EXPIRED
@@ -4921,6 +4969,8 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);
this._activeStreamingSessionId = sessionId;
providerName = this.getStreamingProviderName();
this._activeStreamingProviderName = providerName;
+ this._activeStreamingConfig = { ...this.sttConfig };
+ this._activePipelineOptions = this.getPipelineCleanupOptions(getSettings());
const ownsSession = () => this._activeStreamingSessionId === sessionId;
const cancellationGeneration = this._streamingCancellationGeneration;
startWasCancelled = () => cancellationGeneration !== this._streamingCancellationGeneration;
@@ -5106,6 +5156,7 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);
language: this.getEffectiveSttLanguage(streamingSettings),
keyterms: this.getKeyterms(),
voiceAgentRequested: this.voiceAgentRequested,
+ pipelineOptions: this._activePipelineOptions,
})
);
@@ -5599,7 +5650,9 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);
const stSettings = getSettings();
const streamingSttModel = stopResult?.model || "nova-3";
- const streamingSttProcessingMs = Math.round(tTerminate - t0);
+ const streamingSttProcessingMs = Number.isFinite(orukeetFinal?.asrFinalMs)
+ ? Math.round(orukeetFinal.asrFinalMs)
+ : Math.round(tTerminate - t0);
const streamingAudioBytesSent = stopResult?.audioBytesSent || 0;
const streamingSttLanguage =
getBaseLanguageCode(this.getEffectiveSttLanguage(stSettings)) || undefined;
@@ -5617,6 +5670,41 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);
const detectedLanguageFields = isOrukeetStream
? orukeetDetectedLanguageFields(orukeetFinal)
: {};
+ const languageRouting = evaluateOrukeetLanguageRouting({
+ language: streamingSttLanguage,
+ final: orukeetFinal,
+ mode:
+ isOrukeetStream && stSettings.cloudTranscriptionMode === "openwhispr"
+ ? (this._activeStreamingConfig || this.sttConfig)?.orukeetLanguageRouting
+ : undefined,
+ });
+ const orukeetLanguageRouting = languageRouting.comparison
+ ? {
+ ...languageRouting.comparison,
+ fallbackAvailable:
+ fallbackBlob?.size > 0 && resolveStreamingFallbackTarget(stSettings) === "cloud",
+ }
+ : undefined;
+ const orukeetCleanup = orukeetFinal?.cleanup;
+ const orukeetTelemetry = { orukeetLanguageRouting, orukeetCleanup };
+ // A request whose text isn't the combined cleanup (a language fallback, a
+ // cleanup redone through /api/reason, an agent command) must not report a
+ // completed Gemma cleanup as its own.
+ const uncombinedTelemetry = {
+ orukeetLanguageRouting,
+ orukeetCleanup: orukeetCleanup?.status === "complete" ? undefined : orukeetCleanup,
+ };
+ if (isOrukeetStream && languageRouting.comparison) {
+ logger.info(
+ "Orukeet language routing comparison",
+ {
+ ...languageRouting.comparison,
+ fallbackAvailable:
+ fallbackBlob?.size > 0 && resolveStreamingFallbackTarget(stSettings) === "cloud",
+ },
+ "streaming"
+ );
+ }
// Orukeet renders speech outside its 25 languages as confident nonsense.
// With a confident final estimate, send the kept recording through Cloud
@@ -5626,7 +5714,7 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);
isOrukeetStream &&
fallbackBlob?.size > 0 &&
resolveStreamingFallbackTarget(stSettings) === "cloud" &&
- shouldRetranscribeOrukeetLanguage({ language: streamingSttLanguage, final: orukeetFinal })
+ languageRouting.fallback
) {
logger.info(
"Orukeet detected an unsupported language, re-transcribing through Cloud",
@@ -5657,8 +5745,12 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);
{
durationSeconds,
analyticsOccurredAt: analyticsOccurredAt.toISOString(),
- streamingFallbackReason: "language_detected_unsupported",
+ streamingFallbackReason:
+ languageRouting.comparison && !languageRouting.comparison.legacyFallback
+ ? "language_supported_score_low"
+ : "language_detected_unsupported",
detectedLanguageFields,
+ ...uncombinedTelemetry,
},
wasCancelled
);
@@ -5680,6 +5772,7 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);
}
let usedCloudReasoning = false;
+ let combinedCleanup = false;
// The Cloud batch path already ran its own cleanup, agent or translation.
if (finalText && !usedBatchFallback) {
const reasoningStart = performance.now();
@@ -5720,34 +5813,51 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);
);
} else if (route.kind === "cleanup" && cleanupCloudMode === "openwhispr") {
const customPrompt = this.getCustomPrompt();
- const reasonResult = await withSessionRefresh(async () => {
- const res = await window.electronAPI.cloudReason(finalText, {
- agentName,
- promptMode: "cleanup",
- purpose: "cleanup",
- customDictionary: getDictionaryHintWords(stSettings),
- customPrompt,
- language: this.getCleanupLanguage(stSettings),
- locale: stSettings.uiLanguage || "en",
- sttProvider: providerName,
- sttModel: streamingSttModel,
- sttProcessingMs: streamingSttProcessingMs,
- sttWordCount: streamingSttWordCount,
- sttLanguage: streamingSttLanguage,
- ...detectedLanguageFields,
- audioDurationMs: durationSeconds ? Math.round(durationSeconds * 1000) : undefined,
- audioSizeBytes: streamingAudioBytesSent || undefined,
- audioFormat: "linear16",
- });
- if (!res.success) {
- const err = new Error(res.error || "Cloud reasoning failed");
- err.code = res.code;
- throw err;
- }
- return res;
- });
+ // ASR finished but the combined cleanup didn't: paste the raw text, as
+ // any other failed cleanup does.
+ if (orukeetFinal?.cleanupError) {
+ throw Object.assign(
+ new Error(`Combined cleanup did not finish: ${orukeetFinal.cleanupError}`),
+ { messageKey: "app.toasts.cleanupFailed.title" }
+ );
+ }
+ combinedCleanup =
+ orukeetFinal?.cleanupStatus === "complete" &&
+ JSON.stringify(orukeetFinal.cleanupOptions) ===
+ JSON.stringify(this._activePipelineOptions) &&
+ typeof orukeetFinal.cleanupText === "string" &&
+ hasTextContent(orukeetFinal.cleanupText);
+ const reasonResult = combinedCleanup
+ ? { success: true, text: orukeetFinal.cleanupText, model: orukeetCleanup?.model }
+ : await withSessionRefresh(async () => {
+ const res = await window.electronAPI.cloudReason(finalText, {
+ agentName,
+ promptMode: "cleanup",
+ purpose: "cleanup",
+ customDictionary: getDictionaryHintWords(stSettings),
+ customPrompt,
+ language: this.getCleanupLanguage(stSettings),
+ locale: stSettings.uiLanguage || "en",
+ sttProvider: providerName,
+ sttModel: streamingSttModel,
+ sttProcessingMs: streamingSttProcessingMs,
+ sttWordCount: streamingSttWordCount,
+ sttLanguage: streamingSttLanguage,
+ ...detectedLanguageFields,
+ ...uncombinedTelemetry,
+ audioDurationMs: durationSeconds ? Math.round(durationSeconds * 1000) : undefined,
+ audioSizeBytes: streamingAudioBytesSent || undefined,
+ audioFormat: "linear16",
+ });
+ if (!res.success) {
+ const err = new Error(res.error || "Cloud reasoning failed");
+ err.code = res.code;
+ throw err;
+ }
+ return res;
+ });
- usedCloudReasoning = true;
+ usedCloudReasoning = !combinedCleanup;
if (reasonResult.success && hasTextContent(reasonResult.text)) {
if (!customPrompt) assertValidCleanupOutput(finalText, reasonResult.text);
finalText = reasonResult.text;
@@ -5794,6 +5904,7 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);
sttWordCount: streamingSttWordCount,
sttLanguage: streamingSttLanguage,
...detectedLanguageFields,
+ ...uncombinedTelemetry,
audioDurationMs: durationSeconds
? Math.round(durationSeconds * 1000)
: undefined,
@@ -5967,7 +6078,7 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);
try {
await withSessionRefresh(async () => {
const res = await window.electronAPI.cloudStreamingUsage(
- finalText,
+ combinedCleanup ? rawStreamingText : finalText,
durationSeconds ?? 0,
{
sendLogs: !usedCloudReasoning,
@@ -5976,6 +6087,7 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);
sttProcessingMs: streamingSttProcessingMs,
sttLanguage: streamingSttLanguage,
...detectedLanguageFields,
+ ...(combinedCleanup ? orukeetTelemetry : uncombinedTelemetry),
audioSizeBytes: streamingAudioBytesSent || undefined,
audioFormat: "linear16",
clientTotalMs,
diff --git a/src/helpers/dictationStreamingRouting.js b/src/helpers/dictationStreamingRouting.js
index 8421db5be..9889380ac 100644
--- a/src/helpers/dictationStreamingRouting.js
+++ b/src/helpers/dictationStreamingRouting.js
@@ -13,10 +13,9 @@ 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.
+// Existing default retained during the opt-in group-score rollout. Scores are
+// not calibrated probabilities; see docs/orukeet-streaming-language.md for
+// the expanded evaluation and the separate three/six-second behavior.
const ORUKEET_LANGUAGE_FALLBACK_MIN_CONFIDENCE = 0.9;
const ORUKEET_LANGUAGE_FALLBACK_MIN_AUDIO_SECONDS = 3;
@@ -42,6 +41,70 @@ export function shouldRetranscribeOrukeetLanguage({ language, final }) {
);
}
+// Opt-in, server-controlled rollout. Missing/unknown modes retain the existing
+// rule; shadow records the comparison without changing the user's result.
+const ORUKEET_LANGUAGE_ROUTING_MODES = new Set(["shadow", "supported-0.30", "supported-0.10"]);
+export const ORUKEET_EXPERIMENT_CONFIG_TTL_MS = 30000;
+export function hasOrukeetExperiment(config) {
+ return (
+ ORUKEET_LANGUAGE_ROUTING_MODES.has(config?.orukeetLanguageRouting) ||
+ config?.orukeetPipeline === "gemma12"
+ );
+}
+const validScore = (value) => Number.isFinite(value) && value >= 0 && value <= 1;
+
+export function evaluateOrukeetLanguageRouting({ language, final, mode }) {
+ const legacyFallback = shouldRetranscribeOrukeetLanguage({ language, final });
+ if (!ORUKEET_LANGUAGE_ROUTING_MODES.has(mode)) {
+ return { fallback: legacyFallback, comparison: null };
+ }
+ const auto = !language || language === "auto";
+ const seconds =
+ Number.isFinite(final?.languageAudioSeconds) && final.languageAudioSeconds > 0
+ ? final.languageAudioSeconds
+ : null;
+ const score = validScore(final?.languageSupportedScore) ? final.languageSupportedScore : null;
+ const topLanguage =
+ typeof final?.language === "string" && /^[a-z]{2}$/.test(final.language)
+ ? final.language
+ : null;
+ const topScore = validScore(final?.languageConfidence) ? final.languageConfidence : null;
+ const eligible = auto && final?.success !== false && seconds >= 6 && score !== null;
+ const candidate030 = eligible ? score <= 0.3 : null;
+ const candidate010 = eligible ? score <= 0.1 : null;
+ const candidate = mode === "supported-0.30" ? candidate030 : candidate010;
+ const fallback =
+ mode === "shadow" || candidate === null ? legacyFallback : legacyFallback || candidate;
+
+ // Explicit allowlist: never spread a final result, settings, transcript,
+ // recording, token, account identifier or arbitrary server fields into logs.
+ return {
+ fallback,
+ comparison: {
+ version: 1,
+ mode,
+ auto,
+ eligible,
+ analyzedSeconds: seconds,
+ topLanguage,
+ topScore,
+ supportedScore: score,
+ legacyFallback,
+ top05Fallback:
+ auto &&
+ final?.success !== false &&
+ seconds >= 6 &&
+ topLanguage !== null &&
+ !isOrukeetLanguage(topLanguage) &&
+ topScore !== null &&
+ topScore >= 0.5,
+ candidate030,
+ candidate010,
+ selectedFallback: fallback,
+ },
+ };
+}
+
// 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.
@@ -132,6 +195,7 @@ export function buildStreamingSessionOptions({
language,
keyterms,
voiceAgentRequested = false,
+ pipelineOptions,
}) {
const options = {
provider: providerName,
@@ -150,6 +214,7 @@ export function buildStreamingSessionOptions({
}
if (providerName === "orukeet") {
options.model = ORUKEET_MODEL;
+ if (options.mode !== "byok" && pipelineOptions) options.pipelineOptions = pipelineOptions;
if (options.mode === "byok") {
options.baseUrl = settings.remoteTranscriptionUrl || settings.cloudTranscriptionBaseUrl;
}
diff --git a/src/helpers/ipcHandlers.js b/src/helpers/ipcHandlers.js
index fc3f3839e..f32cf770b 100644
--- a/src/helpers/ipcHandlers.js
+++ b/src/helpers/ipcHandlers.js
@@ -6675,6 +6675,10 @@ class IPCHandlers {
sttDetectedLanguageConfidence: opts.sttDetectedLanguageConfidence,
sttDetectedLanguageAudioSeconds: opts.sttDetectedLanguageAudioSeconds,
sttDetectedLanguageStatus: opts.sttDetectedLanguageStatus,
+ orukeetLanguageRouting: opts.orukeetLanguageRouting
+ ? JSON.stringify(opts.orukeetLanguageRouting)
+ : undefined,
+ orukeetCleanup: opts.orukeetCleanup ? JSON.stringify(opts.orukeetCleanup) : undefined,
};
debugLogger.debug("Cloud transcribe request", { audioSize: audioData.length }, "cloud-api");
@@ -8895,6 +8899,7 @@ class IPCHandlers {
options.mode,
options.model,
options.baseUrl,
+ options.pipelineOptions,
readsSavedKey ? credentialGeneration : null,
provider === "openai-realtime"
? OpenAIRealtimeStreaming.normalizeLanguage(options.language)
@@ -8938,6 +8943,9 @@ class IPCHandlers {
provider === "orukeet"
? new OrukeetStreaming(isCloud ? MANAGED_STREAM_OPTIONS : {})
: new OpenAIRealtimeStreaming();
+ if (provider === "orukeet")
+ streaming.onUsageError = (metadata) =>
+ debugLogger.error("Combined cleanup usage could not be recorded", metadata);
setupDictationCallbacks(streaming, event);
// Assign before the token fetch (a real network round trip) so
// dictation-realtime-send has a live instance to buffer into instead
@@ -8954,6 +8962,7 @@ class IPCHandlers {
proxyFetch,
tokenStore,
withPolicyHeaders,
+ pipelineOptions: options.pipelineOptions,
});
} else {
await streaming.connect({
@@ -9961,6 +9970,8 @@ class IPCHandlers {
sttDetectedLanguageConfidence: opts.sttDetectedLanguageConfidence,
sttDetectedLanguageAudioSeconds: opts.sttDetectedLanguageAudioSeconds,
sttDetectedLanguageStatus: opts.sttDetectedLanguageStatus,
+ orukeetLanguageRouting: opts.orukeetLanguageRouting,
+ orukeetCleanup: opts.orukeetCleanup,
audioDurationMs: opts.audioDurationMs,
audioSizeBytes: opts.audioSizeBytes,
audioFormat: opts.audioFormat,
@@ -10209,6 +10220,8 @@ class IPCHandlers {
sttDetectedLanguageConfidence: opts.sttDetectedLanguageConfidence,
sttDetectedLanguageAudioSeconds: opts.sttDetectedLanguageAudioSeconds,
sttDetectedLanguageStatus: opts.sttDetectedLanguageStatus,
+ orukeetLanguageRouting: opts.orukeetLanguageRouting,
+ orukeetCleanup: opts.orukeetCleanup,
audioSizeBytes: opts.audioSizeBytes,
audioFormat: opts.audioFormat,
clientTotalMs: opts.clientTotalMs,
diff --git a/src/helpers/orukeetCloudSession.js b/src/helpers/orukeetCloudSession.js
index 60221cd3b..62127d117 100644
--- a/src/helpers/orukeetCloudSession.js
+++ b/src/helpers/orukeetCloudSession.js
@@ -1,24 +1,97 @@
const { captureAuthFence } = require("./cloudApiRequest");
const { createPolicyResponseError } = require("./policyResponseError");
-const ORUKEET_BASE_URL = "https://orukeet.gizmovoice.ai";
-const ORUKEET_SESSION_PATH = "/api/stt/orukeet/session";
+const {
+ ORUKEET_BASE_URL,
+ ORUKEET_MODEL,
+ ORUKEET_PCM_PROTOCOL,
+ ORUKEET_PIPELINE_PROTOCOL,
+ ORUKEET_CLEANUP_VARIANT,
+ ORUKEET_CLEANUP_MODEL,
+ ORUKEET_SESSION_PATH,
+ ORUKEET_PIPELINE_SESSION_PATH,
+ ORUKEET_PIPELINE_USAGE_PATH,
+ ORUKEET_LANGUAGE_PREVIEW_URL,
+ ORUKEET_PIPELINE_BASES,
+ isOrukeetClientToken,
+} = require("./orukeetProtocol");
-function validateSession(data) {
+function validateSession(data, pipeline = false) {
+ if (pipeline) {
+ if (
+ !ORUKEET_PIPELINE_BASES.includes(data?.baseUrl) ||
+ data?.websocketUrl !== `${data.baseUrl.replace("https:", "wss:")}/v1/pipeline/stream` ||
+ data.protocol !== ORUKEET_PIPELINE_PROTOCOL ||
+ data.model !== ORUKEET_MODEL ||
+ data.cleanup !== true ||
+ data.cleanupModel !== ORUKEET_CLEANUP_MODEL ||
+ data.requireAccountLimits !== true ||
+ data.singleUse !== true ||
+ data.expiresIn !== 60 ||
+ !isOrukeetClientToken(data.clientToken, true)
+ )
+ throw new Error("Invalid Orukeet pipeline session");
+ return {
+ baseUrl: data.baseUrl,
+ clientToken: data.clientToken,
+ protocol: data.protocol,
+ requireAccountLimits: true,
+ };
+ }
if (
- data?.baseUrl !== ORUKEET_BASE_URL ||
+ ![ORUKEET_BASE_URL, ORUKEET_LANGUAGE_PREVIEW_URL].includes(data?.baseUrl) ||
data?.websocketUrl !==
- `${ORUKEET_BASE_URL.replace("https:", "wss:")}/v1/audio/transcriptions/stream` ||
- data?.protocol !== "orukeet.pcm.v1" ||
- data?.model !== "orukeet-v0.1.0" ||
+ `${data?.baseUrl?.replace("https:", "wss:")}/v1/audio/transcriptions/stream` ||
+ data?.protocol !== ORUKEET_PCM_PROTOCOL ||
+ data?.model !== ORUKEET_MODEL ||
data?.singleUse !== true ||
data?.expiresIn !== 60 ||
- typeof data?.clientToken !== "string" ||
- !/^[A-Za-z0-9._-]{1,96}$/.test(data.clientToken)
+ !isOrukeetClientToken(data?.clientToken)
) {
throw new Error("Invalid Orukeet cloud session");
}
- return { baseUrl: ORUKEET_BASE_URL, clientToken: data.clientToken };
+ return { baseUrl: data.baseUrl, clientToken: data.clientToken };
+}
+
+const CLEANUP_USAGE_ATTEMPTS = 3;
+
+async function relayCleanupUsage({
+ receipt,
+ fence,
+ apiUrl,
+ proxyFetch,
+ withPolicyHeaders,
+ wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
+}) {
+ for (let attempt = 0; attempt < CLEANUP_USAGE_ATTEMPTS; attempt++) {
+ fence.assertCurrent();
+ try {
+ const usage = await fence.awaitBound(() =>
+ proxyFetch(`${apiUrl}${ORUKEET_PIPELINE_USAGE_PATH}`, {
+ method: "POST",
+ headers: withPolicyHeaders({
+ Authorization: fence.authorization,
+ "Content-Type": "application/json",
+ }),
+ body: JSON.stringify({ receipt }),
+ useSessionCookies: false,
+ redirect: "error",
+ cache: "no-store",
+ signal: AbortSignal.timeout(10000),
+ })
+ );
+ if (usage.ok) return;
+ throw Object.assign(new Error("Cleanup usage rejected"), {
+ status: usage.status,
+ permanent: usage.status < 500 && ![401, 408, 429].includes(usage.status),
+ });
+ } catch (error) {
+ // Never relay the receipt under a replacement account, even between retries.
+ fence.assertCurrent();
+ if (error.permanent || attempt === CLEANUP_USAGE_ATTEMPTS - 1) throw error;
+ }
+ await wait(250 * 2 ** attempt);
+ }
}
// Main process only. The account bearer goes to the existing Cloud backend;
@@ -29,6 +102,7 @@ async function connectManagedOrukeet({
proxyFetch,
tokenStore,
withPolicyHeaders,
+ pipelineOptions,
}) {
const apiUrl = getApiUrl();
if (!apiUrl) throw new Error("OpenWhispr API URL not configured");
@@ -55,17 +129,50 @@ async function connectManagedOrukeet({
};
try {
assertActive();
- const response = await fence.awaitBound(() =>
- proxyFetch(`${apiUrl}${ORUKEET_SESSION_PATH}`, {
- method: "POST",
- headers: withPolicyHeaders({ Authorization: fence.authorization }),
- useSessionCookies: false,
- redirect: "error",
- cache: "no-store",
- signal: AbortSignal.any([controller.signal, AbortSignal.timeout(10000)]),
- })
- );
+ const mintSession = (options) =>
+ fence.awaitBound(() =>
+ proxyFetch(`${apiUrl}${options ? ORUKEET_PIPELINE_SESSION_PATH : ORUKEET_SESSION_PATH}`, {
+ method: "POST",
+ headers: withPolicyHeaders({
+ Authorization: fence.authorization,
+ ...(options ? { "Content-Type": "application/json" } : {}),
+ }),
+ ...(options
+ ? {
+ body: JSON.stringify({
+ variant: ORUKEET_CLEANUP_VARIANT,
+ cleanup: true,
+ cleanupOptions: options,
+ }),
+ }
+ : {}),
+ useSessionCookies: false,
+ redirect: "error",
+ cache: "no-store",
+ signal: AbortSignal.any([controller.signal, AbortSignal.timeout(10000)]),
+ })
+ );
+ let options = pipelineOptions;
+ let response = await mintSession(options);
assertActive();
+ // The ASR permission is independent of Cloud AI. A stale policy or an
+ // over-size cleanup prompt must not discard an otherwise valid dictation.
+ if (options && !response.ok) {
+ const payload = await fence.awaitBound(() =>
+ response
+ .clone()
+ .json()
+ .catch(() => null)
+ );
+ if (
+ (response.status === 403 && payload?.code === "POLICY_MODE_BLOCKED") ||
+ (response.status === 400 && payload?.code === "PIPELINE_OPTIONS_UNSUPPORTED")
+ ) {
+ options = undefined;
+ response = await mintSession();
+ assertActive();
+ }
+ }
if (response.status === 401) {
throw Object.assign(new Error("Session expired"), { code: "AUTH_EXPIRED", status: 401 });
}
@@ -89,7 +196,30 @@ async function connectManagedOrukeet({
}
const data = await fence.awaitBound(() => response.json());
assertActive();
- await streaming.connect(validateSession(data));
+ // When only the Gemma side fails, the API answers a pipeline request with a
+ // plain ASR session; cleanup then runs through /api/reason, which is told
+ // the combined cleanup fell back so it doesn't retry Gemma.
+ if (options && data?.protocol === ORUKEET_PCM_PROTOCOL) {
+ options = undefined;
+ streaming.cleanupUnavailable = true;
+ }
+ if (options) {
+ streaming.cleanupOptions = options;
+ streaming.onUsageReceipt = (receipt) => {
+ // Completed model work is recorded independently of text delivery.
+ streaming.usagePromise = relayCleanupUsage({
+ receipt,
+ fence,
+ apiUrl,
+ proxyFetch,
+ withPolicyHeaders,
+ });
+ streaming.usagePromise.catch((error) =>
+ streaming.onUsageError?.({ status: error.status, code: error.code })
+ );
+ };
+ }
+ await streaming.connect(validateSession(data, Boolean(options)));
assertActive();
} catch (error) {
streaming.close();
@@ -97,4 +227,10 @@ async function connectManagedOrukeet({
}
}
-module.exports = { connectManagedOrukeet, validateSession, ORUKEET_BASE_URL, ORUKEET_SESSION_PATH };
+module.exports = {
+ relayCleanupUsage,
+ connectManagedOrukeet,
+ validateSession,
+ ORUKEET_BASE_URL,
+ ORUKEET_SESSION_PATH,
+};
diff --git a/src/helpers/orukeetProtocol.js b/src/helpers/orukeetProtocol.js
new file mode 100644
index 000000000..964f4b52e
--- /dev/null
+++ b/src/helpers/orukeetProtocol.js
@@ -0,0 +1,41 @@
+// Shared main-process wire contract. Managed destinations remain an exact allowlist.
+const ORUKEET_BASE_URL = "https://orukeet.gizmovoice.ai";
+const ORUKEET_MODEL = "orukeet-v0.1.0";
+const ORUKEET_PCM_PROTOCOL = "orukeet.pcm.v1";
+const ORUKEET_PIPELINE_PROTOCOL = "orukeet.pipeline.v2";
+const ORUKEET_CLEANUP_VARIANT = "gemma12";
+const ORUKEET_CLEANUP_MODEL = "gemma-4-12b";
+// Older GPU images report their runtime quantization ID in the final event.
+const ORUKEET_CLEANUP_RUNTIME_MODELS = Object.freeze([ORUKEET_CLEANUP_MODEL, "gemma-4-12B-it-qat"]);
+const ORUKEET_SESSION_PATH = "/api/stt/orukeet/session";
+const ORUKEET_PIPELINE_SESSION_PATH = "/api/stt/orukeet/pipeline-session";
+const ORUKEET_PIPELINE_USAGE_PATH = "/api/stt/orukeet/pipeline-usage";
+const ORUKEET_LANGUAGE_PREVIEW_URL = `${ORUKEET_BASE_URL}/preview/language-routing`;
+const ORUKEET_PIPELINE_BASES = [
+ "preview",
+ "regions/us-west1",
+ "regions/europe-west4",
+ "regions/asia-southeast1",
+].map((path) => `${ORUKEET_BASE_URL}/${path}/${ORUKEET_CLEANUP_VARIANT}`);
+function isOrukeetClientToken(value, pipeline = false) {
+ return (
+ typeof value === "string" &&
+ /^[A-Za-z0-9._-]+$/.test(value) &&
+ value.length <= (pipeline ? 160 : 96)
+ );
+}
+module.exports = {
+ ORUKEET_BASE_URL,
+ ORUKEET_MODEL,
+ ORUKEET_PCM_PROTOCOL,
+ ORUKEET_PIPELINE_PROTOCOL,
+ ORUKEET_CLEANUP_VARIANT,
+ ORUKEET_CLEANUP_MODEL,
+ ORUKEET_CLEANUP_RUNTIME_MODELS,
+ ORUKEET_SESSION_PATH,
+ ORUKEET_PIPELINE_SESSION_PATH,
+ ORUKEET_PIPELINE_USAGE_PATH,
+ ORUKEET_LANGUAGE_PREVIEW_URL,
+ ORUKEET_PIPELINE_BASES,
+ isOrukeetClientToken,
+};
diff --git a/src/helpers/orukeetStreaming.js b/src/helpers/orukeetStreaming.js
index 2f726970f..5cfa2919e 100644
--- a/src/helpers/orukeetStreaming.js
+++ b/src/helpers/orukeetStreaming.js
@@ -1,9 +1,20 @@
const WebSocket = require("ws");
+const {
+ ORUKEET_MODEL,
+ ORUKEET_PCM_PROTOCOL,
+ ORUKEET_PIPELINE_PROTOCOL,
+ ORUKEET_CLEANUP_MODEL,
+ ORUKEET_CLEANUP_RUNTIME_MODELS,
+ isOrukeetClientToken,
+} = require("./orukeetProtocol");
const MAX_PENDING_BYTES = 2 * 1024 * 1024;
// Mono 16 kHz PCM16.
const BYTES_PER_SECOND = 32000;
const MAX_FINAL_WAIT_MS = 30000;
+const PIPELINE_CLEANUP_BUDGET_MS = 15000;
+const PIPELINE_FINAL_MARGIN_MS = 2000;
+const finiteMetric = (value) => (Number.isFinite(value) && value >= 0 ? value : undefined);
// Managed Cloud keeps the capture for a batch upload, so a stalled or
// unreachable GPU host should fail over within seconds rather than hold the
@@ -21,6 +32,15 @@ const MANAGED_STREAM_OPTIONS = {
function languageMetadata(message) {
const language = message.language;
const confidence = message.language_confidence;
+ const supportedScore = message.language_supported_score;
+ const hasSupportedScore =
+ Number.isFinite(supportedScore) && supportedScore >= 0 && supportedScore <= 1;
+ const extra = {
+ ...(hasSupportedScore ? { languageSupportedScore: supportedScore } : {}),
+ ...(Number.isFinite(message.language_audio_seconds) && message.language_audio_seconds > 0
+ ? { languageAudioSeconds: message.language_audio_seconds }
+ : {}),
+ };
if (
typeof language === "string" &&
/^[a-z]{2}$/.test(language) &&
@@ -31,12 +51,10 @@ function languageMetadata(message) {
return {
language,
languageConfidence: confidence,
- ...(Number.isFinite(message.language_audio_seconds) && message.language_audio_seconds > 0
- ? { languageAudioSeconds: message.language_audio_seconds }
- : {}),
+ ...extra,
};
}
- return { language: null, languageConfidence: null };
+ return { language: null, languageConfidence: null, ...(hasSupportedScore ? extra : {}) };
}
function capacityRetryDelay(requestedMs) {
@@ -88,7 +106,7 @@ class OrukeetStreaming {
this.pendingAudio = [];
this.pendingBytes = 0;
this.audioBytesSent = 0;
- this.currentModel = "orukeet-v0.1.0";
+ this.currentModel = ORUKEET_MODEL;
this.result = null;
this.finalPromise = null;
this.intentionalClose = false;
@@ -98,17 +116,30 @@ class OrukeetStreaming {
this.connecting = true;
}
- async connect({ baseUrl, apiKey, clientToken }) {
+ async connect({
+ baseUrl,
+ apiKey,
+ clientToken,
+ protocol = ORUKEET_PCM_PROTOCOL,
+ requireAccountLimits = false,
+ }) {
if (this.intentionalClose || this.failure || this.ws) {
throw new Error("Create a new Orukeet adapter for each recording");
}
if (Boolean(apiKey) === Boolean(clientToken)) {
throw new Error("Supply exactly one Orukeet service key or client token");
}
- if (clientToken && !/^[A-Za-z0-9._-]{1,96}$/.test(clientToken)) {
+ const pipeline = protocol === ORUKEET_PIPELINE_PROTOCOL;
+ if (![ORUKEET_PCM_PROTOCOL, ORUKEET_PIPELINE_PROTOCOL].includes(protocol))
+ throw new Error("Invalid protocol");
+ if (clientToken && !isOrukeetClientToken(clientToken, pipeline)) {
throw new Error("Invalid Orukeet client token");
}
- const url = streamingUrl(baseUrl);
+ this.pipeline = pipeline;
+ this.requireAccountLimits = requireAccountLimits || pipeline;
+ const url = pipeline
+ ? streamingUrl(baseUrl).replace("/v1/audio/transcriptions/stream", "/v1/pipeline/stream")
+ : streamingUrl(baseUrl);
this.beginConnecting();
this.ws = this.createSocket(
url,
@@ -118,7 +149,7 @@ class OrukeetStreaming {
handshakeTimeout: this.timeoutMs,
maxPayload: MAX_PENDING_BYTES,
},
- clientToken ? ["orukeet.pcm.v1", `auth.${clientToken}`] : undefined
+ clientToken ? [protocol, `auth.${clientToken}`] : undefined
);
return new Promise((resolve, reject) => {
const timer = setTimeout(
@@ -163,6 +194,10 @@ class OrukeetStreaming {
) {
throw new Error("Orukeet server does not support mono 16 kHz PCM");
}
+ if (this.requireAccountLimits && message.account_limits !== true)
+ throw new Error("Orukeet account limits missing");
+ if (this.pipeline && (message.pipeline_protocol !== 2 || message.cleanup !== true))
+ throw new Error("Invalid pipeline handshake");
this.maxAudioBytes = message.max_seconds * BYTES_PER_SECOND;
this.isConnected = true;
this.connecting = false;
@@ -181,15 +216,58 @@ class OrukeetStreaming {
// The final message remains authoritative for this recording.
if (!this.isConnected || this.result) return;
const metadata = languageMetadata(message);
- if (metadata.language) this.onLanguage?.(metadata);
+ if (metadata.language || Number.isFinite(metadata.languageSupportedScore))
+ this.onLanguage?.(metadata);
+ } else if (message.type === "transcript") {
+ if (!this.pipeline || !this.finalResolve || typeof message.text !== "string") return;
+ // This is ASR completion, before cleanup starts. Never paste this provisional
+ // event; retain its timing separately from the eventual combined final, and
+ // its text in case cleanup never finishes.
+ this.asrFinalMs ??= Math.max(0, performance.now() - this.finalStartedAt);
+ this.rawTranscript = message.text;
} else if (message.type === "final") {
// A duplicate or unsolicited final must never result in a second paste.
if (this.result) return;
if (!this.finalResolve || typeof message.text !== "string") {
throw new Error("Unexpected Orukeet final transcript");
}
+ if (
+ this.pipeline &&
+ (typeof message.raw_text !== "string" ||
+ !["complete", "fallback", "skipped"].includes(message.cleanup_status))
+ )
+ throw new Error("Invalid pipeline final");
+ if (
+ this.pipeline &&
+ message.cleanup_receipt !== undefined &&
+ (typeof message.cleanup_receipt !== "string" || message.cleanup_receipt.length > 2048)
+ )
+ throw new Error("Invalid cleanup receipt");
this.result = {
- text: message.text || "",
+ text: this.pipeline ? message.raw_text : message.text || "",
+ ...(this.pipeline
+ ? {
+ cleanupText: message.text,
+ cleanupStatus: message.cleanup_status,
+ cleanupOptions: this.cleanupOptions,
+ asrFinalMs: this.asrFinalMs ?? Math.max(0, performance.now() - this.finalStartedAt),
+ cleanup: {
+ status: message.cleanup_status,
+ ...(message.cleanup_status === "complete" &&
+ message.cleanup_method === "model" &&
+ ORUKEET_CLEANUP_RUNTIME_MODELS.includes(message.cleanup_model)
+ ? { model: ORUKEET_CLEANUP_MODEL }
+ : {}),
+ processingMs: finiteMetric(message.cleanup_ms),
+ queueMs: finiteMetric(message.cleanup_queue_ms),
+ firstTextMs: finiteMetric(message.cleanup_first_text_ms),
+ inputTokens: finiteMetric(message.cleanup_input_tokens),
+ outputTokens: finiteMetric(message.cleanup_output_tokens),
+ },
+ }
+ : this.cleanupUnavailable
+ ? { cleanup: { status: "fallback" } }
+ : {}),
model: message.model || this.currentModel,
audioBytesSent: this.audioBytesSent,
inferenceMs: message.inference_ms,
@@ -197,9 +275,8 @@ class OrukeetStreaming {
queueMs: message.queue_ms,
...("language" in message ? languageMetadata(message) : {}),
};
- this.onFinalTranscript?.(this.result.text);
- this.finalResolve?.(this.result);
- this.clearFinal();
+ if (this.pipeline && message.cleanup_receipt) this.onUsageReceipt?.(message.cleanup_receipt);
+ this.settleFinal();
} else if (message.type === "error") {
if (message.code === "capacity" && this.finalResolve && this.retryCapacity) {
clearTimeout(this.retryTimer);
@@ -296,6 +373,7 @@ class OrukeetStreaming {
if (!this.isConnected) return Promise.reject(new Error("Orukeet connection is not ready"));
if (!this.audioBytesSent)
return Promise.resolve({ text: "", model: this.currentModel, audioBytesSent: 0 });
+ this.finalStartedAt = performance.now();
this.finalPromise = new Promise((resolve, reject) => {
this.finalResolve = resolve;
this.finalReject = reject;
@@ -306,12 +384,28 @@ class OrukeetStreaming {
this.finalCapTimer = setTimeout(timedOut, MAX_FINAL_WAIT_MS);
this.sendControl({ type: "commit" }, (error) => {
if (error || !this.finalResolve) return;
- this.finalTimer = setTimeout(timedOut, this.finalTimeoutMs(audioSeconds));
+ this.finalTimer = setTimeout(
+ timedOut,
+ this.pipeline
+ ? Math.min(
+ MAX_FINAL_WAIT_MS,
+ this.finalTimeoutMs(audioSeconds) +
+ PIPELINE_CLEANUP_BUDGET_MS +
+ PIPELINE_FINAL_MARGIN_MS
+ )
+ : this.finalTimeoutMs(audioSeconds)
+ );
});
});
return this.finalPromise;
}
+ settleFinal() {
+ this.onFinalTranscript?.(this.result.text);
+ this.finalResolve?.(this.result);
+ this.clearFinal();
+ }
+
clearFinal() {
clearTimeout(this.finalCapTimer);
clearTimeout(this.finalTimer);
@@ -325,6 +419,21 @@ class OrukeetStreaming {
// socket when the account holds another warm one, so a later close or
// error only ends the connection.
if (this.result) return this.close();
+ // ASR already finished when cleanup stalled or the socket dropped: keep its
+ // text, which is pasted without cleanup, instead of transcribing again.
+ if (this.pipeline && this.finalResolve && typeof this.rawTranscript === "string") {
+ this.result = {
+ text: this.rawTranscript,
+ cleanupError: error.message,
+ asrFinalMs: this.asrFinalMs,
+ cleanup: { status: "fallback" },
+ model: this.currentModel,
+ audioBytesSent: this.audioBytesSent,
+ };
+ this.settleFinal();
+ this.ws?.terminate();
+ 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;
@@ -372,4 +481,11 @@ class OrukeetStreaming {
}
}
-module.exports = { OrukeetStreaming, streamingUrl, MANAGED_STREAM_OPTIONS };
+module.exports = {
+ OrukeetStreaming,
+ streamingUrl,
+ MANAGED_STREAM_OPTIONS,
+ MAX_FINAL_WAIT_MS,
+ PIPELINE_CLEANUP_BUDGET_MS,
+ PIPELINE_FINAL_MARGIN_MS,
+};
diff --git a/src/helpers/policyRequestHeaders.js b/src/helpers/policyRequestHeaders.js
index a0b165193..f13d98281 100644
--- a/src/helpers/policyRequestHeaders.js
+++ b/src/helpers/policyRequestHeaders.js
@@ -4,7 +4,7 @@ const POLICY_CAPABILITY_VERSION = "1";
// Features this build can actually run. The server gates Orukeet on this token,
// not on the version alone, so an older build that passes the version gate is
// never handed a route it would silently reroute.
-const CLIENT_CAPABILITIES = "orukeet";
+const CLIENT_CAPABILITIES = "orukeet,orukeet-pipeline-v2,orukeet-language-routing";
function withPolicyRequestHeaders(headers, appVersion) {
if (!isCanonicalAppVersion(appVersion)) {
diff --git a/src/types/electron.ts b/src/types/electron.ts
index a26fef843..9b69abb22 100644
--- a/src/types/electron.ts
+++ b/src/types/electron.ts
@@ -96,6 +96,13 @@ export interface NoteRecordingProvider {
// main process defaults a missing value to "openai-realtime" for pre-1.8.4
// renderers (#1624).
export interface DictationRealtimeSessionOptions {
+ pipelineOptions?: {
+ agentName?: string;
+ customDictionary?: string[];
+ customPrompt?: string;
+ language?: string;
+ locale?: string;
+ };
provider: string;
baseUrl?: string;
model?: string;
@@ -111,6 +118,8 @@ export interface DictationRealtimeSessionOptions {
export interface DictationLanguageMetadata {
language: string | null;
languageConfidence: number | null;
+ // Sum of detector scores for Orukeet's 25 languages, not a calibrated probability.
+ languageSupportedScore?: number;
languageAudioSeconds?: number;
}
@@ -1007,6 +1016,36 @@ 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 OrukeetLanguageRoutingTelemetry {
+ version: 1;
+ mode: "shadow" | "supported-0.30" | "supported-0.10";
+ auto: boolean;
+ eligible: boolean;
+ analyzedSeconds: number | null;
+ topLanguage: string | null;
+ topScore: number | null;
+ supportedScore: number | null;
+ legacyFallback: boolean;
+ top05Fallback: boolean;
+ candidate030: boolean | null;
+ candidate010: boolean | null;
+ selectedFallback: boolean;
+ fallbackAvailable: boolean;
+}
+export interface OrukeetCleanupTelemetry {
+ status: "complete" | "fallback" | "skipped";
+ model?: "gemma-4-12b";
+ processingMs?: number;
+ queueMs?: number;
+ firstTextMs?: number;
+ inputTokens?: number;
+ outputTokens?: number;
+}
+export interface OrukeetTelemetry {
+ orukeetLanguageRouting?: OrukeetLanguageRoutingTelemetry;
+ orukeetCleanup?: OrukeetCleanupTelemetry;
+}
+
export interface SttDetectedLanguageFields {
sttDetectedLanguage?: string;
sttDetectedLanguageConfidence?: number;
@@ -1444,6 +1483,8 @@ declare global {
dictation?: { mode: string };
notes?: { mode: string };
streamingProvider?: string;
+ orukeetPipeline?: "gemma12";
+ orukeetLanguageRouting?: "off" | "shadow" | "supported-0.30" | "supported-0.10";
} & PolicyFailureMetadata)
| null
>;
@@ -2587,7 +2628,8 @@ declare global {
analyticsOccurredAt?: string;
// Why a managed-streaming user's dictation went batch (rollout metric).
streamingFallbackReason?: string;
- } & SttDetectedLanguageFields
+ } & SttDetectedLanguageFields &
+ OrukeetTelemetry
) => Promise<
{
success: boolean;
@@ -2615,7 +2657,8 @@ declare global {
language?: string;
locale?: string;
streamingFallbackReason?: string;
- } & SttDetectedLanguageFields
+ } & SttDetectedLanguageFields &
+ OrukeetTelemetry
) => Promise<{
success: boolean;
text?: string;
@@ -2645,7 +2688,8 @@ declare global {
analyticsOccurredAt?: string;
analyticsWordCount?: number;
analyticsCounterVersion?: number;
- } & SttDetectedLanguageFields
+ } & SttDetectedLanguageFields &
+ OrukeetTelemetry
) => Promise<{
success: boolean;
wordsUsed?: number;
diff --git a/test/helpers/audioManagerPipelineOptions.test.js b/test/helpers/audioManagerPipelineOptions.test.js
new file mode 100644
index 000000000..d97bc92f9
--- /dev/null
+++ b/test/helpers/audioManagerPipelineOptions.test.js
@@ -0,0 +1,118 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+const { createRendererServer, installBrowserGlobals } = require("../lib/rendererTestHarness");
+
+test("combined cleanup options honor every eligibility guard and use the actual prompt/dictionary", async (t) => {
+ const { window } = installBrowserGlobals(t, { window: { dispatchEvent() {} } });
+ const vite = await createRendererServer(t, {
+ cachePrefix: "orukeet-pipeline-guards-",
+ mockModules: {
+ "/utils/logger":
+ "export default { debug() {}, info() {}, warn() {}, error() {}, logReasoning() {} };",
+ },
+ });
+ const AudioManager = (await vite.ssrLoadModule("/helpers/audioManager.js")).default;
+ const service = (await vite.ssrLoadModule("/services/ReasoningService.ts")).default;
+ t.after(() => service.destroy());
+ const { useSettingsStore } = await vite.ssrLoadModule("/stores/settingsStore.ts");
+ const { usePolicyStore } = await vite.ssrLoadModule("/stores/policyStore.ts");
+ const good = {
+ useLocalWhisper: false,
+ cloudTranscriptionMode: "openwhispr",
+ isSignedIn: true,
+ useCleanupModel: true,
+ cleanupMode: "openwhispr",
+ cleanupCloudMode: "openwhispr",
+ customPrompts: { cleanup: "Keep product names exactly." },
+ customDictionary: ["Orukeet"],
+ uiLanguage: "en",
+ preferredLanguage: "en",
+ };
+ const manager = Object.assign(Object.create(AudioManager.prototype), {
+ sttConfig: { orukeetPipeline: "gemma12" },
+ getCleanupLanguage: () => "en",
+ });
+ usePolicyStore.setState({ status: "unmanaged", policy: null });
+ useSettingsStore.setState(good);
+ assert.deepEqual(manager.getPipelineCleanupOptions(useSettingsStore.getState()), {
+ agentName: "OpenWhispr",
+ customDictionary: ["Orukeet"],
+ customPrompt: good.customPrompts.cleanup,
+ language: "en",
+ locale: "en",
+ });
+ const blocked = [
+ { settings: { useLocalWhisper: true } },
+ { settings: { cloudTranscriptionMode: "byok" } },
+ { settings: { useCleanupModel: false } },
+ { settings: { cleanupMode: "local" } },
+ { settings: { cleanupCloudMode: "byok" } },
+ { manager: { voiceAgentRequested: true } },
+ { manager: { translationRequested: true } },
+ { manager: { sttConfig: {} } },
+ ];
+ for (const entry of blocked) {
+ useSettingsStore.setState({ ...good, ...entry.settings });
+ Object.assign(
+ manager,
+ {
+ voiceAgentRequested: false,
+ translationRequested: false,
+ sttConfig: { orukeetPipeline: "gemma12" },
+ },
+ entry.manager
+ );
+ assert.equal(
+ manager.getPipelineCleanupOptions(useSettingsStore.getState()),
+ undefined,
+ JSON.stringify(entry)
+ );
+ }
+ useSettingsStore.setState(good);
+ Object.assign(manager, {
+ voiceAgentRequested: false,
+ translationRequested: false,
+ sttConfig: { orukeetPipeline: "gemma12" },
+ });
+ const policy = {
+ version: 1,
+ llm: { allowedModes: ["local"], allowedByokProviders: [], allowedEnterpriseProviders: [] },
+ transcription: { allowedModes: ["openwhispr", "local"], allowedByokProviders: [] },
+ features: { agentEnabled: true, webSearchEnabled: true },
+ sharing: { externalLinkSharing: "allowed" },
+ dataRetention: {
+ audioRetentionMaxDays: null,
+ localHistoryMode: "user_choice",
+ cloudBackupAllowed: true,
+ },
+ minAppVersion: null,
+ };
+ usePolicyStore.setState({ status: "managed", policy });
+ // The same policy function used by reasoning dispatch must also gate warmup.
+ assert.equal(manager.getPipelineCleanupOptions(useSettingsStore.getState()), undefined);
+ usePolicyStore.setState({ status: "unmanaged", policy: null });
+ const calls = [];
+ manager.isRecordingAllowedByPolicy = () => true;
+ manager.shouldUseStreaming = () => true;
+ manager.getStreamingProviderName = () => "orukeet";
+ manager.cacheMicrophoneDeviceId = async () => {};
+ manager.getKeyterms = () => [];
+ window.electronAPI.dictationRealtimeWarmup = async (options) => {
+ calls.push(options);
+ return { success: true };
+ };
+ manager.getOrCreateAudioContext = async () => ({ audioWorklet: { addModule: async () => {} } });
+ manager.getWorkletBlobUrl = () => "test";
+ // Warmup prepares the next ordinary dictation, whatever the last one was,
+ // and leaves the last recording's input kind alone.
+ manager.voiceAgentRequested = true;
+ await manager.warmupStreamingConnection({ warmMic: false });
+ assert.equal(calls.length, 1);
+ assert.equal(manager.voiceAgentRequested, true);
+ assert.equal(manager.getPipelineCleanupOptions(useSettingsStore.getState()), undefined);
+ assert.deepEqual(
+ calls[0].pipelineOptions,
+ manager.getPipelineCleanupOptions(useSettingsStore.getState(), { voiceAgentRequested: false })
+ );
+ assert.ok(calls[0].pipelineOptions);
+});
diff --git a/test/helpers/audioManagerStreamingFinalization.test.js b/test/helpers/audioManagerStreamingFinalization.test.js
index 428f2f672..cdd355d68 100644
--- a/test/helpers/audioManagerStreamingFinalization.test.js
+++ b/test/helpers/audioManagerStreamingFinalization.test.js
@@ -1472,8 +1472,8 @@ async function stopManagedDictation(
return { success: true, text: `${text}。` };
};
const usage = [];
- globalThis.window.electronAPI.cloudStreamingUsage = async (_text, _seconds, opts) => {
- usage.push(opts);
+ globalThis.window.electronAPI.cloudStreamingUsage = async (text, seconds, opts) => {
+ usage.push({ ...opts, text, seconds });
return { success: true };
};
let usageSettled;
@@ -1836,3 +1836,271 @@ test("a selection edit that fails during the language re-transcription surfaces
assert.deepEqual(cancelled.errors, []);
assert.deepEqual(cancelled.published, []);
});
+
+test("language-score rollout modes reach the real finalization path without leaking content", async (t) => {
+ globalThis.__orukeetRoutingLog = [];
+ t.after(() => delete globalThis.__orukeetRoutingLog);
+ const AudioManager = await loadManagerClass(t, {
+ "/utils/logger": `export default { debug() {}, warn() {}, error() {}, logReasoning() {}, info(message, meta) { if (message === "Orukeet language routing comparison") globalThis.__orukeetRoutingLog.push(meta); } };`,
+ });
+ const sample = {
+ ...JA_FINAL,
+ text: "PRIVATE DICTATION",
+ language: "hi",
+ languageConfidence: 0.55,
+ languageSupportedScore: 0.02,
+ };
+ for (const [mode, expected] of [
+ ["shadow", false],
+ ["supported-0.30", true],
+ ["supported-0.10", true],
+ ["off", false],
+ ]) {
+ globalThis.__orukeetRoutingLog.length = 0;
+ const result = await stopManagedDictation(AudioManager, {
+ final: sample,
+ overrides: { sttConfig: { orukeetLanguageRouting: mode } },
+ upload: async () => ({ text: "Cloud result", rawText: "Cloud result" }),
+ });
+ assert.equal(result.uploads.length, expected ? 1 : 0, mode);
+ assert.equal(result.published[0].text, expected ? "Cloud result" : sample.text, mode);
+ assert.equal(result.reasonCalls.length, 0, "no extra cleanup call");
+ assert.equal(globalThis.__orukeetRoutingLog.length, mode === "off" ? 0 : 1);
+ assert.doesNotMatch(
+ JSON.stringify(globalThis.__orukeetRoutingLog),
+ /PRIVATE DICTATION|Cloud result/
+ );
+ if (mode !== "off") {
+ assert.equal(globalThis.__orukeetRoutingLog[0].fallbackAvailable, true);
+ const telemetry = expected ? result.uploads[0] : result.usage[0];
+ assert.deepEqual(telemetry.orukeetLanguageRouting, globalThis.__orukeetRoutingLog[0]);
+ if (expected) assert.equal(telemetry.streamingFallbackReason, "language_supported_score_low");
+ }
+ }
+});
+
+test("language-score routing uses analyzed time and preserves explicit language, BYOK and unavailable metadata", async (t) => {
+ const AudioManager = await loadManagerClass(t);
+ const sample = {
+ ...JA_FINAL,
+ language: "hi",
+ languageConfidence: 0.55,
+ languageSupportedScore: 0.02,
+ };
+ for (const overrides of [
+ { final: { ...sample, languageAudioSeconds: 3 } },
+ { final: { ...sample, languageSupportedScore: undefined } },
+ { language: "en" },
+ { settings: { cloudTranscriptionMode: "byok" } },
+ { providerName: "deepgram" },
+ ]) {
+ const r = await stopManagedDictation(AudioManager, {
+ final: sample,
+ overrides: { sttConfig: { orukeetLanguageRouting: "supported-0.30" } },
+ upload: async () => ({ text: "Unexpected cloud", rawText: "Unexpected cloud" }),
+ ...overrides,
+ });
+ assert.equal(r.uploads.length, 0, JSON.stringify(overrides));
+ if (
+ overrides.settings?.cloudTranscriptionMode === "byok" ||
+ overrides.providerName === "deepgram"
+ )
+ assert.equal(r.usage[0].orukeetLanguageRouting, undefined);
+ }
+});
+
+test("group-score fallback failure still discards the unsupported transcript", async (t) => {
+ const AudioManager = await loadManagerClass(t);
+ const r = await stopManagedDictation(AudioManager, {
+ final: { ...JA_FINAL, languageConfidence: 0.4, languageSupportedScore: 0.01 },
+ overrides: {
+ sttConfig: { orukeetLanguageRouting: "supported-0.30" },
+ saveFailedTranscription() {},
+ },
+ upload: async () => {
+ throw Object.assign(new Error("Cloud unavailable"), { code: "NETWORK_ERROR" });
+ },
+ });
+ assert.equal(r.uploads.length, 1);
+ assert.equal(
+ r.published.some((x) => x.text === JA_FINAL.text),
+ false
+ );
+ assert.equal(r.errors.length, 1);
+});
+
+test("combined cleanup is reused once, while changed options or failed cleanup use the ordinary route", 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;
+ `,
+ });
+ for (const [cleanupStatus, changed, calls, empty] of [
+ ["complete", false, 0, false],
+ ["complete", true, 1, false],
+ ["fallback", false, 1, false],
+ ["complete", false, 1, true],
+ ]) {
+ const options = { customDictionary: ["Orukeet"], language: "en" };
+ const { reasonCalls, usage, published } = await stopManagedDictation(AudioManager, {
+ final: {
+ success: true,
+ text: "please send invoice 128",
+ cleanupStatus,
+ cleanupText: empty ? "" : "Please send invoice 128.",
+ asrFinalMs: 103,
+ cleanup: {
+ status: cleanupStatus,
+ model: "gemma-4-12b",
+ processingMs: 220,
+ inputTokens: 40,
+ outputTokens: 8,
+ },
+ cleanupOptions: options,
+ },
+ settings: { useCleanupModel: true, cleanupCloudMode: "openwhispr", customPrompts: {} },
+ overrides: {
+ _activePipelineOptions: changed ? { ...options, language: "fr" } : options,
+ finalizeChineseScript: async (text) => text,
+ },
+ });
+ assert.equal(reasonCalls.length, calls);
+ assert.equal(published[0].rawText, "please send invoice 128");
+ assert.equal(
+ published[0].text,
+ calls ? "please send invoice 128。" : "Please send invoice 128."
+ );
+ assert.equal(usage.length, 1);
+ // Raw words are billed only when the combined cleanup is the pasted text.
+ assert.equal(usage[0].text, calls ? published[0].text : "please send invoice 128");
+ assert.equal(usage[0].sendLogs, calls === 0);
+ assert.equal(usage[0].sttProcessingMs, 103);
+ // A completed Gemma cleanup that wasn't used is never reported as this request's.
+ const reported = cleanupStatus === "fallback" || calls === 0;
+ assert.equal(usage[0].orukeetCleanup?.processingMs, reported ? 220 : undefined);
+ if (calls)
+ assert.equal(reasonCalls[0][1].orukeetCleanup?.status, reported ? "fallback" : undefined);
+ }
+});
+
+test("combined cleanup that never finished pastes the raw text with a cleanup notice", 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 { reasonCalls, uploads, usage, published } = await stopManagedDictation(AudioManager, {
+ final: {
+ success: true,
+ text: "please send invoice 128",
+ cleanupError: "Orukeet final transcript timed out",
+ asrFinalMs: 103,
+ cleanup: { status: "fallback" },
+ },
+ upload: async () => assert.fail("The finished ASR text must not be transcribed again"),
+ settings: { useCleanupModel: true, cleanupCloudMode: "openwhispr", customPrompts: {} },
+ });
+ assert.equal(reasonCalls.length, 0);
+ assert.equal(uploads.length, 0);
+ assert.equal(published[0].text, "please send invoice 128");
+ assert.equal(published[0].cleanupFailure.messageKey, "app.toasts.cleanupFailed.title");
+ assert.equal(usage[0].text, "please send invoice 128");
+ assert.equal(usage[0].sendLogs, true);
+ assert.deepEqual(usage[0].orukeetCleanup, { status: "fallback" });
+});
+
+test("combined text never replaces an unsupported-language fallback", async (t) => {
+ const AudioManager = await loadManagerClass(t);
+ const { uploads, published, reasonCalls } = await stopManagedDictation(AudioManager, {
+ final: {
+ ...JA_FINAL,
+ cleanupStatus: "complete",
+ cleanupText: "Wrong cleanup.",
+ cleanupOptions: {},
+ cleanup: { status: "complete", model: "gemma-4-12b" },
+ },
+ upload: async () => ({ text: "明日の会議", rawText: "明日の会議" }),
+ overrides: { getPipelineCleanupOptions: () => ({}) },
+ });
+ assert.equal(uploads.length, 1);
+ assert.equal(uploads[0].orukeetCleanup, undefined);
+ assert.equal(reasonCalls.length, 0);
+ assert.equal(published[0].text, "明日の会議");
+});
+
+test("ordinary Orukeet and BYOK streams continue metering processed text", 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;
+ `,
+ });
+ for (const cloudTranscriptionMode of ["openwhispr", "byok"]) {
+ const result = await stopManagedDictation(AudioManager, {
+ final: { success: true, text: "um please send invoice 128" },
+ settings: {
+ cloudTranscriptionMode,
+ useCleanupModel: true,
+ cleanupCloudMode: "openwhispr",
+ customPrompts: { cleanup: "Keep text." },
+ },
+ });
+ assert.equal(result.usage[0].text, result.published[0].text);
+ assert.equal(result.usage[0].text, "um please send invoice 128。");
+ assert.equal(result.usage[0].sendLogs, false);
+ }
+});
+
+test("recording config snapshot survives a rollback until the next recording", async (t) => {
+ const AudioManager = await loadManagerClass(t);
+ const result = await stopManagedDictation(AudioManager, {
+ final: { ...JA_FINAL, languageConfidence: 0.55, languageSupportedScore: 0.02 },
+ overrides: {
+ _activeStreamingConfig: { orukeetLanguageRouting: "supported-0.30" },
+ sttConfig: { orukeetLanguageRouting: "off", streamingProvider: "deepgram" },
+ },
+ upload: async () => ({ text: "Cloud result" }),
+ });
+ assert.equal(result.uploads.length, 1);
+ assert.equal(result.uploads[0].orukeetLanguageRouting.mode, "supported-0.30");
+ assert.equal(result.manager._activeStreamingConfig, null);
+});
+
+test("combined options are captured and passed through recording start", async (t) => {
+ const AudioManager = await loadManagerClass(t);
+ useManagedOrukeetSettings();
+ installCapture(t);
+ const options = { customDictionary: ["Orukeet"], language: "en" };
+ let sent;
+ const { manager } = createStartingManager(AudioManager, {
+ providerName: "orukeet",
+ provider: startingOrukeetProvider({
+ start: async (value) => {
+ sent = value;
+ return { success: true };
+ },
+ }),
+ });
+ manager.getPipelineCleanupOptions = () => options;
+ manager.sttConfig = { orukeetPipeline: "gemma12", orukeetLanguageRouting: "shadow" };
+ await manager.startStreamingRecording();
+ assert.deepEqual(sent.pipelineOptions, options);
+ assert.equal(manager._activePipelineOptions, options);
+ manager.setSttConfig({ streamingProvider: "deepgram" });
+ assert.equal(manager._activeStreamingConfig.orukeetPipeline, "gemma12");
+ await manager.cancelStreamingRecording();
+});
diff --git a/test/helpers/audioManagerStreamingRouting.test.js b/test/helpers/audioManagerStreamingRouting.test.js
index 171ab814c..f8d77d01c 100644
--- a/test/helpers/audioManagerStreamingRouting.test.js
+++ b/test/helpers/audioManagerStreamingRouting.test.js
@@ -613,3 +613,27 @@ for (const translationRequested of [false, true]) {
}
});
}
+
+test("opt-in language routing refreshes within 30 seconds for rollback without changing normal cache TTL", async (t) => {
+ const manager = await loadManager(t);
+ for (const mode of ["shadow", "supported-0.30", "supported-0.10"]) {
+ manager.setSttConfig({ orukeetLanguageRouting: mode });
+ const at = manager.sttConfigFetchedAt;
+ assert.equal(manager.isSttConfigStale(at + 30000), false);
+ assert.equal(manager.isSttConfigStale(at + 30001), true);
+ }
+ for (const mode of [undefined, "off", "invalid"]) {
+ manager.setSttConfig({ orukeetLanguageRouting: mode });
+ const at = manager.sttConfigFetchedAt;
+ assert.equal(manager.isSttConfigStale(at + 30001), false);
+ assert.equal(manager.isSttConfigStale(at + 900001), true);
+ }
+});
+
+test("combined-pipeline config expires after 30 seconds even when language routing is off", async (t) => {
+ const manager = await loadManager(t);
+ manager.setSttConfig({ orukeetLanguageRouting: "off", orukeetPipeline: "gemma12" });
+ const at = manager.sttConfigFetchedAt;
+ assert.equal(manager.isSttConfigStale(at + 30000), false);
+ assert.equal(manager.isSttConfigStale(at + 30001), true);
+});
diff --git a/test/helpers/cloudConfigRequest.test.js b/test/helpers/cloudConfigRequest.test.js
index 76f62e327..09a1f207e 100644
--- a/test/helpers/cloudConfigRequest.test.js
+++ b/test/helpers/cloudConfigRequest.test.js
@@ -120,8 +120,16 @@ test("every config refetch bypasses the HTTP cache and declares the client capab
assert.deepEqual(
requests.map(({ url, cache, headers }) => [url, cache, headers["x-openwhispr-capabilities"]]),
[
- ["https://api.openwhispr.test/api/stt-config", "no-store", "orukeet"],
- ["https://api.openwhispr.test/api/note-recording-config", "no-store", "orukeet"],
+ [
+ "https://api.openwhispr.test/api/stt-config",
+ "no-store",
+ "orukeet,orukeet-pipeline-v2,orukeet-language-routing",
+ ],
+ [
+ "https://api.openwhispr.test/api/note-recording-config",
+ "no-store",
+ "orukeet,orukeet-pipeline-v2,orukeet-language-routing",
+ ],
]
);
});
diff --git a/test/helpers/orukeetCloudSession.test.js b/test/helpers/orukeetCloudSession.test.js
index c41be0fea..028464d9d 100644
--- a/test/helpers/orukeetCloudSession.test.js
+++ b/test/helpers/orukeetCloudSession.test.js
@@ -86,7 +86,10 @@ async function fixture(t, fetchImpl) {
assert.equal(options.headers.Authorization, "Bearer account-a");
assert.equal(options.headers["x-openwhispr-policy-version"], "1");
// The server mints only for builds that declare they can run Orukeet.
- assert.equal(options.headers["x-openwhispr-capabilities"], "orukeet");
+ assert.equal(
+ options.headers["x-openwhispr-capabilities"],
+ "orukeet,orukeet-pipeline-v2,orukeet-language-routing"
+ );
assert.equal(options.useSessionCookies, false);
assert.equal(options.redirect, "error");
return Response.json(session());
@@ -229,3 +232,39 @@ test("invalid backend destination is rejected before any WebSocket is constructe
await assert.rejects(connectManagedOrukeet(f.options), /Invalid Orukeet cloud session/);
assert.equal(f.sockets.length, 0);
});
+
+test("only the exact authenticated language-preview route can opt into preview sessions", () => {
+ const baseUrl = ORUKEET_BASE_URL + "/preview/language-routing";
+ const candidate = {
+ ...session(),
+ baseUrl,
+ websocketUrl: baseUrl.replace("https:", "wss:") + "/v1/audio/transcriptions/stream",
+ };
+ assert.deepEqual(validateSession(candidate), { baseUrl, clientToken: candidate.clientToken });
+ for (const altered of [
+ { ...candidate, websocketUrl: session().websocketUrl },
+ { ...session(), websocketUrl: candidate.websocketUrl },
+ { ...candidate, baseUrl: baseUrl + "/" },
+ { ...candidate, baseUrl: baseUrl + "?token=secret" },
+ { ...candidate, baseUrl: ORUKEET_BASE_URL + "/preview/other" },
+ { ...candidate, websocketUrl: candidate.websocketUrl + "?token=secret" },
+ {
+ ...candidate,
+ baseUrl: "https://orukeet.gizmovoice.ai.attacker.test/preview/language-routing",
+ },
+ ])
+ assert.throws(() => validateSession(altered), /Invalid Orukeet cloud session/);
+});
+
+test("consistent language preview lookalike is rejected", () => {
+ const baseUrl = "https://orukeet.gizmovoice.ai.attacker.test/preview/language-routing";
+ assert.throws(
+ () =>
+ validateSession({
+ ...session(),
+ baseUrl,
+ websocketUrl: `${baseUrl.replace("https:", "wss:")}/v1/audio/transcriptions/stream`,
+ }),
+ /Invalid Orukeet cloud session/
+ );
+});
diff --git a/test/helpers/orukeetDictationIpc.test.js b/test/helpers/orukeetDictationIpc.test.js
index 3d300576f..71e7c39bf 100644
--- a/test/helpers/orukeetDictationIpc.test.js
+++ b/test/helpers/orukeetDictationIpc.test.js
@@ -43,6 +43,7 @@ const backendFetch = async (url, options) => {
assert.ok(
[
"https://api.openwhispr.test/api/stt/orukeet/session",
+ "https://api.openwhispr.test/api/stt/orukeet/pipeline-session",
"https://api.openwhispr.test/api/reason",
"https://api.openwhispr.test/api/streaming-usage",
"https://api.openwhispr.test/api/transcribe",
@@ -110,7 +111,12 @@ Module._load = function loadWithMocks(request, parent, isMain) {
super({
...options,
createSocket: (url, options, protocols) => {
- assert.equal(url, cloudSession.websocketUrl);
+ assert.equal(
+ url,
+ protocols?.[0] === "orukeet.pipeline.v2"
+ ? "wss://orukeet.gizmovoice.ai/preview/gemma12/v1/pipeline/stream"
+ : cloudSession.websocketUrl
+ );
assert.equal(
options.headers.Authorization,
protocols ? undefined : "Bearer test-key"
@@ -175,6 +181,9 @@ test.before(async () => {
sample_rate: 16000,
encoding: "pcm_s16le",
max_seconds: 600,
+ ...(socket.protocol === "orukeet.pipeline.v2"
+ ? { pipeline_protocol: 2, cleanup: true, account_limits: true }
+ : {}),
})
);
let bytes = 0;
@@ -188,7 +197,12 @@ test.before(async () => {
return;
}
socket.send(
- JSON.stringify({ type: "language", language: "en", language_confidence: 0.99 })
+ JSON.stringify({
+ type: "language",
+ language: "en",
+ language_confidence: 0.99,
+ language_supported_score: 0.995,
+ })
);
socket.send(
JSON.stringify({
@@ -197,6 +211,7 @@ test.before(async () => {
model: "orukeet-v0.1.0",
language: "en",
language_confidence: 0.99,
+ language_supported_score: 0.995,
language_audio_seconds: 6,
})
);
@@ -228,10 +243,12 @@ test("registered managed IPC streams startup audio and returns exactly one compl
assert.equal(final.text, "Recorded 1280 bytes");
assert.equal(final.language, "en");
assert.equal(final.languageConfidence, 0.99);
+ assert.equal(final.languageSupportedScore, 0.995);
assert.equal(final.languageAudioSeconds, 6);
assert.deepEqual(messages.find(([channel]) => channel === "dictation-realtime-language")?.[1], {
language: "en",
languageConfidence: 0.99,
+ languageSupportedScore: 0.995,
});
assert.equal(messages.filter(([channel]) => channel === "dictation-realtime-final").length, 1);
assert.equal((await handlers.get("dictation-realtime-stop")()).text, final.text);
@@ -522,3 +539,96 @@ test("an idle Orukeet warm socket closes after 60 seconds and start cancels expi
assert.equal(target._dictationStreaming.isConnected, true);
await handlers.get("dictation-realtime-stop")();
});
+
+test("pipeline options reach minting through IPC warmup and changed options replace the cached connection", async () => {
+ await handlers.get("dictation-realtime-stop")();
+ const calls = [];
+ backendResponse = async (url, request) => {
+ assert.ok(url.endsWith("pipeline-session"));
+ const body = JSON.parse(request.body);
+ calls.push(body);
+ return Response.json({
+ ...cloudSession,
+ baseUrl: "https://orukeet.gizmovoice.ai/preview/gemma12",
+ websocketUrl: "wss://orukeet.gizmovoice.ai/preview/gemma12/v1/pipeline/stream",
+ protocol: "orukeet.pipeline.v2",
+ cleanup: true,
+ cleanupModel: "gemma-4-12b",
+ requireAccountLimits: true,
+ });
+ };
+ const first = { customDictionary: ["Orukeet"], customPrompt: "Keep names." };
+ assert.equal(
+ (
+ await handlers.get("dictation-realtime-warmup")(event, {
+ ...managedOptions,
+ pipelineOptions: first,
+ })
+ ).success,
+ true
+ );
+ assert.equal(
+ (
+ await handlers.get("dictation-realtime-start")(event, {
+ ...managedOptions,
+ pipelineOptions: first,
+ })
+ ).success,
+ true
+ );
+ assert.equal(calls.length, 1);
+ const second = { ...first, customDictionary: ["Chad"] };
+ assert.equal(
+ (
+ await handlers.get("dictation-realtime-start")(event, {
+ ...managedOptions,
+ pipelineOptions: second,
+ })
+ ).success,
+ true
+ );
+ assert.deepEqual(
+ calls.map((entry) => entry.cleanupOptions),
+ [first, second]
+ );
+ await handlers.get("dictation-realtime-stop")();
+});
+
+test("server telemetry survives streaming usage, fallback upload and cloud cleanup IPC", async () => {
+ const metadata = {
+ orukeetLanguageRouting: {
+ version: 1,
+ mode: "shadow",
+ supportedScore: 0.02,
+ selectedFallback: false,
+ },
+ orukeetCleanup: {
+ status: "complete",
+ model: "gemma-4-12b",
+ inputTokens: 40,
+ outputTokens: 8,
+ processingMs: 220,
+ },
+ };
+ const bodies = [];
+ backendResponse = async (url, request) => {
+ bodies.push([url, request.body]);
+ return Response.json({ text: "result", recorded: true });
+ };
+ await handlers.get("cloud-streaming-usage")(event, "raw", 6, metadata);
+ await handlers.get("cloud-reason")(event, "raw", { purpose: "cleanup", ...metadata });
+ await handlers.get("cloud-transcribe")(event, new Uint8Array(64).buffer, {
+ streamingFallbackReason: "language_supported_score_low",
+ ...metadata,
+ });
+ for (const [, body] of bodies.slice(0, 2)) {
+ const parsed = JSON.parse(body);
+ assert.deepEqual(parsed.orukeetLanguageRouting, metadata.orukeetLanguageRouting);
+ assert.deepEqual(parsed.orukeetCleanup, metadata.orukeetCleanup);
+ }
+ const multipart = Buffer.from(bodies[2][1]).toString("latin1");
+ assert.ok(multipart.includes(JSON.stringify(metadata.orukeetLanguageRouting)));
+ assert.ok(multipart.includes(JSON.stringify(metadata.orukeetCleanup)));
+ assert.match(multipart, /language_supported_score_low/);
+ assert.doesNotMatch(multipart, /\[object Object\]/);
+});
diff --git a/test/helpers/orukeetLanguageRouting.test.js b/test/helpers/orukeetLanguageRouting.test.js
new file mode 100644
index 000000000..81d8866c4
--- /dev/null
+++ b/test/helpers/orukeetLanguageRouting.test.js
@@ -0,0 +1,165 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+const load = () => import("../../src/helpers/dictationStreamingRouting.js");
+const final = {
+ success: true,
+ language: "hi",
+ languageConfidence: 0.55,
+ languageSupportedScore: 0.02,
+ languageAudioSeconds: 6,
+};
+
+test("shadow retains the current policy while comparing both supported-score cutoffs", async () => {
+ const { evaluateOrukeetLanguageRouting: run } = await load();
+ const result = run({ language: "auto", final, mode: "shadow" });
+ assert.equal(result.fallback, false);
+ assert.equal(result.comparison.legacyFallback, false);
+ assert.equal(result.comparison.top05Fallback, true);
+ assert.equal(result.comparison.candidate030, true);
+ assert.equal(result.comparison.candidate010, true);
+});
+
+test("only explicit modes enable group-score fallback", async () => {
+ const { evaluateOrukeetLanguageRouting: run } = await load();
+ for (const mode of [undefined, null, "off", "", "enabled", true, { mode: "supported-0.30" }]) {
+ assert.deepEqual(run({ language: "auto", final, mode }), { fallback: false, comparison: null });
+ }
+ for (const mode of ["supported-0.30", "supported-0.10"])
+ assert.equal(run({ language: "auto", final, mode }).fallback, true);
+});
+
+test("exact boundaries, zero, one and separate cutoffs retain their meaning", async () => {
+ const { evaluateOrukeetLanguageRouting: run } = await load();
+ for (const [score, a, b] of [
+ [0, true, true],
+ [0.1, true, true],
+ [0.100001, true, false],
+ [0.3, true, false],
+ [0.300001, false, false],
+ [1, false, false],
+ ]) {
+ assert.equal(
+ run({ final: { ...final, languageSupportedScore: score }, mode: "supported-0.30" }).fallback,
+ a
+ );
+ assert.equal(
+ run({ final: { ...final, languageSupportedScore: score }, mode: "supported-0.10" }).fallback,
+ b
+ );
+ }
+});
+
+test("group evidence can override an uncertain supported top label or absent top label", async () => {
+ const { evaluateOrukeetLanguageRouting: run } = await load();
+ for (const language of ["en", null])
+ assert.equal(
+ run({
+ final: { ...final, language, languageConfidence: language?.length ? 0.3 : null },
+ mode: "supported-0.30",
+ }).fallback,
+ true
+ );
+});
+
+test("explicit user languages always preserve existing routing", async () => {
+ const { evaluateOrukeetLanguageRouting: run } = await load();
+ for (const language of ["en", "en-US", "hi"]) {
+ const r = run({ language, final, mode: "supported-0.30" });
+ assert.equal(r.fallback, false);
+ assert.equal(r.comparison.eligible, false);
+ }
+});
+
+test("short, invalid or absent evidence retains the old decision", async () => {
+ const { evaluateOrukeetLanguageRouting: run, shouldRetranscribeOrukeetLanguage: legacy } =
+ await load();
+ const cases = [null, undefined, { ...final, success: false }];
+ for (const languageAudioSeconds of [undefined, null, NaN, Infinity, -1, 0, 3, 5.999])
+ cases.push({ ...final, languageConfidence: 0.95, languageAudioSeconds });
+ for (const languageSupportedScore of [undefined, null, NaN, Infinity, -0.01, 1.01, true, "0.02"])
+ cases.push({ ...final, languageConfidence: 0.95, languageSupportedScore });
+ for (const f of cases) {
+ const r = run({ final: f, mode: "supported-0.30" });
+ assert.equal(r.fallback, legacy({ final: f }));
+ assert.equal(r.comparison.eligible, false);
+ }
+});
+
+test("rolling back to off immediately restores the current decision", async () => {
+ const { evaluateOrukeetLanguageRouting: run } = await load();
+ assert.equal(run({ final, mode: "supported-0.30" }).fallback, true);
+ assert.deepEqual(run({ final, mode: "off" }), { fallback: false, comparison: null });
+});
+
+test("comparison logs contain only the allowlisted metadata, including on malformed input", async () => {
+ const { evaluateOrukeetLanguageRouting: run } = await load();
+ const r = run({
+ language: "auto",
+ mode: "shadow",
+ final: {
+ ...final,
+ text: "PRIVATE TRANSCRIPT",
+ rawText: "PRIVATE",
+ token: "SECRET",
+ accountId: "PERSON",
+ audio: Buffer.from("VOICE"),
+ },
+ });
+ assert.deepEqual(
+ Object.keys(r.comparison).sort(),
+ [
+ "version",
+ "mode",
+ "auto",
+ "eligible",
+ "analyzedSeconds",
+ "topLanguage",
+ "topScore",
+ "supportedScore",
+ "legacyFallback",
+ "top05Fallback",
+ "candidate030",
+ "candidate010",
+ "selectedFallback",
+ ].sort()
+ );
+ assert.doesNotMatch(JSON.stringify(r), /PRIVATE|SECRET|PERSON|VOICE/);
+ const bad = run({
+ final: {
+ ...final,
+ language: "PRIVATE TRANSCRIPT",
+ languageConfidence: "SECRET",
+ languageSupportedScore: NaN,
+ languageAudioSeconds: "VOICE",
+ },
+ mode: "shadow",
+ });
+ assert.equal(bad.comparison.topLanguage, null);
+ assert.equal(bad.comparison.topScore, null);
+ assert.equal(bad.comparison.supportedScore, null);
+ assert.equal(bad.comparison.analyzedSeconds, null);
+});
+
+test("supported-score modes never remove a legacy unsupported-language fallback", async () => {
+ const { evaluateOrukeetLanguageRouting: run } = await load();
+ for (const mode of ["supported-0.30", "supported-0.10", "shadow"]) {
+ const result = run({
+ language: "auto",
+ final: { ...final, language: "ja", languageConfidence: 0.95, languageSupportedScore: 0.5 },
+ mode,
+ });
+ assert.equal(result.fallback, true);
+ assert.equal(result.comparison.selectedFallback, true);
+ assert.equal(result.comparison.candidate030, false);
+ }
+});
+
+test("top-score comparator never labels a supported top language unsupported", async () => {
+ const { evaluateOrukeetLanguageRouting: run } = await load();
+ const result = run({
+ final: { ...final, language: "en", languageConfidence: 0.9 },
+ mode: "shadow",
+ });
+ assert.equal(result.comparison.top05Fallback, false);
+ assert.equal(result.comparison.selectedFallback, false);
+});
diff --git a/test/helpers/orukeetLanguageSummary.test.js b/test/helpers/orukeetLanguageSummary.test.js
new file mode 100644
index 000000000..00d8b0e32
--- /dev/null
+++ b/test/helpers/orukeetLanguageSummary.test.js
@@ -0,0 +1,46 @@
+const test = require("node:test"),
+ assert = require("node:assert/strict");
+const { summarize } = require("../../scripts/summarize-orukeet-language-routing.cjs");
+const event = {
+ version: 1,
+ eligible: true,
+ legacyFallback: false,
+ top05Fallback: false,
+ candidate030: true,
+ candidate010: true,
+};
+test("unlabeled observations measure disagreements but never claim recall or false positives", () => {
+ const r = summarize([{ meta: event, text: "PRIVATE" }]);
+ assert.equal(r.eligible, 1);
+ assert.equal(r.labeled, 0);
+ assert.equal(r.rules.candidate030.disagreesWithLegacy, 1);
+ assert.equal(r.rules.candidate030.unsupportedTotal, 0);
+ assert.equal(r.rules.candidate030.supportedTotal, 0);
+ assert.doesNotMatch(JSON.stringify(r), /PRIVATE/);
+});
+test("reference annotations supply explicit denominators and incomplete windows stay separate", () => {
+ const r = summarize([
+ { comparison: event, expectedSupported: false },
+ { ...event, expectedSupported: true },
+ { ...event, eligible: false },
+ { ...event, candidate030: null },
+ { text: "private" },
+ null,
+ ]);
+ assert.equal(r.events, 4);
+ assert.equal(r.eligible, 2);
+ assert.equal(r.labeled, 2);
+ assert.equal(r.skipped, 3);
+ assert.equal(r.rules.candidate030.unsupportedCaught, 1);
+ assert.equal(r.rules.candidate030.unsupportedTotal, 1);
+ assert.equal(r.rules.candidate030.supportedDiverted, 1);
+ assert.equal(r.rules.candidate030.supportedTotal, 1);
+});
+
+test("exported server metadata is readable without renderer debug logs", () => {
+ const result = summarize([
+ { metadata: { orukeetLanguageRouting: event }, expectedSupported: false },
+ ]);
+ assert.equal(result.events, 1);
+ assert.equal(result.rules.candidate030.unsupportedCaught, 1);
+});
diff --git a/test/helpers/orukeetPipeline.test.js b/test/helpers/orukeetPipeline.test.js
new file mode 100644
index 000000000..23375f082
--- /dev/null
+++ b/test/helpers/orukeetPipeline.test.js
@@ -0,0 +1,525 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+const { EventEmitter } = require("node:events");
+const { OrukeetStreaming } = require("../../src/helpers/orukeetStreaming");
+const { connectManagedOrukeet, validateSession } = require("../../src/helpers/orukeetCloudSession");
+const { withPolicyRequestHeaders } = require("../../src/helpers/policyRequestHeaders");
+const session = {
+ baseUrl: "https://orukeet.gizmovoice.ai/preview/gemma12",
+ websocketUrl: "wss://orukeet.gizmovoice.ai/preview/gemma12/v1/pipeline/stream",
+ protocol: "orukeet.pipeline.v2",
+ clientToken: "single.use.token",
+ model: "orukeet-v0.1.0",
+ cleanup: true,
+ cleanupModel: "gemma-4-12b",
+ requireAccountLimits: true,
+ expiresIn: 60,
+ singleUse: true,
+};
+const ready = {
+ type: "ready",
+ sample_rate: 16000,
+ channels: 1,
+ encoding: "pcm_s16le",
+ max_seconds: 600,
+ pipeline_protocol: 2,
+ cleanup: true,
+ account_limits: true,
+};
+const final = {
+ type: "final",
+ text: "Send invoice 128 to Orukeet.",
+ raw_text: "um send invoice one twenty eight to aurakeet",
+ cleanup_status: "complete",
+ cleanup_receipt: "signed.proof",
+};
+function fixture(t, response = final) {
+ let socket;
+ const streaming = new OrukeetStreaming({
+ timeoutMs: 100,
+ createSocket(url, opts, protocols) {
+ assert.equal(url, session.websocketUrl);
+ assert.deepEqual(protocols, [session.protocol, "auth.single.use.token"]);
+ assert.deepEqual(opts.headers, {});
+ socket = new EventEmitter();
+ socket.readyState = 1;
+ socket.bufferedAmount = 0;
+ socket.close = () => {};
+ socket.terminate = () => {};
+ socket.send = (data, cb) => {
+ cb?.();
+ if (typeof data === "string" && JSON.parse(data).type === "commit")
+ queueMicrotask(() => socket.emit("message", JSON.stringify(response)));
+ };
+ queueMicrotask(() => socket.emit("message", JSON.stringify(ready)));
+ return socket;
+ },
+ });
+ t.after(() => streaming.disconnect());
+ return streaming;
+}
+test(
+ "combined stream keeps raw text and cleanup separate and meters exactly once on duplicate final",
+ { timeout: 2500 },
+ async (t) => {
+ const streaming = fixture(t);
+ const options = { customDictionary: ["Orukeet"] };
+ let mints = 0,
+ receipts = 0,
+ finals = 0;
+ const tokenStore = {
+ getState: () => ({ token: "account", generation: 1 }),
+ subscribe: () => () => {},
+ };
+ streaming.onFinalTranscript = (raw) => {
+ finals++;
+ assert.equal(raw, final.raw_text);
+ };
+ await connectManagedOrukeet({
+ streaming,
+ tokenStore,
+ pipelineOptions: options,
+ getApiUrl: () => "https://api.test",
+ withPolicyHeaders: (h) => withPolicyRequestHeaders(h, "1.10.2"),
+ proxyFetch: async (url, req) => {
+ assert.equal(req.headers.Authorization, "Bearer account");
+ if (url.endsWith("pipeline-session")) {
+ mints++;
+ assert.deepEqual(JSON.parse(req.body), {
+ variant: "gemma12",
+ cleanup: true,
+ cleanupOptions: options,
+ });
+ return Response.json(session);
+ }
+ assert.ok(url.endsWith("pipeline-usage"));
+ receipts++;
+ assert.deepEqual(JSON.parse(req.body), { receipt: final.cleanup_receipt });
+ return Response.json({ recorded: true });
+ },
+ });
+ streaming.sendAudio(Buffer.alloc(320));
+ const result = await streaming.finalize();
+ streaming.handleMessage(final);
+ await streaming.usagePromise;
+ assert.equal(result.text, final.raw_text);
+ assert.equal(result.cleanupText, final.text);
+ assert.deepEqual(result.cleanupOptions, options);
+ assert.deepEqual([mints, receipts, finals], [1, 1, 1]);
+ }
+);
+test(
+ "pipeline cannot bypass account-limit handshake or spoof an arbitrary host",
+ { timeout: 2500 },
+ async (t) => {
+ for (const update of [
+ { baseUrl: "https://evil.test" },
+ { cleanup: false },
+ { requireAccountLimits: false },
+ { cleanupModel: "gemma-4-31b" },
+ { clientToken: "x".repeat(161) },
+ ])
+ assert.throws(() => validateSession({ ...session, ...update }, true));
+ const streaming = fixture(t);
+ await streaming.connect(validateSession(session, true));
+ const other = new OrukeetStreaming();
+ other.pipeline = true;
+ other.requireAccountLimits = true;
+ assert.throws(() => other.handleMessage({ ...ready, account_limits: false }), /account limits/);
+ }
+);
+test(
+ "malformed final cannot replace a recoverable raw transcript",
+ { timeout: 2500 },
+ async (t) => {
+ const streaming = fixture(t, { ...final, raw_text: undefined });
+ await streaming.connect(validateSession(session, true));
+ streaming.sendAudio(Buffer.alloc(320));
+ await assert.rejects(streaming.finalize(), /Invalid pipeline final/);
+ }
+);
+test(
+ "a cleanup that stalls, fails or drops after ASR settles with the raw transcript",
+ { timeout: 2500 },
+ async (t) => {
+ for (const interrupt of [
+ (streaming) => streaming.ws.emit("close"),
+ (streaming) => streaming.handleMessage({ type: "error", code: "cleanup", message: "Down" }),
+ (streaming) => streaming.fail(new Error("Orukeet final transcript timed out")),
+ ]) {
+ const streaming = fixture(t, { type: "transcript", text: final.raw_text });
+ let errors = 0;
+ let finals = 0;
+ streaming.onError = () => errors++;
+ streaming.onFinalTranscript = () => finals++;
+ await streaming.connect(validateSession(session, true));
+ streaming.sendAudio(Buffer.alloc(320));
+ const pending = streaming.finalize();
+ await new Promise((resolve) => setImmediate(resolve));
+ interrupt(streaming);
+ const result = await pending;
+ assert.equal(result.text, final.raw_text);
+ assert.ok(result.cleanupError);
+ assert.equal(result.cleanupStatus, undefined);
+ assert.deepEqual(result.cleanup, { status: "fallback" });
+ assert.deepEqual([errors, finals], [0, 1]);
+ }
+ }
+);
+
+test("canceled recording never commits or emits a receipt", { timeout: 2500 }, async (t) => {
+ const streaming = fixture(t);
+ let receipts = 0;
+ streaming.onUsageReceipt = () => receipts++;
+ await streaming.connect(validateSession(session, true));
+ streaming.sendAudio(Buffer.alloc(320));
+ await streaming.disconnect();
+ streaming.handleMessage(final);
+ assert.equal(receipts, 0);
+ assert.equal(streaming.result, null);
+});
+
+test(
+ "pipeline handshake and final metadata reject malformed cleanup contracts promptly",
+ { timeout: 2500 },
+ async (t) => {
+ for (const update of [
+ { pipeline_protocol: 1 },
+ { pipeline_protocol: undefined },
+ { cleanup: false },
+ ]) {
+ const adapter = new OrukeetStreaming();
+ adapter.pipeline = true;
+ assert.throws(() => adapter.handleMessage({ ...ready, ...update }), /pipeline handshake/);
+ }
+ for (const update of [
+ { cleanup_status: "unknown" },
+ { cleanup_receipt: {} },
+ { cleanup_receipt: "x".repeat(2049) },
+ ]) {
+ const adapter = fixture(t, { ...final, ...update });
+ await adapter.connect(validateSession(session, true));
+ adapter.sendAudio(Buffer.alloc(320));
+ await assert.rejects(adapter.finalize(), /Invalid (pipeline final|cleanup receipt)/);
+ }
+ }
+);
+
+test("pipeline endpoint allowlist rejects a consistent lookalike or unlisted region", () => {
+ for (const baseUrl of [
+ "https://orukeet.gizmovoice.ai.attacker.test/preview/gemma12",
+ "https://orukeet.gizmovoice.ai/regions/us-east1/gemma12",
+ "https://orukeet.gizmovoice.ai/regions/us-west1/gemma31",
+ ])
+ assert.throws(
+ () =>
+ validateSession(
+ {
+ ...session,
+ baseUrl,
+ websocketUrl: `${baseUrl.replace("https:", "wss:")}/v1/pipeline/stream`,
+ },
+ true
+ ),
+ /Invalid/
+ );
+});
+
+test("pipeline deadline allows ASR plus full cleanup queue budget, within hard cap", () => {
+ const {
+ MAX_FINAL_WAIT_MS,
+ PIPELINE_CLEANUP_BUDGET_MS,
+ PIPELINE_FINAL_MARGIN_MS,
+ } = require("../../src/helpers/orukeetStreaming");
+ for (const base of [7000, 25000]) {
+ const adapter = new OrukeetStreaming({ finalTimeoutMs: () => base });
+ adapter.pipeline = true;
+ adapter.isConnected = true;
+ adapter.audioBytesSent = 32000;
+ adapter.sendControl = (_message, callback) => callback();
+ const pending = adapter.finalize();
+ assert.equal(
+ adapter.finalTimer._idleTimeout,
+ Math.min(MAX_FINAL_WAIT_MS, base + PIPELINE_CLEANUP_BUDGET_MS + PIPELINE_FINAL_MARGIN_MS)
+ );
+ adapter.finalResolve({});
+ adapter.clearFinal();
+ void pending;
+ }
+});
+
+const plainSession = {
+ baseUrl: "https://orukeet.gizmovoice.ai",
+ websocketUrl: "wss://orukeet.gizmovoice.ai/v1/audio/transcriptions/stream",
+ clientToken: "test.token",
+ protocol: "orukeet.pcm.v1",
+ model: "orukeet-v0.1.0",
+ expiresIn: 60,
+ singleUse: true,
+};
+function managedFixture() {
+ const state = { token: "account", generation: 1 };
+ return {
+ state,
+ tokenStore: { getState: () => ({ ...state }), subscribe: () => () => {} },
+ streaming: {
+ connect: async function (options) {
+ this.connected = options;
+ },
+ close() {},
+ fail(error) {
+ this.failure = error;
+ },
+ },
+ getApiUrl: () => "https://api.test",
+ withPolicyHeaders: (h) => h,
+ };
+}
+test(
+ "cleanup policy or option refusal retries plain ASR without losing capture",
+ { timeout: 2500 },
+ async () => {
+ for (const [status, code] of [
+ [403, "POLICY_MODE_BLOCKED"],
+ [400, "PIPELINE_OPTIONS_UNSUPPORTED"],
+ ]) {
+ const deps = managedFixture();
+ const calls = [];
+ await connectManagedOrukeet({
+ ...deps,
+ pipelineOptions: { customPrompt: "long prompt" },
+ proxyFetch: async (url, request) => {
+ calls.push([url, request]);
+ return calls.length === 1
+ ? Response.json({ code }, { status })
+ : Response.json(plainSession);
+ },
+ });
+ assert.deepEqual(
+ calls.map(([url]) => url.split("/").pop()),
+ ["pipeline-session", "session"]
+ );
+ assert.equal(calls[1][1].body, undefined);
+ assert.equal(deps.streaming.cleanupOptions, undefined);
+ assert.equal(deps.streaming.cleanupUnavailable, undefined);
+ assert.equal(deps.streaming.connected.baseUrl, plainSession.baseUrl);
+ }
+ }
+);
+
+test(
+ "a plain session answering a pipeline request connects as plain ASR",
+ { timeout: 2500 },
+ async () => {
+ const deps = managedFixture();
+ const calls = [];
+ await connectManagedOrukeet({
+ ...deps,
+ pipelineOptions: { customPrompt: "Keep it short." },
+ proxyFetch: async (url) => {
+ calls.push(url);
+ return Response.json(plainSession);
+ },
+ });
+ assert.deepEqual(
+ calls.map((url) => url.split("/").pop()),
+ ["pipeline-session"]
+ );
+ assert.equal(deps.streaming.cleanupOptions, undefined);
+ assert.equal(deps.streaming.cleanupUnavailable, true);
+ assert.equal(deps.streaming.onUsageReceipt, undefined);
+ assert.deepEqual(deps.streaming.connected, {
+ baseUrl: plainSession.baseUrl,
+ clientToken: plainSession.clientToken,
+ });
+
+ const lookalike = managedFixture();
+ await assert.rejects(
+ connectManagedOrukeet({
+ ...lookalike,
+ pipelineOptions: {},
+ proxyFetch: async () =>
+ Response.json({ ...plainSession, baseUrl: "https://orukeet.gizmovoice.ai.test" }),
+ }),
+ /Invalid Orukeet cloud session/
+ );
+ assert.equal(lookalike.streaming.connected, undefined);
+ }
+);
+
+test(
+ "plain retry still honors transcription policy and account quota refusals",
+ { timeout: 2500 },
+ async () => {
+ for (const refusal of [
+ Response.json({ code: "POLICY_MODE_BLOCKED" }, { status: 403 }),
+ Response.json({ limitReached: true }, { status: 429 }),
+ ]) {
+ const deps = managedFixture();
+ let requests = 0;
+ await assert.rejects(
+ connectManagedOrukeet({
+ ...deps,
+ pipelineOptions: {},
+ proxyFetch: async () =>
+ ++requests === 1
+ ? Response.json({ code: "PIPELINE_OPTIONS_UNSUPPORTED" }, { status: 400 })
+ : refusal,
+ }),
+ /./
+ );
+ assert.equal(requests, 2);
+ assert.equal(deps.streaming.connected, undefined);
+ }
+ }
+);
+
+test(
+ "receipt relay retries transient responses exactly twice and stops on permanent rejection",
+ { timeout: 2500 },
+ async () => {
+ const { relayCleanupUsage } = require("../../src/helpers/orukeetCloudSession");
+ const { captureAuthFence } = require("../../src/helpers/cloudApiRequest");
+ for (const status of [401, 408, 429, 500, 400, 403]) {
+ const deps = managedFixture();
+ let requests = 0;
+ const waits = [];
+ await assert.rejects(
+ relayCleanupUsage({
+ ...deps,
+ receipt: "signed",
+ apiUrl: "https://api.test",
+ fence: captureAuthFence(deps.tokenStore, 1),
+ wait: async (ms) => waits.push(ms),
+ proxyFetch: async () => {
+ requests++;
+ return new Response(null, { status });
+ },
+ }),
+ /Cleanup usage rejected/
+ );
+ assert.equal(requests, [400, 403].includes(status) ? 1 : 3, String(status));
+ assert.deepEqual(waits, [400, 403].includes(status) ? [] : [250, 500]);
+ }
+ }
+);
+
+test(
+ "receipt retries cannot cross an account change and errors reach the adapter observer",
+ { timeout: 2500 },
+ async () => {
+ const { relayCleanupUsage } = require("../../src/helpers/orukeetCloudSession");
+ const { captureAuthFence } = require("../../src/helpers/cloudApiRequest");
+ const deps = managedFixture();
+ let calls = 0;
+ await assert.rejects(
+ relayCleanupUsage({
+ ...deps,
+ receipt: "signed",
+ apiUrl: "https://api.test",
+ fence: captureAuthFence(deps.tokenStore, 1),
+ wait: async () => {
+ deps.state.token = "other";
+ deps.state.generation++;
+ },
+ proxyFetch: async () => {
+ calls++;
+ return new Response(null, { status: 500 });
+ },
+ }),
+ /Authentication context changed/
+ );
+ assert.equal(calls, 1);
+ const fresh = managedFixture();
+ let observed;
+ fresh.streaming.onUsageError = (error) => {
+ observed = error;
+ };
+ await connectManagedOrukeet({
+ ...fresh,
+ pipelineOptions: {},
+ proxyFetch: async (url) =>
+ url.endsWith("pipeline-session")
+ ? Response.json(session)
+ : new Response(null, { status: 403 }),
+ });
+ fresh.streaming.onUsageReceipt("signed");
+ await assert.rejects(fresh.streaming.usagePromise);
+ await new Promise(setImmediate);
+ assert.deepEqual(observed, { status: 403, code: undefined });
+ }
+);
+
+test(
+ "ASR arrival timing stays separate from cleanup and only real model work has attribution",
+ { timeout: 2500 },
+ async (t) => {
+ for (const { extra, model } of [
+ {
+ extra: {
+ cleanup_status: "complete",
+ cleanup_method: "model",
+ cleanup_model: "gemma-4-12b",
+ cleanup_ms: 230,
+ cleanup_input_tokens: 31,
+ cleanup_output_tokens: 9,
+ },
+ model: "gemma-4-12b",
+ },
+ {
+ extra: {
+ cleanup_status: "complete",
+ cleanup_method: "model",
+ cleanup_model: "gemma-4-12B-it-qat",
+ cleanup_ms: 230,
+ cleanup_input_tokens: 31,
+ cleanup_output_tokens: 9,
+ },
+ model: "gemma-4-12b",
+ },
+ {
+ extra: {
+ cleanup_status: "complete",
+ cleanup_method: "passthrough",
+ cleanup_model: "gemma-4-12B-it-qat",
+ },
+ },
+ {
+ extra: {
+ cleanup_status: "fallback",
+ cleanup_method: "model",
+ cleanup_model: "gemma-4-12B-it-qat",
+ },
+ },
+ {
+ extra: {
+ cleanup_status: "skipped",
+ cleanup_method: "model",
+ cleanup_model: "gemma-4-12b",
+ },
+ },
+ {
+ extra: {
+ cleanup_status: "complete",
+ cleanup_method: "model",
+ cleanup_model: "untrusted",
+ },
+ },
+ ]) {
+ const adapter = fixture(t);
+ await adapter.connect(validateSession(session, true));
+ adapter.sendAudio(Buffer.alloc(320));
+ adapter.sendControl = (_message, callback) => {
+ callback();
+ adapter.handleMessage({ type: "transcript", text: final.raw_text });
+ setTimeout(() => adapter.handleMessage({ ...final, ...extra }), 20);
+ };
+ const result = await adapter.finalize();
+ assert.ok(result.asrFinalMs < performance.now() - adapter.finalStartedAt - 10);
+ assert.equal(result.cleanup.status, extra.cleanup_status);
+ assert.equal(result.cleanup.model, model);
+ assert.equal(result.cleanup.processingMs, extra.cleanup_ms);
+ assert.equal(result.cleanup.inputTokens, extra.cleanup_input_tokens);
+ }
+ }
+);
diff --git a/test/helpers/orukeetStreaming.test.js b/test/helpers/orukeetStreaming.test.js
index db22d6e4a..66b656aaa 100644
--- a/test/helpers/orukeetStreaming.test.js
+++ b/test/helpers/orukeetStreaming.test.js
@@ -123,6 +123,62 @@ test("language hints are advisory and the final language is passed through", asy
assert.equal(finals, 1);
});
+for (const metadata of [
+ { language: "hi", language_confidence: 0.55, language_supported_score: 0.02 },
+ { language: "en", language_confidence: 0.3, language_supported_score: 0.75 },
+ { language: null, language_confidence: null, language_supported_score: 0.01 },
+ { language: "hi", language_confidence: 1, language_supported_score: 0 },
+ { language: "en", language_confidence: 1, language_supported_score: 1 },
+]) {
+ test(`supported language score reaches hints and final: ${JSON.stringify(metadata)}`, async (t) => {
+ const { adapter, options } = await fixture(t, (socket, event) => {
+ if (event.type === "commit") {
+ socket.send(JSON.stringify({ type: "language", ...metadata, language_audio_seconds: 6 }));
+ socket.send(
+ JSON.stringify({
+ type: "final",
+ text: "Transcript",
+ ...metadata,
+ language_audio_seconds: 6,
+ })
+ );
+ }
+ });
+ const hints = [];
+ adapter.onLanguage = (value) => hints.push(value);
+ await adapter.connect(options);
+ adapter.sendAudio(Buffer.alloc(640));
+ const result = await adapter.finalize();
+ assert.equal(hints.length, 1);
+ assert.equal(hints[0].languageSupportedScore, metadata.language_supported_score);
+ assert.equal(result.languageSupportedScore, metadata.language_supported_score);
+ assert.equal(result.languageAudioSeconds, 6);
+ assert.equal(result.language, metadata.language);
+ });
+}
+
+for (const score of [undefined, null, "0.5", true, -0.1, 1.1]) {
+ test(`invalid or absent supported score stays absent: ${String(score)}`, async (t) => {
+ const { adapter, options } = await fixture(t, (socket, event) => {
+ if (event.type === "commit")
+ socket.send(
+ JSON.stringify({
+ type: "final",
+ text: "Transcript",
+ language: "en",
+ language_confidence: 0.9,
+ language_supported_score: score,
+ })
+ );
+ });
+ await adapter.connect(options);
+ adapter.sendAudio(Buffer.alloc(640));
+ const result = await adapter.finalize();
+ assert.equal(result.languageSupportedScore, undefined);
+ assert.equal(result.language, "en");
+ });
+}
+
for (const metadata of [
{ language: null, language_confidence: null },
{ language: "english", language_confidence: 0.9 },
@@ -147,6 +203,19 @@ for (const metadata of [
});
}
+test("a plain stream standing in for a failed pipeline reports the cleanup fallback", async (t) => {
+ const { adapter, options } = await fixture(t, (socket, event) => {
+ if (event.type === "commit") socket.send(JSON.stringify({ type: "final", text: "Raw." }));
+ });
+ adapter.cleanupUnavailable = true;
+ await adapter.connect(options);
+ adapter.sendAudio(Buffer.alloc(640));
+ const result = await adapter.finalize();
+ assert.equal(result.text, "Raw.");
+ assert.deepEqual(result.cleanup, { status: "fallback" });
+ assert.equal(result.cleanupStatus, undefined);
+});
+
test("cancellation closes without committing audio", async (t) => {
const { adapter, seen, options } = await fixture(t);
await adapter.connect(options);
diff --git a/test/helpers/policyRequestHeaders.test.js b/test/helpers/policyRequestHeaders.test.js
index 14068cd2b..4675681f3 100644
--- a/test/helpers/policyRequestHeaders.test.js
+++ b/test/helpers/policyRequestHeaders.test.js
@@ -9,12 +9,12 @@ const {
test("adds the exact policy capability, canonical app version and client capability headers", () => {
assert.equal(POLICY_CAPABILITY_VERSION, "1");
- assert.equal(CLIENT_CAPABILITIES, "orukeet");
+ assert.equal(CLIENT_CAPABILITIES, "orukeet,orukeet-pipeline-v2,orukeet-language-routing");
assert.deepEqual(withPolicyRequestHeaders({ Authorization: "Bearer token" }, "1.8.1"), {
Authorization: "Bearer token",
"x-openwhispr-policy-version": "1",
"x-openwhispr-version": "1.8.1",
- "x-openwhispr-capabilities": "orukeet",
+ "x-openwhispr-capabilities": "orukeet,orukeet-pipeline-v2,orukeet-language-routing",
});
});
@@ -31,7 +31,7 @@ test("does not allow callers to override desktop policy capability headers", ()
{
"x-openwhispr-policy-version": "1",
"x-openwhispr-version": "1.8.1",
- "x-openwhispr-capabilities": "orukeet",
+ "x-openwhispr-capabilities": "orukeet,orukeet-pipeline-v2,orukeet-language-routing",
}
);
});