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
refactor(cloud): route all sync services through IPC with generic API proxy
Gabriel Steineb0a87211c01
diff --git a/preload.js b/preload.jsindex 9a7ce890a..5e8e484ea 100644--- a/preload.js+++ b/preload.js@@ -439,9 +439,7 @@ contextBridge.exposeInMainWorld("electronAPI", {cloudBillingPortal: () => ipcRenderer.invoke("cloud-billing-portal"),cloudSwitchPlan: (opts) => ipcRenderer.invoke("cloud-switch-plan", opts),cloudPreviewSwitch: (opts) => ipcRenderer.invoke("cloud-preview-switch", opts),- cloudApiKeysList: () => ipcRenderer.invoke("cloud-api-keys-list"),- cloudApiKeysCreate: (opts) => ipcRenderer.invoke("cloud-api-keys-create", opts),- cloudApiKeysRevoke: (id) => ipcRenderer.invoke("cloud-api-keys-revoke", id),+ cloudApiRequest: (opts) => ipcRenderer.invoke("cloud-api-request", opts),getSttConfig: () => ipcRenderer.invoke("get-stt-config"),// Cloud audio file transcriptiondiff --git a/src/helpers/ipcHandlers.js b/src/helpers/ipcHandlers.jsindex dfbdaf647..7e9847c45 100644--- a/src/helpers/ipcHandlers.js+++ b/src/helpers/ipcHandlers.js@@ -5104,7 +5104,7 @@ class IPCHandlers {}});- ipcMain.handle("cloud-api-keys-list", async (event) => {+ ipcMain.handle("cloud-api-request", async (event, opts) => {try {const apiUrl = getApiUrl();if (!apiUrl) throw new Error("OpenWhispr API URL not configured");@@ -5112,80 +5112,34 @@ class IPCHandlers {const cookieHeader = await getSessionCookies(event);if (!cookieHeader) throw new Error("No session cookies available");- const response = await fetch(`${apiUrl}/api/v1/keys/list`, {- headers: { Cookie: cookieHeader },- });+ const method = (opts.method || "GET").toUpperCase();+ const headers = { Cookie: cookieHeader };+ const fetchOpts = { method, headers };- if (response.status === 401) {- return { success: false, error: "Session expired", code: "AUTH_EXPIRED" };+ if (opts.body !== undefined) {+ headers["Content-Type"] = "application/json";+ fetchOpts.body = JSON.stringify(opts.body);}- if (!response.ok) throw new Error(`API error: ${response.status}`);-- const { data } = await response.json();- return { success: true, keys: data.keys };- } catch (error) {- debugLogger.error("Cloud API keys list error:", error);- return { success: false, error: error.message };- }- });-- ipcMain.handle("cloud-api-keys-create", async (event, 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/v1/keys/create`, {- method: "POST",- headers: { Cookie: cookieHeader, "Content-Type": "application/json" },- body: JSON.stringify(opts),- });+ const response = await fetch(`${apiUrl}${opts.path}`, fetchOpts);if (response.status === 401) {return { success: false, error: "Session expired", code: "AUTH_EXPIRED" };}-- if (!response.ok) {- const errorData = await response.json().catch(() => ({}));- throw new Error(errorData.error?.message || `API error: ${response.status}`);+ if (response.status === 503) {+ return { success: false, error: "Service temporarily unavailable", code: "SERVER_ERROR" };}- const { data } = await response.json();- return { success: true, ...data };- } catch (error) {- debugLogger.error("Cloud API keys create error:", error);- return { success: false, error: error.message };- }- });-- ipcMain.handle("cloud-api-keys-revoke", async (event, id) => {- 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/v1/keys/${id}/revoke`, {- method: "POST",- headers: { Cookie: cookieHeader },- });-- if (response.status === 401) {- return { success: false, error: "Session expired", code: "AUTH_EXPIRED" };- }+ const data = await response.json().catch(() => null);if (!response.ok) {- const errorData = await response.json().catch(() => ({}));- throw new Error(errorData.error?.message || `API error: ${response.status}`);+ const message = data?.error?.message || data?.error || `API error: ${response.status}`;+ return { success: false, error: message };}- return { success: true, revoked: true };+ return { success: true, data };} catch (error) {- debugLogger.error("Cloud API keys revoke error:", error);+ debugLogger.error(`Cloud API request error (${opts?.path}):`, error);return { success: false, error: error.message };}});diff --git a/src/services/ApiKeysService.ts b/src/services/ApiKeysService.tsindex 2e83b7371..317ef9f19 100644--- a/src/services/ApiKeysService.ts+++ b/src/services/ApiKeysService.ts@@ -1,3 +1,5 @@+import { cloudGet, cloudPost } from "./cloudApi.js";+interface ApiKey {id: string;name: string;@@ -18,25 +20,26 @@ interface CreateApiKeyOptions {expiresInDays?: number | null;}+interface V1Response<T> {+ data: T;+}+async function listApiKeys(): Promise<{ keys: ApiKey[] }> {- const result = await window.electronAPI?.cloudApiKeysList?.();- if (!result?.success) throw new Error(result?.error ?? "Failed to list API keys");- return { keys: result.keys ?? [] };+ const res = await cloudGet<V1Response<{ keys: ApiKey[] }>>("/api/v1/keys/list");+ return { keys: res.data.keys };}async function createApiKey(options: CreateApiKeyOptions): Promise<CreateApiKeyResponse> {- const result = await window.electronAPI?.cloudApiKeysCreate?.({+ const res = await cloudPost<V1Response<CreateApiKeyResponse>>("/api/v1/keys/create", {name: options.name,scopes: options.scopes,- expires_in_days: options.expiresInDays ?? undefined,+ ...(options.expiresInDays != null ? { expires_in_days: options.expiresInDays } : {}),});- if (!result?.success) throw new Error(result?.error ?? "Failed to create API key");- return result as unknown as CreateApiKeyResponse;+ return res.data;}async function revokeApiKey(id: string): Promise<{ revoked: true }> {- const result = await window.electronAPI?.cloudApiKeysRevoke?.(id);- if (!result?.success) throw new Error(result?.error ?? "Failed to revoke API key");+ await cloudPost(`/api/v1/keys/${id}/revoke`);return { revoked: true };}diff --git a/src/services/ConversationsService.ts b/src/services/ConversationsService.tsindex 6d14782d9..94e4f650e 100644--- a/src/services/ConversationsService.ts+++ b/src/services/ConversationsService.ts@@ -1,4 +1,4 @@-import { OPENWHISPR_API_URL } from "../config/constants.js";+import { cloudGet, cloudPost, cloudPatch, cloudDelete } from "./cloudApi.js";interface ConversationInput {client_conversation_id?: string;@@ -31,43 +31,23 @@ interface CloudMessage {created_at: string;}+interface CloudConversationWithMessages extends CloudConversation {+ messages?: CloudMessage[];+}+async function create(input: ConversationInput): Promise<CloudConversation> {- const res = await fetch(`${OPENWHISPR_API_URL}/api/conversations/create`, {- method: "POST",- headers: { "Content-Type": "application/json" },- credentials: "include",- body: JSON.stringify(input),- });- if (!res.ok) throw new Error(await res.text());- return res.json() as Promise<CloudConversation>;+ return cloudPost<CloudConversation>("/api/conversations/create", input);}async function update(id: string,updates: { title?: string; archived_at?: string }): Promise<CloudConversation> {- const res = await fetch(`${OPENWHISPR_API_URL}/api/conversations/update`, {- method: "PATCH",- headers: { "Content-Type": "application/json" },- credentials: "include",- body: JSON.stringify({ id, ...updates }),- });- if (!res.ok) throw new Error(await res.text());- return res.json() as Promise<CloudConversation>;+ return cloudPatch<CloudConversation>("/api/conversations/update", { id, ...updates });}async function deleteConversation(id: string): Promise<void> {- const res = await fetch(`${OPENWHISPR_API_URL}/api/conversations/delete`, {- method: "DELETE",- headers: { "Content-Type": "application/json" },- credentials: "include",- body: JSON.stringify({ id }),- });- if (!res.ok) throw new Error(await res.text());-}--interface CloudConversationWithMessages extends CloudConversation {- messages?: CloudMessage[];+ await cloudDelete("/api/conversations/delete", { id });}async function list(@@ -82,12 +62,9 @@ async function list(if (archived) params.set("archived", "true");if (include !== undefined) params.set("include", include);const query = params.toString();- const res = await fetch(- `${OPENWHISPR_API_URL}/api/conversations/list${query ? `?${query}` : ""}`,- { credentials: "include" }+ return cloudGet<{ conversations: CloudConversationWithMessages[] }>(+ `/api/conversations/list${query ? `?${query}` : ""}`);- if (!res.ok) throw new Error(await res.text());- return res.json() as Promise<{ conversations: CloudConversationWithMessages[] }>;}async function addMessage(@@ -96,42 +73,27 @@ async function addMessage(content: string,metadata?: Record<string, unknown> | null): Promise<CloudMessage> {- const res = await fetch(`${OPENWHISPR_API_URL}/api/conversations/messages`, {- method: "POST",- headers: { "Content-Type": "application/json" },- credentials: "include",- body: JSON.stringify({- conversation_id: conversationId,- role,- content,- ...(metadata ? { metadata } : {}),- }),+ return cloudPost<CloudMessage>("/api/conversations/messages", {+ conversation_id: conversationId,+ role,+ content,+ ...(metadata ? { metadata } : {}),});- if (!res.ok) throw new Error(await res.text());- return res.json() as Promise<CloudMessage>;}async function listMessages(conversationId: string): Promise<{ messages: CloudMessage[] }> {const params = new URLSearchParams({ conversation_id: conversationId });- const res = await fetch(`${OPENWHISPR_API_URL}/api/conversations/messages?${params}`, {- credentials: "include",- });- if (!res.ok) throw new Error(await res.text());- return res.json() as Promise<{ messages: CloudMessage[] }>;+ return cloudGet<{ messages: CloudMessage[] }>(`/api/conversations/messages?${params}`);}async function search(query: string,limit?: number): Promise<{ conversations: CloudConversation[] }> {- const res = await fetch(`${OPENWHISPR_API_URL}/api/conversations/search`, {- method: "POST",- headers: { "Content-Type": "application/json" },- credentials: "include",- body: JSON.stringify({ query, ...(limit !== undefined ? { limit } : {}) }),+ return cloudPost<{ conversations: CloudConversation[] }>("/api/conversations/search", {+ query,+ ...(limit !== undefined ? { limit } : {}),});- if (!res.ok) throw new Error(await res.text());- return res.json() as Promise<{ conversations: CloudConversation[] }>;}export { create, update, deleteConversation, list, addMessage, listMessages, search };diff --git a/src/services/FoldersService.ts b/src/services/FoldersService.tsindex 2859a13af..5ff9c95b1 100644--- a/src/services/FoldersService.ts+++ b/src/services/FoldersService.ts@@ -1,4 +1,4 @@-import { OPENWHISPR_API_URL } from "../config/constants.js";+import { cloudGet, cloudPost, cloudPatch, cloudDelete } from "./cloudApi.js";interface FolderInput {name: string;@@ -18,54 +18,23 @@ interface CloudFolder {}async function create(folder: FolderInput): Promise<CloudFolder> {- const res = await fetch(`${OPENWHISPR_API_URL}/api/folders/create`, {- method: "POST",- headers: { "Content-Type": "application/json" },- credentials: "include",- body: JSON.stringify(folder),- });- if (!res.ok) throw new Error(await res.text());- return res.json() as Promise<CloudFolder>;+ return cloudPost<CloudFolder>("/api/folders/create", folder);}async function batchCreate(folders: FolderInput[]): Promise<{ created: CloudFolder[] }> {- const res = await fetch(`${OPENWHISPR_API_URL}/api/folders/batch-create`, {- method: "POST",- headers: { "Content-Type": "application/json" },- credentials: "include",- body: JSON.stringify({ folders }),- });- if (!res.ok) throw new Error(await res.text());- return res.json() as Promise<{ created: CloudFolder[] }>;+ return cloudPost<{ created: CloudFolder[] }>("/api/folders/batch-create", { folders });}async function update(id: string, updates: Partial<FolderInput>): Promise<CloudFolder> {- const res = await fetch(`${OPENWHISPR_API_URL}/api/folders/update`, {- method: "PATCH",- headers: { "Content-Type": "application/json" },- credentials: "include",- body: JSON.stringify({ id, ...updates }),- });- if (!res.ok) throw new Error(await res.text());- return res.json() as Promise<CloudFolder>;+ return cloudPatch<CloudFolder>("/api/folders/update", { id, ...updates });}async function deleteFolder(id: string): Promise<void> {- const res = await fetch(`${OPENWHISPR_API_URL}/api/folders/delete`, {- method: "DELETE",- headers: { "Content-Type": "application/json" },- credentials: "include",- body: JSON.stringify({ id }),- });- if (!res.ok) throw new Error(await res.text());+ await cloudDelete("/api/folders/delete", { id });}async function list(): Promise<{ folders: CloudFolder[] }> {- const res = await fetch(`${OPENWHISPR_API_URL}/api/folders/list`, {- credentials: "include",- });- if (!res.ok) throw new Error(await res.text());- return res.json() as Promise<{ folders: CloudFolder[] }>;+ return cloudGet<{ folders: CloudFolder[] }>("/api/folders/list");}export { create, batchCreate, update, deleteFolder, list };diff --git a/src/services/NotesService.ts b/src/services/NotesService.tsindex a7701d425..249d5a62a 100644--- a/src/services/NotesService.ts+++ b/src/services/NotesService.ts@@ -1,4 +1,4 @@-import { OPENWHISPR_API_URL } from "../config/constants.js";+import { cloudGet, cloudPost, cloudPatch, cloudDelete } from "./cloudApi.js";interface NoteInput {client_note_id?: string;@@ -40,48 +40,24 @@ interface SearchResult extends CloudNote {}async function create(note: NoteInput): Promise<CloudNote> {- const res = await fetch(`${OPENWHISPR_API_URL}/api/notes/create`, {- method: "POST",- headers: { "Content-Type": "application/json" },- credentials: "include",- body: JSON.stringify(note),- });- if (!res.ok) throw new Error(await res.text());- return res.json() as Promise<CloudNote>;+ return cloudPost<CloudNote>("/api/notes/create", note);}async function batchCreate(notes: NoteInput[]): Promise<{ created: { client_note_id: string; id: string }[] }> {- const res = await fetch(`${OPENWHISPR_API_URL}/api/notes/batch-create`, {- method: "POST",- headers: { "Content-Type": "application/json" },- credentials: "include",- body: JSON.stringify({ notes }),- });- if (!res.ok) throw new Error(await res.text());- return res.json() as Promise<{ created: { client_note_id: string; id: string }[] }>;+ return cloudPost<{ created: { client_note_id: string; id: string }[] }>(+ "/api/notes/batch-create",+ { notes }+ );}async function update(id: string, updates: Partial<NoteInput>): Promise<CloudNote> {- const res = await fetch(`${OPENWHISPR_API_URL}/api/notes/update`, {- method: "PATCH",- headers: { "Content-Type": "application/json" },- credentials: "include",- body: JSON.stringify({ id, ...updates }),- });- if (!res.ok) throw new Error(await res.text());- return res.json() as Promise<CloudNote>;+ return cloudPatch<CloudNote>("/api/notes/update", { id, ...updates });}async function deleteNote(id: string): Promise<void> {- const res = await fetch(`${OPENWHISPR_API_URL}/api/notes/delete`, {- method: "DELETE",- headers: { "Content-Type": "application/json" },- credentials: "include",- body: JSON.stringify({ id }),- });- if (!res.ok) throw new Error(await res.text());+ await cloudDelete("/api/notes/delete", { id });}async function list(limit?: number, before?: string): Promise<{ notes: CloudNote[] }> {@@ -89,29 +65,17 @@ async function list(limit?: number, before?: string): Promise<{ notes: CloudNoteif (limit !== undefined) params.set("limit", String(limit));if (before !== undefined) params.set("before", before);const query = params.toString();- const res = await fetch(`${OPENWHISPR_API_URL}/api/notes/list${query ? `?${query}` : ""}`, {- credentials: "include",- });- if (!res.ok) throw new Error(await res.text());- return res.json() as Promise<{ notes: CloudNote[] }>;+ return cloudGet<{ notes: CloudNote[] }>(`/api/notes/list${query ? `?${query}` : ""}`);}async function deleteAll(): Promise<{ deleted: number; errors: number }> {- // Try bulk endpoint first; fall back to per-note deletiontry {- const res = await fetch(`${OPENWHISPR_API_URL}/api/notes/delete-all`, {- method: "DELETE",- credentials: "include",- });- if (res.ok) {- const data = (await res.json()) as { deleted?: number };- return { deleted: data.deleted ?? 0, errors: 0 };- }+ const data = await cloudDelete<{ deleted?: number }>("/api/notes/delete-all");+ return { deleted: data?.deleted ?? 0, errors: 0 };} catch {// bulk endpoint doesn't exist — fall through}- // Fallback: list all and delete one-by-oneconst { notes } = await list(9999);const results = await Promise.allSettled(notes.map((n) => deleteNote(n.id)));const errors = results.filter((r) => r.status === "rejected").length;@@ -119,14 +83,10 @@ async function deleteAll(): Promise<{ deleted: number; errors: number }> {}async function search(query: string, limit?: number): Promise<{ notes: SearchResult[] }> {- const res = await fetch(`${OPENWHISPR_API_URL}/api/notes/search`, {- method: "POST",- headers: { "Content-Type": "application/json" },- credentials: "include",- body: JSON.stringify({ query, ...(limit !== undefined ? { limit } : {}) }),+ return cloudPost<{ notes: SearchResult[] }>("/api/notes/search", {+ query,+ ...(limit !== undefined ? { limit } : {}),});- if (!res.ok) throw new Error(await res.text());- return res.json() as Promise<{ notes: SearchResult[] }>;}export { create, batchCreate, update, deleteNote, deleteAll, list, search };diff --git a/src/services/TranscriptionsService.ts b/src/services/TranscriptionsService.tsindex 680962d3a..dd80a9e8a 100644--- a/src/services/TranscriptionsService.ts+++ b/src/services/TranscriptionsService.ts@@ -1,4 +1,4 @@-import { OPENWHISPR_API_URL } from "../config/constants.js";+import { cloudGet, cloudPost, cloudDelete } from "./cloudApi.js";interface TranscriptionInput {client_transcription_id?: string;@@ -29,27 +29,15 @@ interface CloudTranscription {}async function create(transcription: TranscriptionInput): Promise<CloudTranscription> {- const res = await fetch(`${OPENWHISPR_API_URL}/api/transcriptions/create`, {- method: "POST",- headers: { "Content-Type": "application/json" },- credentials: "include",- body: JSON.stringify(transcription),- });- if (!res.ok) throw new Error(await res.text());- return res.json() as Promise<CloudTranscription>;+ return cloudPost<CloudTranscription>("/api/transcriptions/create", transcription);}async function batchCreate(transcriptions: TranscriptionInput[]): Promise<{ created: CloudTranscription[] }> {- const res = await fetch(`${OPENWHISPR_API_URL}/api/transcriptions/batch-create`, {- method: "POST",- headers: { "Content-Type": "application/json" },- credentials: "include",- body: JSON.stringify({ transcriptions }),+ return cloudPost<{ created: CloudTranscription[] }>("/api/transcriptions/batch-create", {+ transcriptions,});- if (!res.ok) throw new Error(await res.text());- return res.json() as Promise<{ created: CloudTranscription[] }>;}async function list(@@ -60,22 +48,13 @@ async function list(if (limit !== undefined) params.set("limit", String(limit));if (before !== undefined) params.set("before", before);const query = params.toString();- const res = await fetch(- `${OPENWHISPR_API_URL}/api/transcriptions/list${query ? `?${query}` : ""}`,- { credentials: "include" }+ return cloudGet<{ transcriptions: CloudTranscription[] }>(+ `/api/transcriptions/list${query ? `?${query}` : ""}`);- if (!res.ok) throw new Error(await res.text());- return res.json() as Promise<{ transcriptions: CloudTranscription[] }>;}async function deleteTranscription(id: string): Promise<void> {- const res = await fetch(`${OPENWHISPR_API_URL}/api/transcriptions/delete`, {- method: "DELETE",- headers: { "Content-Type": "application/json" },- credentials: "include",- body: JSON.stringify({ id }),- });- if (!res.ok) throw new Error(await res.text());+ await cloudDelete("/api/transcriptions/delete", { id });}export { create, batchCreate, list, deleteTranscription };diff --git a/src/services/cloudApi.ts b/src/services/cloudApi.tsnew file mode 100644index 000000000..c1bfb090b--- /dev/null+++ b/src/services/cloudApi.ts@@ -0,0 +1,36 @@+interface CloudApiResponse<T = unknown> {+ success: boolean;+ data?: T;+ error?: string;+ code?: string;+}++async function cloudRequest<T = unknown>(method: string, path: string, body?: unknown): Promise<T> {+ const result = (await window.electronAPI?.cloudApiRequest?.({+ method,+ path,+ body,+ })) as CloudApiResponse<T> | undefined;++ if (!result?.success) {+ throw new Error(result?.error ?? "Cloud API request failed");+ }++ return result.data as T;+}++export async function cloudGet<T = unknown>(path: string): Promise<T> {+ return cloudRequest<T>("GET", path);+}++export async function cloudPost<T = unknown>(path: string, body?: unknown): Promise<T> {+ return cloudRequest<T>("POST", path, body);+}++export async function cloudPatch<T = unknown>(path: string, body?: unknown): Promise<T> {+ return cloudRequest<T>("PATCH", path, body);+}++export async function cloudDelete<T = unknown>(path: string, body?: unknown): Promise<T> {+ return cloudRequest<T>("DELETE", path, body);+}diff --git a/src/types/electron.ts b/src/types/electron.tsindex e191b03fd..508cfce30 100644--- a/src/types/electron.ts+++ b/src/types/electron.ts@@ -1008,40 +1008,10 @@ declare global {error?: string;}>;- // Cloud API keys- cloudApiKeysList?: () => Promise<{+ // Authenticated cloud API proxy+ cloudApiRequest?: (opts: { method?: string; path: string; body?: unknown }) => Promise<{success: boolean;- keys?: Array<{- id: string;- name: string;- key_prefix: string;- scopes: string[];- last_used_at: string | null;- expires_at: string | null;- created_at: string;- }>;- error?: string;- code?: string;- }>;- cloudApiKeysCreate?: (opts: {- name: string;- scopes: string[];- expires_in_days?: number | null;- }) => Promise<{- success: boolean;- key?: string;- id?: string;- name?: string;- key_prefix?: string;- scopes?: string[];- expires_at?: string | null;- created_at?: string;- error?: string;- code?: string;- }>;- cloudApiKeysRevoke?: (id: string) => Promise<{- success: boolean;- revoked?: boolean;+ data?: unknown;error?: string;code?: string;}>;