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: meeting stream reconnect on session expiry + onnx worker packaging (#830)
Alcahest Malus Dienheimf629b07babcf
diff --git a/scripts/afterPack.js b/scripts/afterPack.jsindex 8ef405e8e..0840bf4c2 100644--- a/scripts/afterPack.js+++ b/scripts/afterPack.js@@ -10,8 +10,8 @@// user flags from ~/.config/open-whispr-flags.conf, and falls back to// --no-sandbox where the Chromium sandbox cannot work (AppImage/tar.gz// on distros that restrict unprivileged user namespaces).-// 3. Fails the build if required binaries (ffmpeg-static, ps-list vendor exe)-// are missing from app.asar.unpacked/.+// 3. Fails the build if required binaries (ffmpeg-static, ps-list vendor exe,+// onnx worker script) are missing from app.asar.unpacked/.const fs = require("fs");const path = require("path");@@ -203,11 +203,8 @@ function verifyMeetingAecHelper(context) {}function verifyUnpackedBinaries(context) {- const unpackedModulesDir = path.join(- resolveResourcesDir(context),- "app.asar.unpacked",- "node_modules"- );+ const unpackedDir = path.join(resolveResourcesDir(context), "app.asar.unpacked");+ const unpackedModulesDir = path.join(unpackedDir, "node_modules");const isWindows = context.electronPlatformName === "win32";@@ -222,6 +219,13 @@ function verifyUnpackedBinaries(context) {);}+ const onnxWorkerPath = path.join(unpackedDir, "src", "workers", "onnxWorker.js");+ if (!fs.existsSync(onnxWorkerPath)) {+ throw new Error(+ `afterPack: missing ${onnxWorkerPath} — src/workers was not unpacked from app.asar (asarUnpack/packaging failure); the ONNX utility process would crash-loop in the packed app`+ );+ }+// electron-builder strips *.exe from node_modules on non-Windows targets,// so the ps-list vendor executable only exists in Windows builds.if (isWindows) {diff --git a/src/helpers/ipcHandlers.js b/src/helpers/ipcHandlers.jsindex 8db80f35c..ff7c2ea00 100644--- a/src/helpers/ipcHandlers.js+++ b/src/helpers/ipcHandlers.js@@ -4488,6 +4488,119 @@ class IPCHandlers {streaming.onError = (error) => {send("meeting-transcription-error", error.message);};+ streaming.onSessionExpired = () => reconnectMeetingStreams();+ };++ const reconnectMeetingStreams = async () => {+ if (meetingReconnecting || meetingLocalMode) return;++ const options = meetingConnectionOptions;+ const win = meetingConnectionWin;+ if (!options || !win || win.isDestroyed()) {+ debugLogger.error("Cannot reconnect meeting streams: missing connection context");+ return;+ }++ if (meetingReconnectCount >= MAX_MEETING_RECONNECTS) {+ debugLogger.error("Meeting reconnect limit reached", { count: meetingReconnectCount });+ win.webContents.send(+ "meeting-transcription-error",+ "Session reconnect limit reached. Please stop and restart the recording."+ );+ return;+ }++ meetingReconnecting = true;+ meetingReconnectCount++;++ const StreamingClass =+ STREAMING_CLIENT_BY_PROVIDER[options.provider] ?? OpenAIRealtimeStreaming;++ const oldMic = this._meetingMicStreaming;+ const oldSystem = this._meetingSystemStreaming;++ // Swap fresh instances in before the token fetch so audio arriving during+ // the swap lands in their pre-connect buffers instead of a dead socket.+ const newMic = new StreamingClass();+ newMic.beginConnecting?.();+ attachMeetingStreamingHandlers(newMic, win, "mic");+ this._meetingMicStreaming = newMic;+ let newSystem = null;+ if (oldSystem) {+ newSystem = new StreamingClass();+ newSystem.beginConnecting?.();+ attachMeetingStreamingHandlers(newSystem, win, "system");+ this._meetingSystemStreaming = newSystem;+ }++ debugLogger.info("Reconnecting meeting streams", {+ attempt: meetingReconnectCount,+ maxAttempts: MAX_MEETING_RECONNECTS,+ });++ const tokenEvent = { sender: win.webContents };+ try {+ const connectOpts = {+ model: options.model,+ language: options.language,+ preconfigured: options.mode !== "byok",+ environment: options.environment,+ tenant: options.tenant,+ keyterms: options.keyterms,+ sampleRate: MEETING_STREAM_SAMPLE_RATE,+ };++ let pairs;+ if (newSystem) {+ const secrets = await fetchRealtimeToken(tokenEvent, options, { streams: 2 });+ pairs = [+ { streaming: newMic, secret: secrets[0] },+ { streaming: newSystem, secret: secrets[1] },+ ];+ } else {+ pairs = [{ streaming: newMic, secret: await fetchRealtimeToken(tokenEvent, options) }];+ }++ await Promise.all(+ pairs.map(({ streaming, secret }) =>+ streaming.connect({ apiKey: secret, token: secret, ...connectOpts })+ )+ );++ if (meetingConnectionOptions !== options) {+ // Recording stopped while the reconnect was in flight.+ for (const { streaming } of pairs) streaming.disconnect().catch(() => {});+ oldMic?.disconnect().catch(() => {});+ oldSystem?.disconnect().catch(() => {});+ return;+ }++ oldMic?.disconnect().catch(() => {});+ oldSystem?.disconnect().catch(() => {});++ debugLogger.info("Meeting streams reconnected", { attempt: meetingReconnectCount });+ } catch (error) {+ debugLogger.error("Meeting stream reconnect failed", {+ error: error.message,+ attempt: meetingReconnectCount,+ });+ newMic.disconnect().catch(() => {});+ newSystem?.disconnect().catch(() => {});+ if (meetingConnectionOptions === options) {+ // A proactive reconnect leaves the old connections open; restore them+ // so transcription continues until the hard limit retries this path.+ this._meetingMicStreaming = oldMic;+ this._meetingSystemStreaming = oldSystem;+ if (!win.isDestroyed()) {+ win.webContents.send("meeting-transcription-error", error.message);+ }+ } else {+ oldMic?.disconnect().catch(() => {});+ oldSystem?.disconnect().catch(() => {});+ }+ } finally {+ meetingReconnecting = false;+ }};const fetchRealtimeToken = async (event, options, { streams } = {}) => {@@ -4713,6 +4826,11 @@ class IPCHandlers {let meetingStartedAt = null;let meetingSendCounts = { mic: 0, system: 0 };const meetingEchoLeakDetector = new MeetingEchoLeakDetector();+ let meetingReconnecting = false;+ let meetingReconnectCount = 0;+ const MAX_MEETING_RECONNECTS = 5;+ let meetingConnectionOptions = null;+ let meetingConnectionWin = null;const fs = require("fs");let meetingDiarizationStream = null;@@ -5415,6 +5533,10 @@ class IPCHandlers {resetPendingMicFinals();meetingAecEnabled = false;meetingEchoLeakDetector.reset();+ meetingReconnecting = false;+ meetingReconnectCount = 0;+ meetingConnectionOptions = null;+ meetingConnectionWin = null;};const disconnectMeetingStreaming = async ({ flushPending = false } = {}) => {@@ -5619,6 +5741,9 @@ class IPCHandlers {meetingTranscriptionStartInProgress = true;meetingStartedAt = Date.now();+ meetingConnectionOptions = options;+ meetingConnectionWin = BrowserWindow.fromWebContents(event.sender);+ meetingReconnectCount = 0;this.meetingDetectionEngine?.setUserRecording(true);try {const systemAudioPlan = await getMeetingSystemAudioPlan();diff --git a/src/helpers/onnxWorkerClient.js b/src/helpers/onnxWorkerClient.jsindex a3222ff8c..deee39127 100644--- a/src/helpers/onnxWorkerClient.js+++ b/src/helpers/onnxWorkerClient.js@@ -8,6 +8,8 @@ const RESPAWN_BACKOFF_MS = [1000, 2000, 4000, 8000, 16000, 30000];const MAX_RESPAWN_ATTEMPTS = 5;const SHUTDOWN_TIMEOUT_MS = 5000;+// Forked via the asar-virtual path: Electron redirects the unpacked file read+// while module resolution stays inside app.asar (onnxruntime-common is asar-only).const WORKER_SCRIPT = path.join(__dirname, "..", "workers", "onnxWorker.js");class WorkerCrashedError extends Error {diff --git a/src/helpers/openaiRealtimeStreaming.js b/src/helpers/openaiRealtimeStreaming.jsindex e038e174b..e4aefcb68 100644--- a/src/helpers/openaiRealtimeStreaming.js+++ b/src/helpers/openaiRealtimeStreaming.js@@ -6,6 +6,8 @@ const DISCONNECT_TIMEOUT_MS = 3000;const SAMPLE_RATE = 24000;const COLD_START_BUFFER_MAX = 3 * SAMPLE_RATE * 2; // 3 seconds of 16-bit PCMconst KEEPALIVE_INTERVAL_MS = 15000;+// OpenAI Realtime sessions die at 60 minutes; reconnect proactively before that.+const SESSION_PREEMPT_MS = 55 * 60 * 1000;// A socket factory does network work before the socket exists, so the dial// must be bounded; a socket resolving after the deadline is closed, not leaked.@@ -36,6 +38,9 @@ class OpenAIRealtimeStreaming {this.onFinalTranscript = null;this.onError = null;this.onSessionEnd = null;+ this.onSessionExpired = null;+ this._sessionExpired = false;+ this._sessionTimer = null;this.pendingResolve = null;this.pendingReject = null;this.connectionTimeout = null;@@ -86,6 +91,7 @@ class OpenAIRealtimeStreaming {this.currentPartial = "";this.audioBytesSent = 0;this.speechStartedAt = null;+ this._sessionExpired = false;const url = "wss://api.openai.com/v1/realtime?intent=transcription";debugLogger.debug("OpenAI Realtime connecting", { model: this.model });@@ -148,7 +154,7 @@ class OpenAIRealtimeStreaming {this.pendingResolve = null;}this.cleanup();- if (wasActive && !this.isDisconnecting) {+ if (wasActive && !this.isDisconnecting && !this._sessionExpired) {this.onSessionEnd?.({ text: this.getFullTranscript() });}});@@ -246,6 +252,14 @@ class OpenAIRealtimeStreaming {case "error": {const errCode = event.error?.code;const errMsg = event.error?.message || "OpenAI Realtime error";+ // Only consumers that attach onSessionExpired (meetings) get the+ // reconnect path; others (dictation) keep the onError/onSessionEnd flow.+ if (errCode === "session_expired" && this.onSessionExpired) {+ debugLogger.warn("OpenAI Realtime session expired", { message: errMsg });+ this._sessionExpired = true;+ this.onSessionExpired();+ break;+ }const isEmptyBuffer =errCode === "input_audio_buffer_commit_empty" ||errMsg.includes("buffer too small") ||@@ -277,6 +291,7 @@ class OpenAIRealtimeStreaming {this.isConnecting = false;clearTimeout(this.connectionTimeout);this.startKeepAlive();+ this._startSessionTimer();if (this.pendingResolve) {this.pendingResolve();this.pendingResolve = null;@@ -284,6 +299,15 @@ class OpenAIRealtimeStreaming {}}+ _startSessionTimer() {+ clearTimeout(this._sessionTimer);+ this._sessionTimer = setTimeout(() => {+ if (!this.isConnected) return;+ debugLogger.debug("OpenAI Realtime session approaching 60min limit, requesting reconnect");+ this.onSessionExpired?.();+ }, SESSION_PREEMPT_MS);+ }+// A warm connection sits idle between dictations for up to 5 minutes and is// reused with no other liveness check; a network path that dies silently// (NAT/firewall drop, sleep/wake, VPN toggle) leaves isConnected stuck true@@ -450,6 +474,8 @@ class OpenAIRealtimeStreaming {cleanup() {clearTimeout(this.connectionTimeout);this.connectionTimeout = null;+ clearTimeout(this._sessionTimer);+ this._sessionTimer = null;this.stopKeepAlive();if (this.ws) {diff --git a/test/helpers/openaiRealtimeStreaming.test.js b/test/helpers/openaiRealtimeStreaming.test.jsindex c003cb44f..9b75ebaf3 100644--- a/test/helpers/openaiRealtimeStreaming.test.js+++ b/test/helpers/openaiRealtimeStreaming.test.js@@ -21,6 +21,18 @@ function makeFakeSocket(readyState) {return socket;}+async function connectPreconfigured(streaming, socket) {+ const connected = streaming.connect({+ apiKey: "key",+ preconfigured: true,+ createSocket: async () => socket,+ });+ await new Promise((resolve) => setImmediate(resolve));+ socket.readyState = WS.OPEN;+ socket.emit("message", JSON.stringify({ type: "session.created" }));+ await connected;+}+test("sendAudio buffers frames arriving before the socket exists (token-fetch window)", async () => {const OpenAIRealtimeStreaming = (await load()).default;const streaming = new OpenAIRealtimeStreaming();@@ -204,3 +216,305 @@ test("keep-alive stays alive when a pong is received between pings", (t) => {assert.equal(terminated, false);})();});++// -- session expiry (60-minute OpenAI Realtime session limit) --++test("session_expired error fires onSessionExpired instead of onError and sets the flag", async () => {+ const OpenAIRealtimeStreaming = (await load()).default;+ const streaming = new OpenAIRealtimeStreaming();+ let expiredCalled = false;+ let errorCalled = false;+ streaming.onSessionExpired = () => {+ expiredCalled = true;+ };+ streaming.onError = () => {+ errorCalled = true;+ };++ streaming.handleMessage(+ JSON.stringify({+ type: "error",+ error: { code: "session_expired", message: "Your session hit the maximum duration." },+ })+ );++ assert.equal(expiredCalled, true);+ assert.equal(errorCalled, false);+ assert.equal(streaming._sessionExpired, true);+});++test("session_expired without an onSessionExpired handler falls through to onError (dictation path)", async () => {+ const OpenAIRealtimeStreaming = (await load()).default;+ const streaming = new OpenAIRealtimeStreaming();+ let errorMessage = null;+ streaming.onError = (err) => {+ errorMessage = err.message;+ };++ streaming.handleMessage(+ JSON.stringify({+ type: "error",+ error: { code: "session_expired", message: "Your session hit the maximum duration." },+ })+ );++ assert.equal(errorMessage, "Your session hit the maximum duration.");+ assert.equal(streaming._sessionExpired, false);+});++test("non-session_expired error fires onError normally", async () => {+ const OpenAIRealtimeStreaming = (await load()).default;+ const streaming = new OpenAIRealtimeStreaming();+ let errorMsg = null;+ streaming.onError = (err) => {+ errorMsg = err.message;+ };++ streaming.handleMessage(+ JSON.stringify({+ type: "error",+ error: { code: "server_error", message: "something broke" },+ })+ );++ assert.equal(errorMsg, "something broke");+});++test("empty buffer error is not treated as session expiry", async () => {+ const OpenAIRealtimeStreaming = (await load()).default;+ const streaming = new OpenAIRealtimeStreaming();+ let expiredCalled = false;+ let errorCalled = false;+ streaming.onSessionExpired = () => {+ expiredCalled = true;+ };+ streaming.onError = () => {+ errorCalled = true;+ };++ streaming.handleMessage(+ JSON.stringify({+ type: "error",+ error: { code: "input_audio_buffer_commit_empty", message: "buffer too small" },+ })+ );++ assert.equal(expiredCalled, false);+ assert.equal(errorCalled, true);+});++test("close after session_expired does not fire onSessionEnd (reconnect owns the session)", async () => {+ const OpenAIRealtimeStreaming = (await load()).default;+ const streaming = new OpenAIRealtimeStreaming();+ const socket = makeFakeSocket(WS.CONNECTING);+ await connectPreconfigured(streaming, socket);++ let sessionEndCalled = false;+ streaming.onSessionEnd = () => {+ sessionEndCalled = true;+ };+ streaming.onSessionExpired = () => {};++ socket.emit(+ "message",+ JSON.stringify({ type: "error", error: { code: "session_expired", message: "expired" } })+ );+ socket.emit("close", 1000, Buffer.from(""));++ assert.equal(sessionEndCalled, false);+});++test("connect() resets _sessionExpired left over from a previous session", async () => {+ const OpenAIRealtimeStreaming = (await load()).default;+ const streaming = new OpenAIRealtimeStreaming();+ streaming._sessionExpired = true;++ const socket = makeFakeSocket(WS.CONNECTING);+ const connected = streaming.connect({+ apiKey: "key",+ preconfigured: true,+ createSocket: async () => socket,+ });+ assert.equal(streaming._sessionExpired, false, "flag must reset synchronously in connect()");++ await new Promise((resolve) => setImmediate(resolve));+ socket.readyState = WS.OPEN;+ socket.emit("message", JSON.stringify({ type: "session.created" }));+ await connected;+ streaming.cleanup();+});++// -- proactive session timer (fires before the 60-minute limit) --++test("session timer fires onSessionExpired at the pre-empt deadline while connected", (t) => {+ t.mock.timers.enable({ apis: ["setTimeout"] });+ return (async () => {+ const OpenAIRealtimeStreaming = (await load()).default;+ const streaming = new OpenAIRealtimeStreaming();+ streaming.isConnected = true;+ let expiredCalls = 0;+ streaming.onSessionExpired = () => {+ expiredCalls += 1;+ };++ streaming._startSessionTimer();++ t.mock.timers.tick(55 * 60 * 1000 - 1);+ assert.equal(expiredCalls, 0);+ t.mock.timers.tick(1);+ assert.equal(expiredCalls, 1);+ })();+});++test("cleanup() clears the session timer so a stopped session never requests a reconnect", (t) => {+ t.mock.timers.enable({ apis: ["setTimeout"] });+ return (async () => {+ const OpenAIRealtimeStreaming = (await load()).default;+ const streaming = new OpenAIRealtimeStreaming();+ streaming.isConnected = true;+ let expiredCalls = 0;+ streaming.onSessionExpired = () => {+ expiredCalls += 1;+ };++ streaming._startSessionTimer();+ streaming.cleanup();+ assert.equal(streaming._sessionTimer, null);++ t.mock.timers.tick(55 * 60 * 1000);+ assert.equal(expiredCalls, 0);+ })();+});++// -- reconnect flow: audio accounting across the session boundary --++test("zero audio loss during reactive reconnect (session_expired at 60min)", async () => {+ const OpenAIRealtimeStreaming = (await load()).default;+ const CHUNK = Buffer.alloc(480);++ // Phase 1: old instance streaming normally.+ const old = new OpenAIRealtimeStreaming();+ old.isConnected = true;+ old.ws = makeFakeSocket(WS.OPEN);+ for (let i = 0; i < 100; i++) old.sendAudio(CHUNK);+ assert.equal(old.ws.sent.length, 100, "all chunks sent to old ws");+ const oldSent = old.ws.sent;++ // Phase 2: session_expired fires, server closes the old ws.+ let expiredFired = false;+ old.onSessionExpired = () => {+ expiredFired = true;+ };+ old.handleMessage(+ JSON.stringify({ type: "error", error: { code: "session_expired", message: "60 minutes" } })+ );+ assert.equal(expiredFired, true);+ old.cleanup();+ assert.equal(+ old.sendAudio(CHUNK),+ false,+ "dead instance drops audio, but the swap already happened"+ );++ // Phase 3: reconnect swaps in a fresh instance before the token fetch;+ // beginConnecting() arms the pre-connect buffer for the fetch window.+ const fresh = new OpenAIRealtimeStreaming();+ fresh.beginConnecting();+ for (let i = 0; i < 50; i++) fresh.sendAudio(CHUNK);+ assert.equal(fresh.coldStartBuffer.length, 50, "pre-connect buffer caught all chunks");+ assert.equal(fresh.coldStartBufferSize, 50 * 480);++ // Phase 4: token received, socket still connecting.+ fresh.ws = makeFakeSocket(WS.CONNECTING);+ for (let i = 0; i < 20; i++) fresh.sendAudio(CHUNK);+ assert.equal(fresh.coldStartBuffer.length, 70, "buffer holds pre-connect + connecting chunks");++ // Phase 5: socket opens, next sendAudio flushes everything.+ fresh.ws = makeFakeSocket(WS.OPEN);+ fresh.sendAudio(CHUNK);+ assert.equal(fresh.coldStartBuffer.length, 0, "buffer flushed");+ assert.equal(fresh.ws.sent.length, 71, "all buffered + live chunks sent to new ws");++ assert.equal(oldSent.length + fresh.ws.sent.length, 171, "zero chunks dropped");+});++test("zero audio loss during proactive reconnect (timer before the limit)", async () => {+ const OpenAIRealtimeStreaming = (await load()).default;+ const CHUNK = Buffer.alloc(480);++ // Old instance still alive while the reconnect fetches a token.+ const old = new OpenAIRealtimeStreaming();+ old.isConnected = true;+ old.ws = makeFakeSocket(WS.OPEN);+ for (let i = 0; i < 100; i++) old.sendAudio(CHUNK);++ // Audio dispatched between the timer firing and the instance swap still+ // reaches the old, healthy connection.+ for (let i = 0; i < 10; i++) old.sendAudio(CHUNK);+ assert.equal(old.ws.sent.length, 110, "audio still flows to old instance during token fetch");++ // References swapped; new instance buffers until its socket opens.+ const fresh = new OpenAIRealtimeStreaming();+ fresh.beginConnecting();+ for (let i = 0; i < 30; i++) fresh.sendAudio(CHUNK);+ assert.equal(fresh.coldStartBuffer.length, 30);++ fresh.ws = makeFakeSocket(WS.OPEN);+ fresh.sendAudio(CHUNK);+ assert.equal(fresh.ws.sent.length, 31, "30 flushed + 1 live");+ assert.equal(fresh.coldStartBuffer.length, 0);++ assert.equal(old.ws.sent.length + fresh.ws.sent.length, 141, "zero chunks dropped");+});++test("concurrent session_expired from mic and system streams only reconnects once", async () => {+ const OpenAIRealtimeStreaming = (await load()).default;++ // Mirrors the meetingReconnecting guard in ipcHandlers.+ let reconnectCalls = 0;+ let reconnecting = false;+ const guardedReconnect = () => {+ if (reconnecting) return;+ reconnecting = true;+ reconnectCalls++;+ };++ const mic = new OpenAIRealtimeStreaming();+ const system = new OpenAIRealtimeStreaming();+ mic.onSessionExpired = guardedReconnect;+ system.onSessionExpired = guardedReconnect;++ const expiredEvent = JSON.stringify({+ type: "error",+ error: { code: "session_expired", message: "expired" },+ });+ mic.handleMessage(expiredEvent);+ system.handleMessage(expiredEvent);++ assert.equal(reconnectCalls, 1, "reconnect called exactly once despite two streams expiring");+});++test("completedSegments accumulate across turns", async () => {+ const OpenAIRealtimeStreaming = (await load()).default;+ const streaming = new OpenAIRealtimeStreaming();+ let lastFull = "";+ streaming.onFinalTranscript = (text) => {+ lastFull = text;+ };++ streaming.handleMessage(+ JSON.stringify({+ type: "conversation.item.input_audio_transcription.completed",+ transcript: "Hello world",+ })+ );+ streaming.handleMessage(+ JSON.stringify({+ type: "conversation.item.input_audio_transcription.completed",+ transcript: "How are you",+ })+ );++ assert.equal(streaming.completedSegments.length, 2);+ assert.equal(lastFull, "Hello world How are you");+});