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: add bidirectional cloud sync for notes, folders, conversations, and transcriptions
Gabriel Steina1828602bfe7
diff --git a/preload.js b/preload.jsindex f6886ceac..3741c0629 100644--- a/preload.js+++ b/preload.js@@ -706,6 +706,33 @@ contextBridge.exposeInMainWorld("electronAPI", {semanticSearchConversations: (query, limit) =>ipcRenderer.invoke("db-semantic-search-conversations", query, limit),+ // Sync operations+ getPendingNotes: () => ipcRenderer.invoke('db-get-pending-notes'),+ getPendingNoteDeletes: () => ipcRenderer.invoke('db-get-pending-note-deletes'),+ getNoteByClientId: (clientNoteId) => ipcRenderer.invoke('db-get-note-by-client-id', clientNoteId),+ upsertNoteFromCloud: (cloudNote, localFolderId) => ipcRenderer.invoke('db-upsert-note-from-cloud', cloudNote, localFolderId),+ markNoteSynced: (id, cloudId) => ipcRenderer.invoke('db-mark-note-synced', id, cloudId),+ markNoteSyncError: (id) => ipcRenderer.invoke('db-mark-note-sync-error', id),+ hardDeleteNote: (id) => ipcRenderer.invoke('db-hard-delete-note', id),++ getPendingFolders: () => ipcRenderer.invoke('db-get-pending-folders'),+ getFolderByClientId: (clientFolderId) => ipcRenderer.invoke('db-get-folder-by-client-id', clientFolderId),+ upsertFolderFromCloud: (cloudFolder) => ipcRenderer.invoke('db-upsert-folder-from-cloud', cloudFolder),+ markFolderSynced: (id, cloudId) => ipcRenderer.invoke('db-mark-folder-synced', id, cloudId),+ getFolderIdMap: () => ipcRenderer.invoke('db-get-folder-id-map'),++ getPendingConversations: () => ipcRenderer.invoke('db-get-pending-conversations'),+ getPendingConversationDeletes: () => ipcRenderer.invoke('db-get-pending-conversation-deletes'),+ getConversationByClientId: (clientId) => ipcRenderer.invoke('db-get-conversation-by-client-id', clientId),+ upsertConversationFromCloud: (cloudConv, messages) => ipcRenderer.invoke('db-upsert-conversation-from-cloud', cloudConv, messages),+ markConversationSynced: (id, cloudId) => ipcRenderer.invoke('db-mark-conversation-synced', id, cloudId),+ hardDeleteConversation: (id) => ipcRenderer.invoke('db-hard-delete-conversation', id),++ getPendingTranscriptions: () => ipcRenderer.invoke('db-get-pending-transcriptions'),+ getTranscriptionByClientId: (clientId) => ipcRenderer.invoke('db-get-transcription-by-client-id', clientId),+ upsertTranscriptionFromCloud: (cloudTranscription) => ipcRenderer.invoke('db-upsert-transcription-from-cloud', cloudTranscription),+ markTranscriptionSynced: (id, cloudId) => ipcRenderer.invoke('db-mark-transcription-synced', id, cloudId),+// Google CalendargcalStartOAuth: () => ipcRenderer.invoke("gcal-start-oauth"),gcalDisconnect: () => ipcRenderer.invoke("gcal-disconnect"),diff --git a/src/components/ControlPanel.tsx b/src/components/ControlPanel.tsxindex 26f487066..91b935023 100644--- a/src/components/ControlPanel.tsx+++ b/src/components/ControlPanel.tsx@@ -26,6 +26,7 @@ import { getCachedPlatform } from "../utils/platform";import { isAccessibilitySkipped } from "../utils/permissions";import { setActiveNoteId, setActiveFolderId, initializeNotes } from "../stores/noteStore";import HistoryView from "./HistoryView";+import { syncService } from "../services/SyncService.js";const platform = getCachedPlatform();@@ -268,6 +269,10 @@ export default function ControlPanel() {return () => cleanup?.();}, [toast, t]);+ useEffect(() => {+ syncService.syncAll().catch(console.error);+ }, []);+const handleMeetingRecordingRequestHandled = useCallback(() => setMeetingRecordingRequest(null),[]diff --git a/src/components/NoteEditor.tsx b/src/components/NoteEditor.tsxindex a310e1d1a..52ec9d494 100644--- a/src/components/NoteEditor.tsx+++ b/src/components/NoteEditor.tsx@@ -5,7 +5,7 @@ import { Button } from "./ui/button";import { ConfirmDialog } from "./ui/dialog.js";import { cn } from "./lib/utils";import type { NoteItem } from "../types/electron.js";-import { syncNoteUpdateToCloud, syncNoteDeleteToCloud } from "../stores/noteStore.js";+import { syncService } from "../services/SyncService.js";const NOTE_TYPE_COLORS: Record<NoteItem["note_type"], string> = {personal: "bg-foreground/5 text-foreground/50",@@ -63,9 +63,7 @@ export default function NoteEditor({ note, cloudEnabled, onDelete, onUpdate }: Nawait window.electronAPI.updateNote(note.id, updates);const updated = { ...note, ...updates };onUpdate(updated);- if (cloudEnabled) {- syncNoteUpdateToCloud(updated, updates).catch(() => {});- }+ syncService.debouncedPush('note', note.id);setSaveState("saved");fadeTimerRef.current = setTimeout(() => setSaveState("idle"), 2000);} catch {@@ -73,7 +71,7 @@ export default function NoteEditor({ note, cloudEnabled, onDelete, onUpdate }: N}}, 800);},- [note, cloudEnabled, onUpdate]+ [note, onUpdate]);useEffect(() => {@@ -104,11 +102,8 @@ export default function NoteEditor({ note, cloudEnabled, onDelete, onUpdate }: Nconst handleConfirmDelete = useCallback(async () => {await window.electronAPI.deleteNote(note.id);- if (cloudEnabled && note.cloud_id) {- syncNoteDeleteToCloud(note.cloud_id).catch(() => {});- }onDelete(note.id);- }, [note, cloudEnabled, onDelete]);+ }, [note, onDelete]);return (<div className="flex flex-col h-full min-h-0">diff --git a/src/components/SettingsPage.tsx b/src/components/SettingsPage.tsxindex 826730953..7d46bb43e 100644--- a/src/components/SettingsPage.tsx+++ b/src/components/SettingsPage.tsx@@ -83,6 +83,7 @@ import { useSettingsLayout } from "./ui/useSettingsLayout";import { useUsage } from "../hooks/useUsage";import { cn } from "./lib/utils";import { startMigration, useMigration } from "../stores/noteStore.js";+import { syncService } from "../services/SyncService.js";import { formatBytes } from "../utils/formatBytes";import { useSettingsStore } from "../stores/settingsStore";import { canManageSystemAudioInApp } from "../utils/systemAudioAccess";@@ -3348,7 +3349,10 @@ EOF`,checked={cloudBackupEnabled}onChange={(v) => {setCloudBackupEnabled(v);- if (v) startMigration().catch(console.error);+ if (v) {+ startMigration().catch(console.error);+ syncService.syncAll().catch(console.error);+ }}}/></SettingsRow>@@ -3379,6 +3383,25 @@ EOF`,{t("settingsPage.privacy.cloudNotesMigrationDone")}</p>)}+ {cloudBackupEnabled && isSignedIn && (() => {+ const lastSyncedAt = localStorage.getItem("lastSyncedAt");+ if (!lastSyncedAt) return null;+ const date = new Date(lastSyncedAt);+ const now = new Date();+ const diffMs = now.getTime() - date.getTime();+ const diffMin = Math.floor(diffMs / 60000);+ const diffHr = Math.floor(diffMs / 3600000);+ let relative: string;+ if (diffMin < 1) relative = t("settingsPage.privacy.justNow");+ else if (diffMin < 60) relative = t("settingsPage.privacy.minutesAgo", { count: diffMin });+ else if (diffHr < 24) relative = t("settingsPage.privacy.hoursAgo", { count: diffHr });+ else relative = date.toLocaleDateString(undefined, { month: "short", day: "numeric", hour: "2-digit", minute: "2-digit" });+ return (+ <p className="mt-1 text-xs text-muted-foreground">+ {t("settingsPage.privacy.lastSynced", { time: relative })}+ </p>+ );+ })()}</div>)}diff --git a/src/helpers/database.js b/src/helpers/database.jsindex 5f4e6f581..478ecb7ab 100644--- a/src/helpers/database.js+++ b/src/helpers/database.js@@ -1,6 +1,7 @@const Database = require("better-sqlite3");const path = require("path");const fs = require("fs");+const { randomUUID } = require("crypto");const debugLogger = require("./debugLogger");const { app } = require("electron");@@ -422,6 +423,94 @@ class DatabaseManager {)`);+ // Sync columns for notes+ try {+ this.db.exec("ALTER TABLE notes ADD COLUMN client_note_id TEXT");+ } catch (err) {+ if (!err.message.includes("duplicate column")) throw err;+ }+ try {+ this.db.exec("ALTER TABLE notes ADD COLUMN sync_status TEXT DEFAULT 'pending'");+ } catch (err) {+ if (!err.message.includes("duplicate column")) throw err;+ }+ try {+ this.db.exec("ALTER TABLE notes ADD COLUMN deleted_at TEXT");+ } catch (err) {+ if (!err.message.includes("duplicate column")) throw err;+ }++ // Sync columns for folders+ try {+ this.db.exec("ALTER TABLE folders ADD COLUMN client_folder_id TEXT");+ } catch (err) {+ if (!err.message.includes("duplicate column")) throw err;+ }+ try {+ this.db.exec("ALTER TABLE folders ADD COLUMN cloud_id TEXT");+ } catch (err) {+ if (!err.message.includes("duplicate column")) throw err;+ }+ try {+ this.db.exec("ALTER TABLE folders ADD COLUMN sync_status TEXT DEFAULT 'pending'");+ } catch (err) {+ if (!err.message.includes("duplicate column")) throw err;+ }++ // Sync columns for agent_conversations+ try {+ this.db.exec("ALTER TABLE agent_conversations ADD COLUMN client_conversation_id TEXT");+ } catch (err) {+ if (!err.message.includes("duplicate column")) throw err;+ }+ try {+ this.db.exec("ALTER TABLE agent_conversations ADD COLUMN sync_status TEXT DEFAULT 'pending'");+ } catch (err) {+ if (!err.message.includes("duplicate column")) throw err;+ }+ try {+ this.db.exec("ALTER TABLE agent_conversations ADD COLUMN deleted_at TEXT");+ } catch (err) {+ if (!err.message.includes("duplicate column")) throw err;+ }++ // Sync columns for transcriptions+ try {+ this.db.exec("ALTER TABLE transcriptions ADD COLUMN client_transcription_id TEXT");+ } catch (err) {+ if (!err.message.includes("duplicate column")) throw err;+ }+ try {+ this.db.exec("ALTER TABLE transcriptions ADD COLUMN cloud_id TEXT");+ } catch (err) {+ if (!err.message.includes("duplicate column")) throw err;+ }+ try {+ this.db.exec("ALTER TABLE transcriptions ADD COLUMN sync_status TEXT DEFAULT 'pending'");+ } catch (err) {+ if (!err.message.includes("duplicate column")) throw err;+ }++ // Backfill client IDs for existing rows+ const syncTables = [+ { table: "notes", col: "client_note_id" },+ { table: "folders", col: "client_folder_id" },+ { table: "agent_conversations", col: "client_conversation_id" },+ { table: "transcriptions", col: "client_transcription_id" },+ ];+ for (const { table, col } of syncTables) {+ const rows = this.db.prepare(`SELECT id FROM ${table} WHERE ${col} IS NULL`).all();+ const stmt = this.db.prepare(`UPDATE ${table} SET ${col} = ? WHERE id = ?`);+ for (const row of rows) {+ stmt.run(randomUUID(), row.id);+ }+ }++ this.db.exec("CREATE UNIQUE INDEX IF NOT EXISTS idx_notes_client_note_id ON notes(client_note_id)");+ this.db.exec("CREATE UNIQUE INDEX IF NOT EXISTS idx_folders_client_folder_id ON folders(client_folder_id)");+ this.db.exec("CREATE UNIQUE INDEX IF NOT EXISTS idx_conversations_client_id ON agent_conversations(client_conversation_id)");+ this.db.exec("CREATE UNIQUE INDEX IF NOT EXISTS idx_transcriptions_client_id ON transcriptions(client_transcription_id)");+return true;} catch (error) {debugLogger.error("Database initialization failed", { error: error.message }, "database");@@ -438,10 +527,11 @@ class DatabaseManager {if (!this.db) {throw new Error("Database not initialized");}+ const clientTranscriptionId = randomUUID();const stmt = this.db.prepare(- "INSERT INTO transcriptions (text, raw_text, status, error_message, error_code) VALUES (?, ?, ?, ?, ?)"+ "INSERT INTO transcriptions (text, raw_text, status, error_message, error_code, client_transcription_id) VALUES (?, ?, ?, ?, ?, ?)");- const result = stmt.run(text, rawText, status, errorMessage, errorCode);+ const result = stmt.run(text, rawText, status, errorMessage, errorCode, clientTranscriptionId);const fetchStmt = this.db.prepare("SELECT * FROM transcriptions WHERE id = ?");const transcription = fetchStmt.get(result.lastInsertRowid);@@ -624,10 +714,11 @@ class DatabaseManager {.get(defaultFolderName);folderId = defaultFolder?.id || null;}+ const clientNoteId = randomUUID();const stmt = this.db.prepare(- "INSERT INTO notes (title, content, note_type, source_file, audio_duration_seconds, folder_id) VALUES (?, ?, ?, ?, ?, ?)"+ "INSERT INTO notes (title, content, note_type, source_file, audio_duration_seconds, folder_id, client_note_id) VALUES (?, ?, ?, ?, ?, ?, ?)");- const result = stmt.run(title, content, noteType, sourceFile, audioDuration, folderId);+ const result = stmt.run(title, content, noteType, sourceFile, audioDuration, folderId, clientNoteId);const fetchStmt = this.db.prepare("SELECT * FROM notes WHERE id = ?");const note = fetchStmt.get(result.lastInsertRowid);@@ -657,7 +748,7 @@ class DatabaseManager {if (!this.db) {throw new Error("Database not initialized");}- const conditions = [];+ const conditions = ["deleted_at IS NULL"];const params = [];if (noteType) {conditions.push("note_type = ?");@@ -667,7 +758,7 @@ class DatabaseManager {conditions.push("folder_id = ?");params.push(folderId);}- const where = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";+ const where = `WHERE ${conditions.join(" AND ")}`;const stmt = this.db.prepare(`SELECT * FROM notes ${where} ORDER BY updated_at DESC LIMIT ?`);params.push(limit);return stmt.all(...params);@@ -690,6 +781,10 @@ class DatabaseManager {"transcript","calendar_event_id","participants",+ "sync_status",+ "deleted_at",+ "client_note_id",+ "cloud_id",];const fields = [];const values = [];@@ -732,9 +827,10 @@ class DatabaseManager {if (existing) return { success: false, error: "A folder with that name already exists" };const maxOrder = this.db.prepare("SELECT MAX(sort_order) as max_order FROM folders").get();const sortOrder = (maxOrder?.max_order ?? 0) + 1;+ const clientFolderId = randomUUID();const result = this.db- .prepare("INSERT INTO folders (name, sort_order) VALUES (?, ?)")- .run(trimmed, sortOrder);+ .prepare("INSERT INTO folders (name, sort_order, client_folder_id) VALUES (?, ?, ?)")+ .run(trimmed, sortOrder, clientFolderId);const folder = this.db.prepare("SELECT * FROM folders WHERE id = ?").get(result.lastInsertRowid);@@ -790,7 +886,7 @@ class DatabaseManager {try {if (!this.db) throw new Error("Database not initialized");return this.db- .prepare("SELECT folder_id, COUNT(*) as count FROM notes GROUP BY folder_id")+ .prepare("SELECT folder_id, COUNT(*) as count FROM notes WHERE deleted_at IS NULL GROUP BY folder_id").all();} catch (error) {debugLogger.error("Error getting folder note counts", { error: error.message }, "notes");@@ -885,7 +981,9 @@ class DatabaseManager {if (!this.db) {throw new Error("Database not initialized");}- const stmt = this.db.prepare("DELETE FROM notes WHERE id = ?");+ const stmt = this.db.prepare(+ "UPDATE notes SET deleted_at = datetime('now'), sync_status = 'pending', updated_at = datetime('now') WHERE id = ?"+ );const result = stmt.run(id);return { success: result.changes > 0, id };} catch (error) {@@ -897,9 +995,10 @@ class DatabaseManager {createAgentConversation(title = "Untitled", noteId = null) {try {if (!this.db) throw new Error("Database not initialized");+ const clientConversationId = randomUUID();const result = this.db- .prepare("INSERT INTO agent_conversations (title, note_id) VALUES (?, ?)")- .run(title, noteId);+ .prepare("INSERT INTO agent_conversations (title, note_id, client_conversation_id) VALUES (?, ?, ?)")+ .run(title, noteId, clientConversationId);return this.db.prepare("SELECT * FROM agent_conversations WHERE id = ?").get(result.lastInsertRowid);@@ -938,7 +1037,7 @@ class DatabaseManager {try {if (!this.db) throw new Error("Database not initialized");return this.db- .prepare("SELECT * FROM agent_conversations ORDER BY updated_at DESC LIMIT ?")+ .prepare("SELECT * FROM agent_conversations WHERE deleted_at IS NULL ORDER BY updated_at DESC LIMIT ?").all(limit);} catch (error) {debugLogger.error("Error getting agent conversations", { error: error.message }, "database");@@ -966,8 +1065,11 @@ class DatabaseManager {deleteAgentConversation(id) {try {if (!this.db) throw new Error("Database not initialized");- this.db.prepare("DELETE FROM agent_messages WHERE conversation_id = ?").run(id);- const result = this.db.prepare("DELETE FROM agent_conversations WHERE id = ?").run(id);+ const result = this.db+ .prepare(+ "UPDATE agent_conversations SET deleted_at = datetime('now'), sync_status = 'pending', updated_at = datetime('now') WHERE id = ?"+ )+ .run(id);return { success: result.changes > 0 };} catch (error) {debugLogger.error("Error deleting agent conversation", { error: error.message }, "database");@@ -1266,7 +1368,7 @@ class DatabaseManager {SELECT n.*FROM notes nJOIN notes_fts ON notes_fts.rowid = n.id- WHERE notes_fts MATCH ?+ WHERE notes_fts MATCH ? AND n.deleted_at IS NULLORDER BY notes_fts.rankLIMIT ?`@@ -1427,8 +1529,8 @@ class DatabaseManager {try {if (!this.db) throw new Error("Database not initialized");const archiveFilter = includeArchived- ? "WHERE c.archived_at IS NOT NULL"- : "WHERE c.archived_at IS NULL";+ ? "WHERE c.archived_at IS NOT NULL AND c.deleted_at IS NULL"+ : "WHERE c.archived_at IS NULL AND c.deleted_at IS NULL";return this.db.prepare(`SELECT c.id, c.title, c.created_at, c.updated_at, c.archived_at, c.cloud_id,@@ -1466,7 +1568,7 @@ class DatabaseManager {FROM agent_conversations cLEFT JOIN agent_messages m ON m.conversation_id = c.idLEFT JOIN agent_messages ms ON ms.conversation_id = c.id- WHERE c.archived_at IS NULL+ WHERE c.archived_at IS NULL AND c.deleted_at IS NULLAND (c.title LIKE ? OR ms.content LIKE ?)GROUP BY c.idORDER BY c.updated_at DESC@@ -1755,6 +1857,347 @@ class DatabaseManager {}}++ getPendingNotes() {+ try {+ if (!this.db) throw new Error("Database not initialized");+ return this.db+ .prepare("SELECT * FROM notes WHERE sync_status = 'pending' AND deleted_at IS NULL")+ .all();+ } catch (error) {+ debugLogger.error("Error getting pending notes", { error: error.message }, "database");+ throw error;+ }+ }++ getPendingNoteDeletes() {+ try {+ if (!this.db) throw new Error("Database not initialized");+ return this.db+ .prepare("SELECT * FROM notes WHERE deleted_at IS NOT NULL AND cloud_id IS NOT NULL AND sync_status = 'pending'")+ .all();+ } catch (error) {+ debugLogger.error("Error getting pending note deletes", { error: error.message }, "database");+ throw error;+ }+ }++ getNoteByClientId(clientNoteId) {+ try {+ if (!this.db) throw new Error("Database not initialized");+ return this.db.prepare("SELECT * FROM notes WHERE client_note_id = ?").get(clientNoteId) || null;+ } catch (error) {+ debugLogger.error("Error getting note by client id", { error: error.message }, "database");+ throw error;+ }+ }++ upsertNoteFromCloud(cloudNote, localFolderId) {+ try {+ if (!this.db) throw new Error("Database not initialized");+ const stmt = this.db.prepare(`+ INSERT INTO notes (client_note_id, cloud_id, title, content, enhanced_content,+ enhancement_prompt, enhanced_at_content_hash, note_type, source_file,+ audio_duration_seconds, transcript, folder_id, sync_status, created_at, updated_at)+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'synced', ?, ?)+ ON CONFLICT(client_note_id) DO UPDATE SET+ cloud_id = excluded.cloud_id,+ title = excluded.title,+ content = excluded.content,+ enhanced_content = excluded.enhanced_content,+ enhancement_prompt = excluded.enhancement_prompt,+ enhanced_at_content_hash = excluded.enhanced_at_content_hash,+ transcript = excluded.transcript,+ folder_id = excluded.folder_id,+ sync_status = 'synced',+ updated_at = excluded.updated_at+ `);+ stmt.run(+ cloudNote.client_note_id,+ cloudNote.id,+ cloudNote.title,+ cloudNote.content,+ cloudNote.enhanced_content || null,+ cloudNote.enhancement_prompt || null,+ cloudNote.enhanced_at_content_hash || null,+ cloudNote.note_type || "personal",+ cloudNote.source_file || null,+ cloudNote.audio_duration_seconds || null,+ cloudNote.transcript || null,+ localFolderId,+ cloudNote.created_at,+ cloudNote.updated_at+ );+ return this.db.prepare("SELECT * FROM notes WHERE client_note_id = ?").get(cloudNote.client_note_id);+ } catch (error) {+ debugLogger.error("Error upserting note from cloud", { error: error.message }, "database");+ throw error;+ }+ }++ markNoteSynced(id, cloudId) {+ try {+ if (!this.db) throw new Error("Database not initialized");+ this.db.prepare("UPDATE notes SET sync_status = 'synced', cloud_id = ? WHERE id = ?").run(cloudId, id);+ return { success: true };+ } catch (error) {+ debugLogger.error("Error marking note synced", { error: error.message }, "database");+ throw error;+ }+ }++ markNoteSyncError(id) {+ try {+ if (!this.db) throw new Error("Database not initialized");+ this.db.prepare("UPDATE notes SET sync_status = 'error' WHERE id = ?").run(id);+ return { success: true };+ } catch (error) {+ debugLogger.error("Error marking note sync error", { error: error.message }, "database");+ throw error;+ }+ }++ hardDeleteNote(id) {+ try {+ if (!this.db) throw new Error("Database not initialized");+ const result = this.db.prepare("DELETE FROM notes WHERE id = ?").run(id);+ return { success: result.changes > 0, id };+ } catch (error) {+ debugLogger.error("Error hard deleting note", { error: error.message }, "database");+ throw error;+ }+ }+++ getPendingFolders() {+ try {+ if (!this.db) throw new Error("Database not initialized");+ return this.db.prepare("SELECT * FROM folders WHERE sync_status = 'pending'").all();+ } catch (error) {+ debugLogger.error("Error getting pending folders", { error: error.message }, "database");+ throw error;+ }+ }++ getFolderByClientId(clientFolderId) {+ try {+ if (!this.db) throw new Error("Database not initialized");+ return this.db.prepare("SELECT * FROM folders WHERE client_folder_id = ?").get(clientFolderId) || null;+ } catch (error) {+ debugLogger.error("Error getting folder by client id", { error: error.message }, "database");+ throw error;+ }+ }++ upsertFolderFromCloud(cloudFolder) {+ try {+ if (!this.db) throw new Error("Database not initialized");+ const stmt = this.db.prepare(`+ INSERT INTO folders (client_folder_id, cloud_id, name, is_default, sort_order, sync_status, created_at)+ VALUES (?, ?, ?, ?, ?, 'synced', ?)+ ON CONFLICT(client_folder_id) DO UPDATE SET+ cloud_id = excluded.cloud_id,+ name = excluded.name,+ sort_order = excluded.sort_order,+ sync_status = 'synced'+ `);+ stmt.run(+ cloudFolder.client_folder_id,+ cloudFolder.id,+ cloudFolder.name,+ cloudFolder.is_default ? 1 : 0,+ cloudFolder.sort_order || 0,+ cloudFolder.created_at+ );+ return this.db.prepare("SELECT * FROM folders WHERE client_folder_id = ?").get(cloudFolder.client_folder_id);+ } catch (error) {+ debugLogger.error("Error upserting folder from cloud", { error: error.message }, "database");+ throw error;+ }+ }++ markFolderSynced(id, cloudId) {+ try {+ if (!this.db) throw new Error("Database not initialized");+ this.db.prepare("UPDATE folders SET sync_status = 'synced', cloud_id = ? WHERE id = ?").run(cloudId, id);+ return { success: true };+ } catch (error) {+ debugLogger.error("Error marking folder synced", { error: error.message }, "database");+ throw error;+ }+ }++ getFolderIdMap() {+ try {+ if (!this.db) throw new Error("Database not initialized");+ return this.db.prepare("SELECT * FROM folders").all();+ } catch (error) {+ debugLogger.error("Error getting folder id map", { error: error.message }, "database");+ throw error;+ }+ }+++ getPendingConversations() {+ try {+ if (!this.db) throw new Error("Database not initialized");+ return this.db+ .prepare("SELECT * FROM agent_conversations WHERE sync_status = 'pending' AND deleted_at IS NULL")+ .all();+ } catch (error) {+ debugLogger.error("Error getting pending conversations", { error: error.message }, "database");+ throw error;+ }+ }++ getPendingConversationDeletes() {+ try {+ if (!this.db) throw new Error("Database not initialized");+ return this.db+ .prepare("SELECT * FROM agent_conversations WHERE deleted_at IS NOT NULL AND cloud_id IS NOT NULL AND sync_status = 'pending'")+ .all();+ } catch (error) {+ debugLogger.error("Error getting pending conversation deletes", { error: error.message }, "database");+ throw error;+ }+ }++ getConversationByClientId(clientId) {+ try {+ if (!this.db) throw new Error("Database not initialized");+ return this.db.prepare("SELECT * FROM agent_conversations WHERE client_conversation_id = ?").get(clientId) || null;+ } catch (error) {+ debugLogger.error("Error getting conversation by client id", { error: error.message }, "database");+ throw error;+ }+ }++ upsertConversationFromCloud(cloudConv, messages) {+ try {+ if (!this.db) throw new Error("Database not initialized");+ const transaction = this.db.transaction(() => {+ const convStmt = this.db.prepare(`+ INSERT INTO agent_conversations (client_conversation_id, cloud_id, title, note_id, sync_status, created_at, updated_at)+ VALUES (?, ?, ?, ?, 'synced', ?, ?)+ ON CONFLICT(client_conversation_id) DO UPDATE SET+ cloud_id = excluded.cloud_id,+ title = excluded.title,+ note_id = excluded.note_id,+ sync_status = 'synced',+ updated_at = excluded.updated_at+ `);+ convStmt.run(+ cloudConv.client_conversation_id,+ cloudConv.id,+ cloudConv.title,+ cloudConv.note_id || null,+ cloudConv.created_at,+ cloudConv.updated_at+ );+ const conv = this.db+ .prepare("SELECT * FROM agent_conversations WHERE client_conversation_id = ?")+ .get(cloudConv.client_conversation_id);+ this.db.prepare("DELETE FROM agent_messages WHERE conversation_id = ?").run(conv.id);+ if (messages && messages.length > 0) {+ const msgStmt = this.db.prepare(+ "INSERT INTO agent_messages (conversation_id, role, content, metadata, created_at) VALUES (?, ?, ?, ?, ?)"+ );+ for (const msg of messages) {+ msgStmt.run(conv.id, msg.role, msg.content, msg.metadata || null, msg.created_at);+ }+ }+ return conv;+ });+ return transaction();+ } catch (error) {+ debugLogger.error("Error upserting conversation from cloud", { error: error.message }, "database");+ throw error;+ }+ }++ markConversationSynced(id, cloudId) {+ try {+ if (!this.db) throw new Error("Database not initialized");+ this.db.prepare("UPDATE agent_conversations SET sync_status = 'synced', cloud_id = ? WHERE id = ?").run(cloudId, id);+ return { success: true };+ } catch (error) {+ debugLogger.error("Error marking conversation synced", { error: error.message }, "database");+ throw error;+ }+ }++ hardDeleteConversation(id) {+ try {+ if (!this.db) throw new Error("Database not initialized");+ this.db.prepare("DELETE FROM agent_messages WHERE conversation_id = ?").run(id);+ const result = this.db.prepare("DELETE FROM agent_conversations WHERE id = ?").run(id);+ return { success: result.changes > 0 };+ } catch (error) {+ debugLogger.error("Error hard deleting conversation", { error: error.message }, "database");+ throw error;+ }+ }+++ getPendingTranscriptions() {+ try {+ if (!this.db) throw new Error("Database not initialized");+ return this.db.prepare("SELECT * FROM transcriptions WHERE sync_status = 'pending'").all();+ } catch (error) {+ debugLogger.error("Error getting pending transcriptions", { error: error.message }, "database");+ throw error;+ }+ }++ getTranscriptionByClientId(clientId) {+ try {+ if (!this.db) throw new Error("Database not initialized");+ return this.db.prepare("SELECT * FROM transcriptions WHERE client_transcription_id = ?").get(clientId) || null;+ } catch (error) {+ debugLogger.error("Error getting transcription by client id", { error: error.message }, "database");+ throw error;+ }+ }++ upsertTranscriptionFromCloud(cloudTranscription) {+ try {+ if (!this.db) throw new Error("Database not initialized");+ const stmt = this.db.prepare(`+ INSERT INTO transcriptions (client_transcription_id, cloud_id, text, raw_text, status, sync_status, created_at)+ VALUES (?, ?, ?, ?, ?, 'synced', ?)+ ON CONFLICT(client_transcription_id) DO UPDATE SET+ cloud_id = excluded.cloud_id,+ text = excluded.text,+ raw_text = excluded.raw_text,+ status = excluded.status,+ sync_status = 'synced'+ `);+ stmt.run(+ cloudTranscription.client_transcription_id,+ cloudTranscription.id,+ cloudTranscription.text,+ cloudTranscription.raw_text || null,+ cloudTranscription.status || "completed",+ cloudTranscription.created_at+ );+ return this.db.prepare("SELECT * FROM transcriptions WHERE client_transcription_id = ?").get(cloudTranscription.client_transcription_id);+ } catch (error) {+ debugLogger.error("Error upserting transcription from cloud", { error: error.message }, "database");+ throw error;+ }+ }++ markTranscriptionSynced(id, cloudId) {+ try {+ if (!this.db) throw new Error("Database not initialized");+ this.db.prepare("UPDATE transcriptions SET sync_status = 'synced', cloud_id = ? WHERE id = ?").run(cloudId, id);+ return { success: true };+ } catch (error) {+ debugLogger.error("Error marking transcription synced", { error: error.message }, "database");+ throw error;+ }+ }+getNotesWithUnmappedSpeakers() {try {if (!this.db) throw new Error("Database not initialized");diff --git a/src/helpers/ipcHandlers.js b/src/helpers/ipcHandlers.jsindex be62f7ee2..d7957db01 100644--- a/src/helpers/ipcHandlers.js+++ b/src/helpers/ipcHandlers.js@@ -931,6 +931,36 @@ class IPCHandlers {return this.databaseManager.searchAgentConversations(query, limit);});+ // Notes sync+ ipcMain.handle("db-get-pending-notes", () => this.databaseManager.getPendingNotes());+ ipcMain.handle("db-get-pending-note-deletes", () => this.databaseManager.getPendingNoteDeletes());+ ipcMain.handle("db-get-note-by-client-id", (_, clientNoteId) => this.databaseManager.getNoteByClientId(clientNoteId));+ ipcMain.handle("db-upsert-note-from-cloud", (_, cloudNote, localFolderId) => this.databaseManager.upsertNoteFromCloud(cloudNote, localFolderId));+ ipcMain.handle("db-mark-note-synced", (_, id, cloudId) => this.databaseManager.markNoteSynced(id, cloudId));+ ipcMain.handle("db-mark-note-sync-error", (_, id) => this.databaseManager.markNoteSyncError(id));+ ipcMain.handle("db-hard-delete-note", (_, id) => this.databaseManager.hardDeleteNote(id));++ // Folders sync+ ipcMain.handle("db-get-pending-folders", () => this.databaseManager.getPendingFolders());+ ipcMain.handle("db-get-folder-by-client-id", (_, clientFolderId) => this.databaseManager.getFolderByClientId(clientFolderId));+ ipcMain.handle("db-upsert-folder-from-cloud", (_, cloudFolder) => this.databaseManager.upsertFolderFromCloud(cloudFolder));+ ipcMain.handle("db-mark-folder-synced", (_, id, cloudId) => this.databaseManager.markFolderSynced(id, cloudId));+ ipcMain.handle("db-get-folder-id-map", () => this.databaseManager.getFolderIdMap());++ // Conversations sync+ ipcMain.handle("db-get-pending-conversations", () => this.databaseManager.getPendingConversations());+ ipcMain.handle("db-get-pending-conversation-deletes", () => this.databaseManager.getPendingConversationDeletes());+ ipcMain.handle("db-get-conversation-by-client-id", (_, clientId) => this.databaseManager.getConversationByClientId(clientId));+ ipcMain.handle("db-upsert-conversation-from-cloud", (_, cloudConv, messages) => this.databaseManager.upsertConversationFromCloud(cloudConv, messages));+ ipcMain.handle("db-mark-conversation-synced", (_, id, cloudId) => this.databaseManager.markConversationSynced(id, cloudId));+ ipcMain.handle("db-hard-delete-conversation", (_, id) => this.databaseManager.hardDeleteConversation(id));++ // Transcriptions sync+ ipcMain.handle("db-get-pending-transcriptions", () => this.databaseManager.getPendingTranscriptions());+ ipcMain.handle("db-get-transcription-by-client-id", (_, clientId) => this.databaseManager.getTranscriptionByClientId(clientId));+ ipcMain.handle("db-upsert-transcription-from-cloud", (_, cloudTranscription) => this.databaseManager.upsertTranscriptionFromCloud(cloudTranscription));+ ipcMain.handle("db-mark-transcription-synced", (_, id, cloudId) => this.databaseManager.markTranscriptionSynced(id, cloudId));+ipcMain.handle("export-note", async (event, noteId, format) => {try {const note = this.databaseManager.getNote(noteId);diff --git a/src/services/ConversationsService.ts b/src/services/ConversationsService.tsindex c75f4d663..6d14782d9 100644--- a/src/services/ConversationsService.ts+++ b/src/services/ConversationsService.ts@@ -66,22 +66,28 @@ async function deleteConversation(id: string): Promise<void> {if (!res.ok) throw new Error(await res.text());}+interface CloudConversationWithMessages extends CloudConversation {+ messages?: CloudMessage[];+}+async function list(limit?: number,before?: string,- archived?: boolean-): Promise<{ conversations: CloudConversation[] }> {+ archived?: boolean,+ include?: string+): Promise<{ conversations: CloudConversationWithMessages[] }> {const params = new URLSearchParams();if (limit !== undefined) params.set("limit", String(limit));if (before !== undefined) params.set("before", before);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" });if (!res.ok) throw new Error(await res.text());- return res.json() as Promise<{ conversations: CloudConversation[] }>;+ return res.json() as Promise<{ conversations: CloudConversationWithMessages[] }>;}async function addMessage(diff --git a/src/services/FoldersService.ts b/src/services/FoldersService.tsnew file mode 100644index 000000000..2859a13af--- /dev/null+++ b/src/services/FoldersService.ts@@ -0,0 +1,79 @@+import { OPENWHISPR_API_URL } from "../config/constants.js";++interface FolderInput {+ name: string;+ client_folder_id?: string;+ is_default?: boolean;+ sort_order?: number;+}++interface CloudFolder {+ id: string;+ client_folder_id: string | null;+ name: string;+ is_default: boolean;+ sort_order: number;+ created_at: string;+ updated_at: string;+}++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>;+}++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[] }>;+}++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>;+}++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());+}++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[] }>;+}++export { create, batchCreate, update, deleteFolder, list };++export const FoldersService = {+ create,+ batchCreate,+ update,+ delete: deleteFolder,+ list,+};diff --git a/src/services/NotesService.ts b/src/services/NotesService.tsindex 5c9b78f04..a7701d425 100644--- a/src/services/NotesService.ts+++ b/src/services/NotesService.ts@@ -10,6 +10,9 @@ interface NoteInput {source_file?: string | null;audio_duration_seconds?: number | null;participants?: string | null;+ transcript?: string | null;+ enhanced_at_content_hash?: string | null;+ folder_id?: string | null;created_at?: string;updated_at?: string;}@@ -21,6 +24,13 @@ interface CloudNote {content: string;enhanced_content: string | null;note_type: string;+ enhancement_prompt: string | null;+ source_file: string | null;+ audio_duration_seconds: number | null;+ folder_id: string | null;+ transcript: string | null;+ enhanced_at_content_hash: string | null;+ deleted_at: string | null;created_at: string;updated_at: string;}diff --git a/src/services/SyncService.ts b/src/services/SyncService.tsnew file mode 100644index 000000000..4fc670d89--- /dev/null+++ b/src/services/SyncService.ts@@ -0,0 +1,506 @@+import type {+ NoteItem,+ FolderItem,+ TranscriptionItem,+ ConversationPreview,+} from "../types/electron";+import { NotesService } from "./NotesService.js";+import { ConversationsService } from "./ConversationsService.js";+import { FoldersService } from "./FoldersService.js";+import { TranscriptionsService } from "./TranscriptionsService.js";++const PUSH_DEBOUNCE_MS = 2000;+const BATCH_SIZE = 50;+const TRANSCRIPTION_BATCH_SIZE = 100;++class SyncService {+ private syncing = false;+ private pushTimers = new Map<string, ReturnType<typeof setTimeout>>();++ canSync(): boolean {+ return (+ localStorage.getItem("isSignedIn") === "true" &&+ localStorage.getItem("cloudBackupEnabled") === "true" &&+ localStorage.getItem("isSubscribed") === "true"+ );+ }++ async syncAll(): Promise<void> {+ if (this.syncing || !this.canSync()) return;+ this.syncing = true;+ try {+ await this.syncFolders();+ await this.syncNotes();+ await this.syncConversations();+ await this.syncTranscriptions();+ localStorage.setItem("lastSyncedAt", new Date().toISOString());+ } catch (err) {+ console.error("Sync failed:", err);+ } finally {+ this.syncing = false;+ }+ }++ debouncedPush(entityType: string, entityId: number): void {+ if (!this.canSync()) return;+ const key = `${entityType}:${entityId}`;+ const existing = this.pushTimers.get(key);+ if (existing) clearTimeout(existing);+ this.pushTimers.set(+ key,+ setTimeout(() => {+ this.pushTimers.delete(key);+ this.pushEntity(entityType, entityId).catch(console.error);+ }, PUSH_DEBOUNCE_MS)+ );+ }++ private async pushEntity(entityType: string, entityId: number): Promise<void> {+ if (!this.canSync()) return;+ switch (entityType) {+ case "folder":+ return this.pushFolder(entityId);+ case "note":+ return this.pushNote(entityId);+ case "conversation":+ return this.pushConversation(entityId);+ case "transcription":+ return this.pushTranscription(entityId);+ }+ }++ private async pushFolder(id: number): Promise<void> {+ const folders = (await window.electronAPI.getFolders?.()) ?? [];+ const folder = folders.find((f) => f.id === id);+ if (!folder) return;++ if (folder.cloud_id) {+ await FoldersService.update(folder.cloud_id, {+ name: folder.name,+ sort_order: folder.sort_order,+ });+ } else {+ const cloud = await FoldersService.create({+ name: folder.name,+ client_folder_id: folder.client_folder_id,+ is_default: !!folder.is_default,+ sort_order: folder.sort_order,+ });+ await window.electronAPI.markFolderSynced?.(folder.id, cloud.id);+ }+ }++ private async pushNote(id: number): Promise<void> {+ const note = await window.electronAPI.getNote?.(id);+ if (!note) return;++ const folderMap = await this.buildLocalToCloudFolderMap();+ const cloudFolderId = note.folder_id ? (folderMap.get(note.folder_id) ?? null) : null;++ if (note.cloud_id) {+ await NotesService.update(note.cloud_id, {+ title: note.title,+ content: note.content,+ enhanced_content: note.enhanced_content,+ enhancement_prompt: note.enhancement_prompt,+ enhanced_at_content_hash: note.enhanced_at_content_hash,+ note_type: note.note_type,+ source_file: note.source_file,+ audio_duration_seconds: note.audio_duration_seconds,+ transcript: note.transcript,+ folder_id: cloudFolderId,+ });+ } else {+ const cloud = await NotesService.create({+ client_note_id: note.client_note_id,+ title: note.title,+ content: note.content,+ enhanced_content: note.enhanced_content,+ enhancement_prompt: note.enhancement_prompt,+ enhanced_at_content_hash: note.enhanced_at_content_hash,+ note_type: note.note_type,+ source_file: note.source_file,+ audio_duration_seconds: note.audio_duration_seconds,+ transcript: note.transcript,+ folder_id: cloudFolderId,+ created_at: note.created_at,+ updated_at: note.updated_at,+ });+ await window.electronAPI.markNoteSynced?.(note.id, cloud.id);+ }+ }++ private async pushConversation(id: number): Promise<void> {+ const full = await window.electronAPI.getAgentConversation?.(id);+ if (!full) return;++ if (full.cloud_id) {+ await ConversationsService.update(full.cloud_id, { title: full.title });+ } else {+ const cloud = await ConversationsService.create({+ client_conversation_id: String(full.id),+ title: full.title,+ created_at: full.created_at,+ updated_at: full.updated_at,+ messages: full.messages.map((m) => ({+ role: m.role,+ content: m.content,+ metadata: m.metadata+ ? typeof m.metadata === "string"+ ? JSON.parse(m.metadata)+ : m.metadata+ : null,+ })),+ });+ await window.electronAPI.markConversationSynced?.(full.id, cloud.id);+ }+ }++ private async pushTranscription(id: number): Promise<void> {+ const t = await window.electronAPI.getTranscriptionById?.(id);+ if (!t || t.cloud_id) return;++ const cloud = await TranscriptionsService.create({+ client_transcription_id: t.client_transcription_id,+ text: t.text,+ raw_text: t.raw_text,+ provider: t.provider,+ model: t.model,+ audio_duration_ms: t.audio_duration_ms,+ status: t.status,+ created_at: t.created_at,+ });+ await window.electronAPI.markTranscriptionSynced?.(t.id, cloud.id);+ }++ private async syncFolders(): Promise<void> {+ await this.pushPendingFolders();+ await this.pullFolders();+ }++ private async pushPendingFolders(): Promise<void> {+ const pending = (await window.electronAPI.getPendingFolders?.()) ?? [];+ if (pending.length === 0) return;++ const migration = pending.filter((f) => f.cloud_id);+ const fresh = pending.filter((f) => !f.cloud_id);++ for (const folder of migration) {+ try {+ await FoldersService.update(folder.cloud_id!, { name: folder.name });+ await window.electronAPI.markFolderSynced?.(folder.id, folder.cloud_id!);+ } catch (err) {+ console.error("Folder migration sync failed:", err);+ }+ }++ if (fresh.length > 0) {+ try {+ const { created } = await FoldersService.batchCreate(+ fresh.map((f) => ({+ name: f.name,+ client_folder_id: f.client_folder_id,+ is_default: !!f.is_default,+ sort_order: f.sort_order,+ }))+ );+ for (const cloudFolder of created) {+ const local = fresh.find((f) => f.client_folder_id === cloudFolder.client_folder_id);+ if (local) await window.electronAPI.markFolderSynced?.(local.id, cloudFolder.id);+ }+ } catch (err) {+ console.error("Folder batch create failed:", err);+ }+ }+ }++ private async pullFolders(): Promise<void> {+ try {+ const { folders: cloudFolders } = await FoldersService.list();+ for (const cloudFolder of cloudFolders) {+ const local = await window.electronAPI.getFolderByClientId?.(+ cloudFolder.client_folder_id ?? ""+ );+ if (!local || cloudFolder.updated_at > local.created_at) {+ await window.electronAPI.upsertFolderFromCloud?.(cloudFolder);+ }+ }+ } catch (err) {+ console.error("Folder pull failed:", err);+ }+ }++ private async syncNotes(): Promise<void> {+ await this.pushPendingNotes();+ await this.pushNoteDeletes();+ await this.pullNotes();+ }++ private async pushPendingNotes(): Promise<void> {+ const pending = (await window.electronAPI.getPendingNotes?.()) ?? [];+ if (pending.length === 0) return;++ const folderMap = await this.buildLocalToCloudFolderMap();+ const migration = pending.filter((n) => n.cloud_id);+ const fresh = pending.filter((n) => !n.cloud_id);++ for (const note of migration) {+ try {+ await NotesService.update(note.cloud_id!, { client_note_id: note.client_note_id });+ await window.electronAPI.markNoteSynced?.(note.id, note.cloud_id!);+ } catch {+ await window.electronAPI.markNoteSyncError?.(note.id);+ }+ }++ for (let i = 0; i < fresh.length; i += BATCH_SIZE) {+ const chunk = fresh.slice(i, i + BATCH_SIZE);+ try {+ const { created } = await NotesService.batchCreate(+ chunk.map((n) => ({+ client_note_id: n.client_note_id,+ title: n.title,+ content: n.content,+ enhanced_content: n.enhanced_content,+ enhancement_prompt: n.enhancement_prompt,+ enhanced_at_content_hash: n.enhanced_at_content_hash,+ note_type: n.note_type,+ source_file: n.source_file,+ audio_duration_seconds: n.audio_duration_seconds,+ transcript: n.transcript,+ folder_id: n.folder_id ? (folderMap.get(n.folder_id) ?? undefined) : undefined,+ created_at: n.created_at,+ updated_at: n.updated_at,+ }))+ );+ for (const { client_note_id, id: cloudId } of created) {+ const local = chunk.find((n) => n.client_note_id === client_note_id);+ if (local) await window.electronAPI.markNoteSynced?.(local.id, cloudId);+ }+ } catch {+ for (const n of chunk) {+ await window.electronAPI.markNoteSyncError?.(n.id);+ }+ }+ }+ }++ private async pushNoteDeletes(): Promise<void> {+ const deletes = (await window.electronAPI.getPendingNoteDeletes?.()) ?? [];+ for (const note of deletes) {+ try {+ await NotesService.delete(note.cloud_id!);+ await window.electronAPI.hardDeleteNote?.(note.id);+ } catch (err) {+ console.error("Note delete sync failed:", err);+ }+ }+ }++ private async pullNotes(): Promise<void> {+ try {+ const { cloudToLocal, defaultFolderId } = await this.buildCloudToLocalFolderMap();+ let before: string | undefined;+ let hasMore = true;++ while (hasMore) {+ const { notes: cloudNotes } = await NotesService.list(BATCH_SIZE, before);+ if (cloudNotes.length === 0) break;+ hasMore = cloudNotes.length === BATCH_SIZE;+ before = cloudNotes[cloudNotes.length - 1].created_at;++ for (const cloudNote of cloudNotes) {+ if (cloudNote.deleted_at) continue;+ const local = await window.electronAPI.getNoteByClientId?.(+ cloudNote.client_note_id ?? ""+ );+ const localFolderId = cloudNote.folder_id+ ? (cloudToLocal.get(cloudNote.folder_id) ?? defaultFolderId)+ : defaultFolderId;++ if (!local || cloudNote.updated_at > local.updated_at) {+ await window.electronAPI.upsertNoteFromCloud?.(cloudNote, localFolderId);+ }+ }+ }+ } catch (err) {+ console.error("Note pull failed:", err);+ }+ }++ private async syncConversations(): Promise<void> {+ await this.pushPendingConversations();+ await this.pushConversationDeletes();+ await this.pullConversations();+ }++ private async pushPendingConversations(): Promise<void> {+ const pending = (await window.electronAPI.getPendingConversations?.()) ?? [];+ if (pending.length === 0) return;++ const migration = pending.filter((c) => c.cloud_id);+ const fresh = pending.filter((c) => !c.cloud_id);++ for (const conv of migration) {+ try {+ await ConversationsService.update(conv.cloud_id!, { title: conv.title });+ await window.electronAPI.markConversationSynced?.(conv.id, conv.cloud_id!);+ } catch (err) {+ console.error("Conversation migration sync failed:", err);+ }+ }++ for (const conv of fresh) {+ try {+ const full = await window.electronAPI.getAgentConversation?.(conv.id);+ if (!full) continue;+ const cloudConv = await ConversationsService.create({+ client_conversation_id: conv.client_conversation_id ?? String(conv.id),+ title: conv.title,+ created_at: conv.created_at,+ updated_at: conv.updated_at,+ messages: full.messages.map((m) => ({+ role: m.role,+ content: m.content,+ metadata: m.metadata+ ? typeof m.metadata === "string"+ ? JSON.parse(m.metadata)+ : m.metadata+ : null,+ })),+ });+ await window.electronAPI.markConversationSynced?.(conv.id, cloudConv.id);+ } catch (err) {+ console.error("Conversation sync failed:", err);+ }+ }+ }++ private async pushConversationDeletes(): Promise<void> {+ const deletes = (await window.electronAPI.getPendingConversationDeletes?.()) ?? [];+ for (const conv of deletes) {+ try {+ await ConversationsService.delete(conv.cloud_id!);+ await window.electronAPI.hardDeleteConversation?.(conv.id);+ } catch (err) {+ console.error("Conversation delete sync failed:", err);+ }+ }+ }++ private async pullConversations(): Promise<void> {+ try {+ let before: string | undefined;+ let hasMore = true;++ while (hasMore) {+ const { conversations: cloudConvs } = await ConversationsService.list(+ BATCH_SIZE,+ before,+ false,+ "messages"+ );+ if (cloudConvs.length === 0) break;+ hasMore = cloudConvs.length === BATCH_SIZE;+ before = cloudConvs[cloudConvs.length - 1].created_at;++ for (const cloudConv of cloudConvs) {+ if (cloudConv.deleted_at) continue;+ const local = await window.electronAPI.getConversationByClientId?.(+ cloudConv.client_conversation_id ?? ""+ );+ if (!local || cloudConv.updated_at > local.updated_at) {+ await window.electronAPI.upsertConversationFromCloud?.(+ cloudConv,+ cloudConv.messages ?? []+ );+ }+ }+ }+ } catch (err) {+ console.error("Conversation pull failed:", err);+ }+ }++ private async syncTranscriptions(): Promise<void> {+ await this.pushPendingTranscriptions();+ await this.pullTranscriptions();+ }++ private async pushPendingTranscriptions(): Promise<void> {+ const pending = (await window.electronAPI.getPendingTranscriptions?.()) ?? [];+ if (pending.length === 0) return;++ for (let i = 0; i < pending.length; i += TRANSCRIPTION_BATCH_SIZE) {+ const chunk = pending.slice(i, i + TRANSCRIPTION_BATCH_SIZE);+ try {+ const { created } = await TranscriptionsService.batchCreate(+ chunk.map((t) => ({+ client_transcription_id: t.client_transcription_id,+ text: t.text,+ raw_text: t.raw_text,+ provider: t.provider,+ model: t.model,+ audio_duration_ms: t.audio_duration_ms,+ status: t.status,+ created_at: t.created_at,+ }))+ );+ for (const cloudT of created) {+ const local = chunk.find(+ (t) => t.client_transcription_id === cloudT.client_transcription_id+ );+ if (local) await window.electronAPI.markTranscriptionSynced?.(local.id, cloudT.id);+ }+ } catch (err) {+ console.error("Transcription batch create failed:", err);+ }+ }+ }++ private async pullTranscriptions(): Promise<void> {+ try {+ let before: string | undefined;+ let hasMore = true;++ while (hasMore) {+ const { transcriptions: cloudTs } = await TranscriptionsService.list(+ TRANSCRIPTION_BATCH_SIZE,+ before+ );+ if (cloudTs.length === 0) break;+ hasMore = cloudTs.length === TRANSCRIPTION_BATCH_SIZE;+ before = cloudTs[cloudTs.length - 1].created_at;++ for (const cloudT of cloudTs) {+ if (cloudT.deleted_at) continue;+ const local = await window.electronAPI.getTranscriptionByClientId?.(+ cloudT.client_transcription_id ?? ""+ );+ if (!local) {+ await window.electronAPI.upsertTranscriptionFromCloud?.(cloudT);+ }+ }+ }+ } catch (err) {+ console.error("Transcription pull failed:", err);+ }+ }++ private async buildLocalToCloudFolderMap(): Promise<Map<number, string>> {+ const folders = (await window.electronAPI.getFolderIdMap?.()) ?? [];+ return new Map(folders.filter((f) => f.cloud_id).map((f) => [f.id, f.cloud_id!]));+ }++ private async buildCloudToLocalFolderMap(): Promise<{+ cloudToLocal: Map<string, number>;+ defaultFolderId: number | null;+ }> {+ const folders = (await window.electronAPI.getFolderIdMap?.()) ?? [];+ const cloudToLocal = new Map(folders.filter((f) => f.cloud_id).map((f) => [f.cloud_id!, f.id]));+ const personalFolder = folders.find((f) => f.is_default && f.name === "Personal");+ return { cloudToLocal, defaultFolderId: personalFolder?.id ?? null };+ }+}++export const syncService = new SyncService();diff --git a/src/services/TranscriptionsService.ts b/src/services/TranscriptionsService.tsnew file mode 100644index 000000000..680962d3a--- /dev/null+++ b/src/services/TranscriptionsService.ts@@ -0,0 +1,88 @@+import { OPENWHISPR_API_URL } from "../config/constants.js";++interface TranscriptionInput {+ client_transcription_id?: string;+ text: string;+ raw_text?: string | null;+ provider?: string | null;+ model?: string | null;+ language?: string | null;+ audio_duration_ms?: number | null;+ status?: string;+ created_at?: string;+}++interface CloudTranscription {+ id: string;+ client_transcription_id: string | null;+ text: string;+ raw_text: string | null;+ word_count: number;+ source: string;+ provider: string | null;+ model: string | null;+ language: string | null;+ audio_duration_ms: number | null;+ status: string;+ deleted_at: string | null;+ created_at: string;+}++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>;+}++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 }),+ });+ if (!res.ok) throw new Error(await res.text());+ return res.json() as Promise<{ created: CloudTranscription[] }>;+}++async function list(+ limit?: number,+ before?: string+): Promise<{ transcriptions: CloudTranscription[] }> {+ const params = new URLSearchParams();+ 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" }+ );+ 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());+}++export { create, batchCreate, list, deleteTranscription };++export const TranscriptionsService = {+ create,+ batchCreate,+ list,+ delete: deleteTranscription,+};diff --git a/src/services/tools/createNoteTool.ts b/src/services/tools/createNoteTool.tsindex 5c2fbf982..54776ac6f 100644--- a/src/services/tools/createNoteTool.ts+++ b/src/services/tools/createNoteTool.ts@@ -1,6 +1,6 @@import type { ToolDefinition, ToolResult } from "./ToolRegistry";import { resolveFolderId } from "./utils";-import { syncNoteToCloud } from "../../stores/noteStore";+import { syncService } from "../SyncService.js";export const createNoteTool: ToolDefinition = {name: "create_note",@@ -58,7 +58,7 @@ export const createNoteTool: ToolDefinition = {return { success: false, data: null, displayText: "Failed to create note" };}- syncNoteToCloud(result.note).catch(() => {});+ syncService.debouncedPush('note', result.note.id);const suffix = folderCreated ? ` in new folder "${folderName}"` : "";return {diff --git a/src/services/tools/updateNoteTool.ts b/src/services/tools/updateNoteTool.tsindex 610dbd8b3..8cf99f61d 100644--- a/src/services/tools/updateNoteTool.ts+++ b/src/services/tools/updateNoteTool.ts@@ -1,6 +1,6 @@import type { ToolDefinition, ToolResult } from "./ToolRegistry";import { resolveFolderId } from "./utils";-import { syncNoteUpdateToCloud } from "../../stores/noteStore";+import { syncService } from "../SyncService.js";export const updateNoteTool: ToolDefinition = {name: "update_note",@@ -71,7 +71,7 @@ export const updateNoteTool: ToolDefinition = {return { success: false, data: null, displayText: "Failed to update note" };}- syncNoteUpdateToCloud(note, updates).catch(() => {});+ syncService.debouncedPush('note', id);const suffix = folderCreated ? ` (moved to new folder "${folderName}")` : "";return {diff --git a/src/stores/chatStore.ts b/src/stores/chatStore.tsindex 74a466860..96401d5cc 100644--- a/src/stores/chatStore.ts+++ b/src/stores/chatStore.ts@@ -4,6 +4,7 @@ interface ConversationItem {id: number;title: string;cloud_id?: string | null;+ client_conversation_id?: string | null;archived_at?: string | null;note_id?: number | null;created_at: string;@@ -85,56 +86,6 @@ export function useChatMigration(): { total: number; done: number } | null {return useChatStore((state) => state.migration);}-export async function syncConversationToCloud(conversation: ConversationItem): Promise<void> {- const { ConversationsService } = await import("../services/ConversationsService.js");-- const messages = (await window.electronAPI?.getAgentMessages?.(conversation.id)) ?? [];-- const cloudConv = await ConversationsService.create({- client_conversation_id: String(conversation.id),- title: conversation.title,- created_at: conversation.created_at,- updated_at: conversation.updated_at,- messages: messages.map((m) => ({- role: m.role,- content: m.content,- })),- });-- updateConversation({ ...conversation, cloud_id: cloudConv.id });-}--export async function syncMessageToCloud(- conversation: ConversationItem,- role: "user" | "assistant" | "system",- content: string,- metadata?: Record<string, unknown> | null-): Promise<void> {- const { ConversationsService } = await import("../services/ConversationsService.js");- if (conversation.cloud_id) {- await ConversationsService.addMessage(conversation.cloud_id, role, content, metadata);- } else {- await syncConversationToCloud(conversation);- }-}--export async function syncConversationUpdateToCloud(- conversation: ConversationItem,- updates: { title?: string; archived_at?: string }-): Promise<void> {- const { ConversationsService } = await import("../services/ConversationsService.js");- if (conversation.cloud_id) {- await ConversationsService.update(conversation.cloud_id, updates);- } else {- await syncConversationToCloud(conversation);- }-}--export async function syncConversationDeleteToCloud(cloudId: string): Promise<void> {- const { ConversationsService } = await import("../services/ConversationsService.js");- await ConversationsService.delete(cloudId);-}-export async function startConversationMigration(): Promise<void> {const allConversations = (await window.electronAPI?.getAgentConversations?.(9999)) ?? [];const unsynced = allConversations.filter((c) => !c.cloud_id);@@ -142,9 +93,22 @@ export async function startConversationMigration(): Promise<void> {useChatStore.setState({ migration: { total: unsynced.length, done: 0 } });+ const { ConversationsService } = await import("../services/ConversationsService.js");+for (const conv of unsynced) {try {- await syncConversationToCloud(conv);+ const messages = (await window.electronAPI?.getAgentMessages?.(conv.id)) ?? [];+ const cloudConv = await ConversationsService.create({+ client_conversation_id: conv.client_conversation_id ?? String(conv.id),+ title: conv.title,+ created_at: conv.created_at,+ updated_at: conv.updated_at,+ messages: messages.map((m) => ({+ role: m.role,+ content: m.content,+ })),+ });+ updateConversation({ ...conv, cloud_id: cloudConv.id });useChatStore.setState((s) => ({migration: s.migration? {diff --git a/src/stores/noteStore.ts b/src/stores/noteStore.tsindex 6e5a2ff6b..b146a2673 100644--- a/src/stores/noteStore.ts+++ b/src/stores/noteStore.ts@@ -143,41 +143,6 @@ export function useMigration(): { total: number; done: number } | null {return useNoteStore((state) => state.migration);}-export async function syncNoteToCloud(note: NoteItem): Promise<void> {- const { NotesService } = await import("../services/NotesService.js");- const cloudNote = await NotesService.create({- client_note_id: String(note.id),- title: note.title,- content: note.content,- enhanced_content: note.enhanced_content,- enhancement_prompt: note.enhancement_prompt,- note_type: note.note_type,- source_file: note.source_file,- audio_duration_seconds: note.audio_duration_seconds,- created_at: note.created_at,- updated_at: note.updated_at,- });- await window.electronAPI.updateNoteCloudId(note.id, cloudNote.id);- updateNoteInStore({ ...note, cloud_id: cloudNote.id });-}--export async function syncNoteUpdateToCloud(- note: NoteItem,- updates: Partial<NoteItem>-): Promise<void> {- const { NotesService } = await import("../services/NotesService.js");- if (note.cloud_id) {- await NotesService.update(note.cloud_id, updates);- } else {- await syncNoteToCloud(note);- }-}--export async function syncNoteDeleteToCloud(cloudId: string): Promise<void> {- const { NotesService } = await import("../services/NotesService.js");- await NotesService.delete(cloudId);-}-export async function startMigration(): Promise<void> {const allNotes = (await window.electronAPI?.getNotes(null, 9999, null)) ?? [];const unsynced = allNotes.filter((n) => !n.cloud_id);@@ -193,7 +158,7 @@ export async function startMigration(): Promise<void> {try {const { created } = await NotesService.batchCreate(chunk.map((n) => ({- client_note_id: String(n.id),+ client_note_id: n.client_note_id,title: n.title,content: n.content,enhanced_content: n.enhanced_content,@@ -205,10 +170,14 @@ export async function startMigration(): Promise<void> {updated_at: n.updated_at,})));+ const notesByClientId = new Map(chunk.map((n) => [n.client_note_id, n]));await Promise.all(- created.map(({ client_note_id, id: cloudId }) =>- window.electronAPI.updateNoteCloudId(parseInt(client_note_id, 10), cloudId)- )+ created.map(({ client_note_id, id: cloudId }) => {+ const local = notesByClientId.get(client_note_id);+ return local+ ? window.electronAPI.updateNoteCloudId(local.id, cloudId)+ : Promise.resolve();+ }));useNoteStore.setState((s) => ({migration: s.migrationdiff --git a/src/types/electron.ts b/src/types/electron.tsindex 383a2ca0b..f8530daa6 100644--- a/src/types/electron.ts+++ b/src/types/electron.ts@@ -32,6 +32,9 @@ export interface TranscriptionItem {status: TranscriptionStatus;error_message: string | null;error_code: TranscriptionErrorCode;+ client_transcription_id: string;+ cloud_id: string | null;+ sync_status: "synced" | "pending" | "error";}export interface NoteItem {@@ -51,6 +54,9 @@ export interface NoteItem {cloud_id: string | null;created_at: string;updated_at: string;+ client_note_id: string;+ sync_status: "synced" | "pending" | "error";+ deleted_at: string | null;}export interface FolderItem {@@ -59,6 +65,9 @@ export interface FolderItem {is_default: number;sort_order: number;created_at: string;+ client_folder_id: string;+ cloud_id: string | null;+ sync_status: "synced" | "pending" | "error";}export interface ActionItem {@@ -317,6 +326,9 @@ export interface ConversationPreview {updated_at: string;archived_at?: string | null;cloud_id?: string | null;+ client_conversation_id?: string;+ sync_status?: "synced" | "pending" | "error";+ deleted_at?: string | null;message_count: number;last_message?: string | null;last_message_role?: "user" | "assistant" | "system" | null;@@ -1528,6 +1540,41 @@ declare global {bounds?: { x: number; y: number; width: number; height: number };}>;sendDictationPreviewAudio?: (data: ArrayBuffer) => void;++ // Sync operations+ getPendingNotes?: () => Promise<NoteItem[]>;+ getPendingNoteDeletes?: () => Promise<NoteItem[]>;+ getNoteByClientId?: (clientNoteId: string) => Promise<NoteItem | null>;+ upsertNoteFromCloud?: (+ cloudNote: Record<string, unknown>,+ localFolderId: number | null+ ) => Promise<NoteItem>;+ markNoteSynced?: (id: number, cloudId: string) => Promise<void>;+ markNoteSyncError?: (id: number) => Promise<void>;+ hardDeleteNote?: (id: number) => Promise<void>;++ getPendingFolders?: () => Promise<FolderItem[]>;+ getFolderByClientId?: (clientFolderId: string) => Promise<FolderItem | null>;+ upsertFolderFromCloud?: (cloudFolder: Record<string, unknown>) => Promise<FolderItem>;+ markFolderSynced?: (id: number, cloudId: string) => Promise<void>;+ getFolderIdMap?: () => Promise<FolderItem[]>;++ getPendingConversations?: () => Promise<ConversationPreview[]>;+ getPendingConversationDeletes?: () => Promise<ConversationPreview[]>;+ getConversationByClientId?: (clientId: string) => Promise<ConversationPreview | null>;+ upsertConversationFromCloud?: (+ cloudConv: Record<string, unknown>,+ messages: Array<Record<string, unknown>>+ ) => Promise<void>;+ markConversationSynced?: (id: number, cloudId: string) => Promise<void>;+ hardDeleteConversation?: (id: number) => Promise<void>;++ getPendingTranscriptions?: () => Promise<TranscriptionItem[]>;+ getTranscriptionByClientId?: (clientId: string) => Promise<TranscriptionItem | null>;+ upsertTranscriptionFromCloud?: (+ cloudTranscription: Record<string, unknown>+ ) => Promise<TranscriptionItem>;+ markTranscriptionSynced?: (id: number, cloudId: string) => Promise<void>;};api?: {