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: snippets sync (#1037)
Chad Piha995afaadd828
diff --git a/preload.js b/preload.jsindex fa371475e..6d5b27460 100644--- a/preload.js+++ b/preload.js@@ -61,6 +61,13 @@ contextBridge.exposeInMainWorld("electronAPI", {ipcRenderer.on("dictionary-updated", listener);return () => ipcRenderer.removeListener("dictionary-updated", listener);},+ getSnippets: () => ipcRenderer.invoke("db-get-snippets"),+ setSnippets: (snippets) => ipcRenderer.invoke("db-set-snippets", snippets),+ onSnippetsUpdated: (callback) => {+ const listener = (_event, snippets) => callback?.(snippets);+ ipcRenderer.on("snippets-updated", listener);+ return () => ipcRenderer.removeListener("snippets-updated", listener);+ },setAutoLearnEnabled: (enabled) => ipcRenderer.send("auto-learn-changed", enabled),onCorrectionsLearned: (callback) => {const listener = (_event, words) => callback?.(words);@@ -852,6 +859,25 @@ contextBridge.exposeInMainWorld("electronAPI", {clearDictionaryCloudId: (id) => ipcRenderer.invoke("db-clear-dictionary-cloud-id", id),broadcastDictionaryUpdated: () => ipcRenderer.invoke("db-broadcast-dictionary-updated"),+ getPendingSnippets: () => ipcRenderer.invoke("db-get-pending-snippets"),+ getPendingSnippetDeletes: () => ipcRenderer.invoke("db-get-pending-snippet-deletes"),+ getSnippetForCloudMerge: (cloudEntry) =>+ ipcRenderer.invoke("db-get-snippet-for-cloud-merge", cloudEntry),+ upsertSnippetFromCloud: (cloudEntry) =>+ ipcRenderer.invoke("db-upsert-snippet-from-cloud", cloudEntry),+ markSnippetSynced: (id, cloudId, serverUpdatedAt, expectedTrigger, expectedReplacement) =>+ ipcRenderer.invoke(+ "db-mark-snippet-synced",+ id,+ cloudId,+ serverUpdatedAt,+ expectedTrigger,+ expectedReplacement+ ),+ hardDeleteSnippet: (id) => ipcRenderer.invoke("db-hard-delete-snippet", id),+ clearSnippetCloudId: (id) => ipcRenderer.invoke("db-clear-snippet-cloud-id", id),+ broadcastSnippetsUpdated: () => ipcRenderer.invoke("db-broadcast-snippets-updated"),+// Google CalendargcalStartOAuth: () => ipcRenderer.invoke("gcal-start-oauth"),gcalDisconnect: () => ipcRenderer.invoke("gcal-disconnect"),diff --git a/src/helpers/database.js b/src/helpers/database.jsindex 1b2f05eab..bf4b2b7be 100644--- a/src/helpers/database.js+++ b/src/helpers/database.js@@ -5,6 +5,10 @@ const { randomUUID } = require("crypto");const debugLogger = require("./debugLogger");const { app } = require("electron");+// Server-enforced trigger cap (openwhispr-api); enforced here so one oversized+// trigger can't 400 the whole sync batch.+const MAX_SNIPPET_TRIGGER_LENGTH = 100;+class DatabaseManager {constructor() {this.db = null;@@ -82,6 +86,20 @@ class DatabaseManager {)`);+ this.db.exec(`+ CREATE TABLE IF NOT EXISTS snippets (+ id INTEGER PRIMARY KEY AUTOINCREMENT,+ trigger TEXT NOT NULL,+ replacement TEXT NOT NULL,+ client_snippet_id TEXT,+ cloud_id TEXT,+ sync_status TEXT DEFAULT 'pending',+ deleted_at TEXT,+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP,+ updated_at DATETIME DEFAULT CURRENT_TIMESTAMP+ )+ `);+this.db.exec(`CREATE TABLE IF NOT EXISTS notes (id INTEGER PRIMARY KEY AUTOINCREMENT,@@ -572,6 +590,7 @@ class DatabaseManager {{ table: "agent_conversations", col: "client_conversation_id" },{ table: "transcriptions", col: "client_transcription_id" },{ table: "custom_dictionary", col: "client_dict_id" },+ { table: "snippets", col: "client_snippet_id" },];for (const { table, col } of syncTables) {const rows = this.db.prepare(`SELECT id FROM ${table} WHERE ${col} IS NULL`).all();@@ -596,6 +615,15 @@ class DatabaseManager {this.db.exec("CREATE UNIQUE INDEX IF NOT EXISTS idx_custom_dictionary_client_id ON custom_dictionary(client_dict_id)");+ this.db.exec(+ "CREATE UNIQUE INDEX IF NOT EXISTS idx_snippets_client_id ON snippets(client_snippet_id) WHERE client_snippet_id IS NOT NULL"+ );+ this.db.exec(+ "CREATE UNIQUE INDEX IF NOT EXISTS idx_snippets_trigger_lower_active ON snippets(lower(trigger)) WHERE deleted_at IS NULL"+ );+ this.db.exec(+ "CREATE INDEX IF NOT EXISTS idx_snippets_pending_sync ON snippets(sync_status) WHERE sync_status = 'pending'"+ );return true;} catch (error) {@@ -1047,6 +1075,312 @@ class DatabaseManager {}}+ getSnippets() {+ try {+ if (!this.db) {+ throw new Error("Database not initialized");+ }+ return this.db+ .prepare(+ "SELECT trigger, replacement FROM snippets WHERE deleted_at IS NULL ORDER BY id ASC"+ )+ .all();+ } catch (error) {+ debugLogger.error("Error getting snippets", { error: error.message }, "database");+ throw error;+ }+ }++ setSnippets(snippets) {+ try {+ if (!this.db) {+ throw new Error("Database not initialized");+ }++ const incomingByLower = new Map();+ for (const raw of Array.isArray(snippets) ? snippets : []) {+ if (!raw || typeof raw !== "object") continue;+ const trigger = typeof raw.trigger === "string" ? raw.trigger.trim() : "";+ const replacement = typeof raw.replacement === "string" ? raw.replacement.trim() : "";+ if (!trigger || !replacement) continue;+ if (trigger.length > MAX_SNIPPET_TRIGGER_LENGTH) continue;+ const lower = trigger.toLowerCase();+ if (!incomingByLower.has(lower)) incomingByLower.set(lower, { trigger, replacement });+ }+ const cleaned = Array.from(incomingByLower.values());+ const incomingLower = new Set(incomingByLower.keys());++ const existingRows = this.db.prepare("SELECT * FROM snippets").all();+ const existingByLower = new Map();+ for (const row of existingRows) {+ const lower = row.trigger.toLowerCase();+ const current = existingByLower.get(lower);+ if (!current || (current.deleted_at && !row.deleted_at)) existingByLower.set(lower, row);+ }++ const tombstone = this.db.prepare(+ "UPDATE snippets SET deleted_at = datetime('now'), updated_at = datetime('now'), sync_status = 'pending' WHERE id = ? AND deleted_at IS NULL"+ );+ const hardDelete = this.db.prepare("DELETE FROM snippets WHERE id = ? AND cloud_id IS NULL");+ const restore = this.db.prepare(+ "UPDATE snippets SET deleted_at = NULL, trigger = ?, replacement = ?, updated_at = datetime('now'), sync_status = 'pending' WHERE id = ?"+ );+ const updateActive = this.db.prepare(+ "UPDATE snippets SET trigger = ?, replacement = ?, updated_at = datetime('now'), sync_status = 'pending' WHERE id = ? AND (trigger != ? OR replacement != ?)"+ );+ const insert = this.db.prepare(+ "INSERT OR IGNORE INTO snippets (trigger, replacement, client_snippet_id, sync_status, updated_at) VALUES (?, ?, ?, 'pending', datetime('now'))"+ );++ this.db.transaction(() => {+ for (const existing of existingRows) {+ if (incomingLower.has(existing.trigger.toLowerCase())) continue;+ if (existing.deleted_at) continue;+ const hardResult = hardDelete.run(existing.id);+ if (hardResult.changes === 0) tombstone.run(existing.id);+ }++ for (const snippet of cleaned) {+ const existing = existingByLower.get(snippet.trigger.toLowerCase());+ if (existing) {+ if (existing.deleted_at) {+ restore.run(snippet.trigger, snippet.replacement, existing.id);+ } else {+ updateActive.run(+ snippet.trigger,+ snippet.replacement,+ existing.id,+ snippet.trigger,+ snippet.replacement+ );+ }+ continue;+ }+ insert.run(snippet.trigger, snippet.replacement, randomUUID());+ }+ })();++ return { success: true };+ } catch (error) {+ debugLogger.error("Error setting snippets", { error: error.message }, "database");+ throw error;+ }+ }++ getPendingSnippets() {+ try {+ if (!this.db) throw new Error("Database not initialized");+ return this.db+ .prepare("SELECT * FROM snippets WHERE sync_status = 'pending' AND deleted_at IS NULL")+ .all();+ } catch (error) {+ debugLogger.error("Error getting pending snippets", { error: error.message }, "database");+ throw error;+ }+ }++ getPendingSnippetDeletes() {+ try {+ if (!this.db) throw new Error("Database not initialized");+ return this.db+ .prepare(+ "SELECT * FROM snippets WHERE deleted_at IS NOT NULL AND cloud_id IS NOT NULL AND sync_status = 'pending'"+ )+ .all();+ } catch (error) {+ debugLogger.error(+ "Error getting pending snippet deletes",+ { error: error.message },+ "database"+ );+ throw error;+ }+ }++ hardDeleteSnippet(id) {+ try {+ if (!this.db) throw new Error("Database not initialized");+ const result = this.db.prepare("DELETE FROM snippets WHERE id = ?").run(id);+ return { success: result.changes > 0, id };+ } catch (error) {+ debugLogger.error("Error hard deleting snippet", { error: error.message }, "database");+ throw error;+ }+ }++ getSnippetForCloudMerge(cloudEntry) {+ try {+ if (!this.db) throw new Error("Database not initialized");+ if (!cloudEntry || typeof cloudEntry !== "object") return null;++ const clientSnippetId =+ typeof cloudEntry.client_snippet_id === "string" && cloudEntry.client_snippet_id+ ? cloudEntry.client_snippet_id+ : "";+ if (clientSnippetId) {+ const byClient = this.db+ .prepare("SELECT * FROM snippets WHERE client_snippet_id = ? LIMIT 1")+ .get(clientSnippetId);+ if (byClient) return byClient;+ }++ if (typeof cloudEntry.id === "string" && cloudEntry.id) {+ const byCloud = this.db+ .prepare("SELECT * FROM snippets WHERE cloud_id = ? LIMIT 1")+ .get(cloudEntry.id);+ if (byCloud) return byCloud;+ }++ const trigger = typeof cloudEntry.trigger === "string" ? cloudEntry.trigger.trim() : "";+ if (!trigger) return null;+ const byActiveTrigger = this.db+ .prepare(+ "SELECT * FROM snippets WHERE lower(trigger) = lower(?) AND deleted_at IS NULL LIMIT 1"+ )+ .get(trigger);+ if (byActiveTrigger) return byActiveTrigger;+ return (+ this.db+ .prepare(+ "SELECT * FROM snippets WHERE lower(trigger) = lower(?) AND deleted_at IS NOT NULL LIMIT 1"+ )+ .get(trigger) || null+ );+ } catch (error) {+ debugLogger.error(+ "Error getting snippet for cloud merge",+ { error: error.message },+ "database"+ );+ throw error;+ }+ }++ upsertSnippetFromCloud(cloudEntry) {+ try {+ if (!this.db) throw new Error("Database not initialized");+ if (!cloudEntry || typeof cloudEntry !== "object") return null;+ if (typeof cloudEntry.id !== "string" || !cloudEntry.id) return null;++ const trigger = typeof cloudEntry.trigger === "string" ? cloudEntry.trigger.trim() : "";+ const replacement =+ typeof cloudEntry.replacement === "string" ? cloudEntry.replacement.trim() : "";+ if (!trigger || !replacement) return null;++ const clientSnippetId =+ typeof cloudEntry.client_snippet_id === "string" && cloudEntry.client_snippet_id+ ? cloudEntry.client_snippet_id+ : randomUUID();+ const updatedAt =+ typeof cloudEntry.updated_at === "string" && cloudEntry.updated_at+ ? cloudEntry.updated_at+ : typeof cloudEntry.created_at === "string" && cloudEntry.created_at+ ? cloudEntry.created_at+ : new Date().toISOString();+ const createdAt =+ typeof cloudEntry.created_at === "string" && cloudEntry.created_at+ ? cloudEntry.created_at+ : updatedAt;++ const existing = this.getSnippetForCloudMerge({+ ...cloudEntry,+ client_snippet_id: clientSnippetId,+ trigger,+ });++ if (existing) {+ // A different active row may already hold this trigger (cross-device+ // rename); it must yield first or the UPDATE trips the active-trigger+ // unique index and aborts the pull.+ const collidingActive = this.db+ .prepare(+ "SELECT * FROM snippets WHERE lower(trigger) = lower(?) AND deleted_at IS NULL AND id != ? LIMIT 1"+ )+ .get(trigger, existing.id);+ // Tombstone existing → keep the active collider; else keep existing and+ // drop the stale collider.+ const target = existing.deleted_at && collidingActive ? collidingActive : existing;+ const orphanId = target.id === existing.id ? collidingActive?.id : existing.id;+ if (orphanId) {+ this.db.prepare("DELETE FROM snippets WHERE id = ?").run(orphanId);+ }+ this.db+ .prepare(+ `UPDATE snippets+ SET cloud_id = ?, client_snippet_id = ?, trigger = ?, replacement = ?,+ sync_status = 'synced', deleted_at = NULL, updated_at = ?+ WHERE id = ?`+ )+ .run(cloudEntry.id, clientSnippetId, trigger, replacement, updatedAt, target.id);+ return this.db.prepare("SELECT * FROM snippets WHERE id = ?").get(target.id);+ }++ this.db+ .prepare(+ `INSERT INTO snippets+ (trigger, replacement, client_snippet_id, cloud_id, sync_status, created_at, updated_at)+ VALUES (?, ?, ?, ?, 'synced', ?, ?)`+ )+ .run(trigger, replacement, clientSnippetId, cloudEntry.id, createdAt, updatedAt);+ return this.db+ .prepare("SELECT * FROM snippets WHERE client_snippet_id = ?")+ .get(clientSnippetId);+ } catch (error) {+ debugLogger.error("Error upserting snippet from cloud", { error: error.message }, "database");+ throw error;+ }+ }++ markSnippetSynced(+ id,+ cloudId,+ serverUpdatedAt = null,+ expectedTrigger = null,+ expectedReplacement = null+ ) {+ try {+ if (!this.db) throw new Error("Database not initialized");+ // If a user edit landed between push and ack, the row no longer matches+ // what was pushed — leave it 'pending' so the next sync re-pushes it.+ const result = this.db+ .prepare(+ `UPDATE snippets+ SET sync_status = 'synced',+ cloud_id = ?,+ updated_at = COALESCE(?, updated_at)+ WHERE id = ? AND deleted_at IS NULL+ AND (? IS NULL OR trigger = ?)+ AND (? IS NULL OR replacement = ?)`+ )+ .run(+ cloudId,+ serverUpdatedAt,+ id,+ expectedTrigger,+ expectedTrigger,+ expectedReplacement,+ expectedReplacement+ );+ return { success: result.changes > 0, changes: result.changes };+ } catch (error) {+ debugLogger.error("Error marking snippet synced", { error: error.message }, "database");+ throw error;+ }+ }++ clearSnippetCloudId(id) {+ try {+ if (!this.db) throw new Error("Database not initialized");+ const result = this.db+ .prepare("UPDATE snippets SET cloud_id = NULL, sync_status = 'pending' WHERE id = ?")+ .run(id);+ return { success: result.changes > 0 };+ } catch (error) {+ debugLogger.error("Error clearing snippet cloud_id", { error: error.message }, "database");+ throw error;+ }+ }+saveNote(title,content,diff --git a/src/helpers/ipcHandlers.js b/src/helpers/ipcHandlers.jsindex b63729f20..1e112f056 100644--- a/src/helpers/ipcHandlers.js+++ b/src/helpers/ipcHandlers.js@@ -962,6 +962,60 @@ class IPCHandlers {return { success: true };});+ ipcMain.handle("db-get-snippets", async () => {+ return this.databaseManager.getSnippets();+ });++ ipcMain.handle("db-set-snippets", async (_event, snippets) => {+ if (!Array.isArray(snippets)) {+ throw new Error("snippets must be an array");+ }+ return this.databaseManager.setSnippets(snippets);+ });++ ipcMain.handle("db-get-pending-snippets", async () => {+ return this.databaseManager.getPendingSnippets();+ });++ ipcMain.handle("db-get-pending-snippet-deletes", async () => {+ return this.databaseManager.getPendingSnippetDeletes();+ });++ ipcMain.handle("db-get-snippet-for-cloud-merge", async (_event, cloudEntry) => {+ return this.databaseManager.getSnippetForCloudMerge(cloudEntry);+ });++ ipcMain.handle("db-upsert-snippet-from-cloud", async (_event, cloudEntry) => {+ return this.databaseManager.upsertSnippetFromCloud(cloudEntry);+ });++ ipcMain.handle(+ "db-mark-snippet-synced",+ async (_event, id, cloudId, serverUpdatedAt, expectedTrigger, expectedReplacement) => {+ return this.databaseManager.markSnippetSynced(+ id,+ cloudId,+ serverUpdatedAt,+ expectedTrigger,+ expectedReplacement+ );+ }+ );++ ipcMain.handle("db-hard-delete-snippet", async (_event, id) => {+ return this.databaseManager.hardDeleteSnippet(id);+ });++ ipcMain.handle("db-clear-snippet-cloud-id", async (_event, id) => {+ return this.databaseManager.clearSnippetCloudId(id);+ });++ ipcMain.handle("db-broadcast-snippets-updated", async () => {+ const snippets = this.databaseManager.getSnippets();+ this.broadcastToWindows("snippets-updated", snippets);+ return { success: true };+ });+ipcMain.handle("undo-learned-corrections", async (_event, words) => {try {if (!Array.isArray(words) || words.length === 0) {diff --git a/src/hooks/useSettings.ts b/src/hooks/useSettings.tsindex 276870df8..e8e5a4849 100644--- a/src/hooks/useSettings.ts+++ b/src/hooks/useSettings.ts@@ -96,7 +96,8 @@ export interface ChatAgentSettings {function useSettingsInternal() {const store = useSettingsStore();- const { setCustomDictionary, applyCustomDictionaryFromExternal } = store;+ const { setCustomDictionary, applyCustomDictionaryFromExternal, applySnippetsFromExternal } =+ store;// One-time initialization: sync API keys, dictation key, activation mode,// UI language, and dictionary from the main process / SQLite.@@ -126,6 +127,16 @@ function useSettingsInternal() {return unsubscribe;}, [applyCustomDictionaryFromExternal]);+ useEffect(() => {+ if (typeof window === "undefined" || !window.electronAPI?.onSnippetsUpdated) return;+ const unsubscribe = window.electronAPI.onSnippetsUpdated((snippets: Snippet[]) => {+ if (Array.isArray(snippets)) {+ applySnippetsFromExternal(snippets);+ }+ });+ return unsubscribe;+ }, [applySnippetsFromExternal]);+// Auto-learn corrections from user edits in external appsconst [autoLearnCorrections, setAutoLearnCorrectionsRaw] = useLocalStorage("autoLearnCorrections",diff --git a/src/services/SnippetService.ts b/src/services/SnippetService.tsnew file mode 100644index 000000000..49a304415--- /dev/null+++ b/src/services/SnippetService.ts@@ -0,0 +1,72 @@+import { cloudGet, cloudPost, cloudPatch, cloudDelete } from "./cloudApi.js";++interface SnippetEntryInput {+ trigger: string;+ replacement: string;+ client_snippet_id?: string;+ created_at?: string;+ updated_at?: string;+}++export interface CloudSnippetEntry {+ id: string;+ client_snippet_id: string | null;+ trigger: string;+ replacement: string;+ deleted_at: string | null;+ created_at: string;+ updated_at: string;+}++async function batchCreate(+ entries: SnippetEntryInput[]+): Promise<{ created: CloudSnippetEntry[] }> {+ return cloudPost<{ created: CloudSnippetEntry[] }>("/api/snippets/batch-create", {+ entries,+ });+}++async function update(+ id: string,+ updates: { trigger?: string; replacement?: string }+): Promise<CloudSnippetEntry> {+ return cloudPatch<CloudSnippetEntry>("/api/snippets/update", { id, ...updates });+}++async function deleteEntry(id: string): Promise<void> {+ await cloudDelete("/api/snippets/delete", { id });+}++async function listSnapshot(+ cursor?: string,+ limit?: number,+ cursorId?: string+): Promise<{ entries: CloudSnippetEntry[]; hasMore: boolean }> {+ const params = new URLSearchParams();+ if (cursor) params.set("cursor", cursor);+ if (cursorId) params.set("cursor_id", cursorId);+ if (limit) params.set("limit", String(limit));+ const query = params.toString() ? `?${params}` : "";+ return cloudGet<{ entries: CloudSnippetEntry[]; hasMore: boolean }>(`/api/snippets/list${query}`);+}++async function listDelta(+ since?: string,+ limit?: number,+ sinceId?: string+): Promise<{ entries: CloudSnippetEntry[]; hasMore: boolean }> {+ const params = new URLSearchParams();+ if (since) params.set("since", since);+ if (sinceId) params.set("since_id", sinceId);+ if (limit) params.set("limit", String(limit));+ const query = params.toString() ? `?${params}` : "";+ return cloudGet<{ entries: CloudSnippetEntry[]; hasMore: boolean }>(`/api/snippets/list${query}`);+}++export const SnippetService = {+ batchCreate,+ update,+ delete: deleteEntry,+ listSnapshot,+ listDelta,+};diff --git a/src/services/SyncService.ts b/src/services/SyncService.tsindex 6dca40143..76f7be520 100644--- a/src/services/SyncService.ts+++ b/src/services/SyncService.ts@@ -9,6 +9,7 @@ import { ConversationsService } from "./ConversationsService.js";import { FoldersService } from "./FoldersService.js";import { TranscriptionsService } from "./TranscriptionsService.js";import { DictionaryService } from "./DictionaryService.js";+import { SnippetService, type CloudSnippetEntry } from "./SnippetService.js";import { CloudApiError } from "./cloudApi.js";function isHttpStatus(err: unknown, status: number): boolean {@@ -19,6 +20,7 @@ const PUSH_DEBOUNCE_MS = 2000;const BATCH_SIZE = 50;const TRANSCRIPTION_BATCH_SIZE = 100;const DICTIONARY_BATCH_SIZE = 200;+const SNIPPET_BATCH_SIZE = 200;// SQLite `datetime('now')` yields "YYYY-MM-DD HH:MM:SS" (no T, no millis, no Z);// the cloud sends ISO 8601 "YYYY-MM-DDTHH:MM:SS.sssZ". Normalize both to@@ -34,6 +36,7 @@ function normalizeTimestamp(value: string | null | undefined): string {class SyncService {private syncing = false;private dictionaryDirty = false;+ private snippetsDirty = false;private pushTimers = new Map<string, ReturnType<typeof setTimeout>>();canSync(): boolean {@@ -58,6 +61,10 @@ class SyncService {this.dictionaryDirty = false;await this.syncDictionary();} while (this.dictionaryDirty);+ do {+ this.snippetsDirty = false;+ await this.syncSnippets();+ } while (this.snippetsDirty);localStorage.setItem("lastSyncedAt", new Date().toISOString());} catch (err) {console.error("Sync failed:", err);@@ -87,6 +94,25 @@ class SyncService {}}+ async syncSnippetsNow(): Promise<void> {+ if (!this.canSync()) return;+ if (this.syncing) {+ this.snippetsDirty = true;+ return;+ }+ this.syncing = true;+ try {+ do {+ this.snippetsDirty = false;+ await this.syncSnippets();+ } while (this.snippetsDirty);+ } catch (err) {+ console.error("Snippets sync failed:", err);+ } finally {+ this.syncing = false;+ }+ }+debouncedPush(entityType: string, entityId: number): void {if (!this.canSync()) return;const key = `${entityType}:${entityId}`;@@ -810,6 +836,203 @@ class SyncService {}}+ private async syncSnippets(): Promise<void> {+ const api = window.electronAPI;+ const required = [+ "getPendingSnippets",+ "getPendingSnippetDeletes",+ "getSnippetForCloudMerge",+ "upsertSnippetFromCloud",+ "markSnippetSynced",+ "hardDeleteSnippet",+ "clearSnippetCloudId",+ "broadcastSnippetsUpdated",+ ] as const;+ const missing = required.filter((name) => typeof api[name] !== "function");+ if (missing.length > 0) {+ throw new Error(`Snippet IPC bindings missing — preload out of date: ${missing.join(", ")}`);+ }++ await this.pushPendingSnippets();+ await this.pushSnippetDeletes();+ await this.pullSnippets();+ }++ private async pushPendingSnippets(): Promise<void> {+ const pending = (await window.electronAPI.getPendingSnippets?.()) ?? [];+ if (pending.length === 0) return;++ const updates = pending.filter((e) => e.cloud_id);+ const creates = pending.filter((e) => !e.cloud_id);++ for (const entry of updates) {+ try {+ const server = await SnippetService.update(entry.cloud_id!, {+ trigger: entry.trigger,+ replacement: entry.replacement,+ });+ await window.electronAPI.markSnippetSynced?.(+ entry.id,+ server.id,+ server.updated_at,+ entry.trigger,+ entry.replacement+ );+ } catch (err) {+ if (isHttpStatus(err, 404)) {+ // Cloud row purged elsewhere — drop the stale cloud_id so the next push+ // re-creates it via batchCreate.+ await window.electronAPI.clearSnippetCloudId?.(entry.id);+ } else if (isHttpStatus(err, 409)) {+ // Another snippet already holds this trigger, so the server keeps+ // rejecting the rename. Mark synced to stop re-pushing the doomed PATCH.+ await window.electronAPI.markSnippetSynced?.(+ entry.id,+ entry.cloud_id!,+ undefined,+ entry.trigger,+ entry.replacement+ );+ } else {+ console.error("Snippet update sync failed:", err);+ }+ }+ }++ for (let i = 0; i < creates.length; i += SNIPPET_BATCH_SIZE) {+ const chunk = creates.slice(i, i + SNIPPET_BATCH_SIZE);+ try {+ const { created } = await SnippetService.batchCreate(+ chunk.map((e) => ({+ client_snippet_id: e.client_snippet_id,+ trigger: e.trigger,+ replacement: e.replacement,+ created_at: e.created_at,+ updated_at: e.updated_at,+ }))+ );+ const byClientId = new Map(created.map((c) => [c.client_snippet_id, c]));+ let unmatched = 0;+ for (const local of chunk) {+ const server = byClientId.get(local.client_snippet_id);+ if (!server) {+ unmatched += 1;+ continue;+ }+ const result = await window.electronAPI.markSnippetSynced?.(+ local.id,+ server.id,+ server.updated_at,+ local.trigger,+ local.replacement+ );+ if (result && result.changes === 0) {+ try {+ await SnippetService.delete(server.id);+ } catch (deleteErr) {+ console.error("Snippet orphan cleanup failed:", deleteErr);+ }+ }+ }+ if (unmatched > 0) {+ console.warn(+ `Snippet batch-create: ${unmatched}/${chunk.length} rows had no matching server response`+ );+ }+ } catch (err) {+ console.error("Snippet batch create failed:", err);+ }+ }+ }++ private async pushSnippetDeletes(): Promise<void> {+ const deletes = (await window.electronAPI.getPendingSnippetDeletes?.()) ?? [];+ for (const entry of deletes) {+ if (!entry.cloud_id) continue;+ try {+ await SnippetService.delete(entry.cloud_id);+ await window.electronAPI.hardDeleteSnippet?.(entry.id);+ } catch (err) {+ if (isHttpStatus(err, 404)) {+ await window.electronAPI.hardDeleteSnippet?.(entry.id);+ } else {+ console.error("Snippet delete sync failed:", err);+ }+ }+ }+ }++ private async pullSnippets(): Promise<void> {+ try {+ const since = localStorage.getItem("lastSyncedAt.snippets") ?? undefined;+ const sinceId = localStorage.getItem("lastSyncedAt.snippets.id") ?? undefined;+ let changed = false;++ let cursor: string | undefined = since;+ let cursorId: string | undefined = sinceId;+ let maxUpdatedAt = normalizeTimestamp(since);+ let maxId = sinceId ?? "";+ const cursorField: keyof Pick<CloudSnippetEntry, "created_at" | "updated_at"> = since+ ? "updated_at"+ : "created_at";++ while (true) {+ const { entries, hasMore } = since+ ? await SnippetService.listDelta(cursor, SNIPPET_BATCH_SIZE, cursorId)+ : await SnippetService.listSnapshot(cursor, SNIPPET_BATCH_SIZE, cursorId);+ if (entries.length === 0) break;++ for (const cloudEntry of entries) {+ const cloudTs = normalizeTimestamp(cloudEntry.updated_at);+ const local = await window.electronAPI.getSnippetForCloudMerge?.(+ cloudEntry as unknown as Record<string, unknown>+ );++ if (cloudTs > maxUpdatedAt) {+ maxUpdatedAt = cloudTs;+ maxId = cloudEntry.id;+ } else if (cloudTs === maxUpdatedAt && cloudEntry.id > maxId) {+ maxId = cloudEntry.id;+ }++ if (cloudEntry.deleted_at) {+ if (local && !(local.sync_status === "pending" && !local.cloud_id)) {+ await window.electronAPI.hardDeleteSnippet?.(local.id);+ changed = true;+ }+ continue;+ }++ const localTs = local ? normalizeTimestamp(local.updated_at) : "";+ const shouldApply =+ !local ||+ cloudTs > localTs ||+ (local.sync_status !== "pending" &&+ (!local.cloud_id || local.cloud_id !== cloudEntry.id));+ if (shouldApply) {+ await window.electronAPI.upsertSnippetFromCloud?.(+ cloudEntry as unknown as Record<string, unknown>+ );+ changed = true;+ }+ }++ if (!hasMore) break;+ const last = entries[entries.length - 1];+ const nextCursor = last[cursorField];+ if (nextCursor === cursor && last.id === cursorId) break;+ cursor = nextCursor;+ cursorId = last.id;+ }++ if (maxUpdatedAt) localStorage.setItem("lastSyncedAt.snippets", maxUpdatedAt);+ if (maxId) localStorage.setItem("lastSyncedAt.snippets.id", maxId);+ if (changed) await window.electronAPI.broadcastSnippetsUpdated?.();+ } catch (err) {+ console.error("Snippet 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!]));diff --git a/src/stores/settingsStore.ts b/src/stores/settingsStore.tsindex ebaebe1d6..eb4e9eaa0 100644--- a/src/stores/settingsStore.ts+++ b/src/stores/settingsStore.ts@@ -552,6 +552,7 @@ export interface SettingsStatesetCustomDictionary: (words: string[]) => void;applyCustomDictionaryFromExternal: (words: string[]) => void;setSnippets: (snippets: Snippet[]) => void;+ applySnippetsFromExternal: (snippets: Snippet[]) => void;setAssemblyAiStreaming: (value: boolean) => void;setAutoGenerateNoteTitle: (value: boolean) => void;setUseCleanupModel: (value: boolean) => void;@@ -1239,6 +1240,26 @@ export const useSettingsStore = create<SettingsState>()((set, get) => ({setSnippets: (snippets: Snippet[]) => {if (isBrowser) localStorage.setItem("snippets", JSON.stringify(snippets));set({ snippets });+ window.electronAPI+ ?.setSnippets?.(snippets)+ .then(() => {+ void import("../services/SyncService.js").then(({ syncService }) => {+ if (syncService.canSync()) void syncService.syncSnippetsNow();+ });+ })+ .catch((err) => {+ logger.warn(+ "Failed to sync snippets to SQLite",+ { error: (err as Error).message },+ "settings"+ );+ });+ },++ // For broadcasts from main process — DB is already authoritative, only update UI.+ applySnippetsFromExternal: (snippets: Snippet[]) => {+ if (isBrowser) localStorage.setItem("snippets", JSON.stringify(snippets));+ set({ snippets });},setUiLanguage: (language: string) => {@@ -2107,6 +2128,29 @@ export async function initializeSettings(): Promise<void> {);}+ // Sync snippets from SQLite <-> localStorage+ try {+ if (window.electronAPI.getSnippets) {+ const currentSnippets = useSettingsStore.getState().snippets;+ const dbSnippets = await window.electronAPI.getSnippets();+ if (dbSnippets.length === 0 && currentSnippets.length > 0) {+ await window.electronAPI.setSnippets?.(currentSnippets);+ const normalizedSnippets = await window.electronAPI.getSnippets();+ if (isBrowser) localStorage.setItem("snippets", JSON.stringify(normalizedSnippets));+ useSettingsStore.setState({ snippets: normalizedSnippets });+ } else if (dbSnippets.length > 0) {+ if (isBrowser) localStorage.setItem("snippets", JSON.stringify(dbSnippets));+ useSettingsStore.setState({ snippets: dbSnippets });+ }+ }+ } catch (err) {+ logger.warn(+ "Failed to sync snippets on startup",+ { error: (err as Error).message },+ "settings"+ );+ }+// Audio detection is derived from the meeting-notification toggle in// sync-notification-preferences, so only process detection is sent here.try {diff --git a/src/types/electron.ts b/src/types/electron.tsindex a81d9abec..4f6b43f27 100644--- a/src/types/electron.ts+++ b/src/types/electron.ts@@ -112,6 +112,18 @@ export interface DictionaryEntryItem {deleted_at: string | null;}+export interface SnippetEntryItem {+ id: number;+ trigger: string;+ replacement: string;+ created_at: string;+ updated_at: string;+ client_snippet_id: string;+ cloud_id: string | null;+ sync_status: "synced" | "pending" | "error";+ deleted_at: string | null;+}+export type WorkspaceRole = "owner" | "admin" | "member";export type TeamRole = "admin" | "member";@@ -571,6 +583,13 @@ declare global {getDictionary: () => Promise<string[]>;setDictionary: (words: string[]) => Promise<{ success: boolean }>;onDictionaryUpdated?: (callback: (words: string[]) => void) => () => void;+ getSnippets?: () => Promise<Array<{ trigger: string; replacement: string }>>;+ setSnippets?: (+ snippets: Array<{ trigger: string; replacement: string }>+ ) => Promise<{ success: boolean }>;+ onSnippetsUpdated?: (+ callback: (snippets: Array<{ trigger: string; replacement: string }>) => void+ ) => () => void;setAutoLearnEnabled?: (enabled: boolean) => void;onCorrectionsLearned?: (callback: (words: string[]) => void) => () => void;undoLearnedCorrections?: (words: string[]) => Promise<{ success: boolean }>;@@ -1908,6 +1927,25 @@ declare global {hardDeleteDictionary?: (id: number) => Promise<{ success: boolean; id: number }>;clearDictionaryCloudId?: (id: number) => Promise<{ success: boolean }>;broadcastDictionaryUpdated?: () => Promise<{ success: boolean }>;++ getPendingSnippets?: () => Promise<SnippetEntryItem[]>;+ getPendingSnippetDeletes?: () => Promise<SnippetEntryItem[]>;+ getSnippetForCloudMerge?: (+ cloudEntry: Record<string, unknown>+ ) => Promise<SnippetEntryItem | null>;+ upsertSnippetFromCloud?: (+ cloudEntry: Record<string, unknown>+ ) => Promise<SnippetEntryItem | null>;+ markSnippetSynced?: (+ id: number,+ cloudId: string,+ serverUpdatedAt?: string,+ expectedTrigger?: string,+ expectedReplacement?: string+ ) => Promise<{ success: boolean; changes: number }>;+ hardDeleteSnippet?: (id: number) => Promise<{ success: boolean; id: number }>;+ clearSnippetCloudId?: (id: number) => Promise<{ success: boolean }>;+ broadcastSnippetsUpdated?: () => Promise<{ success: boolean }>;};api?: {diff --git a/test/helpers/snippetsDatabase.test.js b/test/helpers/snippetsDatabase.test.jsnew file mode 100644index 000000000..ed7a5ecef--- /dev/null+++ b/test/helpers/snippetsDatabase.test.js@@ -0,0 +1,215 @@+const test = require("node:test");+const assert = require("node:assert/strict");+const fs = require("node:fs");+const os = require("node:os");+const path = require("node:path");+const Module = require("node:module");++let userDataDir = fs.mkdtempSync(path.join(os.tmpdir(), "openwhispr-snippets-db-"));+const originalLoad = Module._load;++Module._load = function patchedLoad(request, parent, isMain) {+ if (request === "electron") {+ return {+ app: {+ getPath: () => userDataDir,+ getAppPath: () => process.cwd(),+ isReady: () => false,+ },+ };+ }+ return originalLoad.call(this, request, parent, isMain);+};++process.env.NODE_ENV = "test";++const DatabaseManager = require("../../src/helpers/database.js");++function createDb(t) {+ userDataDir = fs.mkdtempSync(path.join(os.tmpdir(), "openwhispr-snippets-db-"));+ try {+ const BetterSqlite = require("better-sqlite3");+ const probe = new BetterSqlite(path.join(userDataDir, "probe.db"));+ probe.close();+ fs.rmSync(path.join(userDataDir, "probe.db"), { force: true });+ } catch (error) {+ if (String(error?.message || error).includes("NODE_MODULE_VERSION")) {+ t.skip("better-sqlite3 native binding is not compiled for this Node runtime");+ return null;+ }+ throw error;+ }++ try {+ return new DatabaseManager();+ } catch (error) {+ if (String(error?.message || error).includes("NODE_MODULE_VERSION")) {+ t.skip("better-sqlite3 native binding is not compiled for this Node runtime");+ return null;+ }+ throw error;+ }+}++test("snippets diff trims, dedupes, updates, and preserves synced no-ops", (t) => {+ const db = createDb(t);+ if (!db) return;+ db.setSnippets([+ { trigger: " signoff ", replacement: " Regards " },+ { trigger: "SIGNOFF", replacement: "Ignored duplicate" },+ ]);++ assert.deepEqual(db.getSnippets(), [{ trigger: "signoff", replacement: "Regards" }]);+ const [created] = db.getPendingSnippets();+ assert.ok(created.client_snippet_id);++ db.markSnippetSynced(created.id, "cloud-1", "2026-07-01T10:00:00.000Z");+ db.setSnippets([{ trigger: "signoff", replacement: "Regards" }]);+ assert.equal(db.getPendingSnippets().length, 0);++ db.setSnippets([{ trigger: "signoff", replacement: "Best regards" }]);+ const [updated] = db.getPendingSnippets();+ assert.equal(updated.id, created.id);+ assert.equal(updated.replacement, "Best regards");+});++test("snippet removals hard-delete unsynced rows and tombstone synced rows", (t) => {+ const db = createDb(t);+ if (!db) return;++ db.setSnippets([{ trigger: "temp", replacement: "Temporary" }]);+ db.setSnippets([]);+ assert.equal(db.db.prepare("SELECT COUNT(*) AS count FROM snippets").get().count, 0);++ db.setSnippets([{ trigger: "synced", replacement: "Synced" }]);+ const [created] = db.getPendingSnippets();+ db.markSnippetSynced(created.id, "cloud-2", "2026-07-01T10:00:00.000Z");++ db.setSnippets([]);+ assert.deepEqual(db.getSnippets(), []);+ const [deleted] = db.getPendingSnippetDeletes();+ assert.equal(deleted.id, created.id);+ assert.equal(deleted.cloud_id, "cloud-2");+});++test("cloud snippets upsert by client id, cloud id, then trigger", (t) => {+ const db = createDb(t);+ if (!db) return;++ const first = db.upsertSnippetFromCloud({+ id: "cloud-1",+ client_snippet_id: "client-1",+ trigger: "intro",+ replacement: "Hello there",+ created_at: "2026-07-01T10:00:00.000Z",+ updated_at: "2026-07-01T10:00:00.000Z",+ });+ assert.equal(first.trigger, "intro");+ assert.equal(first.sync_status, "synced");++ const byClient = db.upsertSnippetFromCloud({+ id: "cloud-1",+ client_snippet_id: "client-1",+ trigger: "intro",+ replacement: "Hello again",+ created_at: "2026-07-01T10:00:00.000Z",+ updated_at: "2026-07-01T11:00:00.000Z",+ });+ assert.equal(byClient.id, first.id);+ assert.equal(byClient.replacement, "Hello again");++ const byTrigger = db.upsertSnippetFromCloud({+ id: "cloud-2",+ client_snippet_id: "client-2",+ trigger: "INTRO",+ replacement: "Case merge",+ created_at: "2026-07-01T12:00:00.000Z",+ updated_at: "2026-07-01T12:00:00.000Z",+ });+ assert.equal(byTrigger.id, first.id);+ assert.equal(byTrigger.cloud_id, "cloud-2");+ assert.equal(byTrigger.client_snippet_id, "client-2");+ assert.equal(db.db.prepare("SELECT COUNT(*) AS count FROM snippets").get().count, 1);+});++test("cloud rename onto a trigger another active snippet holds converges without throwing", (t) => {+ const db = createDb(t);+ if (!db) return;++ db.upsertSnippetFromCloud({+ id: "cloud-a",+ client_snippet_id: "ca",+ trigger: "foo",+ replacement: "Foo text",+ created_at: "2026-07-01T10:00:00.000Z",+ updated_at: "2026-07-01T10:00:00.000Z",+ });+ db.upsertSnippetFromCloud({+ id: "cloud-b",+ client_snippet_id: "cb",+ trigger: "bar",+ replacement: "Bar text",+ created_at: "2026-07-01T10:00:00.000Z",+ updated_at: "2026-07-01T10:00:00.000Z",+ });++ const merged = db.upsertSnippetFromCloud({+ id: "cloud-a",+ client_snippet_id: "ca",+ trigger: "bar",+ replacement: "Foo renamed",+ created_at: "2026-07-01T10:00:00.000Z",+ updated_at: "2026-07-01T12:00:00.000Z",+ });++ assert.equal(merged.trigger, "bar");+ assert.equal(merged.cloud_id, "cloud-a");+ assert.deepEqual(db.getSnippets(), [{ trigger: "bar", replacement: "Foo renamed" }]);+ assert.equal(db.db.prepare("SELECT COUNT(*) AS count FROM snippets").get().count, 1);+});++test("markSnippetSynced leaves a row pending when its content changed since the push", (t) => {+ const db = createDb(t);+ if (!db) return;++ db.setSnippets([{ trigger: "brb", replacement: "be right back" }]);+ const [pushed] = db.getPendingSnippets();++ // A concurrent edit lands while the push (snapshot 'be right back') is in flight.+ db.setSnippets([{ trigger: "brb", replacement: "back in a bit" }]);++ const stale = db.markSnippetSynced(+ pushed.id,+ "cloud-1",+ "2026-07-01T10:00:00.000Z",+ "brb",+ "be right back"+ );+ assert.equal(stale.changes, 0);+ const [stillPending] = db.getPendingSnippets();+ assert.equal(stillPending.id, pushed.id);+ assert.equal(stillPending.replacement, "back in a bit");+ assert.equal(stillPending.cloud_id, null);++ const ok = db.markSnippetSynced(+ pushed.id,+ "cloud-1",+ "2026-07-01T11:00:00.000Z",+ "brb",+ "back in a bit"+ );+ assert.equal(ok.changes, 1);+ assert.equal(db.getPendingSnippets().length, 0);+});++test("setSnippets drops triggers longer than the sync limit", (t) => {+ const db = createDb(t);+ if (!db) return;++ db.setSnippets([+ { trigger: "x".repeat(101), replacement: "too long" },+ { trigger: "ok", replacement: "fine" },+ ]);++ assert.deepEqual(db.getSnippets(), [{ trigger: "ok", replacement: "fine" }]);+});