Voice-to-text dictation app with local (Nvidia Parakeet/Whisper) and cloud models (BYOK). Privacy-first and available cross-platform.
JavaScript aianthropiccross-platformgeminigroqlinuxmacosnvidiaopen-sourceopenaiparakeetspeech-to-texttranscribewhisperwindows
refactor(dictionary): add a delta write path and move word edits onto it (#1361) (#1365)
Gabriel Stein7803c471b317
diff --git a/preload.js b/preload.jsindex 7b040a83f..82ce35ddc 100644--- a/preload.js+++ b/preload.js@@ -79,6 +79,7 @@ contextBridge.exposeInMainWorld("electronAPI", {// Dictionary functionsgetDictionary: () => ipcRenderer.invoke("db-get-dictionary"),setDictionary: (words) => ipcRenderer.invoke("db-set-dictionary", words),+ applyDictionaryChanges: (changes) => ipcRenderer.invoke("db-apply-dictionary-changes", changes),onDictionaryUpdated: (callback) => {const listener = (_event, words) => callback?.(words);ipcRenderer.on("dictionary-updated", listener);diff --git a/src/components/DictionaryView.tsx b/src/components/DictionaryView.tsxindex 45d96dd70..c54a3d396 100644--- a/src/components/DictionaryView.tsx+++ b/src/components/DictionaryView.tsx@@ -23,7 +23,7 @@ import { parseDictionaryImportText } from "../helpers/dictionaryImport";export default function DictionaryView() {const { t } = useTranslation();- const { customDictionary, setCustomDictionary } = useSettings();+ const { customDictionary, updateCustomDictionary } = useSettings();const agentName = getAgentName();const { toast } = useToast();@@ -58,11 +58,11 @@ export default function DictionaryView() {return true;});if (words.length > 0) {- setCustomDictionary([...customDictionary, ...words]);+ updateCustomDictionary({ add: words });}return words.length;},- [customDictionary, setCustomDictionary]+ [customDictionary, updateCustomDictionary]);const handleAdd = useCallback(() => {@@ -77,9 +77,9 @@ export default function DictionaryView() {const handleRemove = useCallback((word: string) => {- setCustomDictionary(customDictionary.filter((w) => w !== word));+ updateCustomDictionary({ remove: [word] });},- [customDictionary, setCustomDictionary]+ [updateCustomDictionary]);const startEdit = useCallback((word: string) => {@@ -94,10 +94,10 @@ export default function DictionaryView() {(w) => w !== editingWord && w.toLowerCase() === trimmed.toLowerCase());if (trimmed && trimmed !== editingWord && !isDuplicate) {- setCustomDictionary(customDictionary.map((w) => (w === editingWord ? trimmed : w)));+ updateCustomDictionary({ add: [trimmed], remove: [editingWord] });}setEditingWord(null);- }, [editingWord, editValue, customDictionary, setCustomDictionary]);+ }, [editingWord, editValue, customDictionary, updateCustomDictionary]);const handleExport = useCallback(async () => {const result = await window.electronAPI?.exportDictionary?.(customDictionary);@@ -140,7 +140,7 @@ export default function DictionaryView() {onOpenChange={setConfirmClear}title={t("dictionary.clearTitle")}description={t("dictionary.clearDescription")}- onConfirm={() => setCustomDictionary(customDictionary.filter((w) => w === agentName))}+ onConfirm={() => updateCustomDictionary({ remove: userWords })}variant="destructive"/>diff --git a/src/components/SettingsPage.tsx b/src/components/SettingsPage.tsxindex fc447f348..5fca6f0d1 100644--- a/src/components/SettingsPage.tsx+++ b/src/components/SettingsPage.tsx@@ -784,7 +784,6 @@ export default function SettingsPage({saveDiscardedTranscriptions,setSaveDiscardedTranscriptions,customDictionary,- setCustomDictionary,noteFilesEnabled,setNoteFilesEnabled,noteFilesPath,diff --git a/src/components/settings/DictationAgentSettings.tsx b/src/components/settings/DictationAgentSettings.tsxindex 0894eee8e..ad7e019d2 100644--- a/src/components/settings/DictationAgentSettings.tsx+++ b/src/components/settings/DictationAgentSettings.tsx@@ -2,7 +2,6 @@ import { useCallback, useState } from "react";import { useTranslation } from "react-i18next";import { useSettingsStore } from "../../stores/settingsStore";import { useAgentName } from "../../utils/agentName";-import { useSettings } from "../../hooks/useSettings";import { useDialogs } from "../../hooks/useDialogs";import { Toggle } from "../ui/toggle";import { Input } from "../ui/input";@@ -18,40 +17,22 @@ export default function DictationAgentSettings() {const { agentName, setAgentName } = useAgentName();const [agentNameInput, setAgentNameInput] = useState(agentName);- const { customDictionary, setCustomDictionary } = useSettings();const { showAlertDialog } = useDialogs();const handleSaveAgentName = useCallback(() => {const trimmed = agentNameInput.trim();- const previousName = agentName;+ // setAgentName also moves the name in the dictionary.setAgentName(trimmed);setAgentNameInput(trimmed);- let nextDictionary = customDictionary.filter((w) => w !== previousName);- if (trimmed) {- const hasName = nextDictionary.some((w) => w.toLowerCase() === trimmed.toLowerCase());- if (!hasName) {- nextDictionary = [trimmed, ...nextDictionary];- }- }- setCustomDictionary(nextDictionary);-showAlertDialog({title: t("settingsPage.agentConfig.dialogs.updatedTitle"),description: t("settingsPage.agentConfig.dialogs.updatedDescription", {name: trimmed,}),});- }, [- agentNameInput,- agentName,- customDictionary,- setAgentName,- setCustomDictionary,- showAlertDialog,- t,- ]);+ }, [agentNameInput, setAgentName, showAlertDialog, t]);const instructionMode = t("settingsPage.agentConfig.instructionMode");const examples = [diff --git a/src/helpers/agentNameDictionary.js b/src/helpers/agentNameDictionary.jsindex cb78608fc..65911f979 100644--- a/src/helpers/agentNameDictionary.js+++ b/src/helpers/agentNameDictionary.js@@ -1,32 +1,22 @@/**- * Drop a renamed-away agent name, move the current one to the front.+ * Work out which dictionary changes an agent name requires: drop a+ * renamed-away name, add the current one.*- * `changed` is false when the snapshot already reflects the name; callers must- * skip the write then, since setCustomDictionary replaces the whole SQLite- * table and a stale snapshot would delete everything it omitted (#1295).+ * Returns a delta, not a whole list. A whole-list write replaces the SQLite+ * table, so a caller holding a stale snapshot deletes everything it omitted+ * (#1295); a delta can only touch the words it names.*- * @param {string[]} dictionary+ * @param {string[]} dictionary current dictionary snapshot* @param {string} newName* @param {string} [oldName]- * @returns {{ changed: boolean, dictionary: string[] }}+ * @returns {{ add: string[], remove: string[] }}*/-export function applyAgentNameToDictionary(dictionary, newName, oldName) {- let words = Array.isArray(dictionary) ? [...dictionary] : [];- let changed = false;-- if (oldName && oldName !== newName) {- const kept = words.filter((w) => w !== oldName);- if (kept.length !== words.length) {- words = kept;- changed = true;- }- }-+export function agentNameDictionaryChanges(dictionary, newName, oldName) {+ const words = Array.isArray(dictionary) ? dictionary : [];const trimmed = newName.trim();- if (trimmed && !words.includes(trimmed)) {- words = [trimmed, ...words];- changed = true;- }- return { changed, dictionary: words };+ return {+ add: trimmed && !words.includes(trimmed) ? [trimmed] : [],+ remove: oldName && oldName !== newName && words.includes(oldName) ? [oldName] : [],+ };}diff --git a/src/helpers/database.js b/src/helpers/database.jsindex 4f4986312..38cf9e640 100644--- a/src/helpers/database.js+++ b/src/helpers/database.js@@ -857,76 +857,142 @@ class DatabaseManager {}}- // 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");- }- // 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(+ // Every dictionary mutation rule lives here once, so the whole-list and+ // delta write paths cannot drift apart.+ _dictionaryWriteStatements() {+ return {+ 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(+ ),+ hardDelete: this.db.prepare("DELETE FROM custom_dictionary WHERE id = ? AND cloud_id IS NULL"- );- const restore = this.db.prepare(+ ),+ 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(+ ),+ 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(+ ),+ // Guarded on word != ? so an unchanged row keeps its sync_status.+ 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(+ // case-sensitive UNIQUE(word) that the lowercase index didn't catch.+ insert: this.db.prepare("INSERT OR IGNORE INTO custom_dictionary (word, source, client_dict_id, sync_status, updated_at) VALUES (?, ?, ?, 'pending', datetime('now'))"- );+ ),+ };+ }++ // Dedupe by lower(word), keeping the first occurrence's casing, so no caller+ // can present two spellings of the same word to a write loop.+ _normalizeDictionaryWords(words) {+ const byLower = 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 (!byLower.has(lower)) byLower.set(lower, trimmed);+ }+ return byLower;+ }++ _dictionaryRows() {+ const rows = this.db+ .prepare("SELECT id, word, source, deleted_at FROM custom_dictionary")+ .all();+ return { rows, byLower: new Map(rows.map((r) => [r.word.toLowerCase(), r])) };+ }++ // Returns true when the word became present, so callers can report how many+ // words they actually added rather than how many they asked for.+ _upsertDictionaryWord(stmts, word, existing, source) {+ if (!existing) {+ return stmts.insert.run(word, source, randomUUID()).changes > 0;+ }+ if (existing.deleted_at) {+ stmts.restore.run(source, word, existing.id);+ return true;+ }+ if (source === "manual" && existing.source === "learned") {+ stmts.promoteSource.run(word, existing.id);+ } else {+ stmts.updateWord.run(word, existing.id, word);+ }+ return false;+ }++ // Hard-delete when the row never reached the cloud, else tombstone so the+ // next push tells the server about the deletion.+ _deleteDictionaryRow(stmts, existing) {+ if (!existing || existing.deleted_at) return false;+ const hardResult = stmts.hardDelete.run(existing.id);+ if (hardResult.changes === 0) stmts.tombstone.run(existing.id);+ return true;+ }++ // Add and/or remove specific words, leaving every other row untouched.+ // Prefer this over setDictionary, which deletes whatever the caller omitted+ // and so lets a stale snapshot destroy the rest (#1295).+ // `source` tags additions ('manual' for user-typed, 'learned' for auto-learn).+ applyDictionaryChanges({ add = [], remove = [] } = {}, source = "manual") {+ try {+ if (!this.db) {+ throw new Error("Database not initialized");+ }+ const additions = this._normalizeDictionaryWords(add);+ const removals = this._normalizeDictionaryWords(remove);+ // A word on both sides is a rename to itself; adding wins.+ for (const lower of additions.keys()) removals.delete(lower);+ if (additions.size === 0 && removals.size === 0) {+ return { success: true, added: 0, removed: 0 };+ }++ const { byLower } = this._dictionaryRows();+ const stmts = this._dictionaryWriteStatements();+ let added = 0;+ let removed = 0;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 lower of removals.keys()) {+ if (this._deleteDictionaryRow(stmts, byLower.get(lower))) removed += 1;}- 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());+ for (const [lower, word] of additions) {+ if (this._upsertDictionaryWord(stmts, word, byLower.get(lower), source)) added += 1;+ }+ })();++ return { success: true, added, removed };+ } catch (error) {+ debugLogger.error("Error applying dictionary changes", { error: error.message }, "database");+ throw error;+ }+ }++ // Replace the entire dictionary: anything absent from `words` is deleted.+ // Only for deliberate replace-everything callers (settings restore, clear+ // all, first write into an empty database). Everything else wants+ // applyDictionaryChanges.+ //+ // Diff-based so unchanged rows keep their source/created_at/cloud_id.+ setDictionary(words, sourceForNewWords = "manual") {+ try {+ if (!this.db) {+ throw new Error("Database not initialized");+ }+ const incomingByLower = this._normalizeDictionaryWords(words);+ const { rows, byLower } = this._dictionaryRows();+ const stmts = this._dictionaryWriteStatements();++ this.db.transaction(() => {+ for (const existing of rows) {+ if (incomingByLower.has(existing.word.toLowerCase())) continue;+ this._deleteDictionaryRow(stmts, existing);+ }+ for (const [lower, word] of incomingByLower) {+ this._upsertDictionaryWord(stmts, word, byLower.get(lower), sourceForNewWords);}})();diff --git a/src/helpers/ipcHandlers.js b/src/helpers/ipcHandlers.jsindex d1ab06f9d..b6f1b30c0 100644--- a/src/helpers/ipcHandlers.js+++ b/src/helpers/ipcHandlers.js@@ -784,8 +784,10 @@ class IPCHandlers {});if (corrections.length > 0) {- const updatedDict = [...currentDict, ...corrections];- const saveResult = this.databaseManager.setDictionary(updatedDict, "learned");+ const saveResult = this.databaseManager.applyDictionaryChanges(+ { add: corrections },+ "learned"+ );if (saveResult?.success === false) {debugLogger.debug("[AutoLearn] Failed to save dictionary", { error: saveResult.error });@@ -1076,6 +1078,17 @@ class IPCHandlers {return this.databaseManager.setDictionary(words);});+ ipcMain.handle("db-apply-dictionary-changes", async (_event, changes) => {+ const { add, remove } = changes ?? {};+ if (add !== undefined && !Array.isArray(add)) {+ throw new Error("add must be an array");+ }+ if (remove !== undefined && !Array.isArray(remove)) {+ throw new Error("remove must be an array");+ }+ return this.databaseManager.applyDictionaryChanges({ add, remove });+ });+ipcMain.handle("db-get-pending-dictionary", async () => {return this.databaseManager.getPendingDictionary();});@@ -1175,10 +1188,7 @@ class IPCHandlers {if (validWords.length === 0) {return { success: false };}- const currentDict = this._getDictionarySafe();- const removeSet = new Set(validWords.map((w) => w.toLowerCase()));- const updatedDict = currentDict.filter((w) => !removeSet.has(w.toLowerCase()));- const saveResult = this.databaseManager.setDictionary(updatedDict);+ const saveResult = this.databaseManager.applyDictionaryChanges({ remove: validWords });if (saveResult?.success === false) {debugLogger.debug("[AutoLearn] Undo failed to save dictionary", {error: saveResult.error,diff --git a/src/hooks/useSettings.ts b/src/hooks/useSettings.tsindex a1fee207b..cc06cfca9 100644--- a/src/hooks/useSettings.ts+++ b/src/hooks/useSettings.ts@@ -104,8 +104,7 @@ export interface ChatAgentSettings {function useSettingsInternal() {const store = useSettingsStore();- const { setCustomDictionary, applyCustomDictionaryFromExternal, applySnippetsFromExternal } =- store;+ const { applyCustomDictionaryFromExternal, applySnippetsFromExternal } = store;// One-time initialization: sync API keys, dictation key, activation mode,// UI language, and dictionary from the main process / SQLite.@@ -288,6 +287,7 @@ function useSettingsInternal() {setCleanupMode: store.setCleanupMode,setCleanupRemoteUrl: store.setCleanupRemoteUrl,setCustomDictionary: store.setCustomDictionary,+ updateCustomDictionary: store.updateCustomDictionary,setUseCleanupModel: store.setUseCleanupModel,setUseDictationAgent: store.setUseDictationAgent,setCleanupModel: store.setCleanupModel,diff --git a/src/stores/settingsStore.ts b/src/stores/settingsStore.tsindex b0acb390d..4ceb0f2b4 100644--- a/src/stores/settingsStore.ts+++ b/src/stores/settingsStore.ts@@ -584,6 +584,7 @@ export interface SettingsStatesetCleanupCloudMode: (value: string) => void;setCleanupCloudBaseUrl: (value: string) => void;setCustomDictionary: (words: string[]) => void;+ updateCustomDictionary: (changes: { add?: string[]; remove?: string[] }) => void;applyCustomDictionaryFromExternal: (words: string[]) => void;setSnippets: (snippets: Snippet[]) => void;applySnippetsFromExternal: (snippets: Snippet[]) => void;@@ -902,6 +903,13 @@ function createSecretSetter(export const MAX_TRANSLATION_TARGETS = 5;+// Kick the matching cloud push once a local write has landed in SQLite.+function syncAfterLocalWrite(method: "syncDictionaryNow" | "syncSnippetsNow"): void {+ void import("../services/SyncService.js").then(({ syncService }) => {+ if (syncService.canSync()) void syncService[method]();+ });+}+export const useSettingsStore = create<SettingsState>()((set, get) => ({uiLanguage: normalizeUiLanguage(isBrowser ? localStorage.getItem("uiLanguage") : null),useLocalWhisper: readBoolean("useLocalWhisper", false),@@ -1341,16 +1349,14 @@ export const useSettingsStore = create<SettingsState>()((set, get) => ({setCleanupProvider: createStringSetter("cleanupProvider"),setCleanupModel: createStringSetter("cleanupModel"),+ // Replaces the whole dictionary: anything absent from `words` is deleted.+ // Editing specific words wants updateCustomDictionary instead (#1295).setCustomDictionary: (words: string[]) => {if (isBrowser) localStorage.setItem("customDictionary", JSON.stringify(words));set({ customDictionary: words });window.electronAPI?.setDictionary(words)- .then(() => {- void import("../services/SyncService.js").then(({ syncService }) => {- if (syncService.canSync()) void syncService.syncDictionaryNow();- });- })+ .then(() => syncAfterLocalWrite("syncDictionaryNow")).catch((err) => {logger.warn("Failed to sync dictionary to SQLite",@@ -1360,6 +1366,46 @@ export const useSettingsStore = create<SettingsState>()((set, get) => ({});},+ updateCustomDictionary: ({ add = [], remove = [] }) => {+ const removeLower = new Set(remove.map((w) => w.toLowerCase()));+ const addLower = new Set(add.map((w) => w.toLowerCase()));+ // Optimistic so the UI updates immediately; the stored list replaces it below.+ const optimistic = [+ ...get().customDictionary.filter((w) => {+ const lower = w.toLowerCase();+ return !removeLower.has(lower) && !addLower.has(lower);+ }),+ ...add,+ ];+ if (isBrowser) localStorage.setItem("customDictionary", JSON.stringify(optimistic));+ set({ customDictionary: optimistic });++ const api = window.electronAPI;+ if (!api) return;+ // Older preloads have no delta channel; fall back rather than drop the edit.+ const written = api.applyDictionaryChanges+ ? api.applyDictionaryChanges({ add, remove })+ : api.setDictionary(optimistic);++ written+ .then(async () => {+ // SQLite owns ordering, casing and dedupe — adopt what it stored.+ const stored = await api.getDictionary?.();+ if (stored) {+ if (isBrowser) localStorage.setItem("customDictionary", JSON.stringify(stored));+ set({ customDictionary: stored });+ }+ syncAfterLocalWrite("syncDictionaryNow");+ })+ .catch((err) => {+ logger.warn(+ "Failed to apply dictionary changes 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));@@ -1371,11 +1417,7 @@ export const useSettingsStore = create<SettingsState>()((set, get) => ({set({ snippets });window.electronAPI?.setSnippets?.(snippets)- .then(() => {- void import("../services/SyncService.js").then(({ syncService }) => {- if (syncService.canSync()) void syncService.syncSnippetsNow();- });- })+ .then(() => syncAfterLocalWrite("syncSnippetsNow")).catch((err) => {logger.warn("Failed to sync snippets to SQLite",diff --git a/src/types/electron.ts b/src/types/electron.tsindex 33bfa4853..baf5f333a 100644--- a/src/types/electron.ts+++ b/src/types/electron.ts@@ -646,7 +646,12 @@ declare global {// Dictionary operationsgetDictionary: () => Promise<string[]>;+ /** Replaces the whole dictionary — omitted words are deleted. Prefer applyDictionaryChanges. */setDictionary: (words: string[]) => Promise<{ success: boolean }>;+ applyDictionaryChanges?: (changes: {+ add?: string[];+ remove?: string[];+ }) => Promise<{ success: boolean; added: number; removed: number }>;onDictionaryUpdated?: (callback: (words: string[]) => void) => () => void;getSnippets?: () => Promise<Array<{ trigger: string; replacement: string }>>;setSnippets?: (diff --git a/src/utils/agentName.ts b/src/utils/agentName.tsindex df14adfd9..e343e2f18 100644--- a/src/utils/agentName.ts+++ b/src/utils/agentName.ts@@ -1,6 +1,6 @@import { useState } from "react";import { getSettings, useSettingsStore } from "../stores/settingsStore";-import { applyAgentNameToDictionary } from "../helpers/agentNameDictionary";+import { agentNameDictionaryChanges } from "../helpers/agentNameDictionary";const AGENT_NAME_KEY = "agentName";const DEFAULT_AGENT_NAME = "OpenWhispr";@@ -10,14 +10,14 @@ export const getAgentName = (): string => {};function syncAgentNameToDictionary(newName: string, oldName?: string): void {- const { changed, dictionary } = applyAgentNameToDictionary(+ const { add, remove } = agentNameDictionaryChanges(getSettings().customDictionary,newName,oldName);- if (!changed) return;+ if (add.length === 0 && remove.length === 0) return;- useSettingsStore.getState().setCustomDictionary(dictionary);+ useSettingsStore.getState().updateCustomDictionary({ add, remove });}export const setAgentName = (name: string): void => {diff --git a/test/helpers/agentNameDictionary.test.js b/test/helpers/agentNameDictionary.test.jsindex 0318203a2..ef12b9cbd 100644--- a/test/helpers/agentNameDictionary.test.js+++ b/test/helpers/agentNameDictionary.test.js@@ -3,52 +3,54 @@ const assert = require("node:assert/strict");const load = () => import("../../src/helpers/agentNameDictionary.js");-// The `changed` flag is what stops a startup write from replacing the whole-// SQLite dictionary with a stale renderer cache (#1295). Guard it directly.-test("reports no change when the agent name is already present", async () => {- const { applyAgentNameToDictionary } = await load();- const existing = ["OpenWhispr", "Alice", "Bob"];- const result = applyAgentNameToDictionary(existing, "OpenWhispr");- assert.equal(result.changed, false);- assert.deepEqual(result.dictionary, existing);+// An empty delta means no write at all, which is what stops startup from+// touching the dictionary when the renderer cache is stale (#1295).+test("asks for no changes when the agent name is already present", async () => {+ const { agentNameDictionaryChanges } = await load();+ const result = agentNameDictionaryChanges(["OpenWhispr", "Alice", "Bob"], "OpenWhispr");+ assert.deepEqual(result, { add: [], remove: [] });});-test("reports no change for a stale one-word cache that already has the name", async () => {- const { applyAgentNameToDictionary } = await load();- assert.equal(applyAgentNameToDictionary(["OpenWhispr"], "OpenWhispr").changed, false);+test("asks for no changes for a stale one-word cache that already has the name", async () => {+ const { agentNameDictionaryChanges } = await load();+ assert.deepEqual(agentNameDictionaryChanges(["OpenWhispr"], "OpenWhispr"), {+ add: [],+ remove: [],+ });});-test("adds the agent name at the front when missing", async () => {- const { applyAgentNameToDictionary } = await load();- const result = applyAgentNameToDictionary(["Alice"], "OpenWhispr");- assert.equal(result.changed, true);- assert.deepEqual(result.dictionary, ["OpenWhispr", "Alice"]);+test("adds the agent name when missing, without naming other words", async () => {+ const { agentNameDictionaryChanges } = await load();+ assert.deepEqual(agentNameDictionaryChanges(["Alice"], "OpenWhispr"), {+ add: ["OpenWhispr"],+ remove: [],+ });});-test("drops the previous agent name on rename", async () => {- const { applyAgentNameToDictionary } = await load();- const result = applyAgentNameToDictionary(["OpenWhispr", "Alice"], "Jarvis", "OpenWhispr");- assert.equal(result.changed, true);- assert.deepEqual(result.dictionary, ["Jarvis", "Alice"]);+test("swaps the previous agent name for the new one on rename", async () => {+ const { agentNameDictionaryChanges } = await load();+ assert.deepEqual(agentNameDictionaryChanges(["OpenWhispr", "Alice"], "Jarvis", "OpenWhispr"), {+ add: ["Jarvis"],+ remove: ["OpenWhispr"],+ });});-test("reports no change when the old name was never in the dictionary", async () => {- const { applyAgentNameToDictionary } = await load();- const result = applyAgentNameToDictionary(["Jarvis", "Alice"], "Jarvis", "OpenWhispr");- assert.equal(result.changed, false);- assert.deepEqual(result.dictionary, ["Jarvis", "Alice"]);+test("does not ask to remove an old name the dictionary never had", async () => {+ const { agentNameDictionaryChanges } = await load();+ assert.deepEqual(agentNameDictionaryChanges(["Jarvis", "Alice"], "Jarvis", "OpenWhispr"), {+ add: [],+ remove: [],+ });});test("ignores a blank agent name", async () => {- const { applyAgentNameToDictionary } = await load();- const result = applyAgentNameToDictionary(["Alice"], " ");- assert.equal(result.changed, false);- assert.deepEqual(result.dictionary, ["Alice"]);+ const { agentNameDictionaryChanges } = await load();+ assert.deepEqual(agentNameDictionaryChanges(["Alice"], " "), { add: [], remove: [] });});-test("does not mutate the caller's array", async () => {- const { applyAgentNameToDictionary } = await load();- const original = ["Alice"];- applyAgentNameToDictionary(original, "OpenWhispr");- assert.deepEqual(original, ["Alice"]);+test("never names a word outside the agent name itself", async () => {+ const { agentNameDictionaryChanges } = await load();+ const dictionary = ["OpenWhispr", "Alice", "Bob", "Imported Term"];+ const { add, remove } = agentNameDictionaryChanges(dictionary, "Jarvis", "OpenWhispr");+ assert.deepEqual([...add, ...remove].sort(), ["Jarvis", "OpenWhispr"]);});diff --git a/test/helpers/dictionaryDatabase.test.js b/test/helpers/dictionaryDatabase.test.jsindex 0c311baa7..91109856f 100644--- a/test/helpers/dictionaryDatabase.test.js+++ b/test/helpers/dictionaryDatabase.test.js@@ -229,3 +229,181 @@ test("intentional removal tombstones synced rows and hard-deletes unsynced ones"assert.equal(syncedTombstone.sync_status, "pending");assert.equal(syncedTombstone.cloud_id, "cloud-synced");});++// applyDictionaryChanges is the delta write path. Its whole purpose is that a+// caller can only affect the words it names, so the wipe in #1295 stops being+// expressible rather than merely guarded against.++test("adding words leaves every other row untouched", (t) => {+ const db = createDb(t);+ if (!db) return;++ db.setDictionary(["OpenWhispr", "Alice", "Bob"]);+ const result = db.applyDictionaryChanges({ add: ["Carol"] });++ assert.equal(result.added, 1);+ assert.deepEqual(db.getDictionary(), ["OpenWhispr", "Alice", "Bob", "Carol"]);+});++test("a caller holding a stale one-word view cannot delete anything (#1295)", (t) => {+ const db = createDb(t);+ if (!db) return;++ db.setDictionary(["OpenWhispr", "Alice", "Bob", "Imported Term"]);+ // The exact call startup used to make, but expressed as a delta.+ db.applyDictionaryChanges({ add: ["OpenWhispr"] });++ assert.deepEqual(db.getDictionary(), ["OpenWhispr", "Alice", "Bob", "Imported Term"]);+});++test("removing words hard-deletes unsynced rows and tombstones synced ones", (t) => {+ const db = createDb(t);+ if (!db) return;++ db.setDictionary(["OpenWhispr", "Temp", "Synced"]);+ const synced = db.getPendingDictionary().find((row) => row.word === "Synced");+ db.markDictionaryEntrySynced(synced.id, "cloud-synced");++ const result = db.applyDictionaryChanges({ remove: ["Temp", "Synced"] });+ assert.equal(result.removed, 2);+ assert.deepEqual(db.getDictionary(), ["OpenWhispr"]);++ assert.equal(db.db.prepare("SELECT * FROM custom_dictionary WHERE word = 'Temp'").get(), undefined);+ const tombstone = db.db.prepare("SELECT * FROM custom_dictionary WHERE word = 'Synced'").get();+ assert.ok(tombstone.deleted_at);+ assert.equal(tombstone.sync_status, "pending");+ assert.equal(tombstone.cloud_id, "cloud-synced");+});++test("adding a tombstoned word restores it instead of duplicating", (t) => {+ const db = createDb(t);+ if (!db) return;++ db.setDictionary(["OpenWhispr", "Synced"]);+ const synced = db.getPendingDictionary().find((row) => row.word === "Synced");+ db.markDictionaryEntrySynced(synced.id, "cloud-synced");+ db.applyDictionaryChanges({ remove: ["Synced"] });++ db.applyDictionaryChanges({ add: ["Synced"] });++ const rows = db.db.prepare("SELECT * FROM custom_dictionary WHERE word = 'Synced'").all();+ assert.equal(rows.length, 1);+ assert.equal(rows[0].deleted_at, null);+ assert.equal(rows[0].cloud_id, "cloud-synced");+ assert.ok(db.getDictionary().includes("Synced"));+});++test("a manual add promotes a learned word, matching setDictionary", (t) => {+ const db = createDb(t);+ if (!db) return;++ db.applyDictionaryChanges({ add: ["Kubernetes"] }, "learned");+ assert.equal(+ db.db.prepare("SELECT source FROM custom_dictionary WHERE word = 'Kubernetes'").get().source,+ "learned"+ );++ db.applyDictionaryChanges({ add: ["Kubernetes"] }, "manual");+ assert.equal(+ db.db.prepare("SELECT source FROM custom_dictionary WHERE word = 'Kubernetes'").get().source,+ "manual"+ );+});++test("an edit is a remove plus an add in one transaction", (t) => {+ const db = createDb(t);+ if (!db) return;++ db.setDictionary(["OpenWhispr", "Kubernets", "Alice"]);+ db.applyDictionaryChanges({ add: ["Kubernetes"], remove: ["Kubernets"] });++ assert.deepEqual(db.getDictionary(), ["OpenWhispr", "Alice", "Kubernetes"]);+});++test("a word on both sides is kept, not deleted", (t) => {+ const db = createDb(t);+ if (!db) return;++ db.setDictionary(["OpenWhispr", "Alice"]);+ const result = db.applyDictionaryChanges({ add: ["Alice"], remove: ["Alice"] });++ assert.equal(result.removed, 0);+ assert.ok(db.getDictionary().includes("Alice"));+});++// Removing via setDictionary meant re-presenting every surviving word with the+// default 'manual' source, which promoted unrelated auto-learned words and+// marked them pending. A delta names only what it changes.+test("removing a word leaves other learned words untouched", (t) => {+ const db = createDb(t);+ if (!db) return;++ db.applyDictionaryChanges({ add: ["Kubernetes", "Postgres"] }, "learned");+ const before = db.db+ .prepare("SELECT word, source FROM custom_dictionary WHERE word = 'Postgres'")+ .get();+ assert.equal(before.source, "learned");++ db.applyDictionaryChanges({ remove: ["Kubernetes"] });++ const after = db.db+ .prepare("SELECT word, source FROM custom_dictionary WHERE word = 'Postgres'")+ .get();+ assert.equal(after.source, "learned");+});++test("counts report words that changed, not words requested", (t) => {+ const db = createDb(t);+ if (!db) return;++ db.setDictionary(["OpenWhispr", "Alice"]);++ // Already present, so nothing was actually added.+ assert.equal(db.applyDictionaryChanges({ add: ["Alice"] }).added, 0);+ // Never present, so nothing was actually removed.+ assert.equal(db.applyDictionaryChanges({ remove: ["Nobody"] }).removed, 0);++ const mixed = db.applyDictionaryChanges({ add: ["Alice", "Carol"], remove: ["Nobody", "Alice"] });+ assert.equal(mixed.added, 1);+ assert.equal(mixed.removed, 0);+});++test("an empty delta touches nothing", (t) => {+ const db = createDb(t);+ if (!db) return;++ db.setDictionary(["OpenWhispr", "Alice"]);+ const synced = db.getPendingDictionary().find((row) => row.word === "Alice");+ db.markDictionaryEntrySynced(synced.id, "cloud-alice");++ const result = db.applyDictionaryChanges({});+ assert.deepEqual(result, { success: true, added: 0, removed: 0 });++ // Still synced: an empty delta must not mark rows pending again.+ const after = db.db.prepare("SELECT * FROM custom_dictionary WHERE word = 'Alice'").get();+ assert.equal(after.sync_status, "synced");+ assert.deepEqual(db.getDictionary(), ["OpenWhispr", "Alice"]);+});++test("removing a word that isn't there is a no-op", (t) => {+ const db = createDb(t);+ if (!db) return;++ db.setDictionary(["OpenWhispr"]);+ const result = db.applyDictionaryChanges({ remove: ["Nonexistent"] });+ assert.equal(result.removed, 0);+ assert.deepEqual(db.getDictionary(), ["OpenWhispr"]);+});++test("case-variant adds do not create duplicate rows", (t) => {+ const db = createDb(t);+ if (!db) return;++ db.setDictionary(["OpenWhispr", "Alice"]);+ db.applyDictionaryChanges({ add: ["alice", "ALICE"] });++ const rows = db.db+ .prepare("SELECT * FROM custom_dictionary WHERE lower(word) = 'alice' AND deleted_at IS NULL")+ .all();+ assert.equal(rows.length, 1);+});