Voice-to-text dictation app with local (Nvidia Parakeet/Whisper) and cloud models (BYOK). Privacy-first and available cross-platform.
JavaScript aianthropiccross-platformgeminigroqlinuxmacosnvidiaopen-sourceopenaiparakeetspeech-to-texttranscribewhisperwindows
fix(transcription): keep AssemblyAI and Corti audio sent before the socket is ready (#2547)
Joshua4881a74d7273
diff --git a/src/helpers/assemblyAiStreaming.js b/src/helpers/assemblyAiStreaming.jsindex 53e8ee1c5..7e75e8e83 100644--- a/src/helpers/assemblyAiStreaming.js+++ b/src/helpers/assemblyAiStreaming.js@@ -9,6 +9,7 @@ const TOKEN_EXPIRY_MS = 300000;const REWARM_DELAY_MS = 2000;const MAX_REWARM_ATTEMPTS = 10;const KEEPALIVE_INTERVAL_MS = 15000;+const COLD_START_BUFFER_MAX = 3 * SAMPLE_RATE * 2; // 3 seconds of 16-bit PCMconst MIN_FRAME_MS = 50;// 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@@ -53,6 +54,7 @@ class AssemblyAiStreaming {this.isDisconnecting = false;this.pendingAudio = [];this.pendingAudioBytes = 0;+ this.bufferingAudio = false;this.completedSegments = [];this.speechStartedAt = null;}@@ -347,6 +349,14 @@ class AssemblyAiStreaming {);}+ // Starts holding audio before the socket exists, covering the token fetch and+ // the handshake so sendAudio() doesn't drop the first words.+ beginConnecting() {+ this.bufferingAudio = true;+ this.pendingAudio = [];+ this.pendingAudioBytes = 0;+ }+async connect(options = {}) {const { token } = options;if (!token) {@@ -363,6 +373,8 @@ class AssemblyAiStreaming {this.lastTurnText = "";this.turns = [];this.connectionLossNotified = false;+ // The caller may already be holding audio from before its token fetch.+ if (!this.bufferingAudio) this.beginConnecting();this.adoptMode(options);// The server pins speech_model at Begin, so a warm socket opened for another@@ -387,6 +399,7 @@ class AssemblyAiStreaming {if (this.hasWarmConnection()) {if (this.useWarmConnection()) {debugLogger.debug("AssemblyAI using warm connection - instant start");+ this.sendPendingAudio();return;}}@@ -482,6 +495,9 @@ class AssemblyAiStreaming {"transcription");}+ // Audio held through the handshake goes out now: a short dictation may+ // send no further frame to carry it.+ this.sendPendingAudio();if (this.pendingResolve) {this.pendingResolve();this.pendingResolve = null;@@ -593,14 +609,29 @@ class AssemblyAiStreaming {sendAudio(pcmBuffer) {if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {- return false;+ // Held only while a start is in flight (up to three seconds), then framed like live audio.+ if (+ !this.bufferingAudio ||+ this.isConnected ||+ this.pendingAudioBytes >= COLD_START_BUFFER_MAX+ ) {+ return false;+ }+ this.pendingAudio.push(Buffer.from(pcmBuffer));+ this.pendingAudioBytes += pcmBuffer.length;+ return true;}this.pendingAudio.push(pcmBuffer);this.pendingAudioBytes += pcmBuffer.length;+ this.sendPendingAudio();+ return true;+ }++ sendPendingAudio() {const minBytes = minFrameBytes(this.sessionSampleRate);if (this.pendingAudioBytes < minBytes) {- return true;+ return;}const frame = Buffer.concat(this.pendingAudio, this.pendingAudioBytes);@@ -622,7 +653,6 @@ class AssemblyAiStreaming {this.pendingAudio.push(remainder);this.pendingAudioBytes = remainder.length;}- return true;}forceEndpoint() {@@ -679,6 +709,7 @@ class AssemblyAiStreaming {this.pendingAudio = [];this.pendingAudioBytes = 0;+ this.bufferingAudio = false;this.completedSegments = [];this.speechStartedAt = null;diff --git a/src/helpers/cortiStreaming.js b/src/helpers/cortiStreaming.jsindex 0e2017652..f2f584946 100644--- a/src/helpers/cortiStreaming.js+++ b/src/helpers/cortiStreaming.js@@ -29,6 +29,7 @@ class CortiStreaming {this.configAccepted = false;this.preConfigBuffer = [];this.preConfigBufferSize = 0;+ this.bufferingAudio = false;this.sessionStartedAt = null;this.audioBytesSent = 0;this.currentModel = "corti-transcribe";@@ -62,6 +63,15 @@ class CortiStreaming {return configuration;}+ // Starts holding audio before the socket exists, covering the token mint, the+ // handshake and the wait for CONFIG_ACCEPTED so sendAudio() doesn't drop the+ // first words.+ beginConnecting() {+ this.bufferingAudio = true;+ this.preConfigBuffer = [];+ this.preConfigBufferSize = 0;+ }+async connect(options = {}) {const { token, environment, tenant } = options;if (!token || !environment || !tenant) {@@ -77,8 +87,8 @@ class CortiStreaming {this.completedSegments = [];this.configAccepted = false;this.connectionLossNotified = false;- this.preConfigBuffer = [];- this.preConfigBufferSize = 0;+ // The caller may already be holding audio from before its token mint.+ if (!this.bufferingAudio) this.beginConnecting();this.audioBytesSent = 0;this.sampleRate = options.sampleRate || SAMPLE_RATE;@@ -98,6 +108,7 @@ class CortiStreaming {// Reuse the pre-warmed socket for an instant start; cold-connect otherwise.if (this.useWarmConnection()) {debugLogger.debug("Corti using warm connection - instant start");+ this.flushPreConfigBuffer();return;}@@ -114,22 +125,27 @@ class CortiStreaming {reject(new Error("Corti WebSocket connection timeout"));}, WEBSOCKET_TIMEOUT_MS);- this.ws = new WebSocket(url);- this.ws.on("open", () => {+ const ws = new WebSocket(url);+ this.ws = ws;+ ws.on("open", () => {debugLogger.debug("Corti WebSocket connected, sending config");- this.ws.send(JSON.stringify({ type: "config", configuration }));+ ws.send(JSON.stringify({ type: "config", configuration }));});- this.attachSocketHandlers(this.ws);+ this.attachSocketHandlers(ws);});}// Live-socket wiring shared by the cold connect and a promoted warm connection.+ // A socket that cleanup() already replaced can still deliver an ack, error or+ // close; those events must not touch the start now using this.ws.attachSocketHandlers(ws) {ws.on("message", (data) => {+ if (ws !== this.ws) return;this.handleMessage(data);});ws.on("error", (error) => {+ if (ws !== this.ws) return;const wasActive = this.isConnected;debugLogger.error("Corti WebSocket error", { error: error.message });this.cleanup();@@ -146,6 +162,7 @@ class CortiStreaming {});ws.on("close", (code, reason) => {+ if (ws !== this.ws) return;const wasActive = this.isConnected;debugLogger.debug("Corti WebSocket closed", {code,@@ -411,7 +428,8 @@ class CortiStreaming {}flushPreConfigBuffer() {- if (this.preConfigBuffer.length === 0) return;+ // A stale socket's ack can arrive while this start has no open socket yet.+ if (this.preConfigBuffer.length === 0 || this.ws?.readyState !== WebSocket.OPEN) return;debugLogger.debug("Corti flushing pre-config buffer", {chunks: this.preConfigBuffer.length,bytes: this.preConfigBufferSize,@@ -425,19 +443,19 @@ class CortiStreaming {}sendAudio(pcmBuffer) {- if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {- return false;- }-if (!this.configAccepted) {- // Corti rejects audio sent before it acks config; cap the handshake buffer at ~3s.- if (this.preConfigBufferSize < 3 * this.sampleRate * 2) {- const copy = Buffer.from(pcmBuffer);- this.preConfigBuffer.push(copy);- this.preConfigBufferSize += copy.length;+ // Corti rejects audio sent before it acks config; cap the startup buffer at ~3s.+ if (!this.bufferingAudio || this.preConfigBufferSize >= 3 * this.sampleRate * 2) {+ return false;}+ const copy = Buffer.from(pcmBuffer);+ this.preConfigBuffer.push(copy);+ this.preConfigBufferSize += copy.length;return true;}+ if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {+ return false;+ }this.audioBytesSent += pcmBuffer.length;this.ws.send(pcmBuffer);@@ -472,7 +490,11 @@ class CortiStreaming {}async disconnect(closeStream = true) {- if (!this.ws) return { text: this.accumulatedText };+ if (!this.ws) {+ // A stop before the socket exists must not leave the start's held audio behind.+ this.cleanup();+ return { text: this.accumulatedText };+ }this.isDisconnecting = true;@@ -504,6 +526,7 @@ class CortiStreaming {this.connectionTimeout = null;this.preConfigBuffer = [];this.preConfigBufferSize = 0;+ this.bufferingAudio = false;if (this.ws) {try {diff --git a/src/helpers/ipcHandlers.js b/src/helpers/ipcHandlers.jsindex 600bef36e..b6e33de56 100644--- a/src/helpers/ipcHandlers.js+++ b/src/helpers/ipcHandlers.js@@ -11092,6 +11092,10 @@ class IPCHandlers {"streaming");+ // Buffer before the token fetch (a network round trip for BYOK, even when+ // a warm socket will carry the session) so assemblyai-streaming-send has+ // somewhere to put the first frames.+ this.assemblyAiStreaming.beginConnecting();let token = byok ? null : this.assemblyAiStreaming.getCachedToken();if (!token) {debugLogger.debug("Fetching streaming token", { byok }, "streaming");@@ -11136,6 +11140,8 @@ class IPCHandlers {};} catch (error) {debugLogger.error("AssemblyAI streaming start error", { error: error.message });+ // Nothing is in flight after a failed start, so its held audio goes too.+ this.assemblyAiStreaming?.cleanup();if (error.code === "AUTH_EXPIRED") {return { success: false, error: "Session expired", code: "AUTH_EXPIRED" };}@@ -11677,6 +11683,9 @@ class IPCHandlers {await this.cortiStreaming.disconnect(false);}+ // Buffer before the token mint (a network round trip unless cached) so+ // corti-streaming-send has somewhere to put the first frames.+ this.cortiStreaming.beginConnecting();const { token, environment, tenant } = await this._mintStoredCortiToken(options);const win = BrowserWindow.fromWebContents(event.sender);@@ -11704,6 +11713,8 @@ class IPCHandlers {return { success: true };} catch (error) {debugLogger.error("Corti streaming start error", { error: error.message }, "streaming");+ // Nothing is in flight after a failed start, so its held audio goes too.+ this.cortiStreaming?.cleanup();return { success: false, error: error.message, code: error.code };}});diff --git a/test/helpers/assemblyAiStreaming.test.js b/test/helpers/assemblyAiStreaming.test.jsindex fd4e0a819..56af12fa1 100644--- a/test/helpers/assemblyAiStreaming.test.js+++ b/test/helpers/assemblyAiStreaming.test.js@@ -1,8 +1,10 @@const test = require("node:test");const assert = require("node:assert/strict");+const { once } = require("node:events");const { WebSocketServer } = require("ws");const AssemblyAiStreaming = require("../../src/helpers/assemblyAiStreaming");+const { audioRecorder } = require("./harness/audioRecorder");const { deferred } = require("./harness/deferred");async function withPrematureCloseServer(run) {@@ -21,8 +23,9 @@ async function withPrematureCloseServer(run) {// `connections` collects each accepted request URL so a test can count sockets// and read the query the client actually sent. `onAudioFrame` reports each-// binary frame the server receives.-async function withBeginServer(run, { onAudioFrame } = {}) {+// binary frame the server receives. `beginDelayMs` holds Begin back, leaving+// the socket open before the session has begun.+async function withBeginServer(run, { onAudioFrame, beginDelayMs = 0 } = {}) {const server = new WebSocketServer({ host: "127.0.0.1", port: 0 });await new Promise((resolve) => server.once("listening", resolve));const connections = [];@@ -31,7 +34,9 @@ async function withBeginServer(run, { onAudioFrame } = {}) {socket.on("message", (data, isBinary) => {if (isBinary) onAudioFrame?.(data);});- socket.send(JSON.stringify({ type: "Begin", id: "test-session" }));+ const begin = () => socket.send(JSON.stringify({ type: "Begin", id: "test-session" }));+ if (beginDelayMs) setTimeout(begin, beginDelayMs);+ else begin();});try {@@ -188,9 +193,11 @@ 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) {+// must fail the run rather than hang it. Each chunk is filled with its 1-based+// index, so `audio` (every byte received, in order) shows loss and reordering.+async function collectFrames(chunks, assertFrames, { whileConnecting = false } = {}) {const frames = [];+ const received = [];let receivedBytes = 0;const allReceived = deferred();const expectedBytes = chunks.reduce((total, bytes) => total + bytes, 0);@@ -200,14 +207,19 @@ async function collectFrames(chunks, assertFrames) {const streaming = new AssemblyAiStreaming();// The real builder is what pins the session's sample rate: do not stub it.dialLoopback(streaming, url);+ const sendChunks = () =>+ chunks.forEach((bytes, index) => streaming.sendAudio(Buffer.alloc(bytes, index + 1)));try {- await streaming.connect({+ const connected = streaming.connect({token: "byok-key",mode: "byok",sampleRate: MEETING_SAMPLE_RATE,});- for (const bytes of chunks) streaming.sendAudio(Buffer.alloc(bytes));+ // The socket cannot open within this tick, so these arrive while it connects.+ if (whileConnecting) sendChunks();+ await connected;+ if (!whileConnecting) sendChunks();await Promise.race([allReceived.promise,new Promise((_, reject) =>@@ -226,7 +238,7 @@ async function collectFrames(chunks, assertFrames) {/sample_rate=24000/,"the session must open at the meeting rate for the frame maths to mean anything");- assertFrames(frames);+ assertFrames(frames, Buffer.concat(received));} finally {streaming.cleanupAll();}@@ -234,6 +246,7 @@ async function collectFrames(chunks, assertFrames) {{onAudioFrame: (data) => {frames.push(data.length);+ received.push(data);receivedBytes += data.length;if (receivedBytes >= expectedBytes) allReceived.resolve();},@@ -280,6 +293,92 @@ test("a sub-floor remainder is carried into the next frame, not dropped", async});});+test("audio sent while the socket connects arrives in order, in 50-250 ms frames", async () => {+ // 300 ms of 10 ms chunks, all offered while the socket is still connecting —+ // the opening words of a cold start. Sent one by one they would be 10 ms+ // frames; sent as one they would be a 300 ms frame. AssemblyAI rejects both.+ const chunks = Array(30).fill(480);+ await collectFrames(+ chunks,+ (frames, audio) => {+ assert.deepEqual(+ audio,+ Buffer.concat(chunks.map((bytes, index) => Buffer.alloc(bytes, index + 1)))+ );+ 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`+ );+ }+ },+ { whileConnecting: true }+ );+});++test("audio held while connecting goes out ahead of audio sent once the socket opens", async () => {+ // Begin is held back, so the socket opens before the session begins. What+ // arrives in that gap must not overtake the opening words held before it.+ const frames = [1, 2, 3, 4, 5, 6, 7, 8, 9].map((value) => Buffer.alloc(1600, value));+ const audio = audioRecorder();++ await withBeginServer(+ async (url) => {+ const streaming = new AssemblyAiStreaming();+ streaming.buildWebSocketUrl = () => url;++ try {+ const connected = streaming.connect({ token: "test-token" });+ for (const frame of frames.slice(0, 3)) streaming.sendAudio(frame);+ await once(streaming.ws, "open");+ for (const frame of frames.slice(3, 6)) streaming.sendAudio(frame);+ await connected;+ for (const frame of frames.slice(6)) streaming.sendAudio(frame);++ assert.deepEqual(await audio.received(9 * 1600), Buffer.concat(frames));+ } finally {+ streaming.cleanupAll();+ }+ },+ { onAudioFrame: (data) => audio.record(data), beginDelayMs: 100 }+ );+});++test("a client with no start in flight takes no audio", () => {+ const streaming = new AssemblyAiStreaming();+ assert.equal(streaming.sendAudio(Buffer.alloc(1600)), false, "an idle client held audio");++ streaming.beginConnecting();+ streaming.cleanup(); // what a closed or failed socket runs+ assert.equal(streaming.sendAudio(Buffer.alloc(1600)), false, "an ended start held audio");+});++test("a session that has begun drops audio while its socket closes", async () => {+ await withBeginServer(async (url) => {+ const streaming = new AssemblyAiStreaming();+ streaming.buildWebSocketUrl = () => url;++ try {+ await streaming.connect({ token: "test-token" });+ streaming.ws.close(); // CLOSING until the close handshake ends the session++ assert.equal(streaming.sendAudio(Buffer.alloc(1600)), false);+ } finally {+ streaming.cleanupAll();+ }+ });+});++test("audio held during a start is capped at three seconds", () => {+ const streaming = new AssemblyAiStreaming();+ streaming.beginConnecting();++ // Five seconds of 50 ms frames at 16 kHz: the first three seconds are 60 frames.+ const held = Array.from({ length: 100 }, () => streaming.sendAudio(Buffer.alloc(1600)));++ assert.deepEqual(held, [...Array(60).fill(true), ...Array(40).fill(false)]);+});+test("a warm connection opened at another sample rate is not reused", async () => {await withBeginServer(async (url, connections) => {const streaming = new AssemblyAiStreaming();diff --git a/test/helpers/cortiStreaming.test.js b/test/helpers/cortiStreaming.test.jsnew file mode 100644index 000000000..1178877d4--- /dev/null+++ b/test/helpers/cortiStreaming.test.js@@ -0,0 +1,129 @@+const test = require("node:test");+const assert = require("node:assert/strict");+const { EventEmitter, once } = require("node:events");+const { WebSocketServer } = require("ws");++const CortiStreaming = require("../../src/helpers/cortiStreaming");+const { audioRecorder } = require("./harness/audioRecorder");++const OPTIONS = { token: "test-token", environment: "us", tenant: "base" };+const FRAME_BYTES = 1600; // one 50 ms worklet frame at 16 kHz++// Loopback audio bridge. It accepts the config a beat after it arrives, so audio+// sent ahead of the ack shows up in `audioBeforeAccept`, and it answers flush.+async function withCortiServer(run) {+ const server = new WebSocketServer({ host: "127.0.0.1", port: 0 });+ await new Promise((resolve) => server.once("listening", resolve));+ const sessions = [];+ server.on("connection", (socket) => {+ const session = { audio: audioRecorder(), audioBeforeAccept: 0, accepted: false };+ sessions.push(session);+ socket.on("message", (data, isBinary) => {+ if (isBinary) {+ if (!session.accepted) session.audioBeforeAccept++;+ session.audio.record(data);+ return;+ }+ const message = JSON.parse(data.toString());+ if (message.type === "config") {+ setTimeout(() => {+ session.accepted = true;+ socket.send(JSON.stringify({ type: "CONFIG_ACCEPTED", sessionId: "test-session" }));+ }, 50);+ } else if (message.type === "flush") {+ socket.send(JSON.stringify({ type: "flushed" }));+ }+ });+ });++ try {+ await run(`ws://127.0.0.1:${server.address().port}`, sessions);+ } finally {+ await new Promise((resolve) => server.close(resolve));+ }+}++test("audio sent before the config is accepted reaches the server after it, in order", async () => {+ await withCortiServer(async (url, sessions) => {+ const streaming = new CortiStreaming();+ streaming.buildWebSocketUrl = () => url;+ const frames = [1, 2, 3, 4, 5, 6].map((value) => Buffer.alloc(FRAME_BYTES, value));++ try {+ const connected = streaming.connect(OPTIONS);+ // The opening words of a cold start: offered while the socket connects,+ // then while it is open but the config is not yet accepted.+ for (const frame of frames.slice(0, 2)) streaming.sendAudio(frame);+ await once(streaming.ws, "open");+ for (const frame of frames.slice(2, 4)) streaming.sendAudio(frame);+ await connected;+ for (const frame of frames.slice(4)) streaming.sendAudio(frame);++ assert.deepEqual(await sessions[0].audio.received(6 * FRAME_BYTES), Buffer.concat(frames));+ assert.equal(sessions[0].audioBeforeAccept, 0, "Corti rejects audio sent before its ack");+ } finally {+ streaming.cleanup();+ }+ });+});++test("a client with no start in flight takes no audio", () => {+ const streaming = new CortiStreaming();+ assert.equal(streaming.sendAudio(Buffer.alloc(FRAME_BYTES)), false, "an idle client held audio");++ streaming.beginConnecting();+ streaming.cleanup(); // what a closed or failed socket runs+ assert.equal(streaming.sendAudio(Buffer.alloc(FRAME_BYTES)), false, "an ended start held audio");+});++test("a late CONFIG_ACCEPTED with no socket open does not throw", () => {+ // A stale socket's listener can deliver it (one whose start already timed+ // out) while a new start holds audio and has no socket of its own yet.+ const streaming = new CortiStreaming();+ streaming.beginConnecting();+ streaming.sendAudio(Buffer.alloc(FRAME_BYTES));++ assert.doesNotThrow(() =>+ streaming.handleMessage(Buffer.from(JSON.stringify({ type: "CONFIG_ACCEPTED" })))+ );+});++test("audio held before the config is accepted is capped at three seconds", () => {+ const streaming = new CortiStreaming();+ streaming.beginConnecting();++ // Five seconds of 50 ms frames at 16 kHz: the first three seconds are 60 frames.+ const held = Array.from({ length: 100 }, () => streaming.sendAudio(Buffer.alloc(FRAME_BYTES)));++ assert.deepEqual(held, [...Array(60).fill(true), ...Array(40).fill(false)]);+});++test("events from a socket this start replaced leave the start alone", () => {+ const streaming = new CortiStreaming();+ const staleSocket = new EventEmitter();+ streaming.attachSocketHandlers(staleSocket);+ streaming.beginConnecting();+ streaming.sendAudio(Buffer.alloc(FRAME_BYTES));++ staleSocket.emit("message", Buffer.from(JSON.stringify({ type: "CONFIG_ACCEPTED" })));+ staleSocket.emit("close", 1000, Buffer.alloc(0));++ assert.equal(streaming.configAccepted, false, "a stale ack marked the new start accepted");+ assert.equal(streaming.preConfigBufferSize, FRAME_BYTES, "a stale close wiped the held audio");+ assert.equal(streaming.sendAudio(Buffer.alloc(FRAME_BYTES)), true, "the start stopped holding");+});++test("a stop before the socket exists drops the audio the start was holding", async () => {+ const streaming = new CortiStreaming();+ streaming.beginConnecting();+ streaming.sendAudio(Buffer.alloc(FRAME_BYTES));++ await streaming.disconnect(true);++ assert.equal(+ streaming.sendAudio(Buffer.alloc(FRAME_BYTES)),+ false,+ "a stopped client held audio"+ );+ assert.equal(streaming.preConfigBufferSize, 0);+});diff --git a/test/helpers/harness/audioRecorder.js b/test/helpers/harness/audioRecorder.jsnew file mode 100644index 000000000..22c597b4e--- /dev/null+++ b/test/helpers/harness/audioRecorder.js@@ -0,0 +1,37 @@+const { deferred } = require("./deferred");++// Collects the binary audio a loopback provider receives. node:test has no+// default timeout, so the wait is bounded: withheld audio must fail the run+// rather than hang it.+function audioRecorder() {+ const chunks = [];+ let bytes = 0;+ let onChunk = () => {};+ return {+ record(data) {+ chunks.push(data);+ bytes += data.length;+ onChunk();+ },+ // Everything received, in order, once `expectedBytes` have arrived.+ async received(expectedBytes) {+ const arrived = deferred();+ onChunk = () => {+ if (bytes >= expectedBytes) arrived.resolve();+ };+ onChunk();+ await Promise.race([+ arrived.promise,+ new Promise((_, reject) =>+ setTimeout(+ () => reject(new Error(`only ${bytes} of ${expectedBytes} bytes reached the server`)),+ 2000+ ).unref()+ ),+ ]);+ return Buffer.concat(chunks);+ },+ };+}++module.exports = { audioRecorder };diff --git a/test/helpers/streamingStartAudioIpc.test.js b/test/helpers/streamingStartAudioIpc.test.jsnew file mode 100644index 000000000..1fb0a7646--- /dev/null+++ b/test/helpers/streamingStartAudioIpc.test.js@@ -0,0 +1,206 @@+const test = require("node:test");+const assert = require("node:assert/strict");+const fs = require("node:fs");+const os = require("node:os");+const path = require("node:path");+const Module = require("node:module");+const { WebSocketServer } = require("ws");++const AssemblyAiStreaming = require("../../src/helpers/assemblyAiStreaming");+const CortiStreaming = require("../../src/helpers/cortiStreaming");+const { audioRecorder } = require("./harness/audioRecorder");+const { deferred } = require("./harness/deferred");++// Runs the registered start/send/stop handlers with the real streaming clients+// against a loopback provider. Electron, the stored credentials, the token mint+// and the provider host are the only stand-ins.+const handlers = new Map();+const modulePath = require.resolve("../../src/helpers/ipcHandlers");+const originalLoad = Module._load;+const userDataDirectory = fs.mkdtempSync(path.join(os.tmpdir(), "streaming-start-audio-ipc-"));+const event = { sender: { id: 1 } };+// The audio each provider socket received, in the order the sockets opened.+const sockets = [];+let server;+// When set, the next token mint waits on it: the network round trip a start+// makes before its socket exists.+let pendingMint = null;+const mintToken = async (token) => {+ await pendingMint?.promise;+ return token;+};++const loopbackUrl = (provider) => `ws://127.0.0.1:${server.address().port}/${provider}`;++class LoopbackAssemblyAi extends AssemblyAiStreaming {+ buildWebSocketUrl(options) {+ return super+ .buildWebSocketUrl(options)+ .replace("wss://streaming.assemblyai.com/v3/ws", loopbackUrl("assemblyai"));+ }+}++class LoopbackCorti extends CortiStreaming {+ buildWebSocketUrl(options) {+ return super.buildWebSocketUrl(options).replace(/^wss:\/\/[^?]+/, loopbackUrl("corti"));+ }+}++const electron = {+ app: {+ getPath: () => userDataDirectory,+ getName: () => "test",+ getVersion: () => "0.0.0",+ isPackaged: false,+ on() {},+ },+ ipcMain: {+ handle: (channel, fn) => handlers.set(channel, fn),+ on: (channel, fn) => handlers.set(channel, fn),+ removeHandler() {},+ },+ BrowserWindow: { getAllWindows: () => [], fromWebContents: () => null },+ net: {+ // The only request a BYOK AssemblyAI start makes before it connects.+ fetch: async (url) => {+ assert.equal(url, "https://streaming.assemblyai.com/v3/token?expires_in_seconds=60");+ return Response.json({ token: await mintToken("assemblyai-token") });+ },+ },+ shell: {},+ dialog: {},+ screen: { getPrimaryDisplay: () => ({ workAreaSize: { width: 0, height: 0 } }) },+ systemPreferences: { getMediaAccessStatus: () => "granted" },+ session: { fromPartition: () => ({}) },+};++Module._load = function loadWithLoopback(request, parent, isMain) {+ if (request === "electron") return electron;+ if (parent?.filename === modulePath) {+ if (request === "./assemblyAiStreaming") return LoopbackAssemblyAi;+ if (request === "./cortiStreaming") return LoopbackCorti;+ }+ return originalLoad.call(this, request, parent, isMain);+};++function anything() {+ return new Proxy(function () {}, {+ get: (_target, property) => {+ if (property === Symbol.toPrimitive || property === "toString") return () => "";+ if (property === "then") return undefined;+ return anything();+ },+ apply: () => anything(),+ });+}++const target = {+ environmentManager: { getAssemblyAIKey: () => "byok-key" },+ assemblyAiStreaming: null,+ cortiStreaming: null,+ _mintStoredCortiToken: async (options) => ({+ token: await mintToken("corti-token"),+ environment: options.environment,+ tenant: options.tenant,+ }),+};++test.before(async () => {+ server = new WebSocketServer({ host: "127.0.0.1", port: 0 });+ await new Promise((resolve) => server.once("listening", resolve));+ server.on("connection", (socket, request) => {+ const audio = audioRecorder();+ sockets.push(audio);+ // AssemblyAI begins on connect; Corti waits for its config.+ if (request.url.startsWith("/assemblyai")) {+ socket.send(JSON.stringify({ type: "Begin", id: "test-session" }));+ }+ socket.on("message", (data, isBinary) => {+ if (isBinary) {+ audio.record(data);+ return;+ }+ const reply = {+ Terminate: { type: "Termination", audio_duration_seconds: 0 },+ config: { type: "CONFIG_ACCEPTED", sessionId: "test-session" },+ flush: { type: "flushed" },+ }[JSON.parse(data.toString()).type];+ if (reply) socket.send(JSON.stringify(reply));+ });+ });++ const IPCHandlers = require(modulePath);+ IPCHandlers.prototype.setupHandlers.call(+ new Proxy(target, {+ get: (value, property) => (property in value ? value[property] : anything()),+ })+ );+});++test.after(async () => {+ for (const client of server.clients) client.terminate();+ await new Promise((resolve) => server.close(resolve));+ Module._load = originalLoad;+ fs.rmSync(userDataDirectory, { recursive: true, force: true });+});++const PROVIDERS = [+ {+ name: "AssemblyAI",+ channel: "assemblyai",+ client: "assemblyAiStreaming",+ options: { mode: "byok" },+ },+ {+ name: "Corti",+ channel: "corti",+ client: "cortiStreaming",+ options: { environment: "us", tenant: "base" },+ },+];++for (const { name, channel, client, options } of PROVIDERS) {+ test(`${name} holds no audio once a start has failed`, async () => {+ let failMint;+ pendingMint = { promise: new Promise((_, reject) => (failMint = reject)) };+ const started = handlers.get(`${channel}-streaming-start`)(event, options);+ handlers.get(`${channel}-streaming-send`)(event, Buffer.alloc(1600));+ failMint(new Error("token request failed"));+ pendingMint = null;++ assert.equal((await started).success, false);+ // Nothing is in flight any more, so nothing may be held for a later session.+ assert.equal(target[client].sendAudio(Buffer.alloc(1600)), false);+ });++ for (const warm of [false, true]) {+ const socket = warm ? "warm socket" : "cold socket";+ test(`${name} keeps the audio sent while a start mints its token (${socket})`, async () => {+ if (warm) {+ const warmup = await handlers.get(`${channel}-streaming-warmup`)(event, options);+ assert.equal(warmup.success, true);+ }+ const openedBeforeStart = sockets.length;+ // Three 50 ms frames of the opening words, captured while the mint is in flight.+ const frames = [1, 2, 3].map((value) => Buffer.alloc(1600, value));++ pendingMint = deferred();+ const started = handlers.get(`${channel}-streaming-start`)(event, options);+ for (const frame of frames) handlers.get(`${channel}-streaming-send`)(event, frame);+ pendingMint.resolve();+ pendingMint = null;++ try {+ assert.equal((await started).success, true);+ assert.equal(+ sockets.length,+ openedBeforeStart + (warm ? 0 : 1),+ warm ? "the start must ride the warm socket" : "the start must open its own socket"+ );+ assert.deepEqual(await sockets.at(-1).received(4800), Buffer.concat(frames));+ } finally {+ await handlers.get(`${channel}-streaming-stop`)();+ }+ });+ }+}