Skip to content

Voice-to-text dictation app with local (Nvidia Parakeet/Whisper) and cloud models (BYOK). Privacy-first and available cross-platform.

feat: Snippets — spoken trigger word expansion in dictation (#934)

Gabriel Stein8d8c614456c1
diff --git a/src/components/DictionaryView.tsx b/src/components/DictionaryView.tsx
index c8aa435f7..1e43ed04e 100644
--- a/src/components/DictionaryView.tsx
+++ b/src/components/DictionaryView.tsx
@@ -1,11 +1,22 @@
-import { useCallback, useMemo, useState } from "react";
+import { useCallback, useMemo, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
-import { CornerDownLeft, Download, Pencil, Upload, X } from "lucide-react";
+import {
+ BookOpen,
+ CornerDownLeft,
+ Download,
+ Pencil,
+ Plus,
+ Sparkles,
+ Upload,
+ X,
+} from "lucide-react";
import { Input } from "./ui/input";
import { Textarea } from "./ui/textarea";
import { Button } from "./ui/button";
import { ConfirmDialog } from "./ui/dialog";
+import { Tabs, TabsList, TabsTrigger, TabsContent } from "./ui/tabs";
import { useToast } from "./ui/useToast";
+import SnippetsView from "./SnippetsView";
import { useSettings } from "../hooks/useSettings";
import { getAgentName } from "../utils/agentName";
@@ -27,16 +38,20 @@ export default function DictionaryView() {
const [editingWord, setEditingWord] = useState<string | null>(null);
const [editValue, setEditValue] = useState("");
const [confirmClear, setConfirmClear] = useState(false);
+ const addInputRef = useRef<HTMLInputElement>(null);
const pendingImportCount = useMemo(() => parseWords(bulkText).length, [bulkText]);
+ const userWords = useMemo(
+ () => customDictionary.filter((w) => w !== agentName),
+ [customDictionary, agentName]
+ );
+
const searchQuery = newWord.trim().toLowerCase();
const visibleWords = useMemo(
() =>
- searchQuery
- ? customDictionary.filter((w) => w.toLowerCase().includes(searchQuery))
- : customDictionary,
- [customDictionary, searchQuery]
+ searchQuery ? userWords.filter((w) => w.toLowerCase().includes(searchQuery)) : userWords,
+ [userWords, searchQuery]
);
const addWords = useCallback(
@@ -67,10 +82,9 @@ export default function DictionaryView() {
const handleRemove = useCallback(
(word: string) => {
- if (word === agentName) return;
setCustomDictionary(customDictionary.filter((w) => w !== word));
},
- [customDictionary, setCustomDictionary, agentName]
+ [customDictionary, setCustomDictionary]
);
const startEdit = useCallback((word: string) => {
@@ -101,8 +115,31 @@ export default function DictionaryView() {
}
}, [customDictionary, toast, t]);
+ const emptyState = (
+ <div className="flex flex-col items-center text-center py-8">
+ <div className="w-10 h-10 rounded-[10px] bg-gradient-to-b from-primary/8 to-primary/4 dark:from-primary/12 dark:to-primary/6 border border-primary/10 dark:border-primary/15 flex items-center justify-center mb-3.5">
+ <BookOpen size={17} strokeWidth={1.5} className="text-primary/50 dark:text-primary/60" />
+ </div>
+ <h4 className="text-xs font-semibold text-foreground mb-1">{t("dictionary.emptyTitle")}</h4>
+ <p className="text-xs text-foreground/30 leading-relaxed max-w-[240px] mb-4">
+ {t("dictionary.emptyDescription", { agentName })}
+ </p>
+ <Button size="sm" onClick={() => addInputRef.current?.focus()}>
+ <Plus size={12} />
+ {t("dictionary.addFirstWord")}
+ </Button>
+ <button
+ onClick={() => setShowBulkImport(true)}
+ className="mt-3 flex items-center gap-1.5 text-xs text-foreground/30 hover:text-foreground/60 transition-colors"
+ >
+ <Upload size={11} />
+ {t("dictionary.importList")}
+ </button>
+ </div>
+ );
+
return (
- <div className="flex flex-col h-full overflow-y-auto">
+ <Tabs defaultValue="dictionary" className="flex flex-col h-full">
<ConfirmDialog
open={confirmClear}
onOpenChange={setConfirmClear}
@@ -112,173 +149,194 @@ export default function DictionaryView() {
variant="destructive"
/>
- <div className="px-5 py-4 flex flex-col gap-3">
- {/* ─── Add word ─── */}
- <div>
- <div className="relative">
- <Input
- placeholder={t("dictionary.addPlaceholder")}
- value={newWord}
- onChange={(e) => setNewWord(e.target.value)}
- onKeyDown={(e) => {
- if (e.key === "Enter") handleAdd();
- }}
- className="w-full h-8 text-xs pr-24 placeholder:text-foreground/20"
- />
- <div className="absolute right-2.5 top-1/2 -translate-y-1/2 flex items-center gap-2">
- <button
- onClick={handleAdd}
- disabled={!newWord.trim()}
- aria-label={t("dictionary.addWord")}
- className="flex items-center gap-1 text-xs text-foreground/30 enabled:hover:text-primary disabled:text-foreground/15 transition-colors"
- >
- {t("dictionary.add")}
- <CornerDownLeft size={10} />
- </button>
- <div className="w-px h-3.5 bg-foreground/10 dark:bg-white/8" />
- <button
- onClick={() => setShowBulkImport(true)}
- aria-label={t("dictionary.importWords")}
- className="text-foreground/30 hover:text-foreground/60 transition-colors"
- >
- <Upload size={11} />
- </button>
- </div>
- </div>
- <p className="mt-1.5 text-xs text-foreground/15">{t("dictionary.separatorHint")}</p>
- </div>
+ <div className="px-5 pt-4">
+ <TabsList className="h-7 p-0.5 rounded-[7px]">
+ <TabsTrigger value="dictionary" className="h-6 px-2.5 text-xs rounded-[5px]">
+ {t("dictionary.tabDictionary")}
+ </TabsTrigger>
+ <TabsTrigger value="snippets" className="h-6 px-2.5 text-xs rounded-[5px]">
+ {t("dictionary.tabSnippets")}
+ </TabsTrigger>
+ </TabsList>
+ </div>
- {/* ─── Bulk import ─── */}
- {showBulkImport && (
- <div className="rounded-md border border-primary/30 dark:border-primary/40 px-3 pt-2.5 pb-2">
- <Textarea
- autoFocus
- value={bulkText}
- onChange={(e) => setBulkText(e.target.value)}
- placeholder={t("dictionary.importPlaceholder")}
- rows={4}
- className="min-h-[72px] resize-none border-0 shadow-none rounded-none bg-transparent p-0 text-xs text-foreground placeholder:text-foreground/20 hover:border-0 focus:border-0 focus:ring-0"
- />
- <div className="flex items-center justify-between pt-1.5">
- <p className="text-xs text-foreground/20">
- {t("dictionary.separateWithCommas")}
- {pendingImportCount > 0 && (
- <span className="text-success">
- {" • "}
- {t("dictionary.wordsReady", { count: pendingImportCount })}
- </span>
- )}
- </p>
- <div className="flex items-center gap-2">
- <Button
- variant="ghost"
- size="sm"
- onClick={() => {
- setBulkText("");
- setShowBulkImport(false);
- }}
+ <TabsContent value="dictionary" className="flex-1 min-h-0 mt-0 overflow-y-auto">
+ <div className="px-5 py-4 flex flex-col gap-3">
+ {/* ─── Add word ─── */}
+ <div>
+ <div className="relative">
+ <Input
+ ref={addInputRef}
+ placeholder={t("dictionary.addPlaceholder")}
+ value={newWord}
+ onChange={(e) => setNewWord(e.target.value)}
+ onKeyDown={(e) => {
+ if (e.key === "Enter") handleAdd();
+ }}
+ className="w-full h-8 text-xs pr-24 placeholder:text-foreground/20"
+ />
+ <div className="absolute right-2.5 top-1/2 -translate-y-1/2 flex items-center gap-2">
+ <button
+ onClick={handleAdd}
+ disabled={!newWord.trim()}
+ aria-label={t("dictionary.addWord")}
+ className="flex items-center gap-1 text-xs text-foreground/30 enabled:hover:text-primary disabled:text-foreground/15 transition-colors"
>
- {t("common.cancel")}
- </Button>
- <Button size="sm" onClick={handleImport} disabled={pendingImportCount === 0}>
- {t("dictionary.import")}
- </Button>
- </div>
- </div>
- </div>
- )}
-
- {/* ─── Dictionary list ─── */}
- <div className="rounded-md border border-foreground/8 dark:border-white/6 bg-foreground/[0.02] dark:bg-white/[0.03] px-4 py-3">
- <div className="flex items-center justify-between">
- <h3 className="text-xs font-semibold text-foreground/40">
- {t("dictionary.yourDictionary")}
- </h3>
- <div className="flex items-center gap-3">
- {customDictionary.length > 0 && (
+ {t("dictionary.add")}
+ <CornerDownLeft size={10} />
+ </button>
+ <div className="w-px h-3.5 bg-foreground/10 dark:bg-white/8" />
<button
- onClick={() => setConfirmClear(true)}
- aria-label={t("dictionary.clearAll")}
- className="text-xs text-foreground/15 hover:text-destructive/70 transition-colors"
+ onClick={() => setShowBulkImport(true)}
+ aria-label={t("dictionary.importWords")}
+ className="text-foreground/30 hover:text-foreground/60 transition-colors"
>
- {t("dictionary.clearAll")}
+ <Upload size={11} />
</button>
- )}
- <button
- onClick={handleExport}
- disabled={customDictionary.length === 0}
- aria-label={t("dictionary.exportDictionary")}
- className="text-foreground/25 enabled:hover:text-foreground/60 disabled:text-foreground/10 transition-colors"
- >
- <Download size={12} />
- </button>
+ </div>
</div>
</div>
- <div className="mt-2.5 border-t border-dashed border-foreground/10 dark:border-white/8" />
- {customDictionary.length === 0 ? (
- <p className="py-6 text-xs text-foreground/20 text-center">{t("dictionary.empty")}</p>
- ) : visibleWords.length === 0 ? (
- <p className="py-6 text-xs text-foreground/20 text-center">
- {t("dictionary.noMatches", { word: newWord.trim() })}
- </p>
- ) : (
- <ul>
- {visibleWords.map((word) => {
- const isAgentName = word === agentName;
- const isEditing = editingWord === word;
- return (
- <li
- key={word}
- className="group flex items-center gap-2 h-9 border-b border-foreground/4 dark:border-white/3 last:border-b-0"
- title={isAgentName ? t("dictionary.autoManaged") : undefined}
+ {/* ─── Bulk import ─── */}
+ {showBulkImport && (
+ <div className="rounded-md border border-primary/30 dark:border-primary/40 px-3 pt-2.5 pb-2">
+ <Textarea
+ autoFocus
+ value={bulkText}
+ onChange={(e) => setBulkText(e.target.value)}
+ placeholder={t("dictionary.importPlaceholder")}
+ rows={4}
+ className="min-h-[72px] resize-none border-0 shadow-none rounded-none bg-transparent p-0 text-xs text-foreground placeholder:text-foreground/20 hover:border-0 focus:border-0 focus:ring-0"
+ />
+ <div className="flex items-center justify-between pt-1.5">
+ <p className="text-xs text-foreground/20">
+ {t("dictionary.separateWithCommas")}
+ {pendingImportCount > 0 && (
+ <span className="text-success">
+ {" • "}
+ {t("dictionary.wordsReady", { count: pendingImportCount })}
+ </span>
+ )}
+ </p>
+ <div className="flex items-center gap-2">
+ <Button
+ variant="ghost"
+ size="sm"
+ onClick={() => {
+ setBulkText("");
+ setShowBulkImport(false);
+ }}
>
- {isEditing ? (
- <Input
- autoFocus
- value={editValue}
- onChange={(e) => setEditValue(e.target.value)}
- onKeyDown={(e) => {
- if (e.key === "Enter") commitEdit();
- if (e.key === "Escape") setEditingWord(null);
- }}
- onBlur={commitEdit}
- className="h-7 text-xs flex-1"
- />
- ) : (
- <span
- className={`flex-1 text-xs truncate ${
- isAgentName ? "text-primary" : "text-foreground/60"
- }`}
- >
- {word}
- </span>
- )}
- {!isAgentName && !isEditing && (
- <div className="flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-opacity duration-150">
- <button
- onClick={() => startEdit(word)}
- aria-label={t("dictionary.editWord", { word })}
- className="p-1 text-foreground/25 hover:text-foreground/60 transition-colors"
- >
- <Pencil size={11} />
- </button>
- <button
- onClick={() => handleRemove(word)}
- aria-label={t("dictionary.removeWord", { word })}
- className="p-1 text-foreground/25 hover:text-destructive/70 transition-colors"
- >
- <X size={11} strokeWidth={2} />
- </button>
- </div>
- )}
- </li>
- );
- })}
- </ul>
+ {t("common.cancel")}
+ </Button>
+ <Button size="sm" onClick={handleImport} disabled={pendingImportCount === 0}>
+ {t("dictionary.import")}
+ </Button>
+ </div>
+ </div>
+ </div>
)}
+
+ {/* ─── Agent name (always recognized) ─── */}
+ <div className="rounded-md border border-primary/15 dark:border-primary/20 bg-primary/3 dark:bg-primary/6 px-4 py-2.5 flex items-center justify-between gap-3">
+ <div className="flex items-center gap-2 min-w-0">
+ <Sparkles size={11} className="text-primary/70 shrink-0" />
+ <span className="text-xs font-medium text-primary truncate">{agentName}</span>
+ </div>
+ <span className="text-xs text-foreground/25 shrink-0">
+ {t("dictionary.agentDefault")}
+ </span>
+ </div>
+
+ {/* ─── Dictionary list ─── */}
+ <div className="rounded-md border border-foreground/8 dark:border-white/6 bg-foreground/[0.02] dark:bg-white/[0.03] px-4 py-3">
+ {userWords.length > 0 && (
+ <>
+ <div className="flex items-center justify-between">
+ <h3 className="text-xs font-semibold text-foreground/40">
+ {t("dictionary.yourDictionary")}
+ </h3>
+ <div className="flex items-center gap-3">
+ <button
+ onClick={() => setConfirmClear(true)}
+ aria-label={t("dictionary.clearAll")}
+ className="text-xs text-foreground/15 hover:text-destructive/70 transition-colors"
+ >
+ {t("dictionary.clearAll")}
+ </button>
+ <button
+ onClick={handleExport}
+ aria-label={t("dictionary.exportDictionary")}
+ className="text-foreground/25 hover:text-foreground/60 transition-colors"
+ >
+ <Download size={12} />
+ </button>
+ </div>
+ </div>
+ <div className="mt-2.5 border-t border-dashed border-foreground/10 dark:border-white/8" />
+ </>
+ )}
+
+ {userWords.length === 0 ? (
+ emptyState
+ ) : visibleWords.length === 0 ? (
+ <p className="py-6 text-xs text-foreground/20 text-center">
+ {t("dictionary.noMatches", { word: newWord.trim() })}
+ </p>
+ ) : (
+ <ul>
+ {visibleWords.map((word) => {
+ const isEditing = editingWord === word;
+ return (
+ <li
+ key={word}
+ className="group flex items-center gap-2 h-9 border-b border-foreground/4 dark:border-white/3 last:border-b-0"
+ >
+ {isEditing ? (
+ <Input
+ autoFocus
+ value={editValue}
+ onChange={(e) => setEditValue(e.target.value)}
+ onKeyDown={(e) => {
+ if (e.key === "Enter") commitEdit();
+ if (e.key === "Escape") setEditingWord(null);
+ }}
+ onBlur={commitEdit}
+ className="h-7 text-xs flex-1"
+ />
+ ) : (
+ <span className="flex-1 text-xs truncate text-foreground/60">{word}</span>
+ )}
+ {!isEditing && (
+ <div className="flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-opacity duration-150">
+ <button
+ onClick={() => startEdit(word)}
+ aria-label={t("dictionary.editWord", { word })}
+ className="p-1 text-foreground/25 hover:text-foreground/60 transition-colors"
+ >
+ <Pencil size={11} />
+ </button>
+ <button
+ onClick={() => handleRemove(word)}
+ aria-label={t("dictionary.removeWord", { word })}
+ className="p-1 text-foreground/25 hover:text-destructive/70 transition-colors"
+ >
+ <X size={11} strokeWidth={2} />
+ </button>
+ </div>
+ )}
+ </li>
+ );
+ })}
+ </ul>
+ )}
+ </div>
</div>
- </div>
- </div>
+ </TabsContent>
+
+ <TabsContent value="snippets" className="flex-1 min-h-0 mt-0 overflow-y-auto">
+ <SnippetsView />
+ </TabsContent>
+ </Tabs>
);
}
diff --git a/src/components/SnippetsView.tsx b/src/components/SnippetsView.tsx
new file mode 100644
index 000000000..285253e2e
--- /dev/null
+++ b/src/components/SnippetsView.tsx
@@ -0,0 +1,321 @@
+import { useEffect, useRef, useState } from "react";
+import { useTranslation } from "react-i18next";
+import { CornerDownLeft, Mic, Pencil, Plus, X } from "lucide-react";
+import {
+ Dialog,
+ DialogContent,
+ DialogHeader,
+ DialogTitle,
+ DialogDescription,
+ DialogFooter,
+} from "./ui/dialog";
+import { Button } from "./ui/button";
+import { Input } from "./ui/input";
+import { Label } from "./ui/label";
+import { Textarea } from "./ui/textarea";
+import { useSettings } from "../hooks/useSettings";
+import { getCachedPlatform } from "../utils/platform";
+import type { Snippet } from "../utils/snippets";
+
+const EXAMPLE_KEYS = ["linkedin", "rewrite", "intro", "signoff"] as const;
+
+interface EditSnippetDialogProps {
+ snippet: Snippet | null;
+ onOpenChange: (open: boolean) => void;
+ triggerExists: (trigger: string, except: string) => boolean;
+ onSave: (snippet: Snippet) => void;
+}
+
+function EditSnippetDialog({
+ snippet,
+ onOpenChange,
+ triggerExists,
+ onSave,
+}: EditSnippetDialogProps) {
+ const { t } = useTranslation();
+ const [trigger, setTrigger] = useState("");
+ const [replacement, setReplacement] = useState("");
+
+ useEffect(() => {
+ if (snippet) {
+ setTrigger(snippet.trigger);
+ setReplacement(snippet.replacement);
+ }
+ }, [snippet]);
+
+ const trimmedTrigger = trigger.trim();
+ const duplicate = !!snippet && !!trimmedTrigger && triggerExists(trimmedTrigger, snippet.trigger);
+ const canSave = !!trimmedTrigger && !!replacement.trim() && !duplicate;
+
+ function handleSubmit(e: React.FormEvent) {
+ e.preventDefault();
+ if (!canSave) return;
+ onSave({ trigger: trimmedTrigger, replacement: replacement.trim() });
+ }
+
+ return (
+ <Dialog open={!!snippet} onOpenChange={onOpenChange}>
+ <DialogContent className="max-w-md">
+ <DialogHeader>
+ <DialogTitle>{t("dictionary.snippets.editTitle")}</DialogTitle>
+ <DialogDescription>{t("dictionary.snippets.dialogDescription")}</DialogDescription>
+ </DialogHeader>
+ <form onSubmit={handleSubmit} className="space-y-3">
+ <div className="space-y-1.5">
+ <Label htmlFor="snippet-trigger" className="text-xs font-medium">
+ {t("dictionary.snippets.triggerLabel")}
+ </Label>
+ <Input
+ id="snippet-trigger"
+ value={trigger}
+ onChange={(e) => setTrigger(e.target.value)}
+ placeholder={t("dictionary.snippets.triggerPlaceholder")}
+ maxLength={80}
+ />
+ {duplicate && (
+ <p className="text-xs text-destructive">{t("dictionary.snippets.duplicate")}</p>
+ )}
+ </div>
+ <div className="space-y-1.5">
+ <Label htmlFor="snippet-replacement" className="text-xs font-medium">
+ {t("dictionary.snippets.replacementLabel")}
+ </Label>
+ <Textarea
+ id="snippet-replacement"
+ autoFocus
+ value={replacement}
+ onChange={(e) => setReplacement(e.target.value)}
+ placeholder={t("dictionary.snippets.replacementPlaceholder")}
+ className="min-h-[96px] text-xs"
+ />
+ </div>
+ <DialogFooter className="pt-2">
+ <Button type="button" variant="ghost" onClick={() => onOpenChange(false)}>
+ {t("common.cancel")}
+ </Button>
+ <Button type="submit" disabled={!canSave}>
+ {t("common.save")}
+ </Button>
+ </DialogFooter>
+ </form>
+ </DialogContent>
+ </Dialog>
+ );
+}
+
+export default function SnippetsView() {
+ const { t } = useTranslation();
+ const { snippets, setSnippets } = useSettings();
+ const [trigger, setTrigger] = useState("");
+ const [expansion, setExpansion] = useState("");
+ const [panelOpen, setPanelOpen] = useState(false);
+ const [editing, setEditing] = useState<Snippet | null>(null);
+ const triggerInputRef = useRef<HTMLInputElement>(null);
+
+ const triggerExists = (value: string, except?: string) => {
+ const lower = value.toLowerCase();
+ const exceptLower = except?.toLowerCase();
+ return snippets.some((s) => {
+ const existing = s.trigger.toLowerCase();
+ return existing === lower && existing !== exceptLower;
+ });
+ };
+
+ const trimmedTrigger = trigger.trim();
+ const duplicate = !!trimmedTrigger && triggerExists(trimmedTrigger);
+
+ const searchQuery = trimmedTrigger.toLowerCase();
+ const visibleSnippets =
+ searchQuery && !panelOpen
+ ? snippets.filter(
+ (s) =>
+ s.trigger.toLowerCase().includes(searchQuery) ||
+ s.replacement.toLowerCase().includes(searchQuery)
+ )
+ : snippets;
+
+ const openPanel = () => {
+ if (!trimmedTrigger || duplicate) return;
+ setPanelOpen(true);
+ };
+
+ const closePanel = () => {
+ setPanelOpen(false);
+ setExpansion("");
+ triggerInputRef.current?.focus();
+ };
+
+ const handleCreate = () => {
+ setSnippets([...snippets, { trigger: trimmedTrigger, replacement: expansion.trim() }]);
+ setTrigger("");
+ closePanel();
+ };
+
+ const handleSaveEdit = (snippet: Snippet) => {
+ setSnippets(snippets.map((s) => (s.trigger === editing?.trigger ? snippet : s)));
+ setEditing(null);
+ };
+
+ const handleRemove = (removed: string) => {
+ setSnippets(snippets.filter((s) => s.trigger !== removed));
+ };
+
+ const canCreate = !!trimmedTrigger && !!expansion.trim() && !duplicate;
+
+ return (
+ <div className="px-5 py-4 flex flex-col gap-3">
+ <EditSnippetDialog
+ snippet={editing}
+ onOpenChange={(open) => {
+ if (!open) setEditing(null);
+ }}
+ triggerExists={triggerExists}
+ onSave={handleSaveEdit}
+ />
+
+ {/* ─── Add snippet ─── */}
+ <div>
+ <div className="relative">
+ <Input
+ ref={triggerInputRef}
+ placeholder={t("dictionary.snippets.addPlaceholder")}
+ value={trigger}
+ onChange={(e) => setTrigger(e.target.value)}
+ onKeyDown={(e) => {
+ if (e.key === "Enter") openPanel();
+ }}
+ maxLength={80}
+ className="w-full h-8 text-xs pr-16 placeholder:text-foreground/20"
+ />
+ <button
+ onClick={openPanel}
+ disabled={!trimmedTrigger || duplicate}
+ aria-label={t("dictionary.snippets.create")}
+ className="absolute right-2.5 top-1/2 -translate-y-1/2 flex items-center gap-1 text-xs text-foreground/30 enabled:hover:text-primary disabled:text-foreground/15 transition-colors"
+ >
+ {t("dictionary.add")}
+ <CornerDownLeft size={10} />
+ </button>
+ </div>
+ {duplicate && (
+ <p className="mt-1.5 text-xs text-destructive">{t("dictionary.snippets.duplicate")}</p>
+ )}
+ </div>
+
+ {/* ─── Expansion panel ─── */}
+ {panelOpen && (
+ <div className="rounded-md border border-primary/30 dark:border-primary/40 px-3 pt-2.5 pb-2">
+ <Textarea
+ autoFocus
+ value={expansion}
+ onChange={(e) => setExpansion(e.target.value)}
+ onKeyDown={(e) => {
+ if (e.key === "Escape") closePanel();
+ if (e.key === "Enter" && (e.metaKey || e.ctrlKey) && canCreate) handleCreate();
+ }}
+ placeholder={t("dictionary.snippets.replacementPlaceholder")}
+ rows={4}
+ className="min-h-[72px] resize-none border-0 shadow-none rounded-none bg-transparent p-0 text-xs text-foreground placeholder:text-foreground/20 hover:border-0 focus:border-0 focus:ring-0"
+ />
+ <div className="flex items-center justify-between pt-1.5">
+ <div className="flex items-center gap-0.5">
+ <kbd className="text-[10px] px-1 py-px rounded border border-border/30 dark:border-white/8 bg-muted/40 text-muted-foreground/40 font-mono leading-tight">
+ {getCachedPlatform() === "darwin" ? "⌘" : "Ctrl"}
+ </kbd>
+ <kbd className="text-[10px] px-1 py-px rounded border border-border/30 dark:border-white/8 bg-muted/40 text-muted-foreground/40 font-mono leading-tight">
+ ⏎
+ </kbd>
+ </div>
+ <div className="flex items-center gap-2">
+ <Button variant="ghost" size="sm" onClick={closePanel}>
+ {t("common.cancel")}
+ </Button>
+ <Button size="sm" onClick={handleCreate} disabled={!canCreate}>
+ {t("dictionary.snippets.create")}
+ </Button>
+ </div>
+ </div>
+ </div>
+ )}
+
+ {/* ─── Snippet list ─── */}
+ <div className="rounded-md border border-foreground/8 dark:border-white/6 bg-foreground/[0.02] dark:bg-white/[0.03] px-4 py-3">
+ {snippets.length > 0 && (
+ <>
+ <h3 className="text-xs font-semibold text-foreground/40">
+ {t("dictionary.snippets.title")}
+ </h3>
+ <div className="mt-2.5 border-t border-dashed border-foreground/10 dark:border-white/8" />
+ </>
+ )}
+
+ {snippets.length === 0 ? (
+ <div className="flex flex-wrap items-center gap-x-8 gap-y-5 px-2 py-6">
+ <div className="flex-1 min-w-[220px]">
+ <h4 className="text-sm font-semibold text-foreground leading-snug">
+ {t("dictionary.snippets.emptyTitle")}{" "}
+ <span className="text-primary">{t("dictionary.snippets.emptyTitleAccent")}</span>
+ </h4>
+ <p className="mt-1.5 text-xs text-foreground/30 leading-relaxed">
+ {t("dictionary.snippets.emptyDescription")}
+ </p>
+ <Button size="sm" className="mt-4" onClick={() => triggerInputRef.current?.focus()}>
+ <Plus size={12} />
+ {t("dictionary.snippets.new")}
+ </Button>
+ </div>
+ <div className="flex-1 min-w-[260px] rounded-md border border-foreground/8 dark:border-white/6 bg-foreground/[0.02] dark:bg-white/[0.03] px-3.5 py-3 flex flex-col gap-2.5">
+ {EXAMPLE_KEYS.map((key) => (
+ <div key={key} className="flex items-start gap-2">
+ <span className="shrink-0 inline-flex items-center gap-1 rounded-[5px] bg-primary/10 dark:bg-primary/15 border border-primary/15 dark:border-primary/20 px-1.5 py-0.5 text-xs text-primary">
+ <Mic size={9} />
+ {t(`dictionary.snippets.examples.${key}Trigger`)}
+ </span>
+ <span className="shrink-0 text-xs text-foreground/20 mt-0.5">→</span>
+ <span className="min-w-0 text-xs text-foreground/40 leading-relaxed">
+ {t(`dictionary.snippets.examples.${key}Text`)}
+ </span>
+ </div>
+ ))}
+ </div>
+ </div>
+ ) : visibleSnippets.length === 0 ? (
+ <p className="py-6 text-xs text-foreground/20 text-center">
+ {t("dictionary.noMatches", { word: trimmedTrigger })}
+ </p>
+ ) : (
+ <ul>
+ {visibleSnippets.map((snippet) => (
+ <li
+ key={snippet.trigger}
+ className="group flex items-center gap-2 h-9 border-b border-foreground/4 dark:border-white/3 last:border-b-0"
+ >
+ <div className="flex-1 min-w-0 flex items-center gap-2">
+ <span className="text-xs text-foreground/60 shrink-0">{snippet.trigger}</span>
+ <span className="text-xs text-foreground/20 shrink-0">→</span>
+ <span className="text-xs text-foreground/35 truncate">{snippet.replacement}</span>
+ </div>
+ <div className="flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-opacity duration-150">
+ <button
+ onClick={() => setEditing(snippet)}
+ aria-label={t("dictionary.snippets.edit", { trigger: snippet.trigger })}
+ className="p-1 text-foreground/25 hover:text-foreground/60 transition-colors"
+ >
+ <Pencil size={11} />
+ </button>
+ <button
+ onClick={() => handleRemove(snippet.trigger)}
+ aria-label={t("dictionary.snippets.remove", { trigger: snippet.trigger })}
+ className="p-1 text-foreground/25 hover:text-destructive/70 transition-colors"
+ >
+ <X size={11} strokeWidth={2} />
+ </button>
+ </div>
+ </li>
+ ))}
+ </ul>
+ )}
+ </div>
+ </div>
+ );
+}
diff --git a/src/helpers/audioManager.js b/src/helpers/audioManager.js
index b2c309732..6070f6d6e 100644
--- a/src/helpers/audioManager.js
+++ b/src/helpers/audioManager.js
@@ -17,6 +17,7 @@ import { detectAgentName } from "../config/agentDetection";
import { resolvePrompt } from "../config/prompts";
import { syncService } from "../services/SyncService.js";
import { matchesDictionaryPrompt } from "../utils/dictionaryEchoFilter.js";
+import { getDictionaryHintWords } from "../utils/snippets";
const REASONING_CACHE_TTL = 30000; // 30 seconds
const REALTIME_MODELS = new Set(["gpt-4o-mini-transcribe", "gpt-4o-transcribe"]);
@@ -49,7 +50,7 @@ function resolveReasoningRoute(text, settings, agentName) {
systemPrompt: resolvePrompt("dictationAgent", {
agentName,
language: settings.preferredLanguage,
- customDictionary: settings.customDictionary,
+ customDictionary: getDictionaryHintWords(settings),
uiLanguage: settings.uiLanguage,
}),
},
@@ -229,7 +230,7 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);
}
getCustomDictionaryPrompt() {
- const words = getSettings().customDictionary;
+ const words = getDictionaryHintWords(getSettings());
return words.length > 0 ? words.join(", ") : null;
}
@@ -1414,7 +1415,7 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);
const reasonResult = await withSessionRefresh(async () => {
const res = await window.electronAPI.cloudReason(processedText, {
agentName,
- customDictionary: settings.customDictionary,
+ customDictionary: getDictionaryHintWords(settings),
customPrompt: this.getCustomPrompt(),
language: settings.preferredLanguage || "auto",
locale: settings.uiLanguage || "en",
@@ -2729,7 +2730,7 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);
const reasonResult = await withSessionRefresh(async () => {
const res = await window.electronAPI.cloudReason(finalText, {
agentName,
- customDictionary: stSettings.customDictionary,
+ customDictionary: getDictionaryHintWords(stSettings),
customPrompt: this.getCustomPrompt(),
language: stSettings.preferredLanguage || "auto",
locale: stSettings.uiLanguage || "en",
diff --git a/src/hooks/useAudioRecording.js b/src/hooks/useAudioRecording.js
index 0c5f841a9..c253c692f 100644
--- a/src/hooks/useAudioRecording.js
+++ b/src/hooks/useAudioRecording.js
@@ -4,6 +4,7 @@ import AudioManager from "../helpers/audioManager";
import logger from "../utils/logger";
import { playStartCue, playStopCue } from "../utils/dictationCues";
import { getSettings } from "../stores/settingsStore";
+import { expandSnippets } from "../utils/snippets";
import { getRecordingErrorTitle, getRecordingErrorDescription } from "../utils/recordingErrors";
import { isAccessibilitySkipped } from "../utils/permissions";
@@ -132,6 +133,8 @@ export const useAudioRecording = (toast, options = {}) => {
return;
}
+ result.text = expandSnippets(result.text, getSettings().snippets);
+
setTranscript(result.text);
window.electronAPI?.completeDictationPreview?.({ text: result.text });
diff --git a/src/hooks/useSettings.ts b/src/hooks/useSettings.ts
index 377973f5e..5f029de3d 100644
--- a/src/hooks/useSettings.ts
+++ b/src/hooks/useSettings.ts
@@ -3,6 +3,7 @@ import { useSettingsStore, initializeSettings } from "../stores/settingsStore";
import logger from "../utils/logger";
import { useLocalStorage } from "./useLocalStorage";
import type { LocalTranscriptionProvider, InferenceMode, SelfHostedType } from "../types/electron";
+import type { Snippet } from "../utils/snippets";
export interface TranscriptionSettings {
uiLanguage: string;
@@ -22,6 +23,7 @@ export interface TranscriptionSettings {
remoteTranscriptionType: SelfHostedType;
remoteTranscriptionUrl: string;
customDictionary: string[];
+ snippets: Snippet[];
assemblyAiStreaming: boolean;
showTranscriptionPreview: boolean;
}
@@ -205,6 +207,8 @@ function useSettingsInternal() {
cleanupMode: store.cleanupMode,
cleanupRemoteUrl: store.cleanupRemoteUrl,
customDictionary: store.customDictionary,
+ snippets: store.snippets,
+ setSnippets: store.setSnippets,
assemblyAiStreaming: store.assemblyAiStreaming,
setAssemblyAiStreaming: store.setAssemblyAiStreaming,
autoGenerateNoteTitle: store.autoGenerateNoteTitle,
diff --git a/src/locales/de/translation.json b/src/locales/de/translation.json
index 3dcee3003..5bed39049 100644
--- a/src/locales/de/translation.json
+++ b/src/locales/de/translation.json
@@ -2149,13 +2149,11 @@
"addWord": "Wort hinzufügen",
"removeWord": "{{word}} entfernen",
"clearAll": "Alle löschen",
- "autoManaged": "Agent-Name (automatisch verwaltet)",
"clearTitle": "Wörterbuch leeren?",
"clearDescription": "Dadurch werden alle Wörter aus deinem benutzerdefinierten Wörterbuch entfernt. Diese Aktion kann nicht rückgängig gemacht werden.",
- "addPlaceholder": "Wort eingeben",
+ "addPlaceholder": "Wörter durch Kommas getrennt hinzufügen – OpenWhispr, Supabase, John Snow, ARR",
"add": "Hinzufügen",
"importWords": "Wörter importieren",
- "separatorHint": "Mit Kommas trennen — OpenWhispr, Supabase, John Snow, ARR",
"importPlaceholder": "Wörter durch Kommas getrennt einfügen...",
"separateWithCommas": "Mit Kommas trennen",
"wordsReady_one": "{{count}} Wort bereit",
@@ -2164,9 +2162,43 @@
"yourDictionary": "Dein Wörterbuch",
"exportDictionary": "Wörterbuch exportieren",
"exportFailed": "Export fehlgeschlagen",
- "empty": "Noch keine Wörter",
"editWord": "{{word}} bearbeiten",
- "noMatches": "Keine Treffer — Enter drücken, um \"{{word}}\" hinzuzufügen"
+ "noMatches": "Keine Treffer — Enter drücken, um \"{{word}}\" hinzuzufügen",
+ "tabDictionary": "Wörterbuch",
+ "tabSnippets": "Snippets",
+ "snippets": {
+ "title": "Snippets",
+ "edit": "{{trigger}} bearbeiten",
+ "remove": "{{trigger}} entfernen",
+ "editTitle": "Snippet bearbeiten",
+ "dialogDescription": "Wenn du den Auslöser sprichst, wird er durch deinen gespeicherten Text ersetzt.",
+ "triggerLabel": "Auslöser",
+ "triggerPlaceholder": "z. B. mein Kalender",
+ "replacementLabel": "Ersetzung",
+ "replacementPlaceholder": "Text, der beim Sprechen des Auslösers eingefügt wird …",
+ "create": "Snippet erstellen",
+ "duplicate": "Ein Snippet mit diesem Auslöser existiert bereits",
+ "emptyTitle": "Sag es nur",
+ "emptyTitleAccent": "einmal",
+ "emptyDescription": "Sprich ein Auslösewort und OpenWhispr ersetzt es durch deinen gespeicherten Text – Links, Intros, Grußformeln, Prompts.",
+ "new": "Neues Snippet",
+ "examples": {
+ "linkedinTrigger": "Mein LinkedIn",
+ "linkedinText": "linkedin.com/in/du",
+ "rewriteTrigger": "Umschreib-Prompt",
+ "rewriteText": "Schreibe das prägnanter und professioneller um",
+ "introTrigger": "Intro-E-Mail",
+ "introText": "Hallo, ich würde mich freuen, diese Woche Zeit für ein Gespräch zu finden …",
+ "signoffTrigger": "Grußformel",
+ "signoffText": "Viele Grüße, Alex · [email protected]"
+ },
+ "addPlaceholder": "Auslöser-Phrase hinzufügen – „mein Kalender“, „mein LinkedIn“"
+ },
+ "emptyTitle": "Dein Wörterbuch ist leer",
+ "emptyDescription": "Füge Wörter hinzu, die {{agentName}} immer richtig erkennen soll: Namen, Tools, Abkürzungen.",
+ "addFirstWord": "Füge dein erstes Wort hinzu",
+ "importList": "Liste importieren",
+ "agentDefault": "Standardmäßig enthalten"
},
"sidebar": {
"home": "Startseite",
diff --git a/src/locales/en/translation.json b/src/locales/en/translation.json
index 0c3ede713..e6439d3fc 100644
--- a/src/locales/en/translation.json
+++ b/src/locales/en/translation.json
@@ -2356,13 +2356,11 @@
"clearTitle": "Clear dictionary?",
"clearDescription": "This will remove all words from your custom dictionary. This action cannot be undone.",
"addWord": "Add word",
- "addPlaceholder": "Type a word",
+ "addPlaceholder": "Add words separated by commas — OpenWhispr, Supabase, John Snow, ARR",
"removeWord": "Remove {{word}}",
"clearAll": "Clear all",
- "autoManaged": "Auto-managed — synced from agent name",
"add": "Add",
"importWords": "Import words",
- "separatorHint": "Separate with commas — OpenWhispr, Supabase, John Snow, ARR",
"importPlaceholder": "Paste words separated by commas...",
"separateWithCommas": "Separate with commas",
"wordsReady_one": "{{count}} word ready",
@@ -2371,9 +2369,43 @@
"yourDictionary": "Your dictionary",
"exportDictionary": "Export dictionary",
"exportFailed": "Export failed",
- "empty": "No words yet",
"editWord": "Edit {{word}}",
- "noMatches": "No matches — press Enter to add \"{{word}}\""
+ "noMatches": "No matches — press Enter to add \"{{word}}\"",
+ "tabDictionary": "Dictionary",
+ "tabSnippets": "Snippets",
+ "snippets": {
+ "title": "Snippets",
+ "edit": "Edit {{trigger}}",
+ "remove": "Remove {{trigger}}",
+ "editTitle": "Edit snippet",
+ "dialogDescription": "When you speak the trigger, it's replaced with your saved text.",
+ "triggerLabel": "Trigger",
+ "triggerPlaceholder": "e.g. cal link",
+ "replacementLabel": "Replacement",
+ "replacementPlaceholder": "Text to insert when you say the trigger…",
+ "create": "Create snippet",
+ "duplicate": "A snippet with this trigger already exists",
+ "emptyTitle": "The stuff you shouldn't have to say",
+ "emptyTitleAccent": "twice",
+ "emptyDescription": "Speak a trigger word and OpenWhispr replaces it with whatever you saved — URLs, intros, sign-offs, prompts.",
+ "new": "New snippet",
+ "examples": {
+ "linkedinTrigger": "My LinkedIn",
+ "linkedinText": "linkedin.com/in/you",
+ "rewriteTrigger": "Rewrite prompt",
+ "rewriteText": "Rewrite this to be more concise and professional",
+ "introTrigger": "Intro email",
+ "introText": "Hey, would love to find some time to chat later this week…",
+ "signoffTrigger": "Sign off",
+ "signoffText": "Best, Alex · [email protected]"
+ },
+ "addPlaceholder": "Add a trigger phrase — \"investor ask\", \"cal link\""
+ },
+ "emptyTitle": "Your dictionary is empty",
+ "emptyDescription": "Add words {{agentName}} should always get right: names, tools, acronyms.",
+ "addFirstWord": "Add your first word",
+ "importList": "Import a list",
+ "agentDefault": "Added by default"
},
"support": {
"documentation": "Documentation",
diff --git a/src/locales/es/translation.json b/src/locales/es/translation.json
index 357c621cd..8873ed648 100644
--- a/src/locales/es/translation.json
+++ b/src/locales/es/translation.json
@@ -2197,13 +2197,11 @@
"addWord": "Añadir palabra",
"removeWord": "Eliminar {{word}}",
"clearAll": "Borrar todo",
- "autoManaged": "Nombre del agente (gestionado automáticamente)",
"clearTitle": "¿Borrar el diccionario?",
"clearDescription": "Esto eliminará todas las palabras de tu diccionario personalizado. Esta acción no se puede deshacer.",
- "addPlaceholder": "Escribe una palabra",
+ "addPlaceholder": "Añade palabras separadas por comas: OpenWhispr, Supabase, John Snow, ARR",
"add": "Añadir",
"importWords": "Importar palabras",
- "separatorHint": "Separa con comas — OpenWhispr, Supabase, John Snow, ARR",
"importPlaceholder": "Pega palabras separadas por comas...",
"separateWithCommas": "Separa con comas",
"wordsReady_one": "{{count}} palabra lista",
@@ -2212,9 +2210,43 @@
"yourDictionary": "Tu diccionario",
"exportDictionary": "Exportar diccionario",
"exportFailed": "Error al exportar",
- "empty": "Aún no hay palabras",
"editWord": "Editar {{word}}",
- "noMatches": "Sin coincidencias — pulsa Enter para añadir \"{{word}}\""
+ "noMatches": "Sin coincidencias — pulsa Enter para añadir \"{{word}}\"",
+ "tabDictionary": "Diccionario",
+ "tabSnippets": "Snippets",
+ "snippets": {
+ "title": "Snippets",
+ "edit": "Editar {{trigger}}",
+ "remove": "Eliminar {{trigger}}",
+ "editTitle": "Editar snippet",
+ "dialogDescription": "Cuando digas el disparador, se reemplazará por tu texto guardado.",
+ "triggerLabel": "Disparador",
+ "triggerPlaceholder": "p. ej. mi agenda",
+ "replacementLabel": "Reemplazo",
+ "replacementPlaceholder": "Texto que se insertará al decir el disparador…",
+ "create": "Crear snippet",
+ "duplicate": "Ya existe un snippet con este disparador",
+ "emptyTitle": "Lo que no deberías tener que decir",
+ "emptyTitleAccent": "dos veces",
+ "emptyDescription": "Di una palabra disparadora y OpenWhispr la reemplaza por lo que guardaste: URLs, presentaciones, despedidas, prompts.",
+ "new": "Nuevo snippet",
+ "examples": {
+ "linkedinTrigger": "Mi LinkedIn",
+ "linkedinText": "linkedin.com/in/tu",
+ "rewriteTrigger": "Prompt de reescritura",
+ "rewriteText": "Reescribe esto para que sea más conciso y profesional",
+ "introTrigger": "Email de presentación",
+ "introText": "Hola, me encantaría encontrar un momento para hablar esta semana…",
+ "signoffTrigger": "Despedida",
+ "signoffText": "Saludos, Alex · [email protected]"
+ },
+ "addPlaceholder": "Añade una frase disparadora: \"mi agenda\", \"mi LinkedIn\""
+ },
+ "emptyTitle": "Tu diccionario está vacío",
+ "emptyDescription": "Añade palabras que {{agentName}} siempre debe reconocer: nombres, herramientas, siglas.",
+ "addFirstWord": "Añade tu primera palabra",
+ "importList": "Importar una lista",
+ "agentDefault": "Añadido por defecto"
},
"sidebar": {
"home": "Inicio",
diff --git a/src/locales/fr/translation.json b/src/locales/fr/translation.json
index 37fa3bc07..2da5613f2 100644
--- a/src/locales/fr/translation.json
+++ b/src/locales/fr/translation.json
@@ -2260,13 +2260,11 @@
"clearTitle": "Vider le dictionnaire ?",
"clearDescription": "Cela supprimera tous les mots de votre dictionnaire personnalisé. Cette action est irréversible.",
"addWord": "Ajouter un mot",
- "addPlaceholder": "Saisissez un mot",
+ "addPlaceholder": "Ajoutez des mots séparés par des virgules — OpenWhispr, Supabase, John Snow, ARR",
"removeWord": "Supprimer {{word}}",
"clearAll": "Tout effacer",
- "autoManaged": "Géré automatiquement — synchronisé depuis le nom de l'agent",
"add": "Ajouter",
"importWords": "Importer des mots",
- "separatorHint": "Séparez par des virgules — OpenWhispr, Supabase, John Snow, ARR",
"importPlaceholder": "Collez des mots séparés par des virgules...",
"separateWithCommas": "Séparez par des virgules",
"wordsReady_one": "{{count}} mot prêt",
@@ -2275,9 +2273,43 @@
"yourDictionary": "Votre dictionnaire",
"exportDictionary": "Exporter le dictionnaire",
"exportFailed": "Échec de l'exportation",
- "empty": "Aucun mot pour l'instant",
"editWord": "Modifier {{word}}",
- "noMatches": "Aucune correspondance — appuyez sur Entrée pour ajouter « {{word}} »"
+ "noMatches": "Aucune correspondance — appuyez sur Entrée pour ajouter « {{word}} »",
+ "tabDictionary": "Dictionnaire",
+ "tabSnippets": "Snippets",
+ "snippets": {
+ "title": "Snippets",
+ "edit": "Modifier {{trigger}}",
+ "remove": "Supprimer {{trigger}}",
+ "editTitle": "Modifier le snippet",
+ "dialogDescription": "Quand vous prononcez le déclencheur, il est remplacé par votre texte enregistré.",
+ "triggerLabel": "Déclencheur",
+ "triggerPlaceholder": "ex. mon agenda",
+ "replacementLabel": "Remplacement",
+ "replacementPlaceholder": "Texte à insérer quand vous dites le déclencheur…",
+ "create": "Créer le snippet",
+ "duplicate": "Un snippet avec ce déclencheur existe déjà",
+ "emptyTitle": "Ce que vous ne devriez pas avoir à dire",
+ "emptyTitleAccent": "deux fois",
+ "emptyDescription": "Prononcez un mot déclencheur et OpenWhispr le remplace par ce que vous avez enregistré : URL, intros, signatures, prompts.",
+ "new": "Nouveau snippet",
+ "examples": {
+ "linkedinTrigger": "Mon LinkedIn",
+ "linkedinText": "linkedin.com/in/vous",
+ "rewriteTrigger": "Prompt de réécriture",
+ "rewriteText": "Réécris ceci de façon plus concise et professionnelle",
+ "introTrigger": "Email d'intro",
+ "introText": "Bonjour, j'aimerais trouver un moment pour échanger cette semaine…",
+ "signoffTrigger": "Signature",
+ "signoffText": "Cordialement, Alex · [email protected]"
+ },
+ "addPlaceholder": "Ajoutez une phrase déclencheur — « mon agenda », « mon LinkedIn »"
+ },
+ "emptyTitle": "Votre dictionnaire est vide",
+ "emptyDescription": "Ajoutez les mots que {{agentName}} doit toujours reconnaître : noms, outils, acronymes.",
+ "addFirstWord": "Ajoutez votre premier mot",
+ "importList": "Importer une liste",
+ "agentDefault": "Ajouté par défaut"
},
"support": {
"documentation": "Documentation",
diff --git a/src/locales/it/translation.json b/src/locales/it/translation.json
index 92ea9e4ef..d0a45c317 100644
--- a/src/locales/it/translation.json
+++ b/src/locales/it/translation.json
@@ -2149,13 +2149,11 @@
"addWord": "Aggiungi parola",
"removeWord": "Rimuovi {{word}}",
"clearAll": "Cancella tutto",
- "autoManaged": "Gestito automaticamente",
"clearTitle": "Svuotare il dizionario?",
"clearDescription": "Verranno rimossi tutti i termini dal tuo dizionario personalizzato. Questa azione non può essere annullata.",
- "addPlaceholder": "Digita una parola",
+ "addPlaceholder": "Aggiungi parole separate da virgole: OpenWhispr, Supabase, John Snow, ARR",
"add": "Aggiungi",
"importWords": "Importa parole",
- "separatorHint": "Separa con virgole — OpenWhispr, Supabase, John Snow, ARR",
"importPlaceholder": "Incolla parole separate da virgole...",
"separateWithCommas": "Separa con virgole",
"wordsReady_one": "{{count}} parola pronta",
@@ -2164,9 +2162,43 @@
"yourDictionary": "Il tuo dizionario",
"exportDictionary": "Esporta dizionario",
"exportFailed": "Esportazione non riuscita",
- "empty": "Nessuna parola",
"editWord": "Modifica {{word}}",
- "noMatches": "Nessuna corrispondenza — premi Invio per aggiungere \"{{word}}\""
+ "noMatches": "Nessuna corrispondenza — premi Invio per aggiungere \"{{word}}\"",
+ "tabDictionary": "Dizionario",
+ "tabSnippets": "Snippet",
+ "snippets": {
+ "title": "Snippet",
+ "edit": "Modifica {{trigger}}",
+ "remove": "Rimuovi {{trigger}}",
+ "editTitle": "Modifica snippet",
+ "dialogDescription": "Quando pronunci il trigger, viene sostituito con il tuo testo salvato.",
+ "triggerLabel": "Trigger",
+ "triggerPlaceholder": "es. mio calendario",
+ "replacementLabel": "Sostituzione",
+ "replacementPlaceholder": "Testo da inserire quando pronunci il trigger…",
+ "create": "Crea snippet",
+ "duplicate": "Esiste già uno snippet con questo trigger",
+ "emptyTitle": "Quello che non dovresti dover dire",
+ "emptyTitleAccent": "due volte",
+ "emptyDescription": "Pronuncia un trigger e OpenWhispr lo sostituisce con ciò che hai salvato: URL, presentazioni, firme, prompt.",
+ "new": "Nuovo snippet",
+ "examples": {
+ "linkedinTrigger": "Il mio LinkedIn",
+ "linkedinText": "linkedin.com/in/tu",
+ "rewriteTrigger": "Prompt di riscrittura",
+ "rewriteText": "Riscrivi questo testo in modo più conciso e professionale",
+ "introTrigger": "Email di presentazione",
+ "introText": "Ciao, mi piacerebbe trovare un momento per parlare questa settimana…",
+ "signoffTrigger": "Firma",
+ "signoffText": "Saluti, Alex · [email protected]"
+ },
+ "addPlaceholder": "Aggiungi una frase trigger: \"mio calendario\", \"il mio LinkedIn\""
+ },
+ "emptyTitle": "Il tuo dizionario è vuoto",
+ "emptyDescription": "Aggiungi le parole che {{agentName}} deve sempre riconoscere: nomi, strumenti, acronimi.",
+ "addFirstWord": "Aggiungi la tua prima parola",
+ "importList": "Importa un elenco",
+ "agentDefault": "Aggiunto di default"
},
"sidebar": {
"home": "Home",
diff --git a/src/locales/ja/translation.json b/src/locales/ja/translation.json
index 95a9ef35b..bcb312874 100644
--- a/src/locales/ja/translation.json
+++ b/src/locales/ja/translation.json
@@ -2077,13 +2077,11 @@
"addWord": "単語を追加",
"removeWord": "{{word}} を削除",
"clearAll": "すべてクリア",
- "autoManaged": "自動管理",
"clearTitle": "辞書をクリアしますか?",
"clearDescription": "カスタム辞書のすべての単語が削除されます。この操作は元に戻せません。",
- "addPlaceholder": "単語を入力",
+ "addPlaceholder": "カンマ区切りで単語を追加 — OpenWhispr、Supabase、ARR など",
"add": "追加",
"importWords": "単語をインポート",
- "separatorHint": "カンマで区切る — OpenWhispr, Supabase, John Snow, ARR",
"importPlaceholder": "カンマ区切りの単語を貼り付け...",
"separateWithCommas": "カンマで区切る",
"wordsReady_other": "{{count}} 個の単語が準備完了",
@@ -2091,10 +2089,44 @@
"yourDictionary": "あなたの辞書",
"exportDictionary": "辞書をエクスポート",
"exportFailed": "エクスポートに失敗しました",
- "empty": "まだ単語がありません",
"editWord": "{{word}} を編集",
"wordsReady_one": "{{count}} 個の単語が準備完了",
- "noMatches": "一致なし — Enter キーで「{{word}}」を追加"
+ "noMatches": "一致なし — Enter キーで「{{word}}」を追加",
+ "tabDictionary": "辞書",
+ "tabSnippets": "スニペット",
+ "snippets": {
+ "title": "スニペット",
+ "edit": "{{trigger}}を編集",
+ "remove": "{{trigger}}を削除",
+ "editTitle": "スニペットを編集",
+ "dialogDescription": "トリガーを話すと、保存したテキストに置き換わります。",
+ "triggerLabel": "トリガー",
+ "triggerPlaceholder": "例: カレンダーリンク",
+ "replacementLabel": "置換テキスト",
+ "replacementPlaceholder": "トリガーを話したときに挿入されるテキスト…",
+ "create": "スニペットを作成",
+ "duplicate": "このトリガーのスニペットは既に存在します",
+ "emptyTitle": "同じことを言うのは",
+ "emptyTitleAccent": "一度だけ",
+ "emptyDescription": "トリガーワードを話すと、OpenWhisprが保存した内容に置き換えます。URL、自己紹介、署名、プロンプトなど。",
+ "new": "新規スニペット",
+ "examples": {
+ "linkedinTrigger": "私のLinkedIn",
+ "linkedinText": "linkedin.com/in/you",
+ "rewriteTrigger": "書き直しプロンプト",
+ "rewriteText": "これをより簡潔でプロフェッショナルに書き直して",
+ "introTrigger": "挨拶メール",
+ "introText": "こんにちは、今週どこかでお話しできれば嬉しいです…",
+ "signoffTrigger": "署名",
+ "signoffText": "よろしくお願いします。Alex · [email protected]"
+ },
+ "addPlaceholder": "トリガーフレーズを追加 — 「カレンダーリンク」「署名」など"
+ },
+ "emptyTitle": "辞書は空です",
+ "emptyDescription": "{{agentName}}に正しく認識してほしい言葉を追加しましょう。名前、ツール、略語など。",
+ "addFirstWord": "最初の単語を追加",
+ "importList": "リストをインポート",
+ "agentDefault": "デフォルトで追加済み"
},
"referral": {
"title": "紹介して特典をゲット",
diff --git a/src/locales/pt/translation.json b/src/locales/pt/translation.json
index 3b7329cd0..1ffe31540 100644
--- a/src/locales/pt/translation.json
+++ b/src/locales/pt/translation.json
@@ -2149,13 +2149,11 @@
"addWord": "Adicionar palavra",
"removeWord": "Remover {{word}}",
"clearAll": "Limpar tudo",
- "autoManaged": "Gerenciado automaticamente",
"clearTitle": "Limpar o dicionário?",
"clearDescription": "Isso removerá todas as palavras do seu dicionário personalizado. Esta ação não pode ser desfeita.",
- "addPlaceholder": "Digite uma palavra",
+ "addPlaceholder": "Adicione palavras separadas por vírgulas — OpenWhispr, Supabase, John Snow, ARR",
"add": "Adicionar",
"importWords": "Importar palavras",
- "separatorHint": "Separe com vírgulas — OpenWhispr, Supabase, John Snow, ARR",
"importPlaceholder": "Cole palavras separadas por vírgulas...",
"separateWithCommas": "Separe com vírgulas",
"wordsReady_one": "{{count}} palavra pronta",
@@ -2164,9 +2162,43 @@
"yourDictionary": "Seu dicionário",
"exportDictionary": "Exportar dicionário",
"exportFailed": "Falha ao exportar",
- "empty": "Nenhuma palavra ainda",
"editWord": "Editar {{word}}",
- "noMatches": "Nenhuma correspondência — pressione Enter para adicionar \"{{word}}\""
+ "noMatches": "Nenhuma correspondência — pressione Enter para adicionar \"{{word}}\"",
+ "tabDictionary": "Dicionário",
+ "tabSnippets": "Snippets",
+ "snippets": {
+ "title": "Snippets",
+ "edit": "Editar {{trigger}}",
+ "remove": "Remover {{trigger}}",
+ "editTitle": "Editar snippet",
+ "dialogDescription": "Quando você falar o gatilho, ele será substituído pelo seu texto salvo.",
+ "triggerLabel": "Gatilho",
+ "triggerPlaceholder": "ex.: minha agenda",
+ "replacementLabel": "Substituição",
+ "replacementPlaceholder": "Texto a inserir quando você disser o gatilho…",
+ "create": "Criar snippet",
+ "duplicate": "Já existe um snippet com esse gatilho",
+ "emptyTitle": "O que você não deveria ter que dizer",
+ "emptyTitleAccent": "duas vezes",
+ "emptyDescription": "Fale um gatilho e o OpenWhispr o substitui pelo que você salvou: URLs, introduções, assinaturas, prompts.",
+ "new": "Novo snippet",
+ "examples": {
+ "linkedinTrigger": "Meu LinkedIn",
+ "linkedinText": "linkedin.com/in/voce",
+ "rewriteTrigger": "Prompt de reescrita",
+ "rewriteText": "Reescreva isto para ficar mais conciso e profissional",
+ "introTrigger": "Email de apresentação",
+ "introText": "Olá, adoraria encontrar um horário para conversar esta semana…",
+ "signoffTrigger": "Assinatura",
+ "signoffText": "Abraços, Alex · [email protected]"
+ },
+ "addPlaceholder": "Adicione uma frase-gatilho — \"minha agenda\", \"meu LinkedIn\""
+ },
+ "emptyTitle": "Seu dicionário está vazio",
+ "emptyDescription": "Adicione palavras que {{agentName}} deve sempre acertar: nomes, ferramentas, siglas.",
+ "addFirstWord": "Adicione sua primeira palavra",
+ "importList": "Importar uma lista",
+ "agentDefault": "Adicionado por padrão"
},
"sidebar": {
"home": "Início",
diff --git a/src/locales/ru/translation.json b/src/locales/ru/translation.json
index d1b50ffb7..03812affa 100644
--- a/src/locales/ru/translation.json
+++ b/src/locales/ru/translation.json
@@ -2151,13 +2151,11 @@
"addWord": "Добавить слово",
"removeWord": "Удалить {{word}}",
"clearAll": "Очистить все",
- "autoManaged": "Имя агента (управляется автоматически)",
- "addPlaceholder": "Введите слово",
+ "addPlaceholder": "Добавьте слова через запятую — OpenWhispr, Supabase, John Snow, ARR",
"clearTitle": "Очистить словарь?",
"clearDescription": "Все слова будут удалены без возможности восстановления.",
"add": "Добавить",
"importWords": "Импортировать слова",
- "separatorHint": "Разделяйте запятыми — OpenWhispr, Supabase, John Snow, ARR",
"importPlaceholder": "Вставьте слова, разделённые запятыми...",
"separateWithCommas": "Разделяйте запятыми",
"wordsReady_one": "{{count}} слово готово",
@@ -2168,9 +2166,43 @@
"yourDictionary": "Ваш словарь",
"exportDictionary": "Экспортировать словарь",
"exportFailed": "Не удалось экспортировать",
- "empty": "Пока нет слов",
"editWord": "Изменить {{word}}",
- "noMatches": "Совпадений нет — нажмите Enter, чтобы добавить «{{word}}»"
+ "noMatches": "Совпадений нет — нажмите Enter, чтобы добавить «{{word}}»",
+ "tabDictionary": "Словарь",
+ "tabSnippets": "Сниппеты",
+ "snippets": {
+ "title": "Сниппеты",
+ "edit": "Изменить {{trigger}}",
+ "remove": "Удалить {{trigger}}",
+ "editTitle": "Изменить сниппет",
+ "dialogDescription": "Когда вы произносите триггер, он заменяется сохранённым текстом.",
+ "triggerLabel": "Триггер",
+ "triggerPlaceholder": "например, мой календарь",
+ "replacementLabel": "Замена",
+ "replacementPlaceholder": "Текст, который будет вставлен при произнесении триггера…",
+ "create": "Создать сниппет",
+ "duplicate": "Сниппет с таким триггером уже существует",
+ "emptyTitle": "То, что не нужно повторять",
+ "emptyTitleAccent": "дважды",
+ "emptyDescription": "Произнесите слово-триггер, и OpenWhispr заменит его сохранённым текстом: ссылки, приветствия, подписи, промпты.",
+ "new": "Новый сниппет",
+ "examples": {
+ "linkedinTrigger": "Мой LinkedIn",
+ "linkedinText": "linkedin.com/in/you",
+ "rewriteTrigger": "Промпт для переписывания",
+ "rewriteText": "Перепиши это более кратко и профессионально",
+ "introTrigger": "Вступительное письмо",
+ "introText": "Привет, буду рад найти время пообщаться на этой неделе…",
+ "signoffTrigger": "Подпись",
+ "signoffText": "С уважением, Алекс · [email protected]"
+ },
+ "addPlaceholder": "Добавьте фразу-триггер — «мой календарь», «мой LinkedIn»"
+ },
+ "emptyTitle": "Ваш словарь пуст",
+ "emptyDescription": "Добавьте слова, которые {{agentName}} всегда должен распознавать: имена, инструменты, аббревиатуры.",
+ "addFirstWord": "Добавьте первое слово",
+ "importList": "Импортировать список",
+ "agentDefault": "Добавлено по умолчанию"
},
"sidebar": {
"home": "Главная",
diff --git a/src/locales/zh-CN/translation.json b/src/locales/zh-CN/translation.json
index f91e89e7a..f21e6abbc 100644
--- a/src/locales/zh-CN/translation.json
+++ b/src/locales/zh-CN/translation.json
@@ -2144,13 +2144,11 @@
"addWord": "添加词语",
"removeWord": "移除 {{word}}",
"clearAll": "全部清除",
- "autoManaged": "助手名称(自动管理)",
"clearTitle": "清空词典?",
"clearDescription": "这将删除自定义词典中的所有词汇,此操作无法撤销。",
- "addPlaceholder": "输入词语",
+ "addPlaceholder": "用逗号分隔添加多个词——OpenWhispr、Supabase、ARR",
"add": "添加",
"importWords": "导入词语",
- "separatorHint": "用逗号分隔 — OpenWhispr, Supabase, John Snow, ARR",
"importPlaceholder": "粘贴以逗号分隔的词语...",
"separateWithCommas": "用逗号分隔",
"wordsReady_other": "{{count}} 个词语就绪",
@@ -2158,10 +2156,44 @@
"yourDictionary": "你的词典",
"exportDictionary": "导出词典",
"exportFailed": "导出失败",
- "empty": "暂无词语",
"editWord": "编辑 {{word}}",
"wordsReady_one": "{{count}} 个词语就绪",
- "noMatches": "无匹配项 — 按 Enter 添加“{{word}}”"
+ "noMatches": "无匹配项 — 按 Enter 添加“{{word}}”",
+ "tabDictionary": "词典",
+ "tabSnippets": "片段",
+ "snippets": {
+ "title": "片段",
+ "edit": "编辑 {{trigger}}",
+ "remove": "删除 {{trigger}}",
+ "editTitle": "编辑片段",
+ "dialogDescription": "当你说出触发词时,它会被替换为你保存的文本。",
+ "triggerLabel": "触发词",
+ "triggerPlaceholder": "例如:我的日程链接",
+ "replacementLabel": "替换文本",
+ "replacementPlaceholder": "说出触发词时插入的文本…",
+ "create": "创建片段",
+ "duplicate": "已存在使用此触发词的片段",
+ "emptyTitle": "同样的话,只说",
+ "emptyTitleAccent": "一遍",
+ "emptyDescription": "说出触发词,OpenWhispr 会把它替换为你保存的内容:链接、开场白、签名、提示词。",
+ "new": "新建片段",
+ "examples": {
+ "linkedinTrigger": "我的 LinkedIn",
+ "linkedinText": "linkedin.com/in/you",
+ "rewriteTrigger": "改写提示词",
+ "rewriteText": "把这段话改写得更简洁、更专业",
+ "introTrigger": "开场邮件",
+ "introText": "你好,希望本周能找个时间聊聊…",
+ "signoffTrigger": "签名",
+ "signoffText": "祝好,Alex · [email protected]"
+ },
+ "addPlaceholder": "添加触发词——“我的日程链接”“签名”"
+ },
+ "emptyTitle": "你的词典是空的",
+ "emptyDescription": "添加希望{{agentName}}始终识别正确的词:名字、工具、缩写。",
+ "addFirstWord": "添加第一个词",
+ "importList": "导入列表",
+ "agentDefault": "默认添加"
},
"sidebar": {
"home": "首页",
diff --git a/src/locales/zh-TW/translation.json b/src/locales/zh-TW/translation.json
index e817078b0..35c590854 100644
--- a/src/locales/zh-TW/translation.json
+++ b/src/locales/zh-TW/translation.json
@@ -2144,13 +2144,11 @@
"addWord": "新增詞語",
"removeWord": "移除 {{word}}",
"clearAll": "全部清除",
- "autoManaged": "助理名稱(自動管理)",
"clearTitle": "清空字典?",
"clearDescription": "這將移除自訂字典中的所有詞彙。此操作無法復原。",
- "addPlaceholder": "輸入詞語",
+ "addPlaceholder": "用逗號分隔新增多個詞——OpenWhispr、Supabase、ARR",
"add": "新增",
"importWords": "匯入詞語",
- "separatorHint": "用逗號分隔 — OpenWhispr, Supabase, John Snow, ARR",
"importPlaceholder": "貼上以逗號分隔的詞語...",
"separateWithCommas": "用逗號分隔",
"wordsReady_other": "{{count}} 個詞語就緒",
@@ -2158,10 +2156,44 @@
"yourDictionary": "你的詞典",
"exportDictionary": "匯出詞典",
"exportFailed": "匯出失敗",
- "empty": "尚無詞語",
"editWord": "編輯 {{word}}",
"wordsReady_one": "{{count}} 個詞語就緒",
- "noMatches": "無相符項目 — 按 Enter 新增「{{word}}」"
+ "noMatches": "無相符項目 — 按 Enter 新增「{{word}}」",
+ "tabDictionary": "字典",
+ "tabSnippets": "片段",
+ "snippets": {
+ "title": "片段",
+ "edit": "編輯 {{trigger}}",
+ "remove": "刪除 {{trigger}}",
+ "editTitle": "編輯片段",
+ "dialogDescription": "當你說出觸發詞時,它會被替換為你儲存的文字。",
+ "triggerLabel": "觸發詞",
+ "triggerPlaceholder": "例如:我的行事曆連結",
+ "replacementLabel": "替換文字",
+ "replacementPlaceholder": "說出觸發詞時插入的文字…",
+ "create": "建立片段",
+ "duplicate": "已存在使用此觸發詞的片段",
+ "emptyTitle": "同樣的話,只說",
+ "emptyTitleAccent": "一遍",
+ "emptyDescription": "說出觸發詞,OpenWhispr 會把它替換為你儲存的內容:連結、開場白、簽名、提示詞。",
+ "new": "建立片段",
+ "examples": {
+ "linkedinTrigger": "我的 LinkedIn",
+ "linkedinText": "linkedin.com/in/you",
+ "rewriteTrigger": "改寫提示詞",
+ "rewriteText": "把這段話改寫得更簡潔、更專業",
+ "introTrigger": "開場郵件",
+ "introText": "你好,希望本週能找個時間聊聊…",
+ "signoffTrigger": "簽名",
+ "signoffText": "祝好,Alex · [email protected]"
+ },
+ "addPlaceholder": "新增觸發詞——「我的行事曆連結」「簽名」"
+ },
+ "emptyTitle": "你的字典是空的",
+ "emptyDescription": "新增希望{{agentName}}始終辨識正確的詞:名字、工具、縮寫。",
+ "addFirstWord": "新增第一個詞",
+ "importList": "匯入清單",
+ "agentDefault": "預設加入"
},
"sidebar": {
"home": "首頁",
diff --git a/src/services/BaseReasoningService.ts b/src/services/BaseReasoningService.ts
index 31981032a..0be1579f1 100644
--- a/src/services/BaseReasoningService.ts
+++ b/src/services/BaseReasoningService.ts
@@ -1,5 +1,6 @@
import { getCleanupSystemPrompt } from "../config/prompts";
import { getSettings } from "../stores/settingsStore";
+import { getDictionaryHintWords } from "../utils/snippets";
export interface ReasoningConfig {
maxTokens?: number;
@@ -17,7 +18,7 @@ export abstract class BaseReasoningService {
protected isProcessing = false;
protected getCustomDictionary(): string[] {
- return getSettings().customDictionary;
+ return getDictionaryHintWords(getSettings());
}
protected getPreferredLanguage(): string {
diff --git a/src/stores/settingsStore.ts b/src/stores/settingsStore.ts
index 30b809401..67b182b18 100644
--- a/src/stores/settingsStore.ts
+++ b/src/stores/settingsStore.ts
@@ -24,6 +24,7 @@ import type {
ThemeSettings,
ChatAgentSettings,
} from "../hooks/useSettings";
+import type { Snippet } from "../utils/snippets";
let _ReasoningService: typeof import("../services/ReasoningService").default | null = null;
@@ -139,7 +140,7 @@ const BOOLEAN_SETTINGS = new Set([
"gcalPrimaryOnly",
]);
-const ARRAY_SETTINGS = new Set(["customDictionary", "gcalAccounts"]);
+const ARRAY_SETTINGS = new Set(["customDictionary", "snippets", "gcalAccounts"]);
const NUMERIC_SETTINGS = new Set([
"audioRetentionDays",
@@ -480,6 +481,7 @@ export interface SettingsState
setCleanupCloudMode: (value: string) => void;
setCleanupCloudBaseUrl: (value: string) => void;
setCustomDictionary: (words: string[]) => void;
+ setSnippets: (snippets: Snippet[]) => void;
setAssemblyAiStreaming: (value: boolean) => void;
setAutoGenerateNoteTitle: (value: boolean) => void;
setUseCleanupModel: (value: boolean) => void;
@@ -726,6 +728,14 @@ export const useSettingsStore = create<SettingsState>()((set, get) => ({
cortiEnvironment: readString("cortiEnvironment", "us"),
cortiTenant: readString("cortiTenant", "base"),
customDictionary: readStringArray("customDictionary", []),
+ snippets: (() => {
+ try {
+ const parsed = JSON.parse(readString("snippets", "[]"));
+ return Array.isArray(parsed) ? (parsed as Snippet[]) : [];
+ } catch {
+ return [];
+ }
+ })(),
assemblyAiStreaming: readBoolean("assemblyAiStreaming", true),
autoGenerateNoteTitle: readBoolean("autoGenerateNoteTitle", true),
@@ -1052,6 +1062,11 @@ export const useSettingsStore = create<SettingsState>()((set, get) => ({
});
},
+ setSnippets: (snippets: Snippet[]) => {
+ if (isBrowser) localStorage.setItem("snippets", JSON.stringify(snippets));
+ set({ snippets });
+ },
+
setUiLanguage: (language: string) => {
const normalized = normalizeUiLanguage(language);
if (isBrowser) localStorage.setItem("uiLanguage", normalized);
@@ -1458,6 +1473,7 @@ export const useSettingsStore = create<SettingsState>()((set, get) => ({
if (settings.cloudTranscriptionMode !== undefined)
s.setCloudTranscriptionMode(settings.cloudTranscriptionMode);
if (settings.customDictionary !== undefined) s.setCustomDictionary(settings.customDictionary);
+ if (settings.snippets !== undefined) s.setSnippets(settings.snippets);
if (settings.assemblyAiStreaming !== undefined)
s.setAssemblyAiStreaming(settings.assemblyAiStreaming);
if (settings.showTranscriptionPreview !== undefined)
diff --git a/src/utils/snippets.ts b/src/utils/snippets.ts
new file mode 100644
index 000000000..fb4e67443
--- /dev/null
+++ b/src/utils/snippets.ts
@@ -0,0 +1,60 @@
+export interface Snippet {
+ trigger: string;
+ replacement: string;
+}
+
+interface SnippetMatcher {
+ regex: RegExp;
+ replacements: Map<string, string>;
+}
+
+let cachedSnippets: Snippet[] | null = null;
+let cachedMatcher: SnippetMatcher | null = null;
+
+function buildMatcher(snippets: Snippet[]): SnippetMatcher | null {
+ const replacements = new Map<string, string>();
+ for (const { trigger, replacement } of snippets) {
+ const key = trigger.trim().toLowerCase();
+ if (key) replacements.set(key, replacement);
+ }
+ if (replacements.size === 0) return null;
+
+ // Longest-first so "investor ask" wins over a shorter "ask" trigger.
+ const escaped = [...replacements.keys()]
+ .sort((a, b) => b.length - a.length)
+ .map((t) => t.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"));
+ // Unicode-aware word boundaries — triggers never match inside a word.
+ const regex = new RegExp(
+ `(?<=^|[\\s\\p{P}\\p{S}])(?:${escaped.join("|")})(?=$|[\\s\\p{P}\\p{S}])`,
+ "giu"
+ );
+ return { regex, replacements };
+}
+
+/**
+ * Replace every spoken trigger with its saved text in a single pass. The
+ * matcher is memoized against the snippets array reference (the settings
+ * store replaces the array on every change).
+ */
+export function expandSnippets(text: string, snippets: Snippet[]): string {
+ if (!text || snippets.length === 0) return text;
+ if (snippets !== cachedSnippets) {
+ cachedSnippets = snippets;
+ cachedMatcher = buildMatcher(snippets);
+ }
+ if (!cachedMatcher) return text;
+ const { regex, replacements } = cachedMatcher;
+ return text.replace(regex, (match) => replacements.get(match.toLowerCase()) ?? match);
+}
+
+/**
+ * Dictionary words plus snippet triggers — the hint list fed to the STT
+ * prompt and cleanup-model dictionary suffix so triggers survive both.
+ */
+export function getDictionaryHintWords(settings: {
+ customDictionary: string[];
+ snippets: Snippet[];
+}): string[] {
+ if (settings.snippets.length === 0) return settings.customDictionary;
+ return [...settings.customDictionary, ...settings.snippets.map((s) => s.trigger)];
+}