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(dictionary): cross-device custom dictionary sync (#966)
Chad Piha3c4ff0f4cf73
diff --git a/preload.js b/preload.jsindex 79166bad5..efd2b9b33 100644--- a/preload.js+++ b/preload.js@@ -840,6 +840,18 @@ contextBridge.exposeInMainWorld("electronAPI", {getPendingTranscriptionDeletes: () => ipcRenderer.invoke("db-get-pending-transcription-deletes"),hardDeleteTranscription: (id) => ipcRenderer.invoke("db-hard-delete-transcription", id),+ getPendingDictionary: () => ipcRenderer.invoke("db-get-pending-dictionary"),+ getPendingDictionaryDeletes: () => ipcRenderer.invoke("db-get-pending-dictionary-deletes"),+ getDictionaryByClientId: (clientDictId) =>+ ipcRenderer.invoke("db-get-dictionary-by-client-id", clientDictId),+ upsertDictionaryFromCloud: (cloudEntry) =>+ ipcRenderer.invoke("db-upsert-dictionary-from-cloud", cloudEntry),+ markDictionarySynced: (id, cloudId) =>+ ipcRenderer.invoke("db-mark-dictionary-synced", id, cloudId),+ hardDeleteDictionary: (id) => ipcRenderer.invoke("db-hard-delete-dictionary", id),+ clearDictionaryCloudId: (id) => ipcRenderer.invoke("db-clear-dictionary-cloud-id", id),+ broadcastDictionaryUpdated: () => ipcRenderer.invoke("db-broadcast-dictionary-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 a0910578d..90c8c76bc 100644--- a/src/helpers/database.js+++ b/src/helpers/database.js@@ -528,12 +528,50 @@ class DatabaseManager {if (!err.message.includes("duplicate column")) throw err;}+ // Sync columns for custom_dictionary+ try {+ this.db.exec("ALTER TABLE custom_dictionary ADD COLUMN client_dict_id TEXT");+ } catch (err) {+ if (!err.message.includes("duplicate column")) throw err;+ }+ try {+ this.db.exec("ALTER TABLE custom_dictionary ADD COLUMN cloud_id TEXT");+ } catch (err) {+ if (!err.message.includes("duplicate column")) throw err;+ }+ try {+ this.db.exec(+ "ALTER TABLE custom_dictionary ADD COLUMN source TEXT NOT NULL DEFAULT 'manual'"+ );+ } catch (err) {+ if (!err.message.includes("duplicate column")) throw err;+ }+ try {+ this.db.exec("ALTER TABLE custom_dictionary ADD COLUMN sync_status TEXT DEFAULT 'pending'");+ } catch (err) {+ if (!err.message.includes("duplicate column")) throw err;+ }+ try {+ this.db.exec("ALTER TABLE custom_dictionary ADD COLUMN deleted_at TEXT");+ } catch (err) {+ if (!err.message.includes("duplicate column")) throw err;+ }+ try {+ this.db.exec("ALTER TABLE custom_dictionary ADD COLUMN updated_at DATETIME");+ this.db.exec(+ "UPDATE custom_dictionary SET updated_at = created_at WHERE updated_at IS NULL"+ );+ } catch (err) {+ if (!err.message.includes("duplicate column")) throw err;+ }+// Backfill client IDs for existing rowsconst 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" },+ { table: "custom_dictionary", col: "client_dict_id" },];for (const { table, col } of syncTables) {const rows = this.db.prepare(`SELECT id FROM ${table} WHERE ${col} IS NULL`).all();@@ -555,6 +593,9 @@ class DatabaseManager {this.db.exec("CREATE UNIQUE INDEX IF NOT EXISTS idx_transcriptions_client_id ON transcriptions(client_transcription_id)");+ this.db.exec(+ "CREATE UNIQUE INDEX IF NOT EXISTS idx_custom_dictionary_client_id ON custom_dictionary(client_dict_id)"+ );return true;} catch (error) {@@ -734,8 +775,9 @@ class DatabaseManager {if (!this.db) {throw new Error("Database not initialized");}- const stmt = this.db.prepare("SELECT word FROM custom_dictionary ORDER BY id ASC");- const rows = stmt.all();+ const rows = this.db+ .prepare("SELECT word FROM custom_dictionary WHERE deleted_at IS NULL ORDER BY id ASC")+ .all();return rows.map((row) => row.word);} catch (error) {debugLogger.error("Error getting dictionary", { error: error.message }, "database");@@ -743,22 +785,79 @@ class DatabaseManager {}}- setDictionary(words) {+ // Diff-based update so unchanged rows keep their source/created_at/cloud_id.+ // `sourceForNewWords` tags additions ('manual' for user-typed, 'learned' for auto-learn).+ setDictionary(words, sourceForNewWords = "manual") {try {if (!this.db) {throw new Error("Database not initialized");}- const transaction = this.db.transaction((wordList) => {- this.db.prepare("DELETE FROM custom_dictionary").run();- const insert = this.db.prepare("INSERT OR IGNORE INTO custom_dictionary (word) VALUES (?)");- for (const word of wordList) {- const trimmed = typeof word === "string" ? word.trim() : "";- if (trimmed) {- insert.run(trimmed);+ // Dedupe input by lower(word), keeping the first occurrence's casing, so+ // the diff loop sees at most one incoming entry per word.+ const incomingByLower = new Map();+ for (const raw of Array.isArray(words) ? words : []) {+ if (typeof raw !== "string") continue;+ const trimmed = raw.trim();+ if (!trimmed) continue;+ const lower = trimmed.toLowerCase();+ if (!incomingByLower.has(lower)) incomingByLower.set(lower, trimmed);+ }+ const cleaned = Array.from(incomingByLower.values());+ const incomingLower = new Set(incomingByLower.keys());++ const existingRows = this.db+ .prepare("SELECT id, word, source, deleted_at FROM custom_dictionary")+ .all();+ const existingByLower = new Map(existingRows.map((r) => [r.word.toLowerCase(), r]));++ const tombstone = this.db.prepare(+ "UPDATE custom_dictionary 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 custom_dictionary WHERE id = ? AND cloud_id IS NULL"+ );+ const restore = this.db.prepare(+ "UPDATE custom_dictionary SET deleted_at = NULL, source = CASE WHEN source = 'learned' AND ? = 'manual' THEN 'manual' ELSE source END, word = ?, updated_at = datetime('now'), sync_status = 'pending' WHERE id = ?"+ );+ const promoteSource = this.db.prepare(+ "UPDATE custom_dictionary SET word = ?, source = 'manual', updated_at = datetime('now'), sync_status = 'pending' WHERE id = ? AND source = 'learned'"+ );+ // Updates word casing on an active row (guarded on word != ? so an+ // unchanged row stays untouched and keeps its sync_status).+ const updateWord = this.db.prepare(+ "UPDATE custom_dictionary SET word = ?, updated_at = datetime('now'), sync_status = 'pending' WHERE id = ? AND word != ?"+ );+ // INSERT OR IGNORE in case a legacy case-variant row collides on the+ // case-sensitive UNIQUE(word) that existingByLower didn't catch.+ const insert = this.db.prepare(+ "INSERT OR IGNORE INTO custom_dictionary (word, source, client_dict_id, sync_status, updated_at) VALUES (?, ?, ?, 'pending', datetime('now'))"+ );++ this.db.transaction(() => {+ for (const existing of existingRows) {+ if (incomingLower.has(existing.word.toLowerCase())) continue;+ if (existing.deleted_at) continue;+ // Removed word: hard-delete if never synced (no cloud_id), else+ // tombstone so the next push tells the server about the deletion.+ const hardResult = hardDelete.run(existing.id);+ if (hardResult.changes === 0) tombstone.run(existing.id);+ }+ for (const word of cleaned) {+ const existing = existingByLower.get(word.toLowerCase());+ if (existing) {+ if (existing.deleted_at) {+ restore.run(sourceForNewWords, word, existing.id);+ } else if (sourceForNewWords === "manual" && existing.source === "learned") {+ promoteSource.run(word, existing.id);+ } else {+ updateWord.run(word, existing.id, word);+ }+ continue;}+ insert.run(word, sourceForNewWords, randomUUID());}- });- transaction(words);+ })();+return { success: true };} catch (error) {debugLogger.error("Error setting dictionary", { error: error.message }, "database");@@ -766,6 +865,187 @@ class DatabaseManager {}}+ getPendingDictionary() {+ try {+ if (!this.db) throw new Error("Database not initialized");+ return this.db+ .prepare(+ "SELECT * FROM custom_dictionary WHERE sync_status = 'pending' AND deleted_at IS NULL"+ )+ .all();+ } catch (error) {+ debugLogger.error("Error getting pending dictionary", { error: error.message }, "database");+ throw error;+ }+ }++ getPendingDictionaryDeletes() {+ try {+ if (!this.db) throw new Error("Database not initialized");+ return this.db+ .prepare(+ "SELECT * FROM custom_dictionary WHERE deleted_at IS NOT NULL AND cloud_id IS NOT NULL AND sync_status = 'pending'"+ )+ .all();+ } catch (error) {+ debugLogger.error(+ "Error getting pending dictionary deletes",+ { error: error.message },+ "database"+ );+ throw error;+ }+ }++ hardDeleteDictionaryEntry(id) {+ try {+ if (!this.db) throw new Error("Database not initialized");+ const result = this.db.prepare("DELETE FROM custom_dictionary WHERE id = ?").run(id);+ return { success: result.changes > 0, id };+ } catch (error) {+ debugLogger.error(+ "Error hard deleting dictionary entry",+ { error: error.message },+ "database"+ );+ throw error;+ }+ }++ getDictionaryEntryByClientId(clientDictId) {+ try {+ if (!this.db) throw new Error("Database not initialized");+ return (+ this.db+ .prepare("SELECT * FROM custom_dictionary WHERE client_dict_id = ?")+ .get(clientDictId) || null+ );+ } catch (error) {+ debugLogger.error(+ "Error getting dictionary entry by client id",+ { error: error.message },+ "database"+ );+ throw error;+ }+ }++ upsertDictionaryFromCloud(cloudEntry) {+ try {+ if (!this.db) throw new Error("Database not initialized");+ // Reject incomplete payloads rather than corrupt a row with defaults.+ if (!cloudEntry || typeof cloudEntry !== "object") return null;+ if (typeof cloudEntry.id !== "string" || !cloudEntry.id) return null;++ const word = typeof cloudEntry.word === "string" ? cloudEntry.word.trim() : "";+ if (!word) return null;++ const clientDictId =+ typeof cloudEntry.client_dict_id === "string" && cloudEntry.client_dict_id+ ? cloudEntry.client_dict_id+ : randomUUID();+ const incomingSource = cloudEntry.source === "learned" ? "learned" : "manual";+ 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;++ // Resolve the local row deterministically: client_dict_id, then cloud_id,+ // then word.+ const byClient = this.db+ .prepare("SELECT * FROM custom_dictionary WHERE client_dict_id = ? LIMIT 1")+ .get(clientDictId);+ const byCloud =+ byClient ||+ this.db+ .prepare("SELECT * FROM custom_dictionary WHERE cloud_id = ? LIMIT 1")+ .get(cloudEntry.id);+ const existing =+ byCloud ||+ this.db+ .prepare("SELECT * FROM custom_dictionary WHERE lower(word) = lower(?) LIMIT 1")+ .get(word);++ if (existing) {+ // Manual is sticky — a pull never demotes a local manual row to learned.+ const mergedSource =+ existing.source === "manual" || incomingSource === "manual" ? "manual" : "learned";+ this.db+ .prepare(+ `UPDATE custom_dictionary+ SET cloud_id = ?, client_dict_id = ?, word = ?, source = ?,+ sync_status = 'synced', deleted_at = NULL, updated_at = ?+ WHERE id = ?`+ )+ .run(cloudEntry.id, clientDictId, word, mergedSource, updatedAt, existing.id);+ return this.db.prepare("SELECT * FROM custom_dictionary WHERE id = ?").get(existing.id);+ }++ this.db+ .prepare(+ `INSERT INTO custom_dictionary+ (word, source, client_dict_id, cloud_id, sync_status, created_at, updated_at)+ VALUES (?, ?, ?, ?, 'synced', ?, ?)`+ )+ .run(word, incomingSource, clientDictId, cloudEntry.id, createdAt, updatedAt);+ return this.db+ .prepare("SELECT * FROM custom_dictionary WHERE client_dict_id = ?")+ .get(clientDictId);+ } catch (error) {+ debugLogger.error(+ "Error upserting dictionary entry from cloud",+ { error: error.message },+ "database"+ );+ throw error;+ }+ }++ markDictionaryEntrySynced(id, cloudId) {+ try {+ if (!this.db) throw new Error("Database not initialized");+ // Guard on deleted_at so a delete or tombstone that raced the push isn't+ // flipped back to 'synced' (which would strand the deletion). changes=0+ // signals that race to SyncService, which reconciles the cloud row.+ const result = this.db+ .prepare(+ "UPDATE custom_dictionary SET sync_status = 'synced', cloud_id = ? WHERE id = ? AND deleted_at IS NULL"+ )+ .run(cloudId, id);+ return { success: result.changes > 0, changes: result.changes };+ } catch (error) {+ debugLogger.error(+ "Error marking dictionary entry synced",+ { error: error.message },+ "database"+ );+ throw error;+ }+ }++ // Clears cloud_id after a 404 so the next push re-creates the row via+ // batchCreate instead of retrying the dead PATCH.+ clearDictionaryCloudId(id) {+ try {+ if (!this.db) throw new Error("Database not initialized");+ const result = this.db+ .prepare(+ "UPDATE custom_dictionary SET cloud_id = NULL, sync_status = 'pending' WHERE id = ?"+ )+ .run(id);+ return { success: result.changes > 0 };+ } catch (error) {+ debugLogger.error("Error clearing dictionary cloud_id", { error: error.message }, "database");+ throw error;+ }+ }+saveNote(title,content,diff --git a/src/helpers/ipcHandlers.js b/src/helpers/ipcHandlers.jsindex fdb9c1dc2..d21ad1936 100644--- a/src/helpers/ipcHandlers.js+++ b/src/helpers/ipcHandlers.js@@ -649,14 +649,16 @@ class IPCHandlers {if (corrections.length > 0) {const updatedDict = [...currentDict, ...corrections];- const saveResult = this.databaseManager.setDictionary(updatedDict);+ const saveResult = this.databaseManager.setDictionary(updatedDict, "learned");if (saveResult?.success === false) {debugLogger.debug("[AutoLearn] Failed to save dictionary", { error: saveResult.error });return;}- this.broadcastToWindows("dictionary-updated", updatedDict);+ // Broadcast the post-save normalized list, not the raw input (which+ // still has case-variant dupes), so renderers don't flash ghost rows.+ this.broadcastToWindows("dictionary-updated", this.databaseManager.getDictionary());// Show the overlay so the toast is visible (it may have been hidden after dictation)this.windowManager.showDictationPanel();@@ -921,6 +923,42 @@ class IPCHandlers {return this.databaseManager.setDictionary(words);});+ ipcMain.handle("db-get-pending-dictionary", async () => {+ return this.databaseManager.getPendingDictionary();+ });++ ipcMain.handle("db-get-pending-dictionary-deletes", async () => {+ return this.databaseManager.getPendingDictionaryDeletes();+ });++ ipcMain.handle("db-get-dictionary-by-client-id", async (_event, clientDictId) => {+ return this.databaseManager.getDictionaryEntryByClientId(clientDictId);+ });++ ipcMain.handle("db-upsert-dictionary-from-cloud", async (_event, cloudEntry) => {+ return this.databaseManager.upsertDictionaryFromCloud(cloudEntry);+ });++ ipcMain.handle("db-mark-dictionary-synced", async (_event, id, cloudId) => {+ return this.databaseManager.markDictionaryEntrySynced(id, cloudId);+ });++ ipcMain.handle("db-hard-delete-dictionary", async (_event, id) => {+ return this.databaseManager.hardDeleteDictionaryEntry(id);+ });++ ipcMain.handle("db-clear-dictionary-cloud-id", async (_event, id) => {+ return this.databaseManager.clearDictionaryCloudId(id);+ });++ ipcMain.handle("db-broadcast-dictionary-updated", async () => {+ // Emit the normalized list straight from SQLite so renderers see the+ // post-dedupe truth, never a caller-supplied payload.+ const words = this.databaseManager.getDictionary();+ this.broadcastToWindows("dictionary-updated", words);+ return { success: true };+ });+ipcMain.handle("undo-learned-corrections", async (_event, words) => {try {if (!Array.isArray(words) || words.length === 0) {@@ -940,7 +978,7 @@ class IPCHandlers {});return { success: false };}- this.broadcastToWindows("dictionary-updated", updatedDict);+ this.broadcastToWindows("dictionary-updated", this.databaseManager.getDictionary());debugLogger.debug("[AutoLearn] Undo: removed words", { words: validWords });return { success: true };} catch (err) {@@ -6256,17 +6294,27 @@ class IPCHandlers {const response = await proxyFetch(`${apiUrl}${opts.path}`, fetchOpts);if (response.status === 401) {- return { success: false, error: "Session expired", code: "AUTH_EXPIRED" };+ return {+ success: false,+ error: "Session expired",+ code: "AUTH_EXPIRED",+ status: 401,+ };}if (response.status === 503) {- return { success: false, error: "Service temporarily unavailable", code: "SERVER_ERROR" };+ return {+ success: false,+ error: "Service temporarily unavailable",+ code: "SERVER_ERROR",+ status: 503,+ };}const data = await response.json().catch(() => null);if (!response.ok) {const message = data?.error?.message || data?.error || `API error: ${response.status}`;- return { success: false, error: message };+ return { success: false, error: message, status: response.status };}return { success: true, data };diff --git a/src/hooks/useSettings.ts b/src/hooks/useSettings.tsindex 375fc071b..07f091300 100644--- a/src/hooks/useSettings.ts+++ b/src/hooks/useSettings.ts@@ -90,7 +90,7 @@ export interface ChatAgentSettings {function useSettingsInternal() {const store = useSettingsStore();- const { setCustomDictionary } = store;+ const { setCustomDictionary, applyCustomDictionaryFromExternal } = store;// One-time initialization: sync API keys, dictation key, activation mode,// UI language, and dictionary from the main process / SQLite.@@ -107,16 +107,18 @@ function useSettingsInternal() {});}, []);- // Listen for dictionary updates from main process (auto-learn corrections)+ // Refresh the in-memory store from main-process broadcasts (auto-learn, sync+ // pulls) without re-triggering a sync — that would loop, since pulls emit the+ // broadcast. Writes that must sync go through setCustomDictionary instead.useEffect(() => {if (typeof window === "undefined" || !window.electronAPI?.onDictionaryUpdated) return;const unsubscribe = window.electronAPI.onDictionaryUpdated((words: string[]) => {if (Array.isArray(words)) {- setCustomDictionary(words);+ applyCustomDictionaryFromExternal(words);}});return unsubscribe;- }, [setCustomDictionary]);+ }, [applyCustomDictionaryFromExternal]);// Auto-learn corrections from user edits in external appsconst [autoLearnCorrections, setAutoLearnCorrectionsRaw] = useLocalStorage(diff --git a/src/services/DictionaryService.ts b/src/services/DictionaryService.tsnew file mode 100644index 000000000..9116756f3--- /dev/null+++ b/src/services/DictionaryService.ts@@ -0,0 +1,62 @@+import { cloudGet, cloudPost, cloudPatch, cloudDelete } from "./cloudApi.js";++export type DictionarySource = "manual" | "learned";++interface DictionaryEntryInput {+ word: string;+ source?: DictionarySource;+ client_dict_id?: string;+ created_at?: string;+ updated_at?: string;+}++export interface CloudDictionaryEntry {+ id: string;+ client_dict_id: string | null;+ word: string;+ source: DictionarySource;+ deleted_at: string | null;+ created_at: string;+ updated_at: string;+}++async function batchCreate(+ entries: DictionaryEntryInput[]+): Promise<{ created: CloudDictionaryEntry[] }> {+ return cloudPost<{ created: CloudDictionaryEntry[] }>("/api/dictionary/batch-create", {+ entries,+ });+}++async function update(+ id: string,+ updates: { word?: string; source?: DictionarySource }+): Promise<CloudDictionaryEntry> {+ return cloudPatch<CloudDictionaryEntry>("/api/dictionary/update", { id, ...updates });+}++async function deleteEntry(id: string): Promise<void> {+ await cloudDelete("/api/dictionary/delete", { id });+}++async function list(+ since?: string,+ limit?: number,+ sinceId?: string+): Promise<{ entries: CloudDictionaryEntry[]; 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: CloudDictionaryEntry[]; hasMore: boolean }>(+ `/api/dictionary/list${query}`+ );+}++export const DictionaryService = {+ batchCreate,+ update,+ delete: deleteEntry,+ list,+};diff --git a/src/services/SyncService.ts b/src/services/SyncService.tsindex cab4ff931..6dca40143 100644--- a/src/services/SyncService.ts+++ b/src/services/SyncService.ts@@ -8,13 +8,32 @@ import { NotesService } from "./NotesService.js";import { ConversationsService } from "./ConversationsService.js";import { FoldersService } from "./FoldersService.js";import { TranscriptionsService } from "./TranscriptionsService.js";+import { DictionaryService } from "./DictionaryService.js";+import { CloudApiError } from "./cloudApi.js";++function isHttpStatus(err: unknown, status: number): boolean {+ return err instanceof CloudApiError && err.status === status;+}const PUSH_DEBOUNCE_MS = 2000;const BATCH_SIZE = 50;const TRANSCRIPTION_BATCH_SIZE = 100;+const DICTIONARY_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+// millis-precision ISO so the pull loop's lexical greater-than compares+// correctly — without the ".000" pad a whole-second local value sorts after a+// sub-second cloud value at the same instant ('Z' > '.').+function normalizeTimestamp(value: string | null | undefined): string {+ if (!value) return "";+ const iso = value.replace(" ", "T").replace(/Z$/, "");+ return (/\.\d+$/.test(iso) ? iso : `${iso}.000`) + "Z";+}class SyncService {private syncing = false;+ private dictionaryDirty = false;private pushTimers = new Map<string, ReturnType<typeof setTimeout>>();canSync(): boolean {@@ -33,6 +52,12 @@ class SyncService {await this.syncNotes();await this.syncConversations();await this.syncTranscriptions();+ // Edits during the awaits above set dictionaryDirty (syncing is already+ // true), so re-run until clean rather than stalling until the next trigger.+ do {+ this.dictionaryDirty = false;+ await this.syncDictionary();+ } while (this.dictionaryDirty);localStorage.setItem("lastSyncedAt", new Date().toISOString());} catch (err) {console.error("Sync failed:", err);@@ -41,6 +66,27 @@ class SyncService {}}+ async syncDictionaryNow(): Promise<void> {+ if (!this.canSync()) return;+ // A sync already running will drain dictionaryDirty before it finishes, so+ // flag a re-run instead of dropping this request.+ if (this.syncing) {+ this.dictionaryDirty = true;+ return;+ }+ this.syncing = true;+ try {+ do {+ this.dictionaryDirty = false;+ await this.syncDictionary();+ } while (this.dictionaryDirty);+ } catch (err) {+ console.error("Dictionary sync failed:", err);+ } finally {+ this.syncing = false;+ }+ }+debouncedPush(entityType: string, entityId: number): void {if (!this.canSync()) return;const key = `${entityType}:${entityId}`;@@ -586,6 +632,184 @@ class SyncService {}}+ private async syncDictionary(): Promise<void> {+ // Fail loud on preload skew: a missing binding silently optional-chained to+ // a no-op would lose user data, so assert the whole surface up front.+ const api = window.electronAPI;+ const required = [+ "getPendingDictionary",+ "getPendingDictionaryDeletes",+ "getDictionaryByClientId",+ "upsertDictionaryFromCloud",+ "markDictionarySynced",+ "hardDeleteDictionary",+ "clearDictionaryCloudId",+ "broadcastDictionaryUpdated",+ ] as const;+ const missing = required.filter((name) => typeof api[name] !== "function");+ if (missing.length > 0) {+ throw new Error(+ `Dictionary IPC bindings missing — preload out of date: ${missing.join(", ")}`+ );+ }++ await this.pushPendingDictionary();+ await this.pushDictionaryDeletes();+ await this.pullDictionary();+ }++ private async pushPendingDictionary(): Promise<void> {+ const pending = (await window.electronAPI.getPendingDictionary?.()) ?? [];+ 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 {+ await DictionaryService.update(entry.cloud_id!, {+ word: entry.word,+ source: entry.source,+ });+ await window.electronAPI.markDictionarySynced?.(entry.id, entry.cloud_id!);+ } catch (err) {+ // 404: another device purged the cloud row. Clear the stale cloud_id so+ // the next push re-creates it via batchCreate instead of retrying PATCH.+ if (isHttpStatus(err, 404)) {+ await window.electronAPI.clearDictionaryCloudId?.(entry.id);+ } else {+ console.error("Dictionary update sync failed:", err);+ }+ }+ }++ for (let i = 0; i < creates.length; i += DICTIONARY_BATCH_SIZE) {+ const chunk = creates.slice(i, i + DICTIONARY_BATCH_SIZE);+ try {+ const { created } = await DictionaryService.batchCreate(+ chunk.map((e) => ({+ client_dict_id: e.client_dict_id,+ word: e.word,+ source: e.source,+ created_at: e.created_at,+ updated_at: e.updated_at,+ }))+ );+ const byClientId = new Map(created.map((c) => [c.client_dict_id, c]));+ let unmatched = 0;+ for (const local of chunk) {+ const server = byClientId.get(local.client_dict_id);+ if (!server) {+ unmatched += 1;+ continue;+ }+ // 0 changes means the local row was deleted between snapshot and ack —+ // delete the freshly-created server row so we don't orphan it.+ const result = await window.electronAPI.markDictionarySynced?.(local.id, server.id);+ if (result && result.changes === 0) {+ try {+ await DictionaryService.delete(server.id);+ } catch (deleteErr) {+ console.error("Dictionary orphan cleanup failed:", deleteErr);+ }+ }+ }+ if (unmatched > 0) {+ console.warn(+ `Dictionary batch-create: ${unmatched}/${chunk.length} rows had no matching server response`+ );+ }+ } catch (err) {+ console.error("Dictionary batch create failed:", err);+ }+ }+ }++ private async pushDictionaryDeletes(): Promise<void> {+ const deletes = (await window.electronAPI.getPendingDictionaryDeletes?.()) ?? [];+ for (const entry of deletes) {+ if (!entry.cloud_id) continue;+ try {+ await DictionaryService.delete(entry.cloud_id);+ await window.electronAPI.hardDeleteDictionary?.(entry.id);+ } catch (err) {+ // 404 means the row is already gone server-side — treat as success.+ if (isHttpStatus(err, 404)) {+ await window.electronAPI.hardDeleteDictionary?.(entry.id);+ } else {+ console.error("Dictionary delete sync failed:", err);+ }+ }+ }+ }++ private async pullDictionary(): Promise<void> {+ try {+ const since = localStorage.getItem("lastSyncedAt.dictionary") ?? undefined;+ const sinceId = localStorage.getItem("lastSyncedAt.dictionary.id") ?? undefined;+ let changed = false;++ let cursor: string | undefined = since;+ let cursorId: string | undefined = sinceId;+ let maxUpdatedAt = normalizeTimestamp(since);+ let maxId = sinceId ?? "";++ while (true) {+ const { entries, hasMore } = await DictionaryService.list(+ cursor,+ DICTIONARY_BATCH_SIZE,+ cursorId+ );+ if (entries.length === 0) break;++ for (const cloudEntry of entries) {+ const local = await window.electronAPI.getDictionaryByClientId?.(+ cloudEntry.client_dict_id ?? ""+ );++ if (cloudEntry.deleted_at) {+ if (local) {+ await window.electronAPI.hardDeleteDictionary?.(local.id);+ changed = true;+ }+ continue;+ }++ // Last-writer-wins on normalized timestamps (see normalizeTimestamp).+ const cloudTs = normalizeTimestamp(cloudEntry.updated_at);+ const localTs = local ? normalizeTimestamp(local.updated_at) : "";+ if (!local || cloudTs > localTs) {+ await window.electronAPI.upsertDictionaryFromCloud?.(+ cloudEntry as unknown as Record<string, unknown>+ );+ changed = true;+ }++ if (cloudTs > maxUpdatedAt) {+ maxUpdatedAt = cloudTs;+ maxId = cloudEntry.id;+ } else if (cloudTs === maxUpdatedAt && cloudEntry.id > maxId) {+ maxId = cloudEntry.id;+ }+ }++ if (!hasMore) break;+ const last = entries[entries.length - 1];+ // Stall guard: if the (updated_at, id) cursor didn't advance after a+ // full page, bail rather than loop forever.+ if (last.updated_at === cursor && last.id === cursorId) break;+ cursor = last.updated_at;+ cursorId = last.id;+ }++ if (maxUpdatedAt) localStorage.setItem("lastSyncedAt.dictionary", maxUpdatedAt);+ if (maxId) localStorage.setItem("lastSyncedAt.dictionary.id", maxId);+ if (changed) await window.electronAPI.broadcastDictionaryUpdated?.();+ } catch (err) {+ console.error("Dictionary 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/services/cloudApi.ts b/src/services/cloudApi.tsindex c1bfb090b..5c87d5a53 100644--- a/src/services/cloudApi.ts+++ b/src/services/cloudApi.ts@@ -3,6 +3,18 @@ interface CloudApiResponse<T = unknown> {data?: T;error?: string;code?: string;+ status?: number;+}++export class CloudApiError extends Error {+ status: number;+ code?: string;+ constructor(message: string, status: number, code?: string) {+ super(message);+ this.name = "CloudApiError";+ this.status = status;+ this.code = code;+ }}async function cloudRequest<T = unknown>(method: string, path: string, body?: unknown): Promise<T> {@@ -13,7 +25,11 @@ async function cloudRequest<T = unknown>(method: string, path: string, body?: un})) as CloudApiResponse<T> | undefined;if (!result?.success) {- throw new Error(result?.error ?? "Cloud API request failed");+ throw new CloudApiError(+ result?.error ?? "Cloud API request failed",+ result?.status ?? 0,+ result?.code+ );}return result.data as T;diff --git a/src/stores/settingsStore.ts b/src/stores/settingsStore.tsindex 770b81814..1ad6289ac 100644--- a/src/stores/settingsStore.ts+++ b/src/stores/settingsStore.ts@@ -481,6 +481,7 @@ export interface SettingsStatesetCleanupCloudMode: (value: string) => void;setCleanupCloudBaseUrl: (value: string) => void;setCustomDictionary: (words: string[]) => void;+ applyCustomDictionaryFromExternal: (words: string[]) => void;setSnippets: (snippets: Snippet[]) => void;setAssemblyAiStreaming: (value: boolean) => void;setAutoGenerateNoteTitle: (value: boolean) => void;@@ -1107,13 +1108,26 @@ export const useSettingsStore = create<SettingsState>()((set, get) => ({setCustomDictionary: (words: string[]) => {if (isBrowser) localStorage.setItem("customDictionary", JSON.stringify(words));set({ customDictionary: words });- window.electronAPI?.setDictionary(words).catch((err) => {- logger.warn(- "Failed to sync dictionary to SQLite",- { error: (err as Error).message },- "settings"- );- });+ window.electronAPI+ ?.setDictionary(words)+ .then(() => {+ void import("../services/SyncService.js").then(({ syncService }) => {+ if (syncService.canSync()) void syncService.syncDictionaryNow();+ });+ })+ .catch((err) => {+ logger.warn(+ "Failed to sync dictionary to SQLite",+ { error: (err as Error).message },+ "settings"+ );+ });+ },++ // For broadcasts from main process — DB is already authoritative, only update UI.+ applyCustomDictionaryFromExternal: (words: string[]) => {+ if (isBrowser) localStorage.setItem("customDictionary", JSON.stringify(words));+ set({ customDictionary: words });},setSnippets: (snippets: Snippet[]) => {diff --git a/src/types/electron.ts b/src/types/electron.tsindex 47e7f9bde..f75452fdb 100644--- a/src/types/electron.ts+++ b/src/types/electron.ts@@ -100,6 +100,18 @@ export interface FolderItem {team_id?: string | null;}+export interface DictionaryEntryItem {+ id: number;+ word: string;+ source: "manual" | "learned";+ created_at: string;+ updated_at: string;+ client_dict_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";@@ -1879,6 +1891,20 @@ declare global {markTranscriptionSynced?: (id: number, cloudId: string) => Promise<void>;getPendingTranscriptionDeletes?: () => Promise<TranscriptionItem[]>;hardDeleteTranscription?: (id: number) => Promise<{ success: boolean; id: number }>;++ getPendingDictionary?: () => Promise<DictionaryEntryItem[]>;+ getPendingDictionaryDeletes?: () => Promise<DictionaryEntryItem[]>;+ getDictionaryByClientId?: (clientDictId: string) => Promise<DictionaryEntryItem | null>;+ upsertDictionaryFromCloud?: (+ cloudEntry: Record<string, unknown>+ ) => Promise<DictionaryEntryItem | null>;+ markDictionarySynced?: (+ id: number,+ cloudId: string+ ) => Promise<{ success: boolean; changes: number }>;+ hardDeleteDictionary?: (id: number) => Promise<{ success: boolean; id: number }>;+ clearDictionaryCloudId?: (id: number) => Promise<{ success: boolean }>;+ broadcastDictionaryUpdated?: () => Promise<{ success: boolean }>;};api?: {