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(assistant): dictionary and snippet tools for the voice assistant (#2119)
Gabriel Stein005c0ebb3ac0
diff --git a/CLAUDE.md b/CLAUDE.mdindex 154f8029c..6ab436e88 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -677,7 +677,7 @@ A dedicated global hotkey that starts a dictation whose transcript is sent strai1. Hotkey pressed → `voiceAgent` slot callback in `main.js` → `windowManager.sendToggleVoiceAgent()` → `toggle-voice-agent` IPC to the main window → recording capsule appears2. `useAudioRecording.js` starts a recording with `audioManager.setVoiceAgentRequested(true)` (any other start resets it to `false`)3. On transcription, `resolveReasoningRoute` consults `resolveDictationRouteKind()` (`src/helpers/dictationRouting.js`): a voice assistant recording always takes the agent route and never falls back to cleanup. The dictation agent's reachability only gates selection edits — a selection with the dictation agent unconfigured routes to the panel with the selected text quoted instead of editing in place-4. Standalone commands (no text selected) run through the chat pipeline (`src/components/dictation/AssistantPanel.tsx`): chat tools (notes search/create/update, calendar, web search, clipboard), RAG memory, and the custom dictionary injected into the system prompt. Conversations persist in the `agent_conversations` table and are browsable from the ControlPanel chat+4. Standalone commands (no text selected) run through the chat pipeline (`src/components/dictation/AssistantPanel.tsx`): chat tools (notes search/create/update, calendar, web search, clipboard, `get_snippet` — triggers listed in the tool description, body fetched on demand — and `update_dictionary` / `update_snippets`, which write through the settings store so the change syncs like a UI edit), RAG memory, and the custom dictionary plus snippet triggers injected into the system prompt. Conversations persist in the `agent_conversations` table and are browsable from the ControlPanel chat5. Response delivery: a capture with `status: "editable"` (a focused writable non-terminal field with no selection) plus auto-paste banks a `deliverySessionId`; the completed answer is pasted via `paste-at-captured-target`, which revalidates the target and fails closed to the panel + clipboard on any change (`assistantResponseDelivery.ts`, `pasteAtCapturedTarget` in `selectionManager.js`). A follow-up spoken while the panel is already open stays panel-first. Cancelled or empty responses never paste and never touch the clipboard6. Selection edits are unchanged: highlighted text goes through the `dictationAgent` scope and is safely replaced in place — it never opens the paneldiff --git a/src/components/chat/toolIcons.ts b/src/components/chat/toolIcons.tsindex 3f851757c..e15d9c10f 100644--- a/src/components/chat/toolIcons.ts+++ b/src/components/chat/toolIcons.ts@@ -1,4 +1,5 @@import {+ BookOpen,Search,Globe,ClipboardCheck,@@ -7,6 +8,7 @@ import {FileText,FilePlus,FilePen,+ Zap,} from "../icons";export const toolIcons: Record<string, typeof Search> = {@@ -18,4 +20,7 @@ export const toolIcons: Record<string, typeof Search> = {get_note: FileText,create_note: FilePlus,update_note: FilePen,+ get_snippet: Zap,+ update_snippets: Zap,+ update_dictionary: BookOpen,};diff --git a/src/components/chat/useChatStreaming.ts b/src/components/chat/useChatStreaming.tsindex 5c1784743..73f5de813 100644--- a/src/components/chat/useChatStreaming.ts+++ b/src/components/chat/useChatStreaming.ts@@ -3,7 +3,7 @@ import { useTranslation } from "react-i18next";import ReasoningService, { type AgentStreamChunk } from "../../services/ReasoningService";import { isEnterpriseProvider } from "../../models/ModelRegistry";import { providerSupportsImages } from "../../services/ai/inferenceProviders";-import { getSettings } from "../../stores/settingsStore";+import { getSettings, useSettingsStore } from "../../stores/settingsStore";import { resolveChatStreamingInference } from "../../helpers/dictationAgentInference.js";import {isAgentAllowed,@@ -294,7 +294,9 @@ export function useChatStreaming({const calendarConnected =settings.gcalConnected || settings.mcalConnected || settings.appleCalendarConnected;const webSearchEnabled = isWebSearchAllowed(usePolicyStore.getState());- const cacheKey = `${settings.isSignedIn}-${calendarConnected}-${settings.cloudBackupEnabled}-${scopeKey}-${webSearchEnabled}`;+ // Triggers ride in the tool description, so a snippet edit rebuilds the registry.+ const snippetKey = settings.snippets.map((s) => s.trigger).join("|");+ const cacheKey = `${settings.isSignedIn}-${calendarConnected}-${settings.cloudBackupEnabled}-${scopeKey}-${webSearchEnabled}-${snippetKey}`;if (toolRegistryRef.current?.key === cacheKey) {registry = toolRegistryRef.current.registry;} else {@@ -304,6 +306,13 @@ export function useChatStreaming({cloudBackupEnabled: settings.cloudBackupEnabled,searchScope: scope,webSearchEnabled,+ vocabulary: {+ getDictionary: () => getSettings().customDictionary,+ updateDictionary: (changes) =>+ useSettingsStore.getState().updateCustomDictionary(changes),+ getSnippets: () => getSettings().snippets,+ setSnippets: (snippets) => useSettingsStore.getState().setSnippets(snippets),+ },});toolRegistryRef.current = { key: cacheKey, registry };}diff --git a/src/config/prompts.ts b/src/config/prompts.tsindex 5ec8b1e21..c3b2bc07c 100644--- a/src/config/prompts.ts+++ b/src/config/prompts.ts@@ -39,6 +39,12 @@ const TOOL_INSTRUCTIONS: Record<string, string> = {"Use web_search for questions about current events, facts you're unsure about, or anything requiring up-to-date information.",copy_to_clipboard:"Use copy_to_clipboard when the user asks you to copy something to their clipboard.",+ get_snippet:+ "Use get_snippet whenever the user names one of their saved snippets or asks to insert, use, send, or read back saved text; match the trigger even if speech transcribed it slightly differently, and reproduce the returned text verbatim.",+ update_snippets:+ "Use update_snippets when the user asks to create, change, or delete a snippet (a spoken trigger that expands into saved text). If the user did not state both the trigger and the full replacement text, ask before saving.",+ update_dictionary:+ "Use update_dictionary when the user asks to add, remove, or fix the spelling of words in their custom dictionary; the current words are listed under Custom Dictionary. When asked to clean up the dictionary, list the exact removals you propose (duplicates, misspellings, casing variants, ordinary words) and wait for confirmation before removing anything the user did not name.",get_calendar_events:"Use get_calendar_events to check the user's schedule, upcoming meetings, or calendar events.",get_calendar_availability:diff --git a/src/constants/apiKeys.ts b/src/constants/apiKeys.tsindex 709caa74e..469cf918e 100644--- a/src/constants/apiKeys.ts+++ b/src/constants/apiKeys.ts@@ -1,7 +1,15 @@// Source of truth for the desktop side of the public API key UI.// Keep API_SCOPES and MAX_API_KEYS in sync with openwhispr-api/lib/api-keys.ts.-export const API_SCOPES = ["notes:read", "notes:write", "transcriptions:read"] as const;+export const API_SCOPES = [+ "notes:read",+ "notes:write",+ "transcriptions:read",+ "dictionary:read",+ "dictionary:write",+ "snippets:read",+ "snippets:write",+] as const;export type ApiScope = (typeof API_SCOPES)[number];@@ -20,6 +28,10 @@ export const API_SCOPE_I18N_KEY: Record<ApiScope, string> = {"notes:read": "notesRead","notes:write": "notesWrite","transcriptions:read": "transcriptionsRead",+ "dictionary:read": "dictionaryRead",+ "dictionary:write": "dictionaryWrite",+ "snippets:read": "snippetsRead",+ "snippets:write": "snippetsWrite",};export interface ApiKeyExpiryOption {diff --git a/src/helpers/cliBridge.js b/src/helpers/cliBridge.jsindex 4ce4fb207..2594418e4 100644--- a/src/helpers/cliBridge.js+++ b/src/helpers/cliBridge.js@@ -288,6 +288,26 @@ class CliBridge {return value;};+ const requireSnippetList = (value) => {+ if (value === undefined || value === null) return [];+ const valid =+ Array.isArray(value) &&+ value.every(+ (s) =>+ s &&+ typeof s.trigger === "string" &&+ s.trigger.trim() &&+ typeof s.replacement === "string" &&+ s.replacement.trim()+ );+ if (!valid) {+ const err = new Error("'add' must be an array of { trigger, replacement } strings");+ err.code = "VALIDATION";+ throw err;+ }+ return value;+ };+const requireSuccess = (result, message) => {if (!result?.success) {const err = new Error(result?.error || message);@@ -394,6 +414,40 @@ class CliBridge {setImmediate(() => broadcastToWindows("dictionary-updated", words));return { data: { words, added: result.added, removed: result.removed } };}),+ exact("GET", "/v1/snippets/list", () => {+ return { data: db.getSnippets(), has_more: false, next_cursor: null };+ }),+ // Same delta shape as the dictionary route: an add with an existing+ // trigger replaces that snippet's text, and removes are by trigger.+ exact("POST", "/v1/snippets/update", ({ body }) => {+ const add = requireSnippetList(body?.add);+ const remove = requireWordList(body?.remove, "remove");+ if (add.length === 0 && remove.length === 0) {+ const err = new Error("Provide at least one snippet in 'add' or trigger in 'remove'");+ err.code = "VALIDATION";+ throw err;+ }+ const lower = (trigger) => trigger.trim().toLowerCase();+ const removeKeys = new Set(remove.map(lower));+ const addKeys = new Set(add.map((s) => lower(s.trigger)));+ const current = db.getSnippets();+ const kept = current.filter(+ (s) => !removeKeys.has(lower(s.trigger)) && !addKeys.has(lower(s.trigger))+ );+ db.setSnippets([...kept, ...add]);+ const snippets = db.getSnippets();+ setImmediate(() => broadcastToWindows("snippets-updated", snippets));+ // setSnippets drops entries it cannot store (e.g. over-long triggers),+ // so count what landed rather than what was sent.+ const storedKeys = new Set(snippets.map((s) => lower(s.trigger)));+ return {+ data: {+ snippets,+ added: add.filter((s) => storedKeys.has(lower(s.trigger))).length,+ removed: current.filter((s) => removeKeys.has(lower(s.trigger))).length,+ },+ };+ }),exact("GET", "/v1/transcriptions/list", ({ query }) => {const limit = query.get("limit") ? Number(query.get("limit")) : 50;return {diff --git a/src/locales/ar/translation.json b/src/locales/ar/translation.jsonindex 525a9bee3..45c4eb268 100644--- a/src/locales/ar/translation.json+++ b/src/locales/ar/translation.json@@ -1063,7 +1063,11 @@"scopes": {"notesRead": "قراءة الملاحظات","notesWrite": "إنشاء وتعديل الملاحظات",- "transcriptionsRead": "قراءة النصوص المفرَّغة"+ "transcriptionsRead": "قراءة النصوص المفرَّغة",+ "dictionaryRead": "قراءة القاموس",+ "dictionaryWrite": "تعديل القاموس",+ "snippetsRead": "قراءة المقتطفات",+ "snippetsWrite": "تعديل المقتطفات"},"revoke": {"button": "إبطال",@@ -1223,11 +1227,17 @@"web_searchName": "البحث في الويب","get_calendar_eventsName": "الحصول على أحداث التقويم","get_calendar_availabilityName": "التحقق من الأوقات المتاحة في التقويم",+ "get_snippetName": "الحصول على المقتطف",+ "update_dictionaryName": "تحديث القاموس",+ "update_snippetsName": "تحديث المقتطفات","search_notesStatus": "جاري البحث في الملاحظات...","web_searchStatus": "جاري البحث في الويب...","copy_to_clipboardStatus": "جاري النسخ إلى الحافظة...","get_calendar_eventsStatus": "جاري التحقق من التقويم...","get_calendar_availabilityStatus": "جاري التحقق من الأوقات المتاحة...",+ "get_snippetStatus": "جاري جلب المقتطف...",+ "update_dictionaryStatus": "جاري تحديث القاموس...",+ "update_snippetsStatus": "جاري تحديث المقتطفات...","get_noteStatus": "جاري قراءة الملاحظة...","create_noteStatus": "جاري إنشاء الملاحظة...","update_noteStatus": "جاري تحديث الملاحظة...",diff --git a/src/locales/de/translation.json b/src/locales/de/translation.jsonindex 8344c517b..732f8ff88 100644--- a/src/locales/de/translation.json+++ b/src/locales/de/translation.json@@ -1257,7 +1257,11 @@"scopes": {"notesRead": "Notizen lesen","notesWrite": "Notizen erstellen und bearbeiten",- "transcriptionsRead": "Transkriptionen lesen"+ "transcriptionsRead": "Transkriptionen lesen",+ "dictionaryRead": "Wörterbuch lesen",+ "dictionaryWrite": "Wörterbuch bearbeiten",+ "snippetsRead": "Snippets lesen",+ "snippetsWrite": "Snippets bearbeiten"},"revoke": {"button": "Widerrufen",@@ -3737,11 +3741,17 @@"web_searchName": "Websuche","get_calendar_eventsName": "Kalendertermine abrufen","get_calendar_availabilityName": "Verfügbarkeit prüfen",+ "get_snippetName": "Snippet abrufen",+ "update_dictionaryName": "Wörterbuch aktualisieren",+ "update_snippetsName": "Snippets aktualisieren","search_notesStatus": "Notizen werden durchsucht...","web_searchStatus": "Websuche...","copy_to_clipboardStatus": "In Zwischenablage kopieren...","get_calendar_eventsStatus": "Kalender wird geprüft...","get_calendar_availabilityStatus": "Verfügbarkeit wird geprüft...",+ "get_snippetStatus": "Snippet wird abgerufen...",+ "update_dictionaryStatus": "Wörterbuch wird aktualisiert...",+ "update_snippetsStatus": "Snippets werden aktualisiert...","get_noteStatus": "Notiz wird gelesen...","create_noteStatus": "Notiz wird erstellt...","update_noteStatus": "Notiz wird aktualisiert...",diff --git a/src/locales/en/translation.json b/src/locales/en/translation.jsonindex 8729f1985..6cae5494f 100644--- a/src/locales/en/translation.json+++ b/src/locales/en/translation.json@@ -1257,7 +1257,11 @@"scopes": {"notesRead": "Read notes","notesWrite": "Create & edit notes",- "transcriptionsRead": "Read transcriptions"+ "transcriptionsRead": "Read transcriptions",+ "dictionaryRead": "Read dictionary",+ "dictionaryWrite": "Edit dictionary",+ "snippetsRead": "Read snippets",+ "snippetsWrite": "Edit snippets"},"revoke": {"button": "Revoke",@@ -3737,11 +3741,17 @@"web_searchName": "Web search","get_calendar_eventsName": "Get calendar events","get_calendar_availabilityName": "Check calendar availability",+ "get_snippetName": "Get snippet",+ "update_dictionaryName": "Update dictionary",+ "update_snippetsName": "Update snippets","search_notesStatus": "Searching notes...","web_searchStatus": "Searching the web...","copy_to_clipboardStatus": "Copying to clipboard...","get_calendar_eventsStatus": "Checking calendar...","get_calendar_availabilityStatus": "Checking availability...",+ "get_snippetStatus": "Fetching snippet...",+ "update_dictionaryStatus": "Updating dictionary...",+ "update_snippetsStatus": "Updating snippets...","get_noteStatus": "Reading note...","create_noteStatus": "Creating note...","update_noteStatus": "Updating note...",diff --git a/src/locales/es/translation.json b/src/locales/es/translation.jsonindex 3677897ad..dedfb23ba 100644--- a/src/locales/es/translation.json+++ b/src/locales/es/translation.json@@ -1216,7 +1216,11 @@"scopes": {"notesRead": "Leer notas","notesWrite": "Crear y editar notas",- "transcriptionsRead": "Leer transcripciones"+ "transcriptionsRead": "Leer transcripciones",+ "dictionaryRead": "Leer diccionario",+ "dictionaryWrite": "Editar diccionario",+ "snippetsRead": "Leer snippets",+ "snippetsWrite": "Editar snippets"},"revoke": {"button": "Revocar",@@ -3620,11 +3624,17 @@"web_searchName": "Buscar en la web","get_calendar_eventsName": "Obtener eventos del calendario","get_calendar_availabilityName": "Consultar disponibilidad",+ "get_snippetName": "Obtener snippet",+ "update_dictionaryName": "Actualizar diccionario",+ "update_snippetsName": "Actualizar snippets","search_notesStatus": "Buscando notas...","web_searchStatus": "Buscando en la web...","copy_to_clipboardStatus": "Copiando al portapapeles...","get_calendar_eventsStatus": "Consultando calendario...","get_calendar_availabilityStatus": "Consultando disponibilidad...",+ "get_snippetStatus": "Obteniendo snippet...",+ "update_dictionaryStatus": "Actualizando diccionario...",+ "update_snippetsStatus": "Actualizando snippets...","get_noteStatus": "Leyendo nota...","create_noteStatus": "Creando nota...","update_noteStatus": "Actualizando nota...",diff --git a/src/locales/fr/translation.json b/src/locales/fr/translation.jsonindex e1f901baa..e1af18c21 100644--- a/src/locales/fr/translation.json+++ b/src/locales/fr/translation.json@@ -1257,7 +1257,11 @@"scopes": {"notesRead": "Lire les notes","notesWrite": "Créer et modifier les notes",- "transcriptionsRead": "Lire les transcriptions"+ "transcriptionsRead": "Lire les transcriptions",+ "dictionaryRead": "Lire le dictionnaire",+ "dictionaryWrite": "Modifier le dictionnaire",+ "snippetsRead": "Lire les snippets",+ "snippetsWrite": "Modifier les snippets"},"revoke": {"button": "Révoquer",@@ -3737,11 +3741,17 @@"web_searchName": "Rechercher sur le web","get_calendar_eventsName": "Obtenir les événements du calendrier","get_calendar_availabilityName": "Vérifier les disponibilités",+ "get_snippetName": "Obtenir un snippet",+ "update_dictionaryName": "Mettre à jour le dictionnaire",+ "update_snippetsName": "Mettre à jour les snippets","search_notesStatus": "Recherche de notes...","web_searchStatus": "Recherche sur le web...","copy_to_clipboardStatus": "Copie dans le presse-papiers...","get_calendar_eventsStatus": "Vérification du calendrier...","get_calendar_availabilityStatus": "Vérification des disponibilités...",+ "get_snippetStatus": "Récupération du snippet...",+ "update_dictionaryStatus": "Mise à jour du dictionnaire...",+ "update_snippetsStatus": "Mise à jour des snippets...","get_noteStatus": "Lecture de la note...","create_noteStatus": "Création de la note...","update_noteStatus": "Mise à jour de la note...",diff --git a/src/locales/it/translation.json b/src/locales/it/translation.jsonindex ff415a1e1..7914a8c2d 100644--- a/src/locales/it/translation.json+++ b/src/locales/it/translation.json@@ -3572,11 +3572,17 @@"web_searchName": "Cerca sul web","get_calendar_eventsName": "Ottieni eventi del calendario","get_calendar_availabilityName": "Verifica disponibilità",+ "get_snippetName": "Ottieni snippet",+ "update_dictionaryName": "Aggiorna dizionario",+ "update_snippetsName": "Aggiorna snippet","search_notesStatus": "Ricerca nelle note...","web_searchStatus": "Ricerca sul web...","copy_to_clipboardStatus": "Copia negli appunti...","get_calendar_eventsStatus": "Controllo del calendario...","get_calendar_availabilityStatus": "Controllo della disponibilità...",+ "get_snippetStatus": "Recupero dello snippet...",+ "update_dictionaryStatus": "Aggiornamento del dizionario...",+ "update_snippetsStatus": "Aggiornamento degli snippet...","get_noteStatus": "Lettura della nota...","create_noteStatus": "Creazione della nota...","update_noteStatus": "Aggiornamento della nota...",@@ -3894,7 +3900,11 @@"scopes": {"notesRead": "Leggi note","notesWrite": "Crea e modifica note",- "transcriptionsRead": "Leggi trascrizioni"+ "transcriptionsRead": "Leggi trascrizioni",+ "dictionaryRead": "Leggi dizionario",+ "dictionaryWrite": "Modifica dizionario",+ "snippetsRead": "Leggi snippet",+ "snippetsWrite": "Modifica snippet"},"revoke": {"button": "Revoca",diff --git a/src/locales/ja/translation.json b/src/locales/ja/translation.jsonindex 47c84508e..255d28b7f 100644--- a/src/locales/ja/translation.json+++ b/src/locales/ja/translation.json@@ -3572,11 +3572,17 @@"web_searchName": "ウェブ検索","get_calendar_eventsName": "カレンダーの予定を取得","get_calendar_availabilityName": "空き時間を確認",+ "get_snippetName": "スニペットを取得",+ "update_dictionaryName": "辞書を更新",+ "update_snippetsName": "スニペットを更新","search_notesStatus": "ノートを検索中...","web_searchStatus": "ウェブを検索中...","copy_to_clipboardStatus": "クリップボードにコピー中...","get_calendar_eventsStatus": "カレンダーを確認中...","get_calendar_availabilityStatus": "空き時間を確認中...",+ "get_snippetStatus": "スニペットを取得中...",+ "update_dictionaryStatus": "辞書を更新中...",+ "update_snippetsStatus": "スニペットを更新中...","get_noteStatus": "ノートを読み込み中...","create_noteStatus": "ノートを作成中...","update_noteStatus": "ノートを更新中...",@@ -3894,7 +3900,11 @@"scopes": {"notesRead": "ノートの読み取り","notesWrite": "ノートの作成と編集",- "transcriptionsRead": "文字起こしの読み取り"+ "transcriptionsRead": "文字起こしの読み取り",+ "dictionaryRead": "辞書を読み取り",+ "dictionaryWrite": "辞書を編集",+ "snippetsRead": "スニペットを読み取り",+ "snippetsWrite": "スニペットを編集"},"revoke": {"button": "取り消し",diff --git a/src/locales/pt/translation.json b/src/locales/pt/translation.jsonindex 51adccc87..241aca4b8 100644--- a/src/locales/pt/translation.json+++ b/src/locales/pt/translation.json@@ -3572,11 +3572,17 @@"web_searchName": "Pesquisar na web","get_calendar_eventsName": "Obter eventos do calendário","get_calendar_availabilityName": "Verificar disponibilidade",+ "get_snippetName": "Obter snippet",+ "update_dictionaryName": "Atualizar dicionário",+ "update_snippetsName": "Atualizar snippets","search_notesStatus": "Pesquisando notas...","web_searchStatus": "Pesquisando na web...","copy_to_clipboardStatus": "Copiando para a área de transferência...","get_calendar_eventsStatus": "Verificando calendário...","get_calendar_availabilityStatus": "Verificando disponibilidade...",+ "get_snippetStatus": "Obtendo snippet...",+ "update_dictionaryStatus": "Atualizando dicionário...",+ "update_snippetsStatus": "Atualizando snippets...","get_noteStatus": "Lendo nota...","create_noteStatus": "Criando nota...","update_noteStatus": "Atualizando nota...",@@ -3894,7 +3900,11 @@"scopes": {"notesRead": "Ler notas","notesWrite": "Criar e editar notas",- "transcriptionsRead": "Ler transcrições"+ "transcriptionsRead": "Ler transcrições",+ "dictionaryRead": "Ler dicionário",+ "dictionaryWrite": "Editar dicionário",+ "snippetsRead": "Ler snippets",+ "snippetsWrite": "Editar snippets"},"revoke": {"button": "Revogar",diff --git a/src/locales/ru/translation.json b/src/locales/ru/translation.jsonindex dd3ad941d..7c1200e81 100644--- a/src/locales/ru/translation.json+++ b/src/locales/ru/translation.json@@ -3618,11 +3618,17 @@"web_searchName": "Поиск в интернете","get_calendar_eventsName": "Получить события календаря","get_calendar_availabilityName": "Проверить доступность",+ "get_snippetName": "Получить сниппет",+ "update_dictionaryName": "Обновить словарь",+ "update_snippetsName": "Обновить сниппеты","search_notesStatus": "Поиск в заметках...","web_searchStatus": "Поиск в интернете...","copy_to_clipboardStatus": "Копирование в буфер обмена...","get_calendar_eventsStatus": "Проверка календаря...","get_calendar_availabilityStatus": "Проверка доступности...",+ "get_snippetStatus": "Получение сниппета...",+ "update_dictionaryStatus": "Обновление словаря...",+ "update_snippetsStatus": "Обновление сниппетов...","get_noteStatus": "Чтение заметки...","create_noteStatus": "Создание заметки...","update_noteStatus": "Обновление заметки...",@@ -3940,7 +3946,11 @@"scopes": {"notesRead": "Чтение заметок","notesWrite": "Создание и редактирование заметок",- "transcriptionsRead": "Чтение транскрипций"+ "transcriptionsRead": "Чтение транскрипций",+ "dictionaryRead": "Чтение словаря",+ "dictionaryWrite": "Изменение словаря",+ "snippetsRead": "Чтение сниппетов",+ "snippetsWrite": "Изменение сниппетов"},"revoke": {"button": "Отозвать",diff --git a/src/locales/zh-CN/translation.json b/src/locales/zh-CN/translation.jsonindex e1b42812f..a97feddb2 100644--- a/src/locales/zh-CN/translation.json+++ b/src/locales/zh-CN/translation.json@@ -3572,11 +3572,17 @@"web_searchName": "网页搜索","get_calendar_eventsName": "获取日历事件","get_calendar_availabilityName": "查看空闲时间",+ "get_snippetName": "获取片段",+ "update_dictionaryName": "更新词典",+ "update_snippetsName": "更新片段","search_notesStatus": "正在搜索笔记...","web_searchStatus": "正在搜索网页...","copy_to_clipboardStatus": "正在复制到剪贴板...","get_calendar_eventsStatus": "正在查看日历...","get_calendar_availabilityStatus": "正在查看空闲时间...",+ "get_snippetStatus": "正在获取片段...",+ "update_dictionaryStatus": "正在更新词典...",+ "update_snippetsStatus": "正在更新片段...","get_noteStatus": "正在读取笔记...","create_noteStatus": "正在创建笔记...","update_noteStatus": "正在更新笔记...",@@ -3894,7 +3900,11 @@"scopes": {"notesRead": "读取笔记","notesWrite": "创建和编辑笔记",- "transcriptionsRead": "读取转录"+ "transcriptionsRead": "读取转录",+ "dictionaryRead": "读取词典",+ "dictionaryWrite": "编辑词典",+ "snippetsRead": "读取片段",+ "snippetsWrite": "编辑片段"},"revoke": {"button": "撤销",diff --git a/src/locales/zh-TW/translation.json b/src/locales/zh-TW/translation.jsonindex 51bb7d15b..9c18b1eab 100644--- a/src/locales/zh-TW/translation.json+++ b/src/locales/zh-TW/translation.json@@ -3572,11 +3572,17 @@"web_searchName": "網頁搜尋","get_calendar_eventsName": "取得行事曆事件","get_calendar_availabilityName": "查看可用時段",+ "get_snippetName": "取得片段",+ "update_dictionaryName": "更新字典",+ "update_snippetsName": "更新片段","search_notesStatus": "正在搜尋筆記...","web_searchStatus": "正在搜尋網頁...","copy_to_clipboardStatus": "正在複製到剪貼簿...","get_calendar_eventsStatus": "正在查看行事曆...","get_calendar_availabilityStatus": "正在查看可用時段...",+ "get_snippetStatus": "正在取得片段...",+ "update_dictionaryStatus": "正在更新字典...",+ "update_snippetsStatus": "正在更新片段...","get_noteStatus": "正在讀取筆記...","create_noteStatus": "正在建立筆記...","update_noteStatus": "正在更新筆記...",@@ -3894,7 +3900,11 @@"scopes": {"notesRead": "讀取筆記","notesWrite": "建立與編輯筆記",- "transcriptionsRead": "讀取轉錄"+ "transcriptionsRead": "讀取轉錄",+ "dictionaryRead": "讀取字典",+ "dictionaryWrite": "編輯字典",+ "snippetsRead": "讀取片段",+ "snippetsWrite": "編輯片段"},"revoke": {"button": "撤銷",diff --git a/src/services/tools/dictionaryTool.ts b/src/services/tools/dictionaryTool.tsnew file mode 100644index 000000000..72015f5a6--- /dev/null+++ b/src/services/tools/dictionaryTool.ts@@ -0,0 +1,79 @@+import type { ToolDefinition, ToolResult } from "./ToolRegistry";++export interface DictionaryActions {+ getDictionary(): string[];+ updateDictionary(changes: { add: string[]; remove: string[] }): void;+}++export const cleanWordList = (values: unknown): string[] =>+ Array.isArray(values)+ ? [+ ...new Set(+ values+ .filter((value): value is string => typeof value === "string")+ .map((value) => value.trim())+ .filter(Boolean)+ ),+ ]+ : [];++const quoteList = (words: string[]) => words.map((word) => `"${word}"`).join(", ");++export function createUpdateDictionaryTool(actions: DictionaryActions): ToolDefinition {+ return {+ name: "update_dictionary",+ description:+ "Add words to or remove words from the user's custom dictionary: the names, jargon, and terms transcription must spell exactly. To fix a spelling, remove the old word and add the corrected one in the same call.",+ parameters: {+ type: "object",+ properties: {+ add: {+ type: "array",+ items: { type: "string" },+ description: "Words or short phrases to add",+ },+ remove: {+ type: "array",+ items: { type: "string" },+ description: "Existing dictionary words to remove",+ },+ },+ additionalProperties: false,+ },+ readOnly: false,++ async execute(args: Record<string, unknown>): Promise<ToolResult> {+ const existing = new Set(actions.getDictionary().map((word) => word.toLowerCase()));+ const has = (word: string) => existing.has(word.toLowerCase());+ const requestedAdd = cleanWordList(args.add);+ const requestedRemove = cleanWordList(args.remove);+ const add = requestedAdd.filter((word) => !has(word));+ const alreadyPresent = requestedAdd.filter(has);+ const remove = requestedRemove.filter(has);+ const notFound = requestedRemove.filter((word) => !has(word));++ if (add.length === 0 && remove.length === 0) {+ const reasons = [+ notFound.length ? `Not in the dictionary: ${quoteList(notFound)}` : "",+ alreadyPresent.length ? `Already in the dictionary: ${quoteList(alreadyPresent)}` : "",+ ].filter(Boolean);+ return {+ success: false,+ data: null,+ displayText: reasons.join(". ") || "Nothing to change",+ };+ }++ actions.updateDictionary({ add, remove });+ const summary = [+ add.length ? `Added ${quoteList(add)}` : "",+ remove.length ? `Removed ${quoteList(remove)}` : "",+ ].filter(Boolean);+ return {+ success: true,+ data: { added: add, removed: remove, alreadyPresent, notFound },+ displayText: summary.join("; "),+ };+ },+ };+}diff --git a/src/services/tools/index.ts b/src/services/tools/index.tsindex 6ec8838c0..cb71e1ad5 100644--- a/src/services/tools/index.ts+++ b/src/services/tools/index.ts@@ -8,6 +8,8 @@ import { clipboardTool } from "./clipboardTool";import { webSearchTool } from "./webSearchTool";import { calendarTool } from "./calendarTool";import { calendarAvailabilityTool } from "./calendarAvailabilityTool";+import { createSnippetTool, createUpdateSnippetsTool, type SnippetActions } from "./snippetTool";+import { createUpdateDictionaryTool, type DictionaryActions } from "./dictionaryTool";import type { ContainerScope } from "../../types/chat";export { ToolRegistry } from "./ToolRegistry";@@ -20,6 +22,8 @@ interface ToolRegistrySettings {/** Pins search_notes to a container (overview chat); the LLM cannot widen it. */searchScope?: ContainerScope;webSearchEnabled: boolean;+ /** Live dictionary and snippet access; enables the vocabulary tools. */+ vocabulary?: DictionaryActions & SnippetActions;}export function createToolRegistry(settings: ToolRegistrySettings): ToolRegistry {@@ -33,6 +37,13 @@ export function createToolRegistry(settings: ToolRegistrySettings): ToolRegistryregistry.register(listFoldersTool);registry.register(clipboardTool);+ if (settings.vocabulary) {+ const snippets = settings.vocabulary.getSnippets();+ if (snippets.length > 0) registry.register(createSnippetTool(snippets));+ registry.register(createUpdateDictionaryTool(settings.vocabulary));+ registry.register(createUpdateSnippetsTool(settings.vocabulary));+ }+if (settings.isSignedIn && settings.webSearchEnabled) {registry.register(webSearchTool);}diff --git a/src/services/tools/snippetTool.ts b/src/services/tools/snippetTool.tsnew file mode 100644index 000000000..d635fb78e--- /dev/null+++ b/src/services/tools/snippetTool.ts@@ -0,0 +1,143 @@+import { MAX_SNIPPET_TRIGGER_LENGTH, type Snippet } from "../../utils/snippets";+import type { ToolDefinition, ToolResult } from "./ToolRegistry";+import { cleanWordList } from "./dictionaryTool";++export interface SnippetActions {+ getSnippets(): Snippet[];+ setSnippets(snippets: Snippet[]): void;+}++const normalizeTrigger = (trigger: string) => trigger.trim().normalize("NFC").toLowerCase();++const quoteList = (triggers: string[]) => triggers.map((t) => `"${t}"`).join(", ");++/**+ * Snippet bodies stay out of the system prompt: they can run to paragraphs+ * and are only needed when a command names one. The trigger list rides in the+ * tool description so the model knows which snippets exist without a call.+ */+export function createSnippetTool(snippets: Snippet[]): ToolDefinition {+ const triggerList = quoteList(snippets.map((s) => s.trigger));++ return {+ name: "get_snippet",+ description: `Fetch the exact saved text behind one of the user's snippets by its spoken trigger phrase. Saved triggers: ${triggerList}.`,+ parameters: {+ type: "object",+ properties: {+ trigger: {+ type: "string",+ description: "The snippet's trigger phrase, exactly as listed in the saved triggers",+ },+ },+ required: ["trigger"],+ additionalProperties: false,+ },+ readOnly: true,++ async execute(args: Record<string, unknown>): Promise<ToolResult> {+ const requested = typeof args.trigger === "string" ? args.trigger : "";+ const wanted = normalizeTrigger(requested);+ const snippet = snippets.find((s) => normalizeTrigger(s.trigger) === wanted);+ if (!snippet) {+ return {+ success: false,+ data: null,+ displayText: `No snippet with trigger "${requested}". Saved triggers: ${triggerList}`,+ };+ }+ return {+ success: true,+ data: { trigger: snippet.trigger, text: snippet.replacement },+ displayText: `Snippet "${snippet.trigger}"`,+ };+ },+ };+}++function parseSnippetInputs(values: unknown): Snippet[] {+ if (!Array.isArray(values)) return [];+ const byKey = new Map<string, Snippet>();+ for (const value of values) {+ const raw = value as Partial<Snippet> | null;+ const trigger = typeof raw?.trigger === "string" ? raw.trigger.trim() : "";+ const replacement = typeof raw?.replacement === "string" ? raw.replacement.trim() : "";+ if (trigger && trigger.length <= MAX_SNIPPET_TRIGGER_LENGTH && replacement) {+ byKey.set(normalizeTrigger(trigger), { trigger, replacement });+ }+ }+ return [...byKey.values()];+}++export function createUpdateSnippetsTool(actions: SnippetActions): ToolDefinition {+ return {+ name: "update_snippets",+ description:+ "Create, replace, or delete the user's snippets. A snippet is a short spoken trigger phrase that expands into saved text during dictation. Adding a trigger that already exists replaces its saved text.",+ parameters: {+ type: "object",+ properties: {+ add: {+ type: "array",+ description: "Snippets to create or replace",+ items: {+ type: "object",+ properties: {+ trigger: { type: "string", description: "Short spoken trigger phrase" },+ replacement: { type: "string", description: "Full text the trigger expands into" },+ },+ required: ["trigger", "replacement"],+ additionalProperties: false,+ },+ },+ remove: {+ type: "array",+ items: { type: "string" },+ description: "Trigger phrases of snippets to delete",+ },+ },+ additionalProperties: false,+ },+ readOnly: false,++ async execute(args: Record<string, unknown>): Promise<ToolResult> {+ const current = actions.getSnippets();+ const add = parseSnippetInputs(args.add);+ const addKeys = new Set(add.map((s) => normalizeTrigger(s.trigger)));+ const requestedRemove = cleanWordList(args.remove);+ const removeKeys = new Set(requestedRemove.map(normalizeTrigger));+ const keyOf = (s: Snippet) => normalizeTrigger(s.trigger);++ const removed = current.filter((s) => removeKeys.has(keyOf(s))).map((s) => s.trigger);+ const replaced = current.filter((s) => addKeys.has(keyOf(s))).map((s) => s.trigger);+ const existingKeys = new Set(current.map(keyOf));+ const notFound = requestedRemove.filter((t) => !existingKeys.has(normalizeTrigger(t)));++ if (add.length === 0 && removed.length === 0) {+ return {+ success: false,+ data: null,+ displayText: notFound.length+ ? `No snippet with trigger ${quoteList(notFound)}`+ : `Nothing to change: each snippet needs a trigger of at most ${MAX_SNIPPET_TRIGGER_LENGTH} characters and replacement text`,+ };+ }++ const kept = current.filter((s) => !removeKeys.has(keyOf(s)) && !addKeys.has(keyOf(s)));+ actions.setSnippets([...kept, ...add]);++ const replacedKeys = new Set(replaced.map(normalizeTrigger));+ const added = add.map((s) => s.trigger).filter((t) => !replacedKeys.has(normalizeTrigger(t)));+ const summary = [+ added.length ? `Added ${quoteList(added)}` : "",+ replaced.length ? `Replaced ${quoteList(replaced)}` : "",+ removed.length ? `Removed ${quoteList(removed)}` : "",+ ].filter(Boolean);+ return {+ success: true,+ data: { added, replaced, removed, notFound },+ displayText: summary.join("; "),+ };+ },+ };+}diff --git a/src/utils/snippets.ts b/src/utils/snippets.tsindex 7f8b4ad57..8572c6d53 100644--- a/src/utils/snippets.ts+++ b/src/utils/snippets.ts@@ -3,6 +3,9 @@ export interface Snippet {replacement: string;}+// Mirrors the cap database.js enforces when it stores snippets.+export const MAX_SNIPPET_TRIGGER_LENGTH = 100;+interface SnippetMatcher {regex: RegExp;replacements: Map<string, string>;diff --git a/test/helpers/cliBridgeSnippets.test.js b/test/helpers/cliBridgeSnippets.test.jsnew file mode 100644index 000000000..d79d63d74--- /dev/null+++ b/test/helpers/cliBridgeSnippets.test.js@@ -0,0 +1,147 @@+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-cli-snip-"));+const originalLoad = Module._load;+const broadcasts = [];++Module._load = function patchedLoad(request, parent, isMain) {+ if (request === "electron") {+ return {+ app: {+ getPath: () => userDataDir,+ getAppPath: () => process.cwd(),+ isReady: () => false,+ },+ };+ }+ if (request === "./windowBroadcast") {+ return {+ broadcastToWindows: (channel, payload) => broadcasts.push({ channel, payload }),+ };+ }+ return originalLoad.call(this, request, parent, isMain);+};++process.env.NODE_ENV = "test";++const DatabaseManager = require("../../src/helpers/database.js");+const CliBridge = require("../../src/helpers/cliBridge.js");++function isNativeBindingUnavailable(error) {+ const message = String(error?.message || error);+ return (+ message.includes("NODE_MODULE_VERSION") ||+ message.includes("Could not locate the bindings file")+ );+}++function createBridge(t) {+ userDataDir = fs.mkdtempSync(path.join(os.tmpdir(), "openwhispr-cli-snip-"));+ let 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 });+ db = new DatabaseManager();+ } catch (error) {+ if (isNativeBindingUnavailable(error)) {+ t.skip("better-sqlite3 native binding is not available for this Node runtime");+ return null;+ }+ throw error;+ }++ broadcasts.length = 0;+ const bridge = new CliBridge({ databaseManager: db });+ return { bridge, db, broadcasts };+}++function call(bridge, method, pathname, body) {+ for (const route of bridge.routes) {+ if (route.method !== method) continue;+ const params = route.match(pathname);+ if (!params) continue;+ return route.handler({ params, query: new URLSearchParams(), body });+ }+ throw new Error(`No route for ${method} ${pathname}`);+}++const signOff = { trigger: "sign-off", replacement: "Best,\nGabe" };+const ask = { trigger: "investor ask", replacement: "We are raising a seed round." };++test("GET /v1/snippets/list returns the stored snippets", (t) => {+ const ctx = createBridge(t);+ if (!ctx) return;++ ctx.db.setSnippets([signOff, ask]);+ const result = call(ctx.bridge, "GET", "/v1/snippets/list");+ assert.deepEqual(result.data, [signOff, ask]);+});++test("POST /v1/snippets/update adds snippets and replaces an existing trigger", (t) => {+ const ctx = createBridge(t);+ if (!ctx) return;++ ctx.db.setSnippets([signOff]);+ const replaced = { trigger: "Sign-Off", replacement: "Cheers,\nGabe" };+ const result = call(ctx.bridge, "POST", "/v1/snippets/update", { add: [replaced, ask] });++ assert.equal(result.data.added, 2);+ assert.equal(result.data.removed, 0);+ assert.deepEqual(ctx.db.getSnippets(), [replaced, ask]);+});++test("POST /v1/snippets/update removes only the named triggers", (t) => {+ const ctx = createBridge(t);+ if (!ctx) return;++ ctx.db.setSnippets([signOff, ask]);+ const result = call(ctx.bridge, "POST", "/v1/snippets/update", { remove: ["Investor Ask"] });++ assert.equal(result.data.removed, 1);+ assert.deepEqual(ctx.db.getSnippets(), [signOff]);+});++test("POST /v1/snippets/update broadcasts the new list to renderers", async (t) => {+ await new Promise((resolve) => setImmediate(resolve));++ const ctx = createBridge(t);+ if (!ctx) return;++ call(ctx.bridge, "POST", "/v1/snippets/update", { add: [signOff] });+ await new Promise((resolve) => setImmediate(resolve));++ assert.equal(ctx.broadcasts.length, 1);+ assert.equal(ctx.broadcasts[0].channel, "snippets-updated");+ assert.deepEqual(ctx.broadcasts[0].payload, [signOff]);+});++test("POST /v1/snippets/update counts only snippets the database stored", (t) => {+ const ctx = createBridge(t);+ if (!ctx) return;++ const tooLong = { trigger: "x".repeat(101), replacement: "dropped" };+ const result = call(ctx.bridge, "POST", "/v1/snippets/update", { add: [tooLong, signOff] });++ assert.equal(result.data.added, 1);+ assert.deepEqual(ctx.db.getSnippets(), [signOff]);+});++test("POST /v1/snippets/update rejects malformed and empty requests", (t) => {+ const ctx = createBridge(t);+ if (!ctx) return;++ assert.throws(+ () => call(ctx.bridge, "POST", "/v1/snippets/update", { add: [{ trigger: "x" }] }),+ { code: "VALIDATION" }+ );+ assert.throws(() => call(ctx.bridge, "POST", "/v1/snippets/update", {}), {+ code: "VALIDATION",+ });+});diff --git a/test/services/dictionaryTool.test.js b/test/services/dictionaryTool.test.jsnew file mode 100644index 000000000..9583c52ad--- /dev/null+++ b/test/services/dictionaryTool.test.js@@ -0,0 +1,69 @@+const test = require("node:test");+const assert = require("node:assert/strict");++const load = () => import("../../src/services/tools/dictionaryTool.ts");++function harness(words) {+ const calls = [];+ return {+ calls,+ actions: {+ getDictionary: () => words,+ updateDictionary: (changes) => calls.push(changes),+ },+ };+}++test("adds new words and removes existing ones case-insensitively in one call", async () => {+ const { createUpdateDictionaryTool } = await load();+ const { actions, calls } = harness(["OpenWhispr", "Parakeat"]);+ const tool = createUpdateDictionaryTool(actions);++ const result = await tool.execute({ add: [" Parakeet ", "Orukeet"], remove: ["parakeat"] });++ assert.deepEqual(calls, [{ add: ["Parakeet", "Orukeet"], remove: ["parakeat"] }]);+ assert.deepEqual(result, {+ success: true,+ data: {+ added: ["Parakeet", "Orukeet"],+ removed: ["parakeat"],+ alreadyPresent: [],+ notFound: [],+ },+ displayText: 'Added "Parakeet", "Orukeet"; Removed "parakeat"',+ });+});++test("words already present are reported instead of re-added", async () => {+ const { createUpdateDictionaryTool } = await load();+ const { actions, calls } = harness(["OpenWhispr"]);+ const tool = createUpdateDictionaryTool(actions);++ const result = await tool.execute({ add: ["openwhispr"] });++ assert.equal(calls.length, 0);+ assert.equal(result.success, false);+ assert.equal(result.displayText, 'Already in the dictionary: "openwhispr"');+});++test("removing a word that is not there fails without writing", async () => {+ const { createUpdateDictionaryTool } = await load();+ const { actions, calls } = harness(["OpenWhispr"]);+ const tool = createUpdateDictionaryTool(actions);++ const result = await tool.execute({ remove: ["Whisper"] });++ assert.equal(calls.length, 0);+ assert.deepEqual(result, {+ success: false,+ data: null,+ displayText: 'Not in the dictionary: "Whisper"',+ });+});++test("the tool is a write tool", async () => {+ const { createUpdateDictionaryTool } = await load();+ const tool = createUpdateDictionaryTool(harness([]).actions);+ assert.equal(tool.name, "update_dictionary");+ assert.equal(tool.readOnly, false);+});diff --git a/test/services/snippetTool.test.js b/test/services/snippetTool.test.jsnew file mode 100644index 000000000..ba89a4f9a--- /dev/null+++ b/test/services/snippetTool.test.js@@ -0,0 +1,137 @@+const test = require("node:test");+const assert = require("node:assert/strict");++const load = () => import("../../src/services/tools/snippetTool.ts");++const snippets = [+ { trigger: "investor ask", replacement: "We are raising a $2M seed round." },+ { trigger: "Sign-off", replacement: "Best,\nGabe" },+];++test("the description lists every saved trigger so the model can pick one without a call", async () => {+ const { createSnippetTool } = await load();+ const tool = createSnippetTool(snippets);++ assert.equal(tool.name, "get_snippet");+ assert.equal(tool.readOnly, true);+ assert.match(tool.description, /Saved triggers: "investor ask", "Sign-off"\./);+ assert.doesNotMatch(tool.description, /seed round/);+});++test("a trigger resolves case-insensitively to its saved text", async () => {+ const { createSnippetTool } = await load();+ const tool = createSnippetTool(snippets);++ const result = await tool.execute({ trigger: " sign-off " });++ assert.deepEqual(result, {+ success: true,+ data: { trigger: "Sign-off", text: "Best,\nGabe" },+ displayText: 'Snippet "Sign-off"',+ });+});++test("an unknown trigger fails with the saved triggers so the model can retry", async () => {+ const { createSnippetTool } = await load();+ const tool = createSnippetTool(snippets);++ const result = await tool.execute({ trigger: "intro" });++ assert.equal(result.success, false);+ assert.equal(result.data, null);+ assert.equal(+ result.displayText,+ 'No snippet with trigger "intro". Saved triggers: "investor ask", "Sign-off"'+ );+});++function vocabulary(current) {+ const writes = [];+ return {+ writes,+ actions: {+ getDictionary: () => [],+ updateDictionary: () => {},+ getSnippets: () => current,+ setSnippets: (next) => writes.push(next),+ },+ };+}++test("registry exposes the vocabulary tools, and get_snippet only when snippets exist", async () => {+ const { createToolRegistry } = await import("../../src/services/tools/index.ts");+ const settings = {+ isSignedIn: false,+ calendarConnected: false,+ cloudBackupEnabled: false,+ webSearchEnabled: false,+ };++ const withSnippets = createToolRegistry({+ ...settings,+ vocabulary: vocabulary(snippets).actions,+ });+ const withoutSnippets = createToolRegistry({ ...settings, vocabulary: vocabulary([]).actions });+ const noVocabulary = createToolRegistry(settings);++ assert.match(withSnippets.get("get_snippet")?.description ?? "", /"investor ask"/);+ assert.equal(withSnippets.get("update_dictionary")?.readOnly, false);+ assert.equal(withSnippets.get("update_snippets")?.readOnly, false);+ assert.equal(withoutSnippets.get("get_snippet"), undefined);+ assert.equal(withoutSnippets.get("update_snippets")?.readOnly, false);+ assert.equal(noVocabulary.get("update_dictionary"), undefined);+});++test("update_snippets replaces an existing trigger, adds a new one, and removes by trigger", async () => {+ const { createUpdateSnippetsTool } = await load();+ const { actions, writes } = vocabulary(snippets);+ const tool = createUpdateSnippetsTool(actions);++ const result = await tool.execute({+ add: [+ { trigger: "SIGN-OFF", replacement: "Cheers,\nGabe" },+ { trigger: "intro", replacement: "Hi, I'm Gabe." },+ ],+ remove: ["Investor Ask"],+ });++ assert.deepEqual(writes, [+ [+ { trigger: "SIGN-OFF", replacement: "Cheers,\nGabe" },+ { trigger: "intro", replacement: "Hi, I'm Gabe." },+ ],+ ]);+ assert.deepEqual(result.data, {+ added: ["intro"],+ replaced: ["Sign-off"],+ removed: ["investor ask"],+ notFound: [],+ });+ assert.equal(result.displayText, 'Added "intro"; Replaced "Sign-off"; Removed "investor ask"');+});++test("update_snippets refuses incomplete snippets and unknown triggers without writing", async () => {+ const { createUpdateSnippetsTool } = await load();+ const { actions, writes } = vocabulary(snippets);+ const tool = createUpdateSnippetsTool(actions);++ const incomplete = await tool.execute({ add: [{ trigger: "intro" }] });+ const tooLong = await tool.execute({ add: [{ trigger: "x".repeat(101), replacement: "y" }] });+ const unknown = await tool.execute({ remove: ["outro"] });++ assert.equal(writes.length, 0);+ assert.equal(incomplete.success, false);+ assert.equal(tooLong.success, false);+ assert.equal(unknown.success, false);+ assert.equal(unknown.displayText, 'No snippet with trigger "outro"');+});++test("the agent prompt tells the model when to fetch a snippet", async () => {+ const { getAgentSystemPrompt } = await import("../../src/config/prompts.ts");++ const prompt = getAgentSystemPrompt(["get_snippet"]);++ assert.match(prompt, /Use get_snippet whenever the user names one of their saved snippets/);+ assert.match(prompt, /reproduce the returned text verbatim/);+ assert.doesNotMatch(getAgentSystemPrompt(["copy_to_clipboard"]), /get_snippet/);+});