Skip to content

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

fix(transcription): repair BYOK Deepgram and AssemblyAI streaming (#2149)

Chad Piha9789e46646ad
diff --git a/CHANGELOG.md b/CHANGELOG.md
index ba32da563..2c21081cb 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
+### Transcription
+
+- **Your own Deepgram key works again.** Every Deepgram connection failed with `Unexpected server response: 401`, even though the same key tested fine in Settings and worked against Deepgram directly. Deepgram accepts a raw API key only under its `Token` authorization scheme and reserves `Bearer` for the short-lived tokens OpenWhispr Cloud mints on your behalf — and the app was presenting your key as a `Bearer`. This broke bring-your-own-key dictation as well as Note Recording. (#2140, thanks @nikhilmaddirala)
+- **Your own AssemblyAI key works in Note Recording again.** Recordings died seconds in with `Input Duration Violation: 40.0 ms`, followed by a cascade of reconnect errors. AssemblyAI accepts audio in 50-1000 ms frames, and the app measured those frames against dictation's 16 kHz — but Note Recording streams at 24 kHz, where the same frame lasts only 33-40 ms. The frame size now follows the rate each session actually opened at, and an oversized burst — which a busy moment can produce on the system-audio channel — is split instead of being sent as one frame that trips the same limit from the other end. Dictation was never affected. (#2140, thanks @nikhilmaddirala)
+
## [1.10.0] - 2026-09-11
The desktop app gets a new look: an inset content container with a top bar and ⌘K search, a redesigned Home and note editor, the Yowza brand font and Nucleo icons, and one brand-blue glass surface for every primary action, onboarding included. Notes start recording the moment you create them, offer an AI summary when a recording ends, and gain Detailed Notes and Follow-up email as built-in actions. Orukeet arrives as the recommended local speech-to-text model and local models run up to three times faster on Apple silicon. Managed enterprise speech-to-text lands for workspaces on Azure OpenAI or AI Foundry, transcription gains streaming from Deepgram, AssemblyAI and Gemini Live plus Cohere Transcribe as a local engine, gpt-transcribe becomes the OpenAI default, onboarding was rebuilt and reordered, Insights gains an opt-in leaderboard and backfilled history, updates install themselves, Arabic joins as the eleventh UI language, and Astra and Fable 5.1 join the reasoning models.
diff --git a/scripts/stt-canary.mjs b/scripts/stt-canary.mjs
index c4c4ed277..7a288b477 100644
--- a/scripts/stt-canary.mjs
+++ b/scripts/stt-canary.mjs
@@ -29,6 +29,7 @@ import audioUtils from "../src/utils/audioUtils.js";
import geminiTranscription from "../src/helpers/geminiTranscription.js";
import geminiLive from "../src/helpers/geminiLiveStreaming.js";
import AssemblyAiStreaming from "../src/helpers/assemblyAiStreaming.js";
+import DeepgramStreaming from "../src/helpers/deepgramStreaming.js";
import modelRegistryData from "../src/models/modelRegistryData.json" with { type: "json" };
const { fetchRealtimeTokenForProvider } = tokenProviders;
@@ -48,19 +49,25 @@ const HANDSHAKE_TIMEOUT_MS = 15000;
const SILENT_WAV = () => pcm16ToWav(Buffer.alloc(16000));
// Mirrors the app's dial: openaiRealtimeStreaming.js connects with a bare
-// Bearer header; deepgramStreaming.js passes the key as the bearer token; a
-// null token means the credential already rides in the URL (AssemblyAI).
+// Bearer header; a null token means the credential already rides in the URL
+// (AssemblyAI). `authorization` overrides both, for a provider whose scheme is
+// not Bearer; passing the client's own header keeps the probe from drifting.
// `awaitServerEvent` is for providers that authenticate AFTER the upgrade:
// OpenAI opens the socket for any key and only then sends an `error` event
// for a bad one, so resolving on `open` validates nothing (#1624 class).
// `verifyServerEvent` inspects that first event and returns a failure detail,
// or null to accept — for servers that acknowledge the requested configuration
// rather than reject a bad one.
-function probeWebSocket(url, token, { awaitServerEvent = false, verifyServerEvent = null } = {}) {
+function probeWebSocket(
+ url,
+ token,
+ { awaitServerEvent = false, verifyServerEvent = null, authorization = null } = {}
+) {
return new Promise((resolve) => {
+ const credential = authorization ?? (token ? `Bearer ${token}` : null);
const ws = new WebSocket(
url,
- token ? { headers: { Authorization: `Bearer ${token}` } } : undefined
+ credential ? { headers: { Authorization: credential } } : undefined
);
const timer = setTimeout(() => {
ws.terminate();
@@ -259,10 +266,13 @@ const PROBES = [
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
- );
+ const url = new DeepgramStreaming().buildWebSocketUrl({
+ sampleRate: 16000,
+ keyterms: ["OpenWhispr"],
+ });
+ return probeWebSocket(url, null, {
+ authorization: DeepgramStreaming.authorizationHeader("byok", token),
+ });
},
},
{
diff --git a/src/helpers/assemblyAiStreaming.js b/src/helpers/assemblyAiStreaming.js
index d846bf138..a543fb207 100644
--- a/src/helpers/assemblyAiStreaming.js
+++ b/src/helpers/assemblyAiStreaming.js
@@ -10,7 +10,15 @@ const REWARM_DELAY_MS = 2000;
const MAX_REWARM_ATTEMPTS = 10;
const KEEPALIVE_INTERVAL_MS = 15000;
const MIN_FRAME_MS = 50;
-const MIN_FRAME_BYTES = (SAMPLE_RATE * 2 * MIN_FRAME_MS) / 1000;
+// AssemblyAI hard-closes the session outside 50-1000 ms but documents 50-250 ms
+// as the supported shape, so the split targets the recommended ceiling: 1000 would
+// put the first slice of a coalesced read exactly on the limit it exists to avoid.
+const MAX_FRAME_MS = 250;
+// Both bounds follow the rate the socket opened at: Note Recording streams at
+// 24 kHz, where a frame sized against this module's 16 kHz default lasts only
+// 33 ms (#2140).
+const minFrameBytes = (sampleRate) => Math.ceil((sampleRate * 2 * MIN_FRAME_MS) / 1000);
+const maxFrameBytes = (sampleRate) => Math.floor((sampleRate * 2 * MAX_FRAME_MS) / 1000);
class AssemblyAiStreaming {
constructor() {
@@ -38,6 +46,7 @@ class AssemblyAiStreaming {
this.warmConnectionOptions = null;
this.warmSessionId = null;
this.requestedModel = null;
+ this.sessionSampleRate = SAMPLE_RATE;
this.rewarmAttempts = 0;
this.rewarmTimer = null;
this.keepAliveInterval = null;
@@ -50,6 +59,7 @@ class AssemblyAiStreaming {
buildWebSocketUrl(options) {
const sampleRate = options.sampleRate || SAMPLE_RATE;
+ this.sessionSampleRate = sampleRate;
const params = new URLSearchParams({
sample_rate: String(sampleRate),
encoding: "pcm_s16le",
@@ -351,11 +361,15 @@ class AssemblyAiStreaming {
// warning could never fire for the model actually requested.
if (
this.hasWarmConnection() &&
- (this.warmConnectionOptions.model || null) !== (options.model || null)
+ ((this.warmConnectionOptions.model || null) !== (options.model || null) ||
+ (this.warmConnectionOptions.sampleRate || SAMPLE_RATE) !==
+ (options.sampleRate || SAMPLE_RATE))
) {
- debugLogger.debug("AssemblyAI warm connection model differs, cold-starting", {
+ debugLogger.debug("AssemblyAI warm connection differs, cold-starting", {
warm: this.warmConnectionOptions.model || null,
requested: options.model || null,
+ warmSampleRate: this.warmConnectionOptions.sampleRate || SAMPLE_RATE,
+ requestedSampleRate: options.sampleRate || SAMPLE_RATE,
});
this.cleanupWarmConnection();
}
@@ -575,14 +589,30 @@ class AssemblyAiStreaming {
this.pendingAudio.push(pcmBuffer);
this.pendingAudioBytes += pcmBuffer.length;
- if (this.pendingAudioBytes < MIN_FRAME_BYTES) {
+ const minBytes = minFrameBytes(this.sessionSampleRate);
+ if (this.pendingAudioBytes < minBytes) {
return true;
}
const frame = Buffer.concat(this.pendingAudio, this.pendingAudioBytes);
this.pendingAudio = [];
this.pendingAudioBytes = 0;
- this.ws.send(frame);
+
+ // The native system-audio helpers forward raw stdout chunks, so one read can
+ // far exceed the nominal 100 ms when a stalled main process lets the pipe
+ // coalesce. Carry a sub-floor remainder forward rather than sending it short.
+ const maxBytes = maxFrameBytes(this.sessionSampleRate);
+ let offset = 0;
+ while (frame.length - offset >= minBytes) {
+ const end = Math.min(offset + maxBytes, frame.length);
+ this.ws.send(frame.subarray(offset, end));
+ offset = end;
+ }
+ if (offset < frame.length) {
+ const remainder = frame.subarray(offset);
+ this.pendingAudio.push(remainder);
+ this.pendingAudioBytes = remainder.length;
+ }
return true;
}
diff --git a/src/helpers/deepgramStreaming.js b/src/helpers/deepgramStreaming.js
index c258c9824..530d6ad52 100644
--- a/src/helpers/deepgramStreaming.js
+++ b/src/helpers/deepgramStreaming.js
@@ -68,6 +68,21 @@ const NOVA3_LANGUAGES = new Set([
// Deepgram's net0001 idle timeout (which only resets on audio data, not KeepAlive).
const SILENCE_FRAME = Buffer.alloc((SAMPLE_RATE / 10) * 2);
+// Deepgram binds the scheme to the credential: a raw API key (BYOK) is accepted
+// only as `Token`, `Bearer` only for what /v1/auth/grant mints (managed). #2140
+const authorizationHeader = (mode, token) => `${mode === "byok" ? "Token" : "Bearer"} ${token}`;
+
+// Everything buildWebSocketUrl pins on the socket, folded the way it folds it, so
+// a warm connection can be compared against the session that wants to ride it.
+// Dictation warms on the UI language before it can know a translation wants the
+// source language, and the dictionary can be edited between the two.
+const urlIdentity = (options) =>
+ JSON.stringify([
+ options.sampleRate || SAMPLE_RATE,
+ options.language && options.language !== "auto" ? options.language : null,
+ (options.keyterms || []).filter(Boolean),
+ ]);
+
class DeepgramStreaming {
constructor() {
this.ws = null;
@@ -286,7 +301,7 @@ class DeepgramStreaming {
}, WEBSOCKET_TIMEOUT_MS);
this.warmConnection = new WebSocket(url, {
- headers: { Authorization: `Bearer ${token}` },
+ headers: { Authorization: authorizationHeader(this.mode, token) },
});
this.warmConnection.on("open", () => {
@@ -371,6 +386,14 @@ class DeepgramStreaming {
this.rewarmTimer = null;
if (this.hasWarmConnection() || this.isConnected) return;
+ // cleanupWarmConnection() drops these without cancelling this timer, and
+ // spreading a null one loses `mode`, re-warming a BYOK key as a Bearer.
+ const savedOptions = this.warmConnectionOptions;
+ if (!savedOptions) {
+ debugLogger.debug("Deepgram cannot re-warm: options dropped before the timer fired");
+ return;
+ }
+
let token = this.getCachedToken();
if (!token && this.tokenRefreshFn) {
try {
@@ -387,7 +410,7 @@ class DeepgramStreaming {
return;
}
- this.warmup({ ...this.warmConnectionOptions, token }).catch((err) => {
+ this.warmup({ ...savedOptions, token }).catch((err) => {
debugLogger.debug("Deepgram auto re-warm failed", { error: err.message });
});
}, delay);
@@ -604,6 +627,20 @@ class DeepgramStreaming {
this.coldStartBufferSize = 0;
}
+ // The socket carries these for its whole life, so riding a warm one opened
+ // for other values transcribes the session under them — silently, since
+ // Deepgram has no reason to object to the audio.
+ if (
+ this.hasWarmConnection() &&
+ urlIdentity(this.warmConnectionOptions) !== urlIdentity(options)
+ ) {
+ debugLogger.debug("Deepgram warm connection differs, cold-starting", {
+ warm: urlIdentity(this.warmConnectionOptions),
+ requested: urlIdentity(options),
+ });
+ this.cleanupWarmConnection();
+ }
+
if (!forceNew && this.hasWarmConnection()) {
if (this.useWarmConnection()) {
this.startLivenessCheck();
@@ -625,7 +662,7 @@ class DeepgramStreaming {
}, WEBSOCKET_TIMEOUT_MS);
this.ws = new WebSocket(url, {
- headers: { Authorization: `Bearer ${token}` },
+ headers: { Authorization: authorizationHeader(this.mode, token) },
});
this.ws.on("open", () => {
@@ -929,3 +966,4 @@ class DeepgramStreaming {
}
module.exports = DeepgramStreaming;
+module.exports.authorizationHeader = authorizationHeader;
diff --git a/src/helpers/ipcHandlers.js b/src/helpers/ipcHandlers.js
index e5f717e5b..2559d61c9 100644
--- a/src/helpers/ipcHandlers.js
+++ b/src/helpers/ipcHandlers.js
@@ -7039,6 +7039,7 @@ class IPCHandlers {
const connectOpts = {
model: options.model,
language: options.language,
+ mode: options.mode,
preconfigured: options.mode !== "byok",
environment: options.environment,
tenant: options.tenant,
@@ -7249,6 +7250,7 @@ class IPCHandlers {
const connectOpts = {
model: options.model,
language: options.language,
+ mode: options.mode,
preconfigured: options.mode !== "byok",
environment: options.environment,
tenant: options.tenant,
diff --git a/test/helpers/assemblyAiStreaming.test.js b/test/helpers/assemblyAiStreaming.test.js
index 8e376786e..fd4e0a819 100644
--- a/test/helpers/assemblyAiStreaming.test.js
+++ b/test/helpers/assemblyAiStreaming.test.js
@@ -3,6 +3,7 @@ const assert = require("node:assert/strict");
const { WebSocketServer } = require("ws");
const AssemblyAiStreaming = require("../../src/helpers/assemblyAiStreaming");
+const { deferred } = require("./harness/deferred");
async function withPrematureCloseServer(run) {
const server = new WebSocketServer({ host: "127.0.0.1", port: 0 });
@@ -19,13 +20,17 @@ async function withPrematureCloseServer(run) {
}
// `connections` collects each accepted request URL so a test can count sockets
-// and read the query the client actually sent.
-async function withBeginServer(run) {
+// and read the query the client actually sent. `onAudioFrame` reports each
+// binary frame the server receives.
+async function withBeginServer(run, { onAudioFrame } = {}) {
const server = new WebSocketServer({ host: "127.0.0.1", port: 0 });
await new Promise((resolve) => server.once("listening", resolve));
const connections = [];
server.on("connection", (socket, request) => {
connections.push(request.url);
+ socket.on("message", (data, isBinary) => {
+ if (isBinary) onAudioFrame?.(data);
+ });
socket.send(JSON.stringify({ type: "Begin", id: "test-session" }));
});
@@ -177,3 +182,140 @@ test("a warm connection opened for another speech model is not reused", async ()
}
});
});
+
+// Note Recording's MEETING_STREAM_SAMPLE_RATE (#2140).
+const MEETING_SAMPLE_RATE = 24000;
+const frameDurationMs = (bytes) => (bytes / 2 / MEETING_SAMPLE_RATE) * 1000;
+
+// node:test has no default timeout, so the wait is bounded here: withheld audio
+// must fail the run rather than hang it.
+async function collectFrames(chunks, assertFrames) {
+ const frames = [];
+ let receivedBytes = 0;
+ const allReceived = deferred();
+ const expectedBytes = chunks.reduce((total, bytes) => total + bytes, 0);
+
+ await withBeginServer(
+ async (url, connections) => {
+ const streaming = new AssemblyAiStreaming();
+ // The real builder is what pins the session's sample rate: do not stub it.
+ dialLoopback(streaming, url);
+
+ try {
+ await streaming.connect({
+ token: "byok-key",
+ mode: "byok",
+ sampleRate: MEETING_SAMPLE_RATE,
+ });
+ for (const bytes of chunks) streaming.sendAudio(Buffer.alloc(bytes));
+ await Promise.race([
+ allReceived.promise,
+ new Promise((_, reject) =>
+ setTimeout(
+ () =>
+ reject(
+ new Error(`only ${receivedBytes} of ${expectedBytes} bytes reached the server`)
+ ),
+ 2000
+ ).unref()
+ ),
+ ]);
+
+ assert.match(
+ connections[0],
+ /sample_rate=24000/,
+ "the session must open at the meeting rate for the frame maths to mean anything"
+ );
+ assertFrames(frames);
+ } finally {
+ streaming.cleanupAll();
+ }
+ },
+ {
+ onAudioFrame: (data) => {
+ frames.push(data.length);
+ receivedBytes += data.length;
+ if (receivedBytes >= expectedBytes) allReceived.resolve();
+ },
+ }
+ );
+}
+
+test("audio frames respect AssemblyAI's 50 ms floor at the meeting sample rate", async () => {
+ // 480 bytes is the smallest meeting-aec-helper can hand over (one 10 ms frame).
+ await collectFrames(Array(20).fill(480), (frames) => {
+ assert.ok(frames.length > 0, "no audio reached the server");
+ for (const bytes of frames) {
+ assert.ok(
+ frameDurationMs(bytes) >= 50,
+ `sent a ${frameDurationMs(bytes).toFixed(1)} ms frame; AssemblyAI's floor is 50 ms`
+ );
+ }
+ });
+});
+
+test("a coalesced system-audio read is split inside AssemblyAI's frame window", async () => {
+ // A stalled main process gets one 64 KB pipe read off the system-audio helper:
+ // 1365 ms at 24 kHz, which AssemblyAI rejects like an undersized frame. The
+ // slices target the documented 250 ms ceiling, not the 1000 ms hard limit.
+ await collectFrames([65536], (frames) => {
+ assert.ok(frames.length > 1, "a 1365 ms read must be split, not sent whole");
+ for (const bytes of frames) {
+ assert.ok(
+ frameDurationMs(bytes) >= 50 && frameDurationMs(bytes) <= 250,
+ `sent a ${frameDurationMs(bytes).toFixed(1)} ms frame; AssemblyAI documents 50-250 ms`
+ );
+ }
+ });
+});
+
+test("a sub-floor remainder is carried into the next frame, not dropped", async () => {
+ // 50000 B leaves 2000 B after the slices — under the 2400 B floor at 24 kHz, so
+ // it can only go out once the next chunk lifts it over. Without the carry it is
+ // silently discarded and 2000 B of speech never reaches the transcript, which
+ // collectFrames catches as bytes that never arrive. Asserting the tail rather
+ // than the whole shape keeps this independent of MAX_FRAME_MS.
+ await collectFrames([50000, 2400], (frames) => {
+ assert.equal(frames.at(-1), 4400, "the 2000 B tail must ride out on the next frame");
+ });
+});
+
+test("a warm connection opened at another sample rate is not reused", async () => {
+ await withBeginServer(async (url, connections) => {
+ const streaming = new AssemblyAiStreaming();
+ dialLoopback(streaming, url);
+
+ try {
+ await streaming.warmup({ token: "byok-key", mode: "byok" });
+ // The rate is pinned at open, so riding a 16 kHz warm socket with 24 kHz PCM
+ // garbles the transcript silently and re-frames audio against the wrong rate.
+ await streaming.connect({
+ token: "byok-key",
+ mode: "byok",
+ sampleRate: MEETING_SAMPLE_RATE,
+ });
+
+ assert.equal(connections.length, 2);
+ assert.match(connections[0], /sample_rate=16000/);
+ assert.match(connections[1], /sample_rate=24000/);
+ assert.equal(streaming.sessionSampleRate, MEETING_SAMPLE_RATE);
+ } finally {
+ streaming.cleanupAll();
+ }
+ });
+
+ await withBeginServer(async (url, connections) => {
+ const streaming = new AssemblyAiStreaming();
+ dialLoopback(streaming, url);
+
+ try {
+ const options = { token: "byok-key", mode: "byok", sampleRate: MEETING_SAMPLE_RATE };
+ await streaming.warmup(options);
+ await streaming.connect(options);
+
+ assert.equal(connections.length, 1, "same rate rides the warm socket");
+ } finally {
+ streaming.cleanupAll();
+ }
+ });
+});
diff --git a/test/helpers/deepgramStreaming.test.js b/test/helpers/deepgramStreaming.test.js
index 70a553be9..e1b1a5e83 100644
--- a/test/helpers/deepgramStreaming.test.js
+++ b/test/helpers/deepgramStreaming.test.js
@@ -10,13 +10,15 @@ async function withMetadataServer(run) {
const server = new WebSocketServer({ host: "127.0.0.1", port: 0 });
await new Promise((resolve) => server.once("listening", resolve));
const connections = [];
+ const authHeaders = [];
server.on("connection", (socket, request) => {
connections.push(request.url);
+ authHeaders.push(request.headers.authorization);
socket.send(JSON.stringify({ type: "Metadata", request_id: `req-${connections.length}` }));
});
try {
- await run(`ws://127.0.0.1:${server.address().port}`, connections);
+ await run(`ws://127.0.0.1:${server.address().port}`, connections, authHeaders);
} finally {
await new Promise((resolve) => server.close(resolve));
}
@@ -65,6 +67,86 @@ test("a warm connection is reused only within the same credential mode", async (
});
});
+// Keeps the real query string (language, keyterms) while dialing the loopback server.
+function dialLoopback(streaming, url) {
+ const buildRealUrl = streaming.buildWebSocketUrl.bind(streaming);
+ streaming.buildWebSocketUrl = (options) =>
+ buildRealUrl(options).replace("wss://api.deepgram.com/v1/listen", url);
+}
+
+test("a warm connection opened for another language is not reused", async () => {
+ await withMetadataServer(async (url, connections) => {
+ const streaming = new DeepgramStreaming();
+ dialLoopback(streaming, url);
+
+ try {
+ // Dictation warms on the UI language: warmupStreamingConnection() runs at
+ // startup and after each transcription, before setTranslationRequested()
+ // can say a translation wants the source language instead. The URL pins
+ // that language — and with it nova-3 vs nova-2 — for the whole session.
+ await streaming.warmup({ token: "byok-key", mode: "byok", language: "en" });
+ await streaming.connect({ token: "byok-key", mode: "byok", language: "fr" });
+
+ assert.equal(connections.length, 2, "the English warm socket was reused for French");
+ assert.match(connections[0], /language=en/);
+ assert.match(connections[1], /language=fr/);
+ } finally {
+ streaming.cleanupAll();
+ }
+ });
+
+ await withMetadataServer(async (url, connections) => {
+ const streaming = new DeepgramStreaming();
+ dialLoopback(streaming, url);
+
+ try {
+ const options = { token: "byok-key", mode: "byok", language: "en" };
+ await streaming.warmup(options);
+ await streaming.connect(options);
+
+ assert.equal(connections.length, 1, "same language rides the warm socket");
+ } finally {
+ streaming.cleanupAll();
+ }
+ });
+});
+
+test("a warm connection opened for other keyterms is not reused", async () => {
+ await withMetadataServer(async (url, connections) => {
+ const streaming = new DeepgramStreaming();
+ dialLoopback(streaming, url);
+
+ try {
+ await streaming.warmup({ token: "byok-key", mode: "byok", keyterms: ["Whispr"] });
+ await streaming.connect({ token: "byok-key", mode: "byok", keyterms: ["Whispr", "Qdrant"] });
+
+ assert.equal(connections.length, 2, "a dictionary edit must reach the socket");
+ assert.match(connections[1], /keyterm=Qdrant/);
+ } finally {
+ streaming.cleanupAll();
+ }
+ });
+});
+
+test("a warm connection is reused when the two option sets build the same URL", async () => {
+ // buildWebSocketUrl folds "auto" into no language and skips empty keyterms, so
+ // the guard has to fold them the same way — otherwise every dictation cold
+ // starts and the warm socket stops buying anything.
+ await withMetadataServer(async (url, connections) => {
+ const streaming = new DeepgramStreaming();
+ dialLoopback(streaming, url);
+
+ try {
+ await streaming.warmup({ token: "byok-key", mode: "byok", language: "auto" });
+ await streaming.connect({ token: "byok-key", mode: "byok", keyterms: [] });
+
+ assert.equal(connections.length, 1, "an identical URL must ride the warm socket");
+ } finally {
+ streaming.cleanupAll();
+ }
+ });
+});
+
test("adopting a different mode before a warmup drops the other mode's token", async () => {
await withMetadataServer(async (url) => {
const streaming = new DeepgramStreaming();
@@ -83,3 +165,98 @@ test("adopting a different mode before a warmup drops the other mode's token", a
}
});
});
+
+test("a BYOK key authenticates under Deepgram's Token scheme", async () => {
+ await withMetadataServer(async (url, connections, authHeaders) => {
+ const streaming = new DeepgramStreaming();
+ streaming.buildWebSocketUrl = () => url;
+
+ try {
+ await streaming.connect({ token: "byok-key", mode: "byok" });
+
+ assert.deepEqual(authHeaders, ["Token byok-key"]);
+ } finally {
+ streaming.cleanupAll();
+ }
+ });
+});
+
+test("a managed grant token authenticates under the Bearer scheme", async () => {
+ await withMetadataServer(async (url, connections, authHeaders) => {
+ const streaming = new DeepgramStreaming();
+ streaming.buildWebSocketUrl = () => url;
+
+ try {
+ await streaming.connect({ token: "grant-token", mode: "openwhispr" });
+
+ assert.deepEqual(authHeaders, ["Bearer grant-token"]);
+ } finally {
+ streaming.cleanupAll();
+ }
+ });
+});
+
+test("warmup presents the same scheme the session will connect with", async () => {
+ await withMetadataServer(async (url, connections, authHeaders) => {
+ const streaming = new DeepgramStreaming();
+ streaming.buildWebSocketUrl = () => url;
+
+ try {
+ await streaming.warmup({ token: "byok-key", mode: "byok" });
+
+ assert.deepEqual(authHeaders, ["Token byok-key"]);
+ } finally {
+ streaming.cleanupAll();
+ }
+ });
+});
+
+// Runs `schedule` with setTimeout stubbed out and hands back its callback, so a
+// timer-gated branch can be exercised at once. Scoped to the one synchronous
+// call: mocking setTimeout for any longer deadlocks the ws server's teardown.
+function captureScheduledCallback(schedule) {
+ const realSetTimeout = global.setTimeout;
+ let scheduled = null;
+ global.setTimeout = (callback) => {
+ scheduled = callback;
+ return { unref() {} };
+ };
+ try {
+ schedule();
+ } finally {
+ global.setTimeout = realSetTimeout;
+ }
+ assert.ok(scheduled, "nothing was scheduled");
+ return scheduled;
+}
+
+test("a re-warm whose options were dropped does not re-authenticate as managed", async () => {
+ await withMetadataServer(async (url, connections, authHeaders) => {
+ const streaming = new DeepgramStreaming();
+ streaming.buildWebSocketUrl = () => url;
+
+ try {
+ await streaming.warmup({ token: "byok-key", mode: "byok" });
+ assert.deepEqual(authHeaders, ["Token byok-key"]);
+
+ const rewarm = captureScheduledCallback(() => streaming.scheduleRewarm());
+ // cleanupWarmConnection() drops the saved options without cancelling the
+ // timer, and the cached token outlives them — so the re-warm still has a
+ // credential to present, just no longer any record of which kind it is.
+ streaming.cleanupWarmConnection();
+ await rewarm();
+
+ assert.equal(streaming.mode, "byok", "the re-warm renegotiated the credential mode");
+ assert.equal(streaming.warmConnection, null, "a socket was opened without a known mode");
+ } finally {
+ streaming.cleanupAll();
+ }
+ });
+});
+
+// Its only consumer is the weekly canary, not PR CI: without this, deleting the
+// export stays green for a week.
+test("the authorization scheme is exported for the canary to reuse", () => {
+ assert.equal(DeepgramStreaming.authorizationHeader("byok", "k"), "Token k");
+ assert.equal(DeepgramStreaming.authorizationHeader("openwhispr", "k"), "Bearer k");
+});
diff --git a/test/helpers/meetingStreamingWiring.test.js b/test/helpers/meetingStreamingWiring.test.js
index 1b007e14d..effa51781 100644
--- a/test/helpers/meetingStreamingWiring.test.js
+++ b/test/helpers/meetingStreamingWiring.test.js
@@ -157,3 +157,17 @@ test("the watchdog sees every system chunk and the helper's device warning", ()
// user watching a recording that has stopped hearing the call.
assert.match(source, /send\("meeting-system-audio-interrupted", payload\)/);
});
+
+test("meeting connects forward the credential mode", () => {
+ // The Deepgram client picks its Authorization scheme from `mode`; both meeting
+ // connectOpts are built by hand, so omitting it re-authenticates Note Recording
+ // as managed (#2140). Scoped by sample rate so an unrelated connectOpts cannot
+ // drag the assertion off target.
+ const connectOptsBlocks =
+ source.match(/const connectOpts = \{[^}]*sampleRate: MEETING_STREAM_SAMPLE_RATE,\s*\};/g) ?? [];
+ assert.equal(connectOptsBlocks.length, 2, "initial connect and reconnect each build connectOpts");
+ for (const block of connectOptsBlocks) {
+ // Anchored: an unanchored match also accepts the key commented out.
+ assert.match(block, /^\s*mode: options\.mode,$/m);
+ }
+});