Skip to content

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

fix: use event-based IPC streaming instead of direct fetch

Gabriel Stein4a1d3e2c5862
diff --git a/preload.js b/preload.js
index 389644ae6..2e500d855 100644
--- a/preload.js
+++ b/preload.js
@@ -578,8 +578,11 @@ contextBridge.exposeInMainWorld("electronAPI", {
acquireRecordingLock: (pipeline) => ipcRenderer.invoke("acquire-recording-lock", pipeline),
releaseRecordingLock: (pipeline) => ipcRenderer.invoke("release-recording-lock", pipeline),
- // Auth cookies for direct renderer-to-API fetch
- getSessionCookies: () => ipcRenderer.invoke("get-session-cookies"),
+ // Agent cloud streaming (event-based for real-time chunks)
+ startAgentStream: (messages, opts) => ipcRenderer.send("cloud-agent-stream-start", messages, opts),
+ onAgentStreamChunk: registerListener("cloud-agent-stream-chunk", (callback) => (_event, chunk) => callback(chunk)),
+ onAgentStreamError: registerListener("cloud-agent-stream-error", (callback) => (_event, error) => callback(error)),
+ onAgentStreamEnd: registerListener("cloud-agent-stream-end", (callback) => () => callback()),
// Agent cloud tools
agentWebSearch: (query, numResults) => ipcRenderer.invoke("agent-web-search", query, numResults),
diff --git a/src/helpers/ipcHandlers.js b/src/helpers/ipcHandlers.js
index dde6011ff..54e82b345 100644
--- a/src/helpers/ipcHandlers.js
+++ b/src/helpers/ipcHandlers.js
@@ -2146,10 +2146,6 @@ class IPCHandlers {
return getSessionCookiesFromWindow(win);
};
- ipcMain.handle("get-session-cookies", async (event) => {
- return getSessionCookies(event);
- });
-
ipcMain.handle("cloud-transcribe", async (event, audioBuffer, opts = {}) => {
try {
const apiUrl = getApiUrl();
@@ -2652,6 +2648,79 @@ class IPCHandlers {
}
});
+ ipcMain.on("cloud-agent-stream-start", async (event, messages, opts = {}) => {
+ try {
+ 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 response = await fetch(`${apiUrl}/api/agent/stream`, {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ Cookie: cookieHeader,
+ },
+ body: JSON.stringify({
+ messages,
+ systemPrompt: opts.systemPrompt,
+ tools: opts.tools,
+ sessionId: this.sessionId,
+ clientType: "desktop",
+ appVersion: app.getVersion(),
+ }),
+ });
+
+ if (!response.ok) {
+ const errorData = await response.json().catch(() => ({}));
+ event.sender.send("cloud-agent-stream-error", {
+ error: errorData.error || `API error: ${response.status}`,
+ code: response.status === 401 ? "AUTH_EXPIRED" : undefined,
+ });
+ return;
+ }
+
+ const reader = response.body.getReader();
+ const decoder = new TextDecoder();
+ let buffer = "";
+
+ try {
+ while (true) {
+ const { done, value } = await reader.read();
+ if (done) break;
+
+ buffer += decoder.decode(value, { stream: true });
+ const lines = buffer.split("\n");
+ buffer = lines.pop() || "";
+
+ for (const line of lines) {
+ if (!line.trim()) continue;
+ try {
+ event.sender.send("cloud-agent-stream-chunk", JSON.parse(line));
+ } catch {
+ // skip malformed NDJSON line
+ }
+ }
+ }
+ if (buffer.trim()) {
+ try {
+ event.sender.send("cloud-agent-stream-chunk", JSON.parse(buffer));
+ } catch {
+ // skip malformed remainder
+ }
+ }
+ } finally {
+ reader.releaseLock();
+ }
+
+ event.sender.send("cloud-agent-stream-end");
+ } catch (error) {
+ debugLogger.error("Cloud agent stream error:", error);
+ event.sender.send("cloud-agent-stream-error", { error: error.message });
+ }
+ });
+
ipcMain.handle("agent-web-search", async (event, query, numResults = 5) => {
try {
const apiUrl = getApiUrl();
diff --git a/src/services/ReasoningService.ts b/src/services/ReasoningService.ts
index c982cec3f..f704baf22 100644
--- a/src/services/ReasoningService.ts
+++ b/src/services/ReasoningService.ts
@@ -2,13 +2,7 @@ import { getModelProvider, getCloudModel, getOpenAiApiConfig } from "../models/M
import { BaseReasoningService, ReasoningConfig } from "./BaseReasoningService";
import { SecureCache } from "../utils/SecureCache";
import { withRetry, createApiRetryStrategy } from "../utils/retry";
-import {
- API_ENDPOINTS,
- TOKEN_LIMITS,
- buildApiUrl,
- normalizeBaseUrl,
- OPENWHISPR_API_URL,
-} from "../config/constants";
+import { API_ENDPOINTS, TOKEN_LIMITS, buildApiUrl, normalizeBaseUrl } from "../config/constants";
import logger from "../utils/logger";
import { isSecureEndpoint } from "../utils/urlUtils";
import { withSessionRefresh } from "../lib/neonAuth";
@@ -28,7 +22,6 @@ class ReasoningService extends BaseReasoningService {
private static readonly OPENAI_ENDPOINT_PREF_STORAGE_KEY = "openAiEndpointPreference";
private static readonly MAX_TOOL_STEPS = 5;
private cacheCleanupStop: (() => void) | undefined;
- private activeAbortController: AbortController | null = null;
constructor() {
super();
@@ -1359,8 +1352,82 @@ class ReasoningService extends BaseReasoningService {
}
cancelActiveStream(): void {
- this.activeAbortController?.abort();
- this.activeAbortController = null;
+ // No-op — event-based stream cleanup is handled by listener removal
+ }
+
+ private streamFromIPC(
+ messages: Array<{ role: string; content: string | Array<unknown> }>,
+ opts: {
+ systemPrompt?: string;
+ tools?: Array<{ name: string; description: string; parameters: Record<string, unknown> }>;
+ }
+ ): AsyncGenerator<
+ {
+ type: string;
+ text?: string;
+ id?: string;
+ name?: string;
+ arguments?: string;
+ finishReason?: string;
+ },
+ void,
+ unknown
+ > {
+ type StreamEvent = {
+ type: string;
+ text?: string;
+ id?: string;
+ name?: string;
+ arguments?: string;
+ finishReason?: string;
+ };
+ const queue: Array<StreamEvent | { type: "__error"; error: string } | { type: "__end" }> = [];
+ let resolve: (() => void) | null = null;
+
+ const cleanupChunk = window.electronAPI?.onAgentStreamChunk?.((chunk) => {
+ queue.push(chunk);
+ resolve?.();
+ });
+ const cleanupError = window.electronAPI?.onAgentStreamError?.((err) => {
+ queue.push({ type: "__error", error: err.error });
+ resolve?.();
+ });
+ const cleanupEnd = window.electronAPI?.onAgentStreamEnd?.(() => {
+ queue.push({ type: "__end" });
+ resolve?.();
+ });
+
+ const cleanup = () => {
+ cleanupChunk?.();
+ cleanupError?.();
+ cleanupEnd?.();
+ };
+
+ window.electronAPI?.startAgentStream?.(messages, opts);
+
+ const generator = async function* () {
+ try {
+ while (true) {
+ if (queue.length === 0) {
+ await new Promise<void>((r) => {
+ resolve = r;
+ });
+ resolve = null;
+ }
+
+ while (queue.length > 0) {
+ const item = queue.shift()!;
+ if (item.type === "__end") return;
+ if (item.type === "__error") throw new Error((item as { error: string }).error);
+ yield item as StreamEvent;
+ }
+ }
+ } finally {
+ cleanup();
+ }
+ };
+
+ return generator();
}
async *processTextStreamingCloud(
@@ -1371,77 +1438,29 @@ class ReasoningService extends BaseReasoningService {
executeToolCall?: (name: string, args: string) => Promise<string>;
}
): AsyncGenerator<AgentStreamChunk, void, unknown> {
- const cookieHeader = await window.electronAPI?.getSessionCookies?.();
- if (!cookieHeader) {
- throw new Error("No session cookies available");
- }
-
const maxSteps = config.tools?.length ? ReasoningService.MAX_TOOL_STEPS : 1;
let currentMessages = [...messages];
for (let step = 0; step < maxSteps; step++) {
- const controller = new AbortController();
- this.activeAbortController = controller;
-
- const response = await fetch(`${OPENWHISPR_API_URL}/api/agent/stream`, {
- method: "POST",
- headers: {
- "Content-Type": "application/json",
- Cookie: cookieHeader,
- },
- signal: controller.signal,
- body: JSON.stringify({
- messages: currentMessages,
- systemPrompt: config.systemPrompt,
- tools: config.tools,
- clientType: "desktop",
- }),
+ const stream = this.streamFromIPC(currentMessages, {
+ systemPrompt: config.systemPrompt,
+ tools: config.tools,
});
- if (!response.ok) {
- if (response.status === 401) {
- throw new Error("Session expired");
- }
- const err = await response.json().catch(() => ({}));
- throw new Error(err.error || `API error: ${response.status}`);
- }
-
- const reader = response.body!.getReader();
- const decoder = new TextDecoder();
- let buffer = "";
const pendingToolCalls: Array<{ id: string; name: string; arguments: string }> = [];
- try {
- while (true) {
- const { done, value } = await reader.read();
- if (done) break;
-
- buffer += decoder.decode(value, { stream: true });
- const lines = buffer.split("\n");
- buffer = lines.pop() || "";
-
- for (const line of lines) {
- if (!line.trim()) continue;
- try {
- const ev = JSON.parse(line);
- if (ev.type === "content") {
- yield { type: "content", text: ev.text };
- } else if (ev.type === "tool_call") {
- const call = {
- id: ev.id as string,
- name: ev.name as string,
- arguments: ev.arguments as string,
- };
- pendingToolCalls.push(call);
- yield { type: "tool_calls", calls: [call] };
- }
- } catch {
- // skip malformed NDJSON line
- }
- }
+ for await (const ev of stream) {
+ if (ev.type === "content") {
+ yield { type: "content", text: ev.text as string };
+ } else if (ev.type === "tool_call") {
+ const call = {
+ id: ev.id as string,
+ name: ev.name as string,
+ arguments: ev.arguments as string,
+ };
+ pendingToolCalls.push(call);
+ yield { type: "tool_calls", calls: [call] };
}
- } finally {
- reader.releaseLock();
}
if (pendingToolCalls.length === 0 || !config.executeToolCall) {
diff --git a/src/types/electron.ts b/src/types/electron.ts
index 771138b93..e5e0f7e1f 100644
--- a/src/types/electron.ts
+++ b/src/types/electron.ts
@@ -1071,8 +1071,28 @@ declare global {
onAgentStopRecording?: (callback: () => void) => () => void;
onAgentToggleRecording?: (callback: () => void) => () => void;
- // Auth cookies for direct renderer-to-API fetch
- getSessionCookies?: () => Promise<string>;
+ // Agent cloud streaming (event-based)
+ startAgentStream?: (
+ messages: Array<{ role: string; content: string | Array<unknown> }>,
+ opts?: {
+ systemPrompt?: string;
+ tools?: Array<{ name: string; description: string; parameters: Record<string, unknown> }>;
+ }
+ ) => void;
+ onAgentStreamChunk?: (
+ callback: (chunk: {
+ type: "content" | "tool_call" | "done";
+ text?: string;
+ id?: string;
+ name?: string;
+ arguments?: string;
+ finishReason?: string;
+ }) => void
+ ) => () => void;
+ onAgentStreamError?: (
+ callback: (error: { error: string; code?: string }) => void
+ ) => () => void;
+ onAgentStreamEnd?: (callback: () => void) => () => void;
// Agent cloud tools
agentWebSearch?: (