Skip to content

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

feat: stream cloud agent responses directly from renderer

Gabriel Stein589947d2f2e7
diff --git a/preload.js b/preload.js
index d5545f15b..d06231efb 100644
--- a/preload.js
+++ b/preload.js
@@ -578,8 +578,7 @@ contextBridge.exposeInMainWorld("electronAPI", {
acquireRecordingLock: (pipeline) => ipcRenderer.invoke("acquire-recording-lock", pipeline),
releaseRecordingLock: (pipeline) => ipcRenderer.invoke("release-recording-lock", pipeline),
- // Agent cloud streaming
- cloudAgentStream: (messages, opts) => ipcRenderer.invoke("cloud-agent-stream", messages, opts),
+ // Agent cloud tools
agentWebSearch: (query, numResults) => ipcRenderer.invoke("agent-web-search", query, numResults),
// Agent conversation persistence
diff --git a/src/components/AgentOverlay.tsx b/src/components/AgentOverlay.tsx
index f6a3dfe4d..73d2f5cdc 100644
--- a/src/components/AgentOverlay.tsx
+++ b/src/components/AgentOverlay.tsx
@@ -61,6 +61,7 @@ export default function AgentOverlay() {
mountedRef.current = true;
return () => {
mountedRef.current = false;
+ ReasoningService.cancelActiveStream();
};
}, []);
@@ -169,7 +170,10 @@ export default function AgentOverlay() {
}
for await (const chunk of stream) {
- if (!mountedRef.current) break;
+ if (!mountedRef.current) {
+ ReasoningService.cancelActiveStream();
+ break;
+ }
if (chunk.type === "content") {
fullContent += chunk.text;
setMessages((prev) =>
diff --git a/src/helpers/ipcHandlers.js b/src/helpers/ipcHandlers.js
index bfe0e08d7..f78af753d 100644
--- a/src/helpers/ipcHandlers.js
+++ b/src/helpers/ipcHandlers.js
@@ -2648,89 +2648,6 @@ class IPCHandlers {
}
});
- ipcMain.handle("cloud-agent-stream", 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");
-
- debugLogger.debug(
- "Cloud agent stream request",
- { messageCount: messages?.length || 0, toolCount: opts.tools?.length || 0 },
- "cloud-api"
- );
-
- 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) {
- if (response.status === 401) {
- return { success: false, error: "Session expired", code: "AUTH_EXPIRED" };
- }
- const errorData = await response.json().catch(() => ({}));
- return {
- success: false,
- error: errorData.error || `API error: ${response.status}`,
- };
- }
-
- const reader = response.body.getReader();
- const decoder = new TextDecoder();
- let buffer = "";
- const events = [];
-
- 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 {
- events.push(JSON.parse(line));
- } catch {
- // Non-JSON line, skip
- }
- }
- }
- if (buffer.trim()) {
- try {
- events.push(JSON.parse(buffer));
- } catch {
- // Non-JSON remainder, skip
- }
- }
- } finally {
- reader.releaseLock();
- }
-
- debugLogger.debug("Agent stream complete", { eventCount: events.length }, "cloud-api");
- return { success: true, events };
- } catch (error) {
- debugLogger.error("Cloud agent stream error:", error);
- return { success: false, 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 c6bffdf53..7d67c85b4 100644
--- a/src/services/ReasoningService.ts
+++ b/src/services/ReasoningService.ts
@@ -2,7 +2,13 @@ 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 } from "../config/constants";
+import {
+ API_ENDPOINTS,
+ TOKEN_LIMITS,
+ buildApiUrl,
+ normalizeBaseUrl,
+ OPENWHISPR_API_URL,
+} from "../config/constants";
import logger from "../utils/logger";
import { isSecureEndpoint } from "../utils/urlUtils";
import { withSessionRefresh } from "../lib/neonAuth";
@@ -22,6 +28,7 @@ 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();
@@ -1351,6 +1358,11 @@ class ReasoningService extends BaseReasoningService {
}
}
+ cancelActiveStream(): void {
+ this.activeAbortController?.abort();
+ this.activeAbortController = null;
+ }
+
async *processTextStreamingCloud(
messages: Array<{ role: string; content: string | Array<unknown> }>,
config: {
@@ -1363,30 +1375,66 @@ class ReasoningService extends BaseReasoningService {
let currentMessages = [...messages];
for (let step = 0; step < maxSteps; step++) {
- const result = await window.electronAPI?.cloudAgentStream?.(currentMessages, {
- systemPrompt: config.systemPrompt,
- tools: config.tools,
+ const controller = new AbortController();
+ this.activeAbortController = controller;
+
+ const response = await fetch(`${OPENWHISPR_API_URL}/api/agent/stream`, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ credentials: "include",
+ signal: controller.signal,
+ body: JSON.stringify({
+ messages: currentMessages,
+ systemPrompt: config.systemPrompt,
+ tools: config.tools,
+ clientType: "desktop",
+ }),
});
- if (!result || !result.success) {
- throw new Error(result?.error || "Cloud agent streaming failed");
+ 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 events = result.events || [];
+ const reader = response.body!.getReader();
+ const decoder = new TextDecoder();
+ let buffer = "";
const pendingToolCalls: Array<{ id: string; name: string; arguments: string }> = [];
- for (const ev of events) {
- 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] };
+ 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
+ }
+ }
}
+ } finally {
+ reader.releaseLock();
}
if (pendingToolCalls.length === 0 || !config.executeToolCall) {
@@ -1495,6 +1543,7 @@ class ReasoningService extends BaseReasoningService {
}
destroy(): void {
+ this.cancelActiveStream();
if (this.cacheCleanupStop) {
this.cacheCleanupStop();
}
diff --git a/src/types/electron.ts b/src/types/electron.ts
index 9106971ba..d42b8b40c 100644
--- a/src/types/electron.ts
+++ b/src/types/electron.ts
@@ -1071,26 +1071,7 @@ declare global {
onAgentStopRecording?: (callback: () => void) => () => void;
onAgentToggleRecording?: (callback: () => void) => () => void;
- // Agent cloud streaming
- cloudAgentStream?: (
- messages: Array<{ role: string; content: string | Array<unknown> }>,
- opts?: {
- systemPrompt?: string;
- tools?: Array<{ name: string; description: string; parameters: Record<string, unknown> }>;
- }
- ) => Promise<{
- success: boolean;
- error?: string;
- code?: string;
- events?: Array<{
- type: "content" | "tool_call" | "done";
- text?: string;
- id?: string;
- name?: string;
- arguments?: string;
- finishReason?: string;
- }>;
- }>;
+ // Agent cloud tools
agentWebSearch?: (
query: string,
numResults?: number