Skip to content

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

fix(dictation): single source of truth for realtime STT provider routing — fixes #1624 (#1631)

Gabriel Steinc0202dfc419c
diff --git a/.github/workflows/stt-canary.yml b/.github/workflows/stt-canary.yml
new file mode 100644
index 000000000..01685d261
--- /dev/null
+++ b/.github/workflows/stt-canary.yml
@@ -0,0 +1,50 @@
+# Weekly live check that every realtime STT provider still accepts the app's
+# credential flow and WebSocket handshake. Deliberately NOT part of PR CI: it
+# exercises external APIs and its failures are provider news, not code
+# regressions. Same pattern as llm-canary.yml.
+name: stt-canary
+
+on:
+ schedule:
+ - cron: "30 6 * * 1" # Mondays 06:30 UTC
+ workflow_dispatch:
+
+permissions:
+ contents: read
+ issues: write
+
+jobs:
+ canary:
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+ - uses: actions/setup-node@v4
+ with:
+ node-version: 24
+ cache: npm
+ - run: npm ci
+ - name: Run canary
+ id: canary
+ env:
+ STT_CANARY_OPENAI_KEY: ${{ secrets.STT_CANARY_OPENAI_KEY }}
+ STT_CANARY_DEEPGRAM_KEY: ${{ secrets.STT_CANARY_DEEPGRAM_KEY }}
+ STT_CANARY_ASSEMBLYAI_KEY: ${{ secrets.STT_CANARY_ASSEMBLYAI_KEY }}
+ STT_CANARY_TINFOIL_KEY: ${{ secrets.STT_CANARY_TINFOIL_KEY }}
+ run: |
+ set -o pipefail
+ node scripts/stt-canary.mjs | tee canary-report.md
+ - name: File or update failure issue
+ if: failure() && steps.canary.outcome == 'failure'
+ env:
+ GH_TOKEN: ${{ github.token }}
+ run: |
+ title="STT canary: realtime provider handshake failing"
+ body="$(cat canary-report.md)
+
+ _Run: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}_"
+ existing=$(gh issue list --label stt-canary --state open --json number --jq '.[0].number // empty')
+ if [ -n "$existing" ]; then
+ gh issue comment "$existing" --body "$body"
+ else
+ gh issue create --title "$title" --body "$body" --label stt-canary
+ fi
diff --git a/scripts/stt-canary.mjs b/scripts/stt-canary.mjs
new file mode 100644
index 000000000..bc4f3b31a
--- /dev/null
+++ b/scripts/stt-canary.mjs
@@ -0,0 +1,131 @@
+/**
+ * Live realtime-STT canary. Per keyed provider, acquires a session credential
+ * through the app's REAL token registry (realtimeTokenProviders.js) and, where
+ * the transport is a plain WebSocket, performs a live handshake against the
+ * same endpoint the app dials — so a provider changing its auth, endpoint, or
+ * handshake surfaces here on a schedule instead of in a customer report
+ * (#1624 sat in shipped builds for three days as a swallowed warmup warning).
+ *
+ * Run: node scripts/stt-canary.mjs
+ * Keys come from STT_CANARY_<PROVIDER>_KEY env vars; providers without a key
+ * are skipped and listed. Exit 1 when any probe on a keyed provider fails.
+ * Corti is not probed (needs tenant/environment credentials beyond a key).
+ */
+import WebSocket from "ws";
+import tokenProviders from "../src/helpers/realtimeTokenProviders.js";
+
+const { fetchRealtimeTokenForProvider } = tokenProviders;
+
+const HANDSHAKE_TIMEOUT_MS = 15000;
+
+// Mirrors the app's dial: openaiRealtimeStreaming.js connects with a bare
+// Bearer header; deepgramStreaming.js passes the key as the bearer token.
+function probeWebSocket(url, token) {
+ return new Promise((resolve) => {
+ const ws = new WebSocket(url, { headers: { Authorization: `Bearer ${token}` } });
+ const timer = setTimeout(() => {
+ ws.terminate();
+ resolve({ ok: false, detail: `no handshake within ${HANDSHAKE_TIMEOUT_MS}ms` });
+ }, HANDSHAKE_TIMEOUT_MS);
+ ws.on("open", () => {
+ clearTimeout(timer);
+ ws.close();
+ resolve({ ok: true });
+ });
+ ws.on("unexpected-response", (_req, res) => {
+ clearTimeout(timer);
+ ws.terminate();
+ resolve({ ok: false, detail: `handshake rejected: HTTP ${res.statusCode}` });
+ });
+ ws.on("error", (err) => {
+ clearTimeout(timer);
+ resolve({ ok: false, detail: err.message });
+ });
+ });
+}
+
+const tokenDeps = (key) => ({
+ environmentManager: {
+ getOpenAIKey: () => key,
+ getTinfoilKey: () => key,
+ getDeepgramKey: () => key,
+ getAssemblyAIKey: () => key,
+ },
+ proxyFetch: fetch,
+});
+
+const PROBES = [
+ {
+ id: "openai-realtime",
+ keyEnv: "STT_CANARY_OPENAI_KEY",
+ run: async (key) => {
+ const token = await fetchRealtimeTokenForProvider("openai-realtime", tokenDeps(key), {
+ mode: "byok",
+ });
+ return probeWebSocket("wss://api.openai.com/v1/realtime?intent=transcription", token);
+ },
+ },
+ {
+ id: "deepgram-realtime",
+ keyEnv: "STT_CANARY_DEEPGRAM_KEY",
+ run: async (key) => {
+ const token = await fetchRealtimeTokenForProvider("deepgram-realtime", tokenDeps(key), {
+ mode: "byok",
+ });
+ return probeWebSocket(
+ "wss://api.deepgram.com/v1/listen?model=nova-3&encoding=linear16&sample_rate=16000",
+ token
+ );
+ },
+ },
+ {
+ id: "assemblyai-realtime",
+ keyEnv: "STT_CANARY_ASSEMBLYAI_KEY",
+ // AssemblyAI's byok path mints a real short-lived streaming token, so the
+ // registry call itself is the live probe.
+ run: async (key) => {
+ const token = await fetchRealtimeTokenForProvider("assemblyai-realtime", tokenDeps(key), {
+ mode: "byok",
+ });
+ return token ? { ok: true } : { ok: false, detail: "empty token" };
+ },
+ },
+ {
+ id: "tinfoil-realtime",
+ keyEnv: "STT_CANARY_TINFOIL_KEY",
+ // The attested socket needs the Tinfoil SDK's enclave verification; the
+ // canary stops at credential resolution through the registry.
+ run: async (key) => {
+ const token = await fetchRealtimeTokenForProvider("tinfoil-realtime", tokenDeps(key), {
+ mode: "byok",
+ });
+ return token ? { ok: true } : { ok: false, detail: "empty token" };
+ },
+ },
+];
+
+const report = [];
+const failures = [];
+const skipped = [];
+
+for (const probe of PROBES) {
+ const key = process.env[probe.keyEnv];
+ if (!key) {
+ skipped.push(probe.id);
+ continue;
+ }
+ const result = await probe.run(key).catch((err) => ({ ok: false, detail: err.message }));
+ report.push(`| ${probe.id} | ${result.ok ? "✅" : `❌ ${result.detail}`} |`);
+ if (!result.ok) failures.push(`${probe.id}: ${result.detail}`);
+}
+
+console.log("## Realtime STT canary\n");
+console.log("| provider | result |\n|---|---|");
+for (const line of report) console.log(line);
+if (skipped.length) console.log(`\nSkipped (no key configured): ${skipped.join(", ")}`);
+if (failures.length) {
+ console.log(`\n### ${failures.length} failure(s)\n`);
+ for (const f of failures) console.log(`- ${f}`);
+ process.exit(1);
+}
+console.log("\nAll probes passed.");
diff --git a/src/helpers/audioManager.js b/src/helpers/audioManager.js
index 9e8fe5f9b..70cbe3db0 100644
--- a/src/helpers/audioManager.js
+++ b/src/helpers/audioManager.js
@@ -90,12 +90,17 @@ import {
extractSelectionEditReplacement,
getSelectionCaptureDisposition,
} from "./selectionEditing";
+import {
+ REALTIME_MODELS,
+ defaultStreamingProviderName,
+ resolveStreamingProviderName,
+ buildStreamingSessionOptions,
+} from "./dictationStreamingRouting";
const REASONING_CACHE_TTL = 30000; // 30 seconds
const RECORDING_TIMESLICE_MS = 250; // flush chunks periodically so short recordings still carry audio frames. See #871.
// Failure detector only: fires when the worklet or audio graph is dead and never flushes.
const PREVIEW_FLUSH_WATCHDOG_MS = 1000;
-const REALTIME_MODELS = new Set(["gpt-4o-mini-transcribe", "gpt-4o-transcribe"]);
const micDeviceKey = (settings) => `${settings.preferBuiltInMic}|${settings.selectedMicDeviceId}`;
@@ -314,18 +319,8 @@ const STREAMING_PROVIDERS = {
},
"tinfoil-realtime": {
awaitsFinalTranscript: true,
- warmup: (opts) =>
- window.electronAPI.dictationRealtimeWarmup({
- ...opts,
- provider: "tinfoil-realtime",
- preview: true,
- }),
- start: (opts) =>
- window.electronAPI.dictationRealtimeStart({
- ...opts,
- provider: "tinfoil-realtime",
- preview: true,
- }),
+ warmup: (opts) => window.electronAPI.dictationRealtimeWarmup(opts),
+ start: (opts) => window.electronAPI.dictationRealtimeStart(opts),
send: (buf) => window.electronAPI.dictationRealtimeSend(buf),
stop: () => window.electronAPI.dictationRealtimeStop(),
onPartial: (cb) => window.electronAPI.onDictationRealtimePartial(cb),
@@ -480,6 +475,7 @@ class AudioManager {
this.selectionCapturePromise = null;
this.context = "dictation";
this.sttConfig = null;
+ this.warmupFailureStreak = 0;
this.lastAudioBlob = null;
this.lastAudioMetadata = null;
this._localSpeechGateState = null;
@@ -811,23 +807,20 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);
}
getStreamingProvider() {
- const fallback = this.context === "notes" ? "deepgram" : "openai-realtime";
- return STREAMING_PROVIDERS[this.getStreamingProviderName()] || STREAMING_PROVIDERS[fallback];
+ return STREAMING_PROVIDERS[this.getStreamingProviderName()];
}
getStreamingProviderName() {
- const s = getSettings();
- if (s.cloudTranscriptionProvider === "tinfoil") {
- return "tinfoil-realtime";
- }
- if (s.cloudTranscriptionProvider === "corti" && s.cloudTranscriptionMode === "byok") {
- return "corti";
- }
- if (REALTIME_MODELS.has(s.cloudTranscriptionModel)) {
- return "openai-realtime";
- }
- const defaultProvider = this.context === "notes" ? "deepgram" : "openai-realtime";
- return this.sttConfig?.streamingProvider || defaultProvider;
+ const name = resolveStreamingProviderName({
+ settings: getSettings(),
+ context: this.context,
+ sttConfig: this.sttConfig,
+ });
+ // A server-driven sttConfig.streamingProvider we don't recognize must fall
+ // back to a provider we can run — and the reported name must match the
+ // channel bindings actually used, so the main process is never handed a
+ // provider id it would fail closed on.
+ return STREAMING_PROVIDERS[name] ? name : defaultStreamingProviderName(this.context);
}
async getAudioConstraints(forceDefaultMic = false) {
@@ -3611,26 +3604,20 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);
}
try {
- const provider = this.getStreamingProvider();
+ const providerName = this.getStreamingProviderName();
+ const provider = STREAMING_PROVIDERS[providerName];
const [, wsResult] = await Promise.all([
this.cacheMicrophoneDeviceId(),
withSessionRefresh(async () => {
- const {
- preferredLanguage: warmupLang,
- cloudTranscriptionModel,
- cloudTranscriptionMode,
- cortiEnvironment,
- cortiTenant,
- } = getSettings();
- const res = await provider.warmup({
- sampleRate: 16000,
- language: warmupLang && warmupLang !== "auto" ? warmupLang : undefined,
- keyterms: this.getKeyterms(),
- model: cloudTranscriptionModel,
- mode: cloudTranscriptionMode === "byok" ? "byok" : "openwhispr",
- environment: cortiEnvironment,
- tenant: cortiTenant,
- });
+ const settings = getSettings();
+ const res = await provider.warmup(
+ buildStreamingSessionOptions({
+ providerName,
+ settings,
+ language: settings.preferredLanguage,
+ keyterms: this.getKeyterms(),
+ })
+ );
// Throw error to trigger retry if AUTH_EXPIRED
if (!res.success && res.code) {
const err = new Error(res.error || "Warmup failed");
@@ -3663,6 +3650,7 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);
// re-fire once the warm window lapses (#845).
await this._warmMicDriverIfCold("streaming");
+ this.warmupFailureStreak = 0;
logger.info(
"Streaming connection warmed up",
{ alreadyWarm: wsResult.alreadyWarm, micCached: !!this.cachedMicDeviceId },
@@ -3673,15 +3661,28 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);
logger.debug("Streaming warmup skipped - API not configured", {}, "streaming");
return false;
} else {
- logger.warn("Streaming warmup failed", { error: wsResult.error }, "streaming");
+ this._reportWarmupFailure(providerName, wsResult.error, wsResult.code);
return false;
}
} catch (error) {
- logger.error("Streaming warmup error", { error: error.message }, "streaming");
+ this._reportWarmupFailure(this.getStreamingProviderName(), error.message, error.code);
return false;
}
}
+ // Warmup exercises the same connect that recording start will make, so a
+ // failing warmup predicts a guaranteed user-facing failure at the next
+ // keypress — #1624 logged exactly this on every idle cycle for days at warn
+ // level and nobody saw it. Error level, provider named, streak counted.
+ _reportWarmupFailure(provider, error, code) {
+ this.warmupFailureStreak += 1;
+ logger.error(
+ "Streaming warmup failed",
+ { provider, error, code, consecutiveFailures: this.warmupFailureStreak },
+ "streaming"
+ );
+ }
+
async getOrCreateAudioContext() {
if (this.persistentAudioContext && this.persistentAudioContext.state !== "closed") {
if (this.persistentAudioContext.state === "suspended") {
@@ -3914,23 +3915,15 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);
// so Deepgram receives data immediately (no idle timeout).
const result = await withSessionRefresh(async () => {
const streamingSettings = getSettings();
- const {
- cloudTranscriptionModel,
- cloudTranscriptionMode,
- cortiEnvironment,
- cortiTenant,
- useLocalWhisper,
- } = streamingSettings;
- const sttLanguage = this.getEffectiveSttLanguage(streamingSettings);
- const res = await provider.start({
- sampleRate: 16000,
- language: sttLanguage && sttLanguage !== "auto" ? sttLanguage : undefined,
- keyterms: this.getKeyterms(),
- model: cloudTranscriptionModel,
- mode: cloudTranscriptionMode === "byok" ? "byok" : "openwhispr",
- environment: cortiEnvironment,
- tenant: cortiTenant,
- });
+ const { useLocalWhisper } = streamingSettings;
+ const res = await provider.start(
+ buildStreamingSessionOptions({
+ providerName: this.getStreamingProviderName(),
+ settings: streamingSettings,
+ language: this.getEffectiveSttLanguage(streamingSettings),
+ keyterms: this.getKeyterms(),
+ })
+ );
if (!res.success) {
if (res.code === "NO_API") {
@@ -4019,7 +4012,11 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);
return this.startStreamingRecording(true);
}
- logger.error("Failed to start streaming recording", { error: error.message }, "streaming");
+ logger.error(
+ "Failed to start streaming recording",
+ { provider: this.getStreamingProviderName(), error: error.message, code: error.code },
+ "streaming"
+ );
let errorTitle = "Streaming Error";
let errorDescription = `Failed to start streaming: ${error.message}`;
diff --git a/src/helpers/dictationStreamingRouting.js b/src/helpers/dictationStreamingRouting.js
new file mode 100644
index 000000000..db908977c
--- /dev/null
+++ b/src/helpers/dictationStreamingRouting.js
@@ -0,0 +1,47 @@
+// Single source of truth for dictation/notes realtime STT routing: which
+// streaming provider a settings state resolves to, and the exact session
+// options every provider receives over IPC. Provider facts scattered across
+// call sites is what broke default dictation in 1.8.2 (#1624: the
+// openai-realtime entry never sent `provider`, and the hardened main-process
+// allowlist rejected undefined). Pure module, mirrors meetingTranscriptionRouting.
+
+export const REALTIME_MODELS = new Set(["gpt-4o-mini-transcribe", "gpt-4o-transcribe"]);
+
+export function defaultStreamingProviderName(context) {
+ return context === "notes" ? "deepgram" : "openai-realtime";
+}
+
+export function resolveStreamingProviderName({ settings, context, sttConfig }) {
+ if (settings.cloudTranscriptionProvider === "tinfoil") {
+ return "tinfoil-realtime";
+ }
+ if (
+ settings.cloudTranscriptionProvider === "corti" &&
+ settings.cloudTranscriptionMode === "byok"
+ ) {
+ return "corti";
+ }
+ if (REALTIME_MODELS.has(settings.cloudTranscriptionModel)) {
+ return "openai-realtime";
+ }
+ return sttConfig?.streamingProvider || defaultStreamingProviderName(context);
+}
+
+export function buildStreamingSessionOptions({ providerName, settings, language, keyterms }) {
+ const options = {
+ provider: providerName,
+ sampleRate: 16000,
+ language: language && language !== "auto" ? language : undefined,
+ keyterms,
+ model: settings.cloudTranscriptionModel,
+ mode: settings.cloudTranscriptionMode === "byok" ? "byok" : "openwhispr",
+ environment: settings.cortiEnvironment,
+ tenant: settings.cortiTenant,
+ };
+ // Tinfoil realtime always shows the live preview window (#1120); OpenAI
+ // realtime deliberately does not — its partials render in the dictation pill.
+ if (providerName === "tinfoil-realtime") {
+ options.preview = true;
+ }
+ return options;
+}
diff --git a/src/helpers/ipcHandlers.js b/src/helpers/ipcHandlers.js
index 9bd9396c7..cd26a1958 100644
--- a/src/helpers/ipcHandlers.js
+++ b/src/helpers/ipcHandlers.js
@@ -103,6 +103,7 @@ const {
getMeetingStreamingClient,
getMeetingConnectionKey,
} = require("./meetingStreamingProviders");
+const { fetchRealtimeTokenForProvider } = require("./realtimeTokenProviders");
// Meeting capture runs at 24 kHz (see meetingRecordingStore AudioContext); cloud
// streaming providers must be told the true PCM rate or they misread the audio.
@@ -6044,88 +6045,17 @@ class IPCHandlers {
return response.json();
};
- const dual = (factory) => (streams === 2 ? Promise.all([factory(), factory()]) : factory());
-
- if (options.provider === "assemblyai-realtime") {
- if (options.mode === "byok") {
- const apiKey = this.environmentManager.getAssemblyAIKey();
- if (!apiKey) {
- throw new Error("No AssemblyAI API key configured. Add your key in Settings.");
- }
- return dual(async () => {
- const response = await proxyFetch(
- "https://streaming.assemblyai.com/v3/token?expires_in_seconds=60",
- { headers: { Authorization: apiKey } }
- );
- if (!response.ok) {
- const err = await response.json().catch(() => ({}));
- throw new Error(err.error || `AssemblyAI token request failed: ${response.status}`);
- }
- const data = await response.json();
- if (!data.token) throw new Error("No AssemblyAI token received");
- return data.token;
- });
- }
- return dual(async () => {
- const data = await postServerToken("/api/streaming-token");
- if (!data.token) throw new Error("No AssemblyAI token received");
- return data.token;
- });
- }
-
- if (options.provider === "deepgram-realtime") {
- if (options.mode === "byok") {
- const apiKey = this.environmentManager.getDeepgramKey();
- if (!apiKey) {
- throw new Error("No Deepgram API key configured. Add your key in Settings.");
- }
- return streams === 2 ? [apiKey, apiKey] : apiKey;
- }
- return dual(async () => {
- const data = await postServerToken("/api/deepgram-streaming-token");
- if (!data.token) throw new Error("No Deepgram token received");
- return data.token;
- });
- }
-
- if (options.provider === "corti-realtime") {
- // One token covers both meeting streams; it's only used at the WSS handshake.
- const { token } = await this._mintStoredCortiToken(options);
- return streams === 2 ? [token, token] : token;
- }
- if (options.provider === "tinfoil-realtime") {
- const apiKey = this.environmentManager.getTinfoilKey();
- if (!apiKey) {
- const err = new Error("No Tinfoil API key configured. Add your key in Settings.");
- err.code = "NO_API";
- throw err;
- }
- return streams === 2 ? [apiKey, apiKey] : apiKey;
- }
-
- if (options.provider !== "openai-realtime") {
- throw new Error(`Unsupported realtime token provider: ${options.provider}`);
- }
-
- if (options.mode === "byok") {
- const apiKey = this.environmentManager.getOpenAIKey();
- if (!apiKey) throw new Error("No OpenAI API key configured. Add your key in Settings.");
- return streams === 2 ? [apiKey, apiKey] : apiKey;
- }
-
- const data = await postServerToken("/api/openai-realtime-token", {
- model: options.model,
- language: options.language,
- streams: streams || 1,
- });
- if (streams === 2) {
- if (!data.clientSecrets || data.clientSecrets.length < 2) {
- throw new Error("Expected two client secrets for dual-stream");
- }
- return data.clientSecrets;
- }
- if (!data.clientSecret) throw new Error("No client secret received");
- return data.clientSecret;
+ return fetchRealtimeTokenForProvider(
+ options.provider,
+ {
+ environmentManager: this.environmentManager,
+ proxyFetch,
+ postServerToken,
+ mintCortiToken: (tokenOptions) => this._mintStoredCortiToken(tokenOptions),
+ },
+ options,
+ { streams }
+ );
};
const getMeetingSystemAudioCapabilityMode = () => {
@@ -7073,6 +7003,10 @@ class IPCHandlers {
const connectInner = async () => {
const isCloud = options.mode !== "byok";
+ // Dictation renderers before 1.8.4 omit `provider` and mean OpenAI; the
+ // default lives here, at the boundary, so the token allowlist stays
+ // fail-closed for genuinely unknown providers (#1624).
+ const provider = options.provider ?? "openai-realtime";
const streaming = new OpenAIRealtimeStreaming();
setupDictationCallbacks(streaming, event);
// Assign before the token fetch (a real network round trip) so
@@ -7083,9 +7017,9 @@ class IPCHandlers {
try {
const apiKey = await fetchRealtimeToken(event, {
mode: options.mode,
- provider: options.provider,
+ provider,
});
- if (options.provider === "tinfoil-realtime") {
+ if (provider === "tinfoil-realtime") {
const model = options.model || TINFOIL_REALTIME_MODEL;
await streaming.connect({
apiKey,
diff --git a/src/helpers/realtimeTokenProviders.js b/src/helpers/realtimeTokenProviders.js
new file mode 100644
index 000000000..5951056cd
--- /dev/null
+++ b/src/helpers/realtimeTokenProviders.js
@@ -0,0 +1,108 @@
+// Realtime STT token acquisition, one entry per provider. This is the explicit
+// allowlist fetchRealtimeToken enforces: an unknown provider throws (fail-closed,
+// #1480), and the callers that rely on it — meeting prepare/start and dictation
+// streaming — resolve their provider ids in meetingTranscriptionRouting.js and
+// dictationStreamingRouting.js respectively. Dependencies are injected so the
+// table is unit-testable without Electron.
+
+const dual = (streams, factory) =>
+ streams === 2 ? Promise.all([factory(), factory()]) : factory();
+const duplicate = (streams, value) => (streams === 2 ? [value, value] : value);
+
+const REALTIME_TOKEN_PROVIDERS = {
+ "assemblyai-realtime": async (
+ { environmentManager, proxyFetch, postServerToken },
+ options,
+ streams
+ ) => {
+ if (options.mode === "byok") {
+ const apiKey = environmentManager.getAssemblyAIKey();
+ if (!apiKey) {
+ throw new Error("No AssemblyAI API key configured. Add your key in Settings.");
+ }
+ return dual(streams, async () => {
+ const response = await proxyFetch(
+ "https://streaming.assemblyai.com/v3/token?expires_in_seconds=60",
+ { headers: { Authorization: apiKey } }
+ );
+ if (!response.ok) {
+ const err = await response.json().catch(() => ({}));
+ throw new Error(err.error || `AssemblyAI token request failed: ${response.status}`);
+ }
+ const data = await response.json();
+ if (!data.token) throw new Error("No AssemblyAI token received");
+ return data.token;
+ });
+ }
+ return dual(streams, async () => {
+ const data = await postServerToken("/api/streaming-token");
+ if (!data.token) throw new Error("No AssemblyAI token received");
+ return data.token;
+ });
+ },
+
+ "deepgram-realtime": async ({ environmentManager, postServerToken }, options, streams) => {
+ if (options.mode === "byok") {
+ const apiKey = environmentManager.getDeepgramKey();
+ if (!apiKey) {
+ throw new Error("No Deepgram API key configured. Add your key in Settings.");
+ }
+ return duplicate(streams, apiKey);
+ }
+ return dual(streams, async () => {
+ const data = await postServerToken("/api/deepgram-streaming-token");
+ if (!data.token) throw new Error("No Deepgram token received");
+ return data.token;
+ });
+ },
+
+ "corti-realtime": async ({ mintCortiToken }, options, streams) => {
+ // One token covers both meeting streams; it's only used at the WSS handshake.
+ const { token } = await mintCortiToken(options);
+ return duplicate(streams, token);
+ },
+
+ "tinfoil-realtime": async ({ environmentManager }, options, streams) => {
+ const apiKey = environmentManager.getTinfoilKey();
+ if (!apiKey) {
+ const err = new Error("No Tinfoil API key configured. Add your key in Settings.");
+ err.code = "NO_API";
+ throw err;
+ }
+ return duplicate(streams, apiKey);
+ },
+
+ "openai-realtime": async ({ environmentManager, postServerToken }, options, streams) => {
+ if (options.mode === "byok") {
+ const apiKey = environmentManager.getOpenAIKey();
+ if (!apiKey) throw new Error("No OpenAI API key configured. Add your key in Settings.");
+ return duplicate(streams, apiKey);
+ }
+ const data = await postServerToken("/api/openai-realtime-token", {
+ model: options.model,
+ language: options.language,
+ streams: streams || 1,
+ });
+ if (streams === 2) {
+ if (!data.clientSecrets || data.clientSecrets.length < 2) {
+ throw new Error("Expected two client secrets for dual-stream");
+ }
+ return data.clientSecrets;
+ }
+ if (!data.clientSecret) throw new Error("No client secret received");
+ return data.clientSecret;
+ },
+};
+
+async function fetchRealtimeTokenForProvider(provider, deps, options, { streams } = {}) {
+ const acquire = REALTIME_TOKEN_PROVIDERS[provider];
+ if (!acquire) {
+ throw new Error(`Unsupported realtime token provider: ${provider}`);
+ }
+ return acquire(deps, options, streams);
+}
+
+module.exports = {
+ REALTIME_TOKEN_PROVIDERS,
+ fetchRealtimeTokenForProvider,
+};
diff --git a/src/types/electron.ts b/src/types/electron.ts
index 8d719df9a..25ac184d7 100644
--- a/src/types/electron.ts
+++ b/src/types/electron.ts
@@ -34,6 +34,23 @@ export interface NoteRecordingProvider {
models: NoteRecordingProviderModel[];
}
+// Session options for the shared dictation-realtime-* channels. `provider` is
+// what fetchRealtimeToken's allowlist keys on — the renderer must always send
+// it (built by dictationStreamingRouting.buildStreamingSessionOptions); the
+// main process defaults a missing value to "openai-realtime" for pre-1.8.4
+// renderers (#1624).
+export interface DictationRealtimeSessionOptions {
+ provider: string;
+ model?: string;
+ mode?: "byok" | "openwhispr";
+ language?: string;
+ sampleRate?: number;
+ keyterms?: string[];
+ environment?: string;
+ tenant?: string;
+ preview?: boolean;
+}
+
export type NoteRecordingConfigFailure = { success: false } & PolicyFailureMetadata;
export type NoteRecordingConfigResult =
@@ -2461,14 +2478,12 @@ declare global {
) => Promise<{ success: boolean }>;
// Dictation realtime streaming
- dictationRealtimeWarmup?: (options: {
- model?: string;
- mode?: "byok" | "openwhispr";
- }) => Promise<{ success: boolean } & PolicyFailureMetadata>;
- dictationRealtimeStart?: (options: {
- model?: string;
- mode?: "byok" | "openwhispr";
- }) => Promise<{ success: boolean } & PolicyFailureMetadata>;
+ dictationRealtimeWarmup?: (
+ options: DictationRealtimeSessionOptions
+ ) => Promise<{ success: boolean } & PolicyFailureMetadata>;
+ dictationRealtimeStart?: (
+ options: DictationRealtimeSessionOptions
+ ) => Promise<{ success: boolean } & PolicyFailureMetadata>;
dictationRealtimeSend?: (buffer: ArrayBuffer) => void;
dictationRealtimeStop?: () => Promise<{ success: boolean; text: string }>;
onDictationRealtimePartial?: (callback: (text: string) => void) => () => void;
diff --git a/test/helpers/dictationStreamingMatrix.test.js b/test/helpers/dictationStreamingMatrix.test.js
new file mode 100644
index 000000000..bc03e2f6d
--- /dev/null
+++ b/test/helpers/dictationStreamingMatrix.test.js
@@ -0,0 +1,215 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+
+// Exhaustive settings-state × context matrix for dictation/notes realtime STT:
+// which provider each state resolves to, the FULL session options object it
+// sends over IPC (presence and absence), and the cross-boundary closure that
+// every emittable provider id is accepted on the main-process side. #1624
+// shipped because no test looked at the whole renderer→main contract: the
+// openai-realtime path never sent `provider` and the token allowlist rejected
+// undefined, while every per-module test stayed green.
+
+const loadRouting = () => import("../../src/helpers/dictationStreamingRouting.js");
+const loadTokens = () => import("../../src/helpers/realtimeTokenProviders.js");
+const loadMeeting = () => import("../../src/helpers/meetingStreamingProviders.js");
+
+// Keys of audioManager's STREAMING_PROVIDERS channel-binding table. audioManager
+// imports window APIs so it can't load under node:test; this list is the
+// renderer-side contract the resolver must stay within.
+const RENDERER_STREAMING_PROVIDERS = [
+ "deepgram",
+ "assemblyai",
+ "openai-realtime",
+ "corti",
+ "tinfoil-realtime",
+];
+
+// Providers that share the dictation-realtime-* IPC channels and therefore
+// need a fetchRealtimeToken entry under exactly their renderer name.
+const SHARED_CHANNEL_PROVIDERS = ["openai-realtime", "tinfoil-realtime"];
+
+const SETTINGS_DEFAULTS = {
+ cloudTranscriptionProvider: "openai",
+ cloudTranscriptionModel: "gpt-4o-mini-transcribe",
+ cloudTranscriptionMode: "openwhispr",
+ cortiEnvironment: undefined,
+ cortiTenant: undefined,
+};
+
+const settingsWith = (overrides) => ({ ...SETTINGS_DEFAULTS, ...overrides });
+
+// [description, { settings, context, sttConfig }, expected provider name]
+const RESOLUTION_MATRIX = [
+ ["default config (the #1624 repro) resolves to openai-realtime", {}, "openai-realtime"],
+ [
+ "gpt-4o-transcribe also resolves to openai-realtime",
+ { settings: settingsWith({ cloudTranscriptionModel: "gpt-4o-transcribe" }) },
+ "openai-realtime",
+ ],
+ [
+ "tinfoil provider wins regardless of model",
+ { settings: settingsWith({ cloudTranscriptionProvider: "tinfoil" }) },
+ "tinfoil-realtime",
+ ],
+ [
+ "corti byok streams over corti's own channels",
+ {
+ settings: settingsWith({
+ cloudTranscriptionProvider: "corti",
+ cloudTranscriptionMode: "byok",
+ }),
+ },
+ "corti",
+ ],
+ [
+ "corti on openwhispr cloud is not corti streaming; realtime model still wins",
+ { settings: settingsWith({ cloudTranscriptionProvider: "corti" }) },
+ "openai-realtime",
+ ],
+ [
+ "batch model in notes context defaults to deepgram",
+ { settings: settingsWith({ cloudTranscriptionModel: "whisper-1" }), context: "notes" },
+ "deepgram",
+ ],
+ [
+ "batch model in dictation context defaults to openai-realtime",
+ { settings: settingsWith({ cloudTranscriptionModel: "whisper-1" }) },
+ "openai-realtime",
+ ],
+ [
+ "server sttConfig picks the streaming provider for batch models",
+ {
+ settings: settingsWith({ cloudTranscriptionModel: "whisper-1" }),
+ sttConfig: { streamingProvider: "assemblyai" },
+ },
+ "assemblyai",
+ ],
+];
+
+for (const [
+ name,
+ { settings = settingsWith({}), context = "dictation", sttConfig = null },
+ expected,
+] of RESOLUTION_MATRIX) {
+ test(`resolution: ${name}`, async () => {
+ const { resolveStreamingProviderName } = await loadRouting();
+ assert.equal(resolveStreamingProviderName({ settings, context, sttConfig }), expected);
+ });
+}
+
+test("resolution: every matrix outcome is a renderer channel binding", async () => {
+ const { resolveStreamingProviderName } = await loadRouting();
+ for (const [
+ ,
+ { settings = settingsWith({}), context = "dictation", sttConfig = null },
+ ] of RESOLUTION_MATRIX) {
+ const name = resolveStreamingProviderName({ settings, context, sttConfig });
+ assert.ok(
+ RENDERER_STREAMING_PROVIDERS.includes(name),
+ `resolver emitted "${name}", which has no STREAMING_PROVIDERS entry`
+ );
+ }
+});
+
+test("options: openai-realtime sends provider explicitly and no preview (#1624)", async () => {
+ const { buildStreamingSessionOptions } = await loadRouting();
+ const options = buildStreamingSessionOptions({
+ providerName: "openai-realtime",
+ settings: settingsWith({}),
+ language: "en",
+ keyterms: ["OpenWhispr"],
+ });
+ assert.deepEqual(options, {
+ provider: "openai-realtime",
+ sampleRate: 16000,
+ language: "en",
+ keyterms: ["OpenWhispr"],
+ model: "gpt-4o-mini-transcribe",
+ mode: "openwhispr",
+ environment: undefined,
+ tenant: undefined,
+ });
+});
+
+test("options: tinfoil-realtime keeps its always-on preview (#1120)", async () => {
+ const { buildStreamingSessionOptions } = await loadRouting();
+ const options = buildStreamingSessionOptions({
+ providerName: "tinfoil-realtime",
+ settings: settingsWith({
+ cloudTranscriptionProvider: "tinfoil",
+ cloudTranscriptionModel: "kyutai-stt",
+ cloudTranscriptionMode: "byok",
+ }),
+ language: "auto",
+ keyterms: [],
+ });
+ assert.deepEqual(options, {
+ provider: "tinfoil-realtime",
+ sampleRate: 16000,
+ language: undefined,
+ keyterms: [],
+ model: "kyutai-stt",
+ mode: "byok",
+ environment: undefined,
+ tenant: undefined,
+ preview: true,
+ });
+});
+
+test("options: corti carries environment and tenant; auto language is omitted", async () => {
+ const { buildStreamingSessionOptions } = await loadRouting();
+ const options = buildStreamingSessionOptions({
+ providerName: "corti",
+ settings: settingsWith({
+ cloudTranscriptionProvider: "corti",
+ cloudTranscriptionMode: "byok",
+ cloudTranscriptionModel: "corti-stt",
+ cortiEnvironment: "eu",
+ cortiTenant: "acme",
+ }),
+ language: "auto",
+ keyterms: ["hba1c"],
+ });
+ assert.equal(options.provider, "corti");
+ assert.equal(options.mode, "byok");
+ assert.equal(options.environment, "eu");
+ assert.equal(options.tenant, "acme");
+ assert.equal(options.language, undefined);
+});
+
+test("options: provider is stamped for every renderer channel binding", async () => {
+ const { buildStreamingSessionOptions } = await loadRouting();
+ for (const providerName of RENDERER_STREAMING_PROVIDERS) {
+ const options = buildStreamingSessionOptions({
+ providerName,
+ settings: settingsWith({}),
+ language: "en",
+ keyterms: [],
+ });
+ assert.equal(options.provider, providerName);
+ }
+});
+
+test("closure: shared-channel dictation providers have token entries under their own names", async () => {
+ const { REALTIME_TOKEN_PROVIDERS } = await loadTokens();
+ for (const provider of SHARED_CHANNEL_PROVIDERS) {
+ assert.equal(
+ typeof REALTIME_TOKEN_PROVIDERS[provider],
+ "function",
+ `${provider} reaches fetchRealtimeToken but has no token entry`
+ );
+ }
+});
+
+test("closure: every allowed meeting provider has a token entry", async () => {
+ const { REALTIME_TOKEN_PROVIDERS } = await loadTokens();
+ const { ALLOWED_MEETING_PROVIDERS } = await loadMeeting();
+ for (const provider of ALLOWED_MEETING_PROVIDERS) {
+ if (provider === "local") continue;
+ assert.equal(
+ typeof REALTIME_TOKEN_PROVIDERS[provider],
+ "function",
+ `${provider} is meeting-allowed but has no token entry`
+ );
+ }
+});
diff --git a/test/helpers/realtimeTokenProviders.test.js b/test/helpers/realtimeTokenProviders.test.js
new file mode 100644
index 000000000..9f08341e6
--- /dev/null
+++ b/test/helpers/realtimeTokenProviders.test.js
@@ -0,0 +1,160 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+
+const load = () => import("../../src/helpers/realtimeTokenProviders.js");
+
+const jsonResponse = (status, body) => ({
+ ok: status >= 200 && status < 300,
+ status,
+ json: async () => body,
+});
+
+const deps = (overrides = {}) => ({
+ environmentManager: {
+ getOpenAIKey: () => "sk-openai",
+ getTinfoilKey: () => "tk-tinfoil",
+ getDeepgramKey: () => "dg-key",
+ getAssemblyAIKey: () => "aai-key",
+ ...overrides.environmentManager,
+ },
+ proxyFetch: overrides.proxyFetch || (async () => jsonResponse(200, { token: "aai-token" })),
+ postServerToken: overrides.postServerToken || (async () => ({ token: "server-token" })),
+ mintCortiToken: overrides.mintCortiToken || (async () => ({ token: "corti-token" })),
+});
+
+test("provider-less and unknown providers fail closed with the exact #1480 message", async () => {
+ const { fetchRealtimeTokenForProvider } = await load();
+ for (const provider of [undefined, "grok-realtime", "openai"]) {
+ await assert.rejects(
+ fetchRealtimeTokenForProvider(provider, deps(), { mode: "byok" }),
+ new Error(`Unsupported realtime token provider: ${provider}`)
+ );
+ }
+});
+
+test("openai byok returns the key; dual-stream duplicates it", async () => {
+ const { fetchRealtimeTokenForProvider } = await load();
+ assert.equal(
+ await fetchRealtimeTokenForProvider("openai-realtime", deps(), { mode: "byok" }),
+ "sk-openai"
+ );
+ assert.deepEqual(
+ await fetchRealtimeTokenForProvider(
+ "openai-realtime",
+ deps(),
+ { mode: "byok" },
+ { streams: 2 }
+ ),
+ ["sk-openai", "sk-openai"]
+ );
+});
+
+test("openai cloud mints per-stream client secrets and validates the dual pair", async () => {
+ const { fetchRealtimeTokenForProvider } = await load();
+ const calls = [];
+ const cloudDeps = deps({
+ postServerToken: async (path, body) => {
+ calls.push({ path, body });
+ return { clientSecret: "cs-single", clientSecrets: ["cs-a", "cs-b"] };
+ },
+ });
+ const options = { mode: "openwhispr", model: "gpt-4o-mini-transcribe", language: "en" };
+
+ assert.equal(
+ await fetchRealtimeTokenForProvider("openai-realtime", cloudDeps, options),
+ "cs-single"
+ );
+ assert.deepEqual(
+ await fetchRealtimeTokenForProvider("openai-realtime", cloudDeps, options, { streams: 2 }),
+ ["cs-a", "cs-b"]
+ );
+ assert.deepEqual(calls[0], {
+ path: "/api/openai-realtime-token",
+ body: { model: "gpt-4o-mini-transcribe", language: "en", streams: 1 },
+ });
+ assert.equal(calls[1].body.streams, 2);
+
+ await assert.rejects(
+ fetchRealtimeTokenForProvider(
+ "openai-realtime",
+ deps({ postServerToken: async () => ({ clientSecrets: ["only-one"] }) }),
+ options,
+ { streams: 2 }
+ ),
+ /Expected two client secrets/
+ );
+});
+
+test("tinfoil missing key carries the NO_API code the renderer's fallback keys on", async () => {
+ const { fetchRealtimeTokenForProvider } = await load();
+ const noKey = deps({ environmentManager: { getTinfoilKey: () => "" } });
+ await assert.rejects(
+ fetchRealtimeTokenForProvider("tinfoil-realtime", noKey, { mode: "byok" }),
+ (err) => err.code === "NO_API"
+ );
+});
+
+test("assemblyai byok mints one live token per stream", async () => {
+ const { fetchRealtimeTokenForProvider } = await load();
+ let mints = 0;
+ const liveDeps = deps({
+ proxyFetch: async () => jsonResponse(200, { token: `aai-${++mints}` }),
+ });
+ assert.deepEqual(
+ await fetchRealtimeTokenForProvider(
+ "assemblyai-realtime",
+ liveDeps,
+ { mode: "byok" },
+ { streams: 2 }
+ ),
+ ["aai-1", "aai-2"]
+ );
+});
+
+test("deepgram byok duplicates the key; cloud mints per stream", async () => {
+ const { fetchRealtimeTokenForProvider } = await load();
+ assert.deepEqual(
+ await fetchRealtimeTokenForProvider(
+ "deepgram-realtime",
+ deps(),
+ { mode: "byok" },
+ { streams: 2 }
+ ),
+ ["dg-key", "dg-key"]
+ );
+ let mints = 0;
+ const cloudDeps = deps({ postServerToken: async () => ({ token: `dg-${++mints}` }) });
+ assert.deepEqual(
+ await fetchRealtimeTokenForProvider(
+ "deepgram-realtime",
+ cloudDeps,
+ { mode: "openwhispr" },
+ { streams: 2 }
+ ),
+ ["dg-1", "dg-2"]
+ );
+});
+
+test("corti mints one token and shares it across both streams", async () => {
+ const { fetchRealtimeTokenForProvider } = await load();
+ let mints = 0;
+ const cortiDeps = deps({ mintCortiToken: async () => ({ token: `corti-${++mints}` }) });
+ assert.deepEqual(
+ await fetchRealtimeTokenForProvider("corti-realtime", cortiDeps, {}, { streams: 2 }),
+ ["corti-1", "corti-1"]
+ );
+ assert.equal(mints, 1);
+});
+
+test("missing byok keys throw configuration errors, not token errors", async () => {
+ const { fetchRealtimeTokenForProvider } = await load();
+ const empty = { getOpenAIKey: () => "", getDeepgramKey: () => "", getAssemblyAIKey: () => "" };
+ for (const provider of ["openai-realtime", "deepgram-realtime", "assemblyai-realtime"]) {
+ await assert.rejects(
+ fetchRealtimeTokenForProvider(provider, deps({ environmentManager: empty }), {
+ mode: "byok",
+ }),
+ /key configured/
+ );
+ }
+});