Skip to content

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

feat: pre-warm meeting transcription WebSocket for instant recording start

Gabriel Stein9c7a211b1b29
diff --git a/preload.js b/preload.js
index 024ca0cb2..0bb4c8a19 100644
--- a/preload.js
+++ b/preload.js
@@ -446,6 +446,8 @@ contextBridge.exposeInMainWorld("electronAPI", {
ipcRenderer.invoke("meeting-transcribe-chain", blobUrl, opts),
// Meeting transcription (streaming)
+ meetingTranscriptionPrepare: (options) =>
+ ipcRenderer.invoke("meeting-transcription-prepare", options),
meetingTranscriptionStart: (options) =>
ipcRenderer.invoke("meeting-transcription-start", options),
meetingTranscriptionSend: (buffer) => ipcRenderer.send("meeting-transcription-send", buffer),
diff --git a/src/components/notes/PersonalNotesView.tsx b/src/components/notes/PersonalNotesView.tsx
index fe2d57772..216501b37 100644
--- a/src/components/notes/PersonalNotesView.tsx
+++ b/src/components/notes/PersonalNotesView.tsx
@@ -88,6 +88,7 @@ export default function PersonalNotesView({
transcript: meetingTranscript,
partialTranscript: meetingPartialTranscript,
error: meetingError,
+ prepareTranscription: prepareMeetingTranscription,
startTranscription: startMeetingTranscription,
stopTranscription: stopMeetingTranscription,
} = useMeetingTranscription();
@@ -334,6 +335,13 @@ export default function PersonalNotesView({
[activeNoteId]
);
+ // Pre-warm WebSocket when entering meeting mode (before user hits record)
+ useEffect(() => {
+ if (isMeetingMode) {
+ prepareMeetingTranscription();
+ }
+ }, [isMeetingMode, prepareMeetingTranscription]);
+
useEffect(() => {
if (!meetingRecordingRequest || activeNoteId !== meetingRecordingRequest.noteId) return;
setActiveMeetingEvent(meetingRecordingRequest.event);
diff --git a/src/components/ui/TranscriptionItem.tsx b/src/components/ui/TranscriptionItem.tsx
index 589c63a8f..e726f82ad 100644
--- a/src/components/ui/TranscriptionItem.tsx
+++ b/src/components/ui/TranscriptionItem.tsx
@@ -21,6 +21,7 @@ interface TranscriptionItemProps {
onDelete: (id: number) => void;
onShowAudioInFolder?: (id: number) => void;
onRetryTranscription?: (id: number) => Promise<void>;
+ onOpenSettings?: () => void;
}
export default function TranscriptionItem({
@@ -29,6 +30,7 @@ export default function TranscriptionItem({
onDelete,
onShowAudioInFolder,
onRetryTranscription,
+ onOpenSettings,
}: TranscriptionItemProps) {
const { t, i18n } = useTranslation();
const [isHovered, setIsHovered] = useState(false);
@@ -78,8 +80,8 @@ export default function TranscriptionItem({
)}
{isFailed ? (
- <div className="flex-1 min-w-0 flex items-center gap-2">
- <AlertCircle size={14} className="shrink-0 text-destructive" />
+ <div className="flex-1 min-w-0 flex items-start gap-2">
+ <AlertCircle size={14} className="shrink-0 text-destructive mt-0.5" />
<div className="min-w-0">
<p className="text-sm text-destructive font-medium">
{t("controlPanel.history.transcriptionFailed")}
@@ -89,6 +91,26 @@ export default function TranscriptionItem({
{item.error_message}
</p>
)}
+ <p className="text-xs text-muted-foreground mt-1">
+ {hasAudio ? (
+ <>
+ <button
+ onClick={() => onOpenSettings?.()}
+ className="text-primary hover:underline cursor-pointer"
+ >
+ {t("controlPanel.history.failedCtaSettings")}
+ </button>{" "}
+ {t("controlPanel.history.failedCtaAndRetry")}
+ </>
+ ) : (
+ <button
+ onClick={() => onOpenSettings?.()}
+ className="text-primary hover:underline cursor-pointer"
+ >
+ {t("controlPanel.history.failedCtaSettingsOnly")}
+ </button>
+ )}
+ </p>
</div>
</div>
) : (
diff --git a/src/helpers/ipcHandlers.js b/src/helpers/ipcHandlers.js
index 4981113b6..e4f62da78 100644
--- a/src/helpers/ipcHandlers.js
+++ b/src/helpers/ipcHandlers.js
@@ -2189,74 +2189,131 @@ class IPCHandlers {
});
let meetingTranscriptionStartInProgress = false;
+ let meetingTranscriptionPrepareInProgress = false;
+ let meetingTranscriptionPreparePromise = null;
- ipcMain.handle("meeting-transcription-start", async (event, options = {}) => {
- if (meetingTranscriptionStartInProgress) {
- debugLogger.debug("Meeting transcription start already in progress, ignoring");
- return { success: false, error: "Operation in progress" };
+ const attachMeetingStreamingHandlers = (streaming, win) => {
+ streaming.onPartialTranscript = (text) => {
+ if (win && !win.isDestroyed()) {
+ win.webContents.send("meeting-transcription-partial", text);
+ }
+ };
+ streaming.onFinalTranscript = (text) => {
+ if (win && !win.isDestroyed()) {
+ win.webContents.send("meeting-transcription-final", text);
+ }
+ };
+ streaming.onError = (error) => {
+ if (win && !win.isDestroyed()) {
+ win.webContents.send("meeting-transcription-error", error.message);
+ }
+ };
+ };
+
+ const fetchRealtimeToken = async (event, options) => {
+ const apiUrl = getApiUrl();
+ if (!apiUrl) throw new Error("OpenWhispr API URL not configured");
+
+ const cookieHeader = await getSessionCookies(event);
+ if (!cookieHeader) throw new Error("No session cookies available");
+
+ const tokenResponse = await fetch(`${apiUrl}/api/openai-realtime-token`, {
+ method: "POST",
+ headers: { "Content-Type": "application/json", Cookie: cookieHeader },
+ body: JSON.stringify({ model: options.model, language: options.language }),
+ });
+
+ if (!tokenResponse.ok) {
+ const err = await tokenResponse.json().catch(() => ({}));
+ throw new Error(err.error || `Token request failed: ${tokenResponse.status}`);
}
- meetingTranscriptionStartInProgress = true;
- try {
- const win = BrowserWindow.fromWebContents(event.sender);
+ const { clientSecret } = await tokenResponse.json();
+ if (!clientSecret) throw new Error("No client secret received");
+ return clientSecret;
+ };
- if (options.provider !== "openai-realtime") {
- return { success: false, error: `Unsupported provider: ${options.provider}` };
- }
+ const connectRealtimeStreaming = async (event, options) => {
+ if (this.openaiRealtimeStreaming?.isConnected) {
+ await this.openaiRealtimeStreaming.disconnect();
+ }
- const apiUrl = getApiUrl();
- if (!apiUrl) return { success: false, error: "OpenWhispr API URL not configured" };
+ const clientSecret = await fetchRealtimeToken(event, options);
+ this.openaiRealtimeStreaming = new OpenAIRealtimeStreaming();
- const cookieHeader = await getSessionCookies(event);
- if (!cookieHeader) return { success: false, error: "No session cookies available" };
+ const win = BrowserWindow.fromWebContents(event.sender);
+ attachMeetingStreamingHandlers(this.openaiRealtimeStreaming, win);
- const tokenResponse = await fetch(`${apiUrl}/api/openai-realtime-token`, {
- method: "POST",
- headers: { "Content-Type": "application/json", Cookie: cookieHeader },
- body: JSON.stringify({ model: options.model, language: options.language }),
- });
+ await this.openaiRealtimeStreaming.connect({
+ apiKey: clientSecret,
+ model: options.model,
+ language: options.language,
+ });
- if (!tokenResponse.ok) {
- const err = await tokenResponse.json().catch(() => ({}));
- return {
- success: false,
- error: err.error || `Token request failed: ${tokenResponse.status}`,
- };
- }
+ return win;
+ };
+
+ // Pre-warm: fetch token + connect WebSocket before user hits record
+ ipcMain.handle("meeting-transcription-prepare", async (event, options = {}) => {
+ if (meetingTranscriptionPrepareInProgress || meetingTranscriptionStartInProgress) {
+ debugLogger.debug("Meeting transcription prepare already in progress, ignoring");
+ return { success: false, error: "Operation in progress" };
+ }
- const { clientSecret } = await tokenResponse.json();
- if (!clientSecret) return { success: false, error: "No client secret received" };
+ if (this.openaiRealtimeStreaming?.isConnected) {
+ debugLogger.debug("Meeting transcription already prepared (warm connection)");
+ return { success: true, alreadyPrepared: true };
+ }
- if (this.openaiRealtimeStreaming?.isConnected) {
- await this.openaiRealtimeStreaming.disconnect();
+ if (options.provider !== "openai-realtime") {
+ return { success: false, error: `Unsupported provider: ${options.provider}` };
+ }
+
+ meetingTranscriptionPrepareInProgress = true;
+ meetingTranscriptionPreparePromise = (async () => {
+ try {
+ await connectRealtimeStreaming(event, options);
+ debugLogger.debug("Meeting transcription prepared (WebSocket warm)");
+ return { success: true };
+ } catch (error) {
+ debugLogger.error("Meeting transcription prepare error", { error: error.message });
+ return { success: false, error: error.message };
+ } finally {
+ meetingTranscriptionPrepareInProgress = false;
+ meetingTranscriptionPreparePromise = null;
}
+ })();
- this.openaiRealtimeStreaming = new OpenAIRealtimeStreaming();
+ return meetingTranscriptionPreparePromise;
+ });
- this.openaiRealtimeStreaming.onPartialTranscript = (text) => {
- if (win && !win.isDestroyed()) {
- win.webContents.send("meeting-transcription-partial", text);
- }
- };
+ ipcMain.handle("meeting-transcription-start", async (event, options = {}) => {
+ // Wait for any in-flight prepare to finish before starting
+ if (meetingTranscriptionPreparePromise) {
+ debugLogger.debug("Meeting transcription start: waiting for in-flight prepare");
+ await meetingTranscriptionPreparePromise;
+ }
- this.openaiRealtimeStreaming.onFinalTranscript = (text) => {
- if (win && !win.isDestroyed()) {
- win.webContents.send("meeting-transcription-final", text);
- }
- };
+ if (meetingTranscriptionStartInProgress) {
+ debugLogger.debug("Meeting transcription start already in progress, ignoring");
+ return { success: false, error: "Operation in progress" };
+ }
- this.openaiRealtimeStreaming.onError = (error) => {
- if (win && !win.isDestroyed()) {
- win.webContents.send("meeting-transcription-error", error.message);
- }
- };
+ meetingTranscriptionStartInProgress = true;
+ try {
+ // If already prepared (warm connection from prepare), just re-attach handlers
+ if (this.openaiRealtimeStreaming?.isConnected) {
+ debugLogger.debug("Meeting transcription start: reusing warm connection");
+ const win = BrowserWindow.fromWebContents(event.sender);
+ attachMeetingStreamingHandlers(this.openaiRealtimeStreaming, win);
+ return { success: true };
+ }
- await this.openaiRealtimeStreaming.connect({
- apiKey: clientSecret,
- model: options.model,
- language: options.language,
- });
+ if (options.provider !== "openai-realtime") {
+ return { success: false, error: `Unsupported provider: ${options.provider}` };
+ }
+ await connectRealtimeStreaming(event, options);
return { success: true };
} catch (error) {
debugLogger.error("Meeting transcription start error", { error: error.message });
diff --git a/src/hooks/useMeetingTranscription.ts b/src/hooks/useMeetingTranscription.ts
index a2aabdbb4..aa69d70a3 100644
--- a/src/hooks/useMeetingTranscription.ts
+++ b/src/hooks/useMeetingTranscription.ts
@@ -8,6 +8,7 @@ interface UseMeetingTranscriptionReturn {
transcript: string;
partialTranscript: string;
error: string | null;
+ prepareTranscription: () => Promise<void>;
startTranscription: () => Promise<void>;
stopTranscription: () => Promise<void>;
}
@@ -229,6 +230,8 @@ export function useMeetingTranscription(): UseMeetingTranscriptionReturn {
const micStreamRef = useRef<MediaStream | null>(null);
const isRecordingRef = useRef(false);
const isStartingRef = useRef(false);
+ const isPreparedRef = useRef(false);
+ const preparePromiseRef = useRef<Promise<void> | null>(null);
const ipcCleanupsRef = useRef<Array<() => void>>([]);
const cleanup = useCallback(async () => {
@@ -282,14 +285,18 @@ export function useMeetingTranscription(): UseMeetingTranscriptionReturn {
ipcCleanupsRef.current.forEach((fn) => fn());
ipcCleanupsRef.current = [];
+ isPreparedRef.current = false;
}, []);
const stopTranscription = useCallback(async () => {
if (!isRecordingRef.current) return;
+
+ // Signal stop immediately so in-flight startTranscription can abort
+ isRecordingRef.current = false;
+ isStartingRef.current = false;
setIsRecording(false);
await cleanup();
- isRecordingRef.current = false;
try {
const result = await window.electronAPI?.meetingTranscriptionStop?.();
@@ -310,6 +317,44 @@ export function useMeetingTranscription(): UseMeetingTranscriptionReturn {
logger.info("Meeting transcription stopped", {}, "meeting");
}, [cleanup]);
+ const prepareTranscription = useCallback(async () => {
+ if (isPreparedRef.current || isRecordingRef.current || isStartingRef.current) return;
+ if (preparePromiseRef.current) return; // already preparing
+
+ logger.info("Meeting transcription preparing (pre-warming WebSocket)...", {}, "meeting");
+
+ const promise = (async () => {
+ try {
+ const result = await window.electronAPI?.meetingTranscriptionPrepare?.({
+ provider: "openai-realtime",
+ model: "gpt-4o-mini-transcribe",
+ });
+
+ if (result?.success) {
+ isPreparedRef.current = true;
+ logger.info(
+ "Meeting transcription prepared",
+ { alreadyPrepared: result.alreadyPrepared },
+ "meeting"
+ );
+ } else {
+ logger.error("Meeting transcription prepare failed", { error: result?.error }, "meeting");
+ }
+ } catch (err) {
+ logger.error(
+ "Meeting transcription prepare error",
+ { error: (err as Error).message },
+ "meeting"
+ );
+ } finally {
+ preparePromiseRef.current = null;
+ }
+ })();
+
+ preparePromiseRef.current = promise;
+ await promise;
+ }, []);
+
const startTranscription = useCallback(async () => {
if (isRecordingRef.current || isStartingRef.current) return;
isStartingRef.current = true;
@@ -319,14 +364,48 @@ export function useMeetingTranscription(): UseMeetingTranscriptionReturn {
setPartialTranscript("");
setError(null);
+ // Set recording state immediately for instant UI feedback
+ isRecordingRef.current = true;
+ setIsRecording(true);
+
+ // Wait for in-flight prepare to reuse the warm connection
+ if (preparePromiseRef.current) {
+ logger.debug("Waiting for in-flight prepare to finish...", {}, "meeting");
+ await preparePromiseRef.current;
+ }
+
try {
- const [startResult, stream] = await Promise.all([
+ const startTime = performance.now();
+
+ const [startResult, stream, micResult] = await Promise.all([
window.electronAPI?.meetingTranscriptionStart?.({
provider: "openai-realtime",
model: "gpt-4o-mini-transcribe",
}),
getSystemAudioStream(),
+ getMeetingMicConstraints().then((constraints) =>
+ navigator.mediaDevices.getUserMedia(constraints).catch((err) => {
+ logger.error(
+ "Mic capture failed, continuing with system audio only",
+ { error: (err as Error).message },
+ "meeting"
+ );
+ return null;
+ })
+ ),
]);
+
+ const streamsMs = performance.now() - startTime;
+
+ // Abort if stop was called during setup
+ if (!isRecordingRef.current) {
+ logger.info("Meeting transcription aborted during setup (stop called)", {}, "meeting");
+ stream?.getTracks().forEach((t) => t.stop());
+ micResult?.getTracks().forEach((t) => t.stop());
+ isStartingRef.current = false;
+ return;
+ }
+
if (!startResult?.success) {
logger.error(
"Meeting transcription IPC start failed",
@@ -334,21 +413,24 @@ export function useMeetingTranscription(): UseMeetingTranscriptionReturn {
"meeting"
);
stream?.getTracks().forEach((track) => track.stop());
+ micResult?.getTracks().forEach((track) => track.stop());
+ isRecordingRef.current = false;
isStartingRef.current = false;
+ setIsRecording(false);
return;
}
if (!stream) {
logger.error("Could not capture system audio for meeting transcription", {}, "meeting");
+ micResult?.getTracks().forEach((track) => track.stop());
await window.electronAPI?.meetingTranscriptionStop?.();
+ isRecordingRef.current = false;
isStartingRef.current = false;
+ setIsRecording(false);
return;
}
streamRef.current = stream;
- const audioContext = new AudioContext({ sampleRate: 24000 });
- audioContextRef.current = audioContext;
-
const partialCleanup = window.electronAPI?.onMeetingTranscriptionPartial?.((text) => {
setPartialTranscript(text);
});
@@ -369,7 +451,10 @@ export function useMeetingTranscription(): UseMeetingTranscriptionReturn {
const pendingAudioChunks: ArrayBuffer[] = [];
let socketReady = false;
- const { source, processor } = await createAudioPipeline({
+ const audioContext = new AudioContext({ sampleRate: 24000 });
+ audioContextRef.current = audioContext;
+
+ const systemPipelinePromise = createAudioPipeline({
stream,
context: audioContext,
label: "Meeting system",
@@ -391,20 +476,15 @@ export function useMeetingTranscription(): UseMeetingTranscriptionReturn {
pendingAudioChunks.push(chunk.slice(0));
},
});
- sourceRef.current = source;
- processorRef.current = processor;
-
- try {
- const micStream = await navigator.mediaDevices.getUserMedia(
- await getMeetingMicConstraints()
- );
- micStreamRef.current = micStream;
+ let micPipelinePromise: Promise<void> | null = null;
+ if (micResult) {
+ micStreamRef.current = micResult;
const micContext = new AudioContext({ sampleRate: 24000 });
micContextRef.current = micContext;
- const { source: micSource, processor: micProcessor } = await createAudioPipeline({
- stream: micStream,
+ micPipelinePromise = createAudioPipeline({
+ stream: micResult,
context: micContext,
label: "Meeting mic",
onChunk: (chunk) => {
@@ -415,39 +495,59 @@ export function useMeetingTranscription(): UseMeetingTranscriptionReturn {
}
pendingAudioChunks.push(chunk.slice(0));
},
+ }).then(({ source, processor }) => {
+ micSourceRef.current = source;
+ micProcessorRef.current = processor;
+
+ const micTrack = micResult.getAudioTracks()[0];
+ logger.info(
+ "Mic capture started for meeting transcription",
+ {
+ label: micTrack?.label,
+ settings: micTrack?.getSettings(),
+ },
+ "meeting"
+ );
});
- micSourceRef.current = micSource;
- micProcessorRef.current = micProcessor;
+ }
+
+ const [systemPipeline] = await Promise.all(
+ [systemPipelinePromise, micPipelinePromise].filter(Boolean)
+ );
- const micTrack = micStream.getAudioTracks()[0];
+ if (systemPipeline) {
+ sourceRef.current = systemPipeline.source;
+ processorRef.current = systemPipeline.processor;
+ }
+
+ // Abort if stop was called during pipeline setup
+ if (!isRecordingRef.current) {
logger.info(
- "Mic capture started for meeting transcription",
- {
- label: micTrack?.label,
- settings: micTrack?.getSettings(),
- },
- "meeting"
- );
- } catch (micErr) {
- logger.error(
- "Mic capture failed, continuing with system audio only",
- { error: (micErr as Error).message },
+ "Meeting transcription aborted during pipeline setup (stop called)",
+ {},
"meeting"
);
+ isStartingRef.current = false;
+ await cleanup();
+ return;
}
- isRecordingRef.current = true;
isStartingRef.current = false;
- setIsRecording(true);
socketReady = true;
for (const chunk of pendingAudioChunks) {
window.electronAPI?.meetingTranscriptionSend?.(chunk);
}
+ const totalMs = performance.now() - startTime;
logger.info(
"Meeting transcription started successfully",
- { bufferedChunks: pendingAudioChunks.length },
+ {
+ bufferedChunks: pendingAudioChunks.length,
+ streamsMs: Math.round(streamsMs),
+ totalMs: Math.round(totalMs),
+ wasPrepared: isPreparedRef.current,
+ },
"meeting"
);
} catch (err) {
@@ -456,17 +556,22 @@ export function useMeetingTranscription(): UseMeetingTranscriptionReturn {
{ error: (err as Error).message },
"meeting"
);
+ isRecordingRef.current = false;
isStartingRef.current = false;
+ setIsRecording(false);
await cleanup();
}
}, [cleanup]);
+ useEffect(() => {
+ getMeetingWorkletBlobUrl();
+ }, []);
+
useEffect(() => {
return () => {
+ // Don't reset isRecordingRef here — StrictMode double-mount would abort in-flight setup
if (isRecordingRef.current) {
- void cleanup().finally(() => {
- isRecordingRef.current = false;
- });
+ void cleanup();
}
};
}, [cleanup]);
@@ -476,6 +581,7 @@ export function useMeetingTranscription(): UseMeetingTranscriptionReturn {
transcript,
partialTranscript,
error,
+ prepareTranscription,
startTranscription,
stopTranscription,
};
diff --git a/src/types/electron.ts b/src/types/electron.ts
index 2dd138df2..748198776 100644
--- a/src/types/electron.ts
+++ b/src/types/electron.ts
@@ -1065,6 +1065,11 @@ declare global {
}>;
// Meeting transcription (streaming)
+ meetingTranscriptionPrepare?: (options: {
+ provider?: string;
+ model?: string;
+ language?: string;
+ }) => Promise<{ success: boolean; alreadyPrepared?: boolean; error?: string }>;
meetingTranscriptionStart?: (options: {
provider?: string;
model?: string;