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
feat: stream live meeting transcription via OpenAI Realtime API
Gabriel Stein5ec0d480d946
diff --git a/main.js b/main.jsindex fc2c93411..a5095984f 100644--- a/main.js+++ b/main.js@@ -475,6 +475,18 @@ async function startApp() {});+ // Handle getDisplayMedia() calls from the renderer — auto-select the first+ // screen source with loopback audio so no system picker dialog is shown.+ const { desktopCapturer } = require("electron");+ session.defaultSession.setDisplayMediaRequestHandler(async (_request, callback) => {+ const sources = await desktopCapturer.getSources({ types: ["screen"] });+ if (!sources.length) {+ callback({});+ return;+ }+ callback({ video: sources[0], audio: "loopback" });+ });+windowManager.setActivationModeCache(environmentManager.getActivationMode());windowManager.setFloatingIconAutoHide(environmentManager.getFloatingIconAutoHide());@@ -955,6 +967,9 @@ if (gotSingleInstanceLock) {if (updateManager) {updateManager.cleanup();}+ if (clipboardManager) {+ clipboardManager.dispose();+ }// Stop whisper server if runningif (whisperManager) {whisperManager.stopServer().catch(() => {});diff --git a/preload.js b/preload.jsindex 44f15c2f2..ffc8d0ff8 100644--- a/preload.js+++ b/preload.js@@ -399,6 +399,24 @@ contextBridge.exposeInMainWorld("electronAPI", {meetingTranscribeChain: (blobUrl, opts) =>ipcRenderer.invoke("meeting-transcribe-chain", blobUrl, opts),+ // Meeting transcription (streaming)+ meetingTranscriptionStart: (options) =>+ ipcRenderer.invoke("meeting-transcription-start", options),+ meetingTranscriptionSend: (buffer) => ipcRenderer.send("meeting-transcription-send", buffer),+ meetingTranscriptionStop: () => ipcRenderer.invoke("meeting-transcription-stop"),+ onMeetingTranscriptionPartial: registerListener(+ "meeting-transcription-partial",+ (callback) => (_event, data) => callback(data)+ ),+ onMeetingTranscriptionFinal: registerListener(+ "meeting-transcription-final",+ (callback) => (_event, data) => callback(data)+ ),+ onMeetingTranscriptionError: registerListener(+ "meeting-transcription-error",+ (callback) => (_event, data) => callback(data)+ ),+// Usage limit events (for showing UpgradePrompt in ControlPanel)notifyLimitReached: (data) => ipcRenderer.send("limit-reached", data),onLimitReached: registerListener("limit-reached", (callback) => (_event, data) => callback(data)),diff --git a/src/components/notes/NoteEditor.tsx b/src/components/notes/NoteEditor.tsxindex bb2c4e2f9..2a2b92455 100644--- a/src/components/notes/NoteEditor.tsx+++ b/src/components/notes/NoteEditor.tsx@@ -54,8 +54,8 @@ interface NoteEditorProps {actionProcessingState?: ActionProcessingState;actionName?: string | null;isMeetingRecording?: boolean;- isMeetingProcessing?: boolean;meetingTranscript?: string;+ meetingPartialTranscript?: string;meetingEvent?: { summary: string };onStopMeetingRecording?: () => void;}@@ -151,8 +151,8 @@ export default function NoteEditor({actionProcessingState,actionName,isMeetingRecording,- isMeetingProcessing,meetingTranscript,+ meetingPartialTranscript,meetingEvent,onStopMeetingRecording,}: NoteEditorProps) {@@ -764,14 +764,14 @@ export default function NoteEditor({/><DictationWidgetisRecording={isRecording || !!isMeetingRecording}- isProcessing={isProcessing || !!isMeetingProcessing}+ isProcessing={isProcessing}onStart={handleStartRecording}onStop={isMeetingRecording ? onStopMeetingRecording! : onStopRecording}actionPicker={isMeetingRecording ? undefined : actionPicker}/></div>- {(isMeetingRecording || isMeetingProcessing || meetingTranscript) && (+ {(isMeetingRecording || meetingTranscript) && (<div className="border-t border-border/50 bg-surface-0/50 dark:bg-surface-1/30"><div className="px-4 py-1.5 flex items-center gap-1.5"><span className="text-[10px] font-semibold uppercase tracking-wider text-muted-foreground/50">@@ -779,13 +779,12 @@ export default function NoteEditor({</span></div><div className="px-4 pb-3 max-h-32 overflow-y-auto">- {isMeetingProcessing && !meetingTranscript ? (- <p className="text-xs text-muted-foreground/50 italic">Transcribing meeting audio...</p>- ) : (- <p className="text-xs text-muted-foreground/70 leading-relaxed whitespace-pre-wrap">- {meetingTranscript}- </p>- )}+ <p className="text-xs text-muted-foreground/70 leading-relaxed whitespace-pre-wrap">+ {meetingTranscript}+ {meetingPartialTranscript && (+ <span className="text-muted-foreground/40">{meetingPartialTranscript}</span>+ )}+ </p></div></div>)}diff --git a/src/components/notes/PersonalNotesView.tsx b/src/components/notes/PersonalNotesView.tsxindex 07512bb6e..fe2d57772 100644--- a/src/components/notes/PersonalNotesView.tsx+++ b/src/components/notes/PersonalNotesView.tsx@@ -85,13 +85,12 @@ export default function PersonalNotesView({const {isRecording: isMeetingRecording,- isProcessing: isMeetingProcessing,transcript: meetingTranscript,+ partialTranscript: meetingPartialTranscript,error: meetingError,startTranscription: startMeetingTranscription,stopTranscription: stopMeetingTranscription,} = useMeetingTranscription();- const isMeetingActive = isMeetingRecording || isMeetingProcessing;const [activeMeetingEvent, setActiveMeetingEvent] = useState<any>(null);const meetingNoteIdRef = useRef<number | null>(null);@@ -348,12 +347,12 @@ export default function PersonalNotesView({onMeetingRecordingRequestHandled,]);- const prevProcessingRef = useRef(false);+ const prevMeetingRecordingRef = useRef(false);useEffect(() => {if (- prevProcessingRef.current &&- !isMeetingProcessing &&+ prevMeetingRecordingRef.current &&+ !isMeetingRecording &&meetingNoteIdRef.current &&meetingTranscript) {@@ -365,8 +364,8 @@ export default function PersonalNotesView({meetingNoteIdRef.current = null;setActiveMeetingEvent(null);}- prevProcessingRef.current = isMeetingProcessing;- }, [isMeetingProcessing, meetingTranscript]);+ prevMeetingRecordingRef.current = isMeetingRecording;+ }, [isMeetingRecording, meetingTranscript]);const editorNote = activeNote? { ...activeNote, title: localTitle, content: localContent }@@ -707,8 +706,8 @@ export default function PersonalNotesView({: undefined}isMeetingRecording={isMeetingRecording}- isMeetingProcessing={isMeetingProcessing}meetingTranscript={meetingTranscript}+ meetingPartialTranscript={meetingPartialTranscript}meetingEvent={activeMeetingEvent}onStopMeetingRecording={stopMeetingTranscription}actionProcessingState={actionProcessingState}diff --git a/src/helpers/ipcHandlers.js b/src/helpers/ipcHandlers.jsindex 0f66bf19f..f30ffa5f2 100644--- a/src/helpers/ipcHandlers.js+++ b/src/helpers/ipcHandlers.js@@ -9,6 +9,7 @@ const GnomeShortcutManager = require("./gnomeShortcut");const AssemblyAiStreaming = require("./assemblyAiStreaming");const { i18nMain, changeLanguage } = require("./i18nMain");const DeepgramStreaming = require("./deepgramStreaming");+const OpenAIRealtimeStreaming = require("./openaiRealtimeStreaming");const MISTRAL_TRANSCRIPTION_URL = "https://api.mistral.ai/v1/audio/transcriptions";@@ -100,6 +101,7 @@ class IPCHandlers {this.sessionId = crypto.randomUUID();this.assemblyAiStreaming = null;this.deepgramStreaming = null;+ this.openaiRealtimeStreaming = null;this.setupHandlers();if (this.whisperManager?.serverManager) {@@ -1760,6 +1762,100 @@ class IPCHandlers {}});+ let meetingTranscriptionStartInProgress = false;++ 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" };+ }++ meetingTranscriptionStartInProgress = true;+ try {+ const win = BrowserWindow.fromWebContents(event.sender);++ if (options.provider !== "openai-realtime") {+ return { success: false, error: `Unsupported provider: ${options.provider}` };+ }++ const apiUrl = getApiUrl();+ if (!apiUrl) return { success: false, error: "OpenWhispr API URL not configured" };++ const cookieHeader = await getSessionCookies(event);+ if (!cookieHeader) return { success: false, 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(() => ({}));+ return { success: false, error: err.error || `Token request failed: ${tokenResponse.status}` };+ }++ const { clientSecret } = await tokenResponse.json();+ if (!clientSecret) return { success: false, error: "No client secret received" };++ if (this.openaiRealtimeStreaming?.isConnected) {+ await this.openaiRealtimeStreaming.disconnect();+ }++ this.openaiRealtimeStreaming = new OpenAIRealtimeStreaming();++ this.openaiRealtimeStreaming.onPartialTranscript = (text) => {+ if (win && !win.isDestroyed()) {+ win.webContents.send("meeting-transcription-partial", text);+ }+ };++ this.openaiRealtimeStreaming.onFinalTranscript = (text) => {+ if (win && !win.isDestroyed()) {+ win.webContents.send("meeting-transcription-final", text);+ }+ };++ this.openaiRealtimeStreaming.onError = (error) => {+ if (win && !win.isDestroyed()) {+ win.webContents.send("meeting-transcription-error", error.message);+ }+ };++ await this.openaiRealtimeStreaming.connect({+ apiKey: clientSecret,+ model: options.model,+ language: options.language,+ });++ return { success: true };+ } catch (error) {+ debugLogger.error("Meeting transcription start error", { error: error.message });+ return { success: false, error: error.message };+ } finally {+ meetingTranscriptionStartInProgress = false;+ }+ });++ ipcMain.on("meeting-transcription-send", (_event, audioBuffer) => {+ if (!this.openaiRealtimeStreaming) return;+ this.openaiRealtimeStreaming.sendAudio(Buffer.from(audioBuffer));+ });++ ipcMain.handle("meeting-transcription-stop", async () => {+ try {+ let result = { text: "" };+ if (this.openaiRealtimeStreaming) {+ result = await this.openaiRealtimeStreaming.disconnect();+ this.openaiRealtimeStreaming = null;+ }+ return { success: true, transcript: result?.text || "" };+ } catch (error) {+ debugLogger.error("Meeting transcription stop error", { error: error.message });+ return { success: false, error: error.message };+ }+ });+ipcMain.handle("cloud-reason", async (event, text, opts = {}) => {try {const apiUrl = getApiUrl();@@ -2715,7 +2811,6 @@ class IPCHandlers {}});- let sendDropCount = 0;ipcMain.on("deepgram-streaming-send", (event, audioBuffer) => {try {if (!this.deepgramStreaming) return;diff --git a/src/helpers/openaiRealtimeStreaming.js b/src/helpers/openaiRealtimeStreaming.jsnew file mode 100644index 000000000..4a90c21de--- /dev/null+++ b/src/helpers/openaiRealtimeStreaming.js@@ -0,0 +1,236 @@+const WebSocket = require("ws");+const debugLogger = require("./debugLogger");++const WEBSOCKET_TIMEOUT_MS = 15000;+const DISCONNECT_TIMEOUT_MS = 3000;++class OpenAIRealtimeStreaming {+ constructor() {+ this.ws = null;+ this.isConnected = false;+ this.completedSegments = [];+ this.currentPartial = "";+ this.onPartialTranscript = null;+ this.onFinalTranscript = null;+ this.onError = null;+ this.onSessionEnd = null;+ this.pendingResolve = null;+ this.pendingReject = null;+ this.connectionTimeout = null;+ this.closeResolve = null;+ this.isDisconnecting = false;+ this.audioBytesSent = 0;+ this.model = "gpt-4o-mini-transcribe";+ }++ getFullTranscript() {+ return this.completedSegments.join(" ");+ }++ async connect(options = {}) {+ const { apiKey, model } = options;+ if (!apiKey) throw new Error("OpenAI API key is required");++ if (this.isConnected) {+ debugLogger.debug("OpenAI Realtime already connected");+ return;+ }++ this.model = model || "gpt-4o-mini-transcribe";+ this.completedSegments = [];+ this.currentPartial = "";+ this.audioBytesSent = 0;++ const url = "wss://api.openai.com/v1/realtime?intent=transcription";+ debugLogger.debug("OpenAI Realtime connecting", { model: this.model });++ return new Promise((resolve, reject) => {+ this.pendingResolve = resolve;+ this.pendingReject = reject;++ this.connectionTimeout = setTimeout(() => {+ this.cleanup();+ reject(new Error("OpenAI Realtime connection timeout"));+ }, WEBSOCKET_TIMEOUT_MS);++ this.ws = new WebSocket(url, {+ headers: {+ Authorization: `Bearer ${apiKey}`,+ "OpenAI-Beta": "realtime=v1",+ },+ });++ this.ws.on("open", () => {+ debugLogger.debug("OpenAI Realtime WebSocket opened");+ });++ this.ws.on("message", (data) => {+ this.handleMessage(data);+ });++ this.ws.on("error", (error) => {+ debugLogger.error("OpenAI Realtime WebSocket error", { error: error.message });+ this.cleanup();+ if (this.pendingReject) {+ this.pendingReject(error);+ this.pendingReject = null;+ this.pendingResolve = null;+ }+ this.onError?.(error);+ });++ this.ws.on("close", (code, reason) => {+ const wasActive = this.isConnected;+ debugLogger.debug("OpenAI Realtime WebSocket closed", {+ code,+ reason: reason?.toString(),+ wasActive,+ });+ if (this.pendingReject) {+ this.pendingReject(new Error(`WebSocket closed before ready (code: ${code})`));+ this.pendingReject = null;+ this.pendingResolve = null;+ }+ if (this.closeResolve) {+ this.closeResolve({ text: this.getFullTranscript() });+ }+ this.cleanup();+ if (wasActive && !this.isDisconnecting) {+ this.onSessionEnd?.({ text: this.getFullTranscript() });+ }+ });+ });+ }++ handleMessage(data) {+ try {+ const event = JSON.parse(data.toString());++ switch (event.type) {+ case "transcription_session.created":+ case "transcription_session.updated": {+ if (this.pendingResolve) {+ this.isConnected = true;+ clearTimeout(this.connectionTimeout);+ debugLogger.debug("OpenAI Realtime session ready", {+ type: event.type,+ model: this.model,+ });+ this.pendingResolve();+ this.pendingResolve = null;+ this.pendingReject = null;+ }+ break;+ }++ case "conversation.item.input_audio_transcription.delta": {+ this.currentPartial += event.delta || "";+ this.onPartialTranscript?.(this.currentPartial);+ break;+ }++ case "conversation.item.input_audio_transcription.completed": {+ const transcript = (event.transcript || "").trim();+ if (transcript) {+ this.completedSegments.push(transcript);+ }+ this.currentPartial = "";+ const fullText = this.getFullTranscript();+ this.onFinalTranscript?.(fullText);+ debugLogger.debug("OpenAI Realtime turn completed", {+ turnText: transcript.slice(0, 100),+ totalLength: fullText.length,+ segments: this.completedSegments.length,+ });+ break;+ }++ case "input_audio_buffer.speech_started":+ case "input_audio_buffer.speech_stopped":+ case "input_audio_buffer.committed":+ break;++ case "error":+ debugLogger.error("OpenAI Realtime error event", {+ code: event.error?.code,+ message: event.error?.message,+ });+ this.onError?.(new Error(event.error?.message || "OpenAI Realtime error"));+ break;++ default:+ break;+ }+ } catch (err) {+ debugLogger.error("OpenAI Realtime message parse error", { error: err.message });+ }+ }++ sendAudio(pcmBuffer) {+ if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {+ return false;+ }++ const base64Audio = Buffer.from(pcmBuffer).toString("base64");+ this.ws.send(JSON.stringify({ type: "input_audio_buffer.append", audio: base64Audio }));+ this.audioBytesSent += pcmBuffer.length;+ return true;+ }++ async disconnect() {+ debugLogger.debug("OpenAI Realtime disconnect", {+ audioBytesSent: this.audioBytesSent,+ segments: this.completedSegments.length,+ textLength: this.getFullTranscript().length,+ });++ if (!this.ws) return { text: this.getFullTranscript() };++ this.isDisconnecting = true;++ if (this.ws.readyState === WebSocket.OPEN) {+ let timeoutId;+ const result = await Promise.race([+ new Promise((resolve) => {+ this.closeResolve = resolve;+ this.ws.close();+ }),+ new Promise((resolve) => {+ timeoutId = setTimeout(() => {+ debugLogger.debug("OpenAI Realtime close timeout, using accumulated text");+ resolve({ text: this.getFullTranscript() });+ }, DISCONNECT_TIMEOUT_MS);+ }),+ ]);+ clearTimeout(timeoutId);+ this.closeResolve = null;+ this.cleanup();+ this.isDisconnecting = false;+ return result;+ }++ const result = { text: this.getFullTranscript() };+ this.cleanup();+ this.isDisconnecting = false;+ return result;+ }++ cleanup() {+ clearTimeout(this.connectionTimeout);+ this.connectionTimeout = null;++ if (this.ws) {+ try {+ this.ws.close();+ } catch (err) {+ // ignore+ }+ this.ws = null;+ }++ this.isConnected = false;+ this.closeResolve = null;+ }+}++module.exports = OpenAIRealtimeStreaming;diff --git a/src/hooks/useMeetingTranscription.ts b/src/hooks/useMeetingTranscription.tsindex 5baf1cc5d..12373b494 100644--- a/src/hooks/useMeetingTranscription.ts+++ b/src/hooks/useMeetingTranscription.ts@@ -1,82 +1,43 @@import { useState, useEffect, useRef, useCallback } from "react";import logger from "../utils/logger";-import { buildWav } from "../utils/wavBuilder";-import { OPENWHISPR_API_URL } from "../config/constants";interface UseMeetingTranscriptionReturn {isRecording: boolean;- isProcessing: boolean;transcript: string;+ partialTranscript: string;error: string | null;startTranscription: () => Promise<void>;stopTranscription: () => Promise<void>;}-const WORKLET_CODE = `-const BUFFER_SIZE = 800;-class PCMStreamingProcessor extends AudioWorkletProcessor {- constructor() {- super();- this._buffer = new Int16Array(BUFFER_SIZE);- this._offset = 0;- this._stopped = false;- this.port.onmessage = (event) => {- if (event.data === "stop") {- if (this._offset > 0) {- const partial = this._buffer.slice(0, this._offset);- this.port.postMessage(partial.buffer, [partial.buffer]);- this._buffer = new Int16Array(BUFFER_SIZE);- this._offset = 0;- }- this._stopped = true;- }- };- }- process(inputs) {- if (this._stopped) return false;- const input = inputs[0]?.[0];- if (!input) return true;- for (let i = 0; i < input.length; i++) {- const s = Math.max(-1, Math.min(1, input[i]));- this._buffer[this._offset++] = s < 0 ? s * 0x8000 : s * 0x7fff;- if (this._offset >= BUFFER_SIZE) {- this.port.postMessage(this._buffer.buffer, [this._buffer.buffer]);- this._buffer = new Int16Array(BUFFER_SIZE);- this._offset = 0;- }- }- return true;- }-}-registerProcessor("pcm-meeting-processor", PCMStreamingProcessor);-`;-const getSystemAudioStream = async (): Promise<MediaStream | null> => {try {- const sources = await window.electronAPI?.getDesktopSources(["screen"]);- if (!sources?.length) return null;-- const stream = await navigator.mediaDevices.getUserMedia({- audio: {- mandatory: {- chromeMediaSource: "desktop",- chromeMediaSourceId: sources[0].id,- },- } as any,- video: {- mandatory: {- chromeMediaSource: "desktop",- chromeMediaSourceId: sources[0].id,- minWidth: 1,- maxWidth: 1,- minHeight: 1,- maxHeight: 1,- },- } as any,+ // Use getDisplayMedia (handled by setDisplayMediaRequestHandler in main process)+ // which properly captures system audio via macOS ScreenCaptureKit loopback.+ const stream = await navigator.mediaDevices.getDisplayMedia({+ audio: true,+ video: true,});- stream.getVideoTracks().forEach((t) => t.stop());- return new MediaStream(stream.getAudioTracks());+ const audioTracks = stream.getAudioTracks();+ const videoTracks = stream.getVideoTracks();++ if (!audioTracks.length) {+ logger.error("No audio track in display media stream", {}, "meeting");+ videoTracks.forEach((t) => t.stop());+ return null;+ }++ // Stop video tracks — with getDisplayMedia the audio track lifecycle is independent+ videoTracks.forEach((t) => t.stop());++ // Monitor audio track health+ audioTracks[0].addEventListener("ended", () => {+ logger.error("Audio track ended unexpectedly", {}, "meeting");+ });++ const audioOnlyStream = new MediaStream(audioTracks);+ return audioOnlyStream;} catch (err) {logger.error("Failed to capture system audio", { error: (err as Error).message }, "meeting");return null;@@ -85,23 +46,23 @@ const getSystemAudioStream = async (): Promise<MediaStream | null> => {export function useMeetingTranscription(): UseMeetingTranscriptionReturn {const [isRecording, setIsRecording] = useState(false);- const [isProcessing, setIsProcessing] = useState(false);const [transcript, setTranscript] = useState("");+ const [partialTranscript, setPartialTranscript] = useState("");const [error, setError] = useState<string | null>(null);const audioContextRef = useRef<AudioContext | null>(null);const sourceRef = useRef<MediaStreamAudioSourceNode | null>(null);- const processorRef = useRef<AudioWorkletNode | null>(null);+ const scriptNodeRef = useRef<ScriptProcessorNode | null>(null);const streamRef = useRef<MediaStream | null>(null);const isRecordingRef = useRef(false);- const workletBlobUrlRef = useRef<string | null>(null);- const chunksRef = useRef<ArrayBuffer[]>([]);+ const isStartingRef = useRef(false);+ const ipcCleanupsRef = useRef<Array<() => void>>([]);const cleanup = useCallback(async () => {- if (processorRef.current) {- processorRef.current.port.postMessage("stop");- processorRef.current.disconnect();- processorRef.current = null;+ if (scriptNodeRef.current) {+ scriptNodeRef.current.onaudioprocess = null;+ scriptNodeRef.current.disconnect();+ scriptNodeRef.current = null;}if (sourceRef.current) {@@ -123,10 +84,8 @@ export function useMeetingTranscription(): UseMeetingTranscriptionReturn {audioContextRef.current = null;}- if (workletBlobUrlRef.current) {- URL.revokeObjectURL(workletBlobUrlRef.current);- workletBlobUrlRef.current = null;- }+ ipcCleanupsRef.current.forEach((fn) => fn());+ ipcCleanupsRef.current = [];}, []);const stopTranscription = useCallback(async () => {@@ -136,106 +95,105 @@ export function useMeetingTranscription(): UseMeetingTranscriptionReturn {await cleanup();- const chunks = chunksRef.current;- chunksRef.current = [];-- if (chunks.length === 0) {- logger.info("Meeting transcription stopped (no audio captured)", {}, "meeting");- return;- }-- setIsProcessing(true);- setError(null);-try {- const totalLength = chunks.reduce((sum, buf) => sum + buf.byteLength / 2, 0);- const allSamples = new Int16Array(totalLength);- let offset = 0;- for (const buf of chunks) {- const chunk = new Int16Array(buf);- allSamples.set(chunk, offset);- offset += chunk.length;- }-- const wavBlob = buildWav(allSamples, 16000);-- const { upload } = await import("@vercel/blob/client");- const blob = await upload(`meeting-${Date.now()}.wav`, wavBlob, {- access: "public",- handleUploadUrl: `${OPENWHISPR_API_URL}/api/upload-audio`,- });-- const result = await window.electronAPI?.meetingTranscribeChain(blob.url);-- if (result?.success) {- setTranscript(result.text);- } else {- setError(result?.error || "Transcription failed");+ const result = await window.electronAPI?.meetingTranscriptionStop?.();+ if (result?.success && result.transcript) {+ setTranscript(result.transcript);+ } else if (result?.error) {+ setError(result.error);}} catch (err) {setError((err as Error).message);- logger.error("Meeting transcription failed", { error: (err as Error).message }, "meeting");- } finally {- setIsProcessing(false);+ logger.error(+ "Meeting transcription stop failed",+ { error: (err as Error).message },+ "meeting"+ );}logger.info("Meeting transcription stopped", {}, "meeting");}, [cleanup]);const startTranscription = useCallback(async () => {- if (isRecordingRef.current) return;+ if (isRecordingRef.current || isStartingRef.current) return;+ isStartingRef.current = true;logger.info("Meeting transcription starting...", {}, "meeting");- const stream = await getSystemAudioStream();- if (!stream) {- logger.error("Could not capture system audio for meeting transcription", {}, "meeting");- return;- }- logger.info(- "System audio stream captured",- { tracks: stream.getAudioTracks().length },- "meeting"- );- streamRef.current = stream;-try {- const audioContext = new AudioContext({ sampleRate: 16000 });+ const startResult = await window.electronAPI?.meetingTranscriptionStart?.({+ provider: "openai-realtime",+ model: "gpt-4o-mini-transcribe",+ });+ if (!startResult?.success) {+ logger.error(+ "Meeting transcription IPC start failed",+ { error: startResult?.error },+ "meeting"+ );+ isStartingRef.current = false;+ return;+ }++ const stream = await getSystemAudioStream();+ if (!stream) {+ logger.error("Could not capture system audio for meeting transcription", {}, "meeting");+ await window.electronAPI?.meetingTranscriptionStop?.();+ isStartingRef.current = false;+ return;+ }+ streamRef.current = stream;++ const audioContext = new AudioContext({ sampleRate: 24000 });audioContextRef.current = audioContext;- const blobUrl = URL.createObjectURL(- new Blob([WORKLET_CODE], { type: "application/javascript" })- );- workletBlobUrlRef.current = blobUrl;- await audioContext.audioWorklet.addModule(blobUrl);+ if (audioContext.state === "suspended") {+ await audioContext.resume();+ }const source = audioContext.createMediaStreamSource(stream);sourceRef.current = source;- const processor = new AudioWorkletNode(audioContext, "pcm-meeting-processor");- processorRef.current = processor;+ const scriptNode = audioContext.createScriptProcessor(4096, 1, 1);+ scriptNodeRef.current = scriptNode;- chunksRef.current = [];setTranscript("");+ setPartialTranscript("");setError(null);- let chunkCount = 0;- processor.port.onmessage = (event) => {+ const partialCleanup = window.electronAPI?.onMeetingTranscriptionPartial?.((text) => {+ setPartialTranscript(text);+ });+ if (partialCleanup) ipcCleanupsRef.current.push(partialCleanup);++ const finalCleanup = window.electronAPI?.onMeetingTranscriptionFinal?.((text) => {+ setTranscript(text);+ setPartialTranscript("");+ });+ if (finalCleanup) ipcCleanupsRef.current.push(finalCleanup);++ const errorCleanup = window.electronAPI?.onMeetingTranscriptionError?.((err) => {+ setError(err);+ logger.error("Meeting transcription stream error", { error: err }, "meeting");+ });+ if (errorCleanup) ipcCleanupsRef.current.push(errorCleanup);++ scriptNode.onaudioprocess = (event) => {if (!isRecordingRef.current) return;- chunkCount++;- if (chunkCount <= 3 || chunkCount % 50 === 0) {- logger.debug(- "Audio chunk buffered",- { chunk: chunkCount, bytes: event.data.byteLength },- "meeting"- );+ const input = event.inputBuffer.getChannelData(0);+ const pcm = new Int16Array(input.length);+ for (let i = 0; i < input.length; i++) {+ const s = Math.max(-1, Math.min(1, input[i]));+ pcm[i] = s < 0 ? s * 0x8000 : s * 0x7fff;}- chunksRef.current.push(event.data);+ window.electronAPI?.meetingTranscriptionSend?.(pcm.buffer);};- source.connect(processor);+ source.connect(scriptNode);+ scriptNode.connect(audioContext.destination);isRecordingRef.current = true;+ isStartingRef.current = false;setIsRecording(true);logger.info("Meeting transcription started successfully", {}, "meeting");} catch (err) {@@ -244,6 +202,7 @@ export function useMeetingTranscription(): UseMeetingTranscriptionReturn {{ error: (err as Error).message },"meeting");+ isStartingRef.current = false;await cleanup();}}, [cleanup]);@@ -259,8 +218,8 @@ export function useMeetingTranscription(): UseMeetingTranscriptionReturn {return {isRecording,- isProcessing,transcript,+ partialTranscript,error,startTranscription,stopTranscription,diff --git a/src/types/electron.ts b/src/types/electron.tsindex 73e4c6745..8a72ba2a3 100644--- a/src/types/electron.ts+++ b/src/types/electron.ts@@ -929,6 +929,22 @@ declare global {error?: string;}>;+ // Meeting transcription (streaming)+ meetingTranscriptionStart?: (options: {+ provider?: string;+ model?: string;+ language?: string;+ }) => Promise<{ success: boolean; error?: string }>;+ meetingTranscriptionSend?: (buffer: ArrayBuffer) => void;+ meetingTranscriptionStop?: () => Promise<{+ success: boolean;+ transcript?: string;+ error?: string;+ }>;+ onMeetingTranscriptionPartial?: (callback: (text: string) => void) => () => void;+ onMeetingTranscriptionFinal?: (callback: (text: string) => void) => () => void;+ onMeetingTranscriptionError?: (callback: (error: string) => void) => () => void;+// Desktop audio capturegetDesktopSources?: (types: string[]) => Promise<Array<{ id: string; name: string }>>;