Skip to content

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

fix(agent): ignore wake words inside snippet triggers (#2153)

Chad Pihaeae26c40fe76
diff --git a/src/config/agentDetection.ts b/src/config/agentDetection.ts
index b4de78278..4e951b283 100644
--- a/src/config/agentDetection.ts
+++ b/src/config/agentDetection.ts
@@ -1,4 +1,9 @@
import { getBaseLanguageCode } from "../utils/languageSupport";
+import {
+ findSnippetTriggerRanges,
+ type Snippet,
+ type SnippetTriggerRange,
+} from "../utils/snippets";
function levenshteinDistance(a: string, b: string): number {
const m = a.length;
@@ -74,16 +79,68 @@ const LATIN_TO_CJK_RE = new RegExp(`([A-Za-z0-9])(?=[${CJK_CHAR_RANGE}])`, "g");
const TOKEN_PUNCTUATION_RE = /[.,!?;:'"()،؛؟]/g;
const SEPARATE_ADDRESS_PUNCTUATION = new Set([",", "،"]);
-function normalizeCjkTranscript(transcript: string, agentName: string): string {
+interface NormalizedTranscript {
+ text: string;
+ /** For each character of `text`, the index it came from in the NFC transcript. */
+ origin: number[];
+}
+
+/** Output character `i` of the replacement came from `offsets[i]` within the match. */
+type TrackedReplacer = (match: string) => [replacement: string, offsets: number[]];
+
+const identityOffsets = (value: string): number[] =>
+ Array.from({ length: value.length }, (_, index) => index);
+
+// Replaces like String#replace, but carries every output character's origin
+// along, so a span of the normalized text can be measured against snippet
+// ranges found in the transcript the user actually spoke.
+function replaceTracked(
+ input: NormalizedTranscript,
+ regex: RegExp,
+ replacer: TrackedReplacer
+): NormalizedTranscript {
+ let text = "";
+ const origin: number[] = [];
+ let copied = 0;
+ const copyThrough = (until: number) => {
+ text += input.text.slice(copied, until);
+ for (let i = copied; i < until; i++) origin.push(input.origin[i]);
+ };
+
+ for (const match of input.text.matchAll(regex)) {
+ copyThrough(match.index);
+ const [replacement, offsets] = replacer(match[0]);
+ text += replacement;
+ for (const offset of offsets) origin.push(input.origin[match.index + offset]);
+ copied = match.index + match[0].length;
+ }
+ copyThrough(input.text.length);
+ return { text, origin };
+}
+
+// Splitting a CJK/Latin run adds a space that belongs to the character before it.
+const splitAfterMatch: TrackedReplacer = (match) => [`${match} `, [0, 0]];
+
+function normalizeCjkTranscript(nfcTranscript: string, agentName: string): NormalizedTranscript {
const escapedName = agentName.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
const agentNamePattern = new RegExp(escapedName, "giu");
- return transcript
- .normalize("NFC")
- .replace(agentNamePattern, " $& ")
- .replace(CJK_PUNCTUATION_RE, (ch) => CJK_PUNCTUATION_MAP[ch] ?? ch)
- .replace(CJK_TO_LATIN_RE, "$1 ")
- .replace(LATIN_TO_CJK_RE, "$1 ");
+ let result: NormalizedTranscript = {
+ text: nfcTranscript,
+ origin: identityOffsets(nfcTranscript),
+ };
+ // The name keeps its own origins, so a candidate spanning it still measures
+ // its true width against a trigger range.
+ result = replaceTracked(result, agentNamePattern, (match) => [
+ ` ${match} `,
+ [0, ...identityOffsets(match), match.length - 1],
+ ]);
+ result = replaceTracked(result, CJK_PUNCTUATION_RE, (ch) => {
+ const mapped = CJK_PUNCTUATION_MAP[ch] ?? ch;
+ return [mapped, new Array<number>(mapped.length).fill(0)];
+ });
+ result = replaceTracked(result, CJK_TO_LATIN_RE, splitAfterMatch);
+ return replaceTracked(result, LATIN_TO_CJK_RE, splitAfterMatch);
}
// Cues gate on a resolved language; "auto", unknown codes and junk fail closed
@@ -109,6 +166,15 @@ function isAddressedAt(
return /[.!?…]["')\]]*$/.test(rawWords[index - 1]);
}
+// A snippet trigger is a phrase the user reserved for expansion, so a name
+// inside one is the trigger being spoken, not the agent being addressed. The
+// window has to be *contained*: candidates span up to maxSpan tokens to absorb
+// STT splitting the name, so a window that merely clips a trigger ("open" out
+// of "open whispr summarize this") is still a real address.
+function insideTrigger(start: number, end: number, ranges: SnippetTriggerRange[]): boolean {
+ return ranges.some((range) => range.start <= start && end <= range.end);
+}
+
interface AgentAddress {
/** Index of the first raw word to drop (the cue, when one precedes the name). */
start: number;
@@ -121,7 +187,8 @@ interface AgentAddress {
function locateAgentAddress(
transcript: string,
agentName: string,
- language?: string
+ language?: string,
+ snippets?: Snippet[] | null
): AgentAddress | null {
const name = agentName.trim();
if (!name || name.length < 2) return null;
@@ -130,11 +197,26 @@ function locateAgentAddress(
const localizedCues = (base && LOCALIZED_CUE_SETS.get(base)) || EMPTY_CUES;
const normalizeCjk = base === "ja" || base === "zh";
const detectionName = normalizeCjk ? name.normalize("NFC") : name;
- const source = normalizeCjk ? normalizeCjkTranscript(transcript, detectionName) : transcript;
+ // Snippet ranges and the normalized text share this frame, so a candidate
+ // span in `source` can be mapped back onto a range.
+ const rangeSource = normalizeCjk ? transcript.normalize("NFC") : transcript;
+ const normalized = normalizeCjk ? normalizeCjkTranscript(rangeSource, detectionName) : null;
+ const source = normalized ? normalized.text : transcript;
const nameLower = detectionName.toLowerCase().replace(/\s+/g, "");
- const rawWords = source.split(/\s+/).filter(Boolean);
+ // Tokenize with offsets so candidates can be tested against trigger ranges.
+ const tokens = [...source.matchAll(/\S+/g)];
+ const rawWords = tokens.map((token) => token[0]);
+ const wordStarts = tokens.map((token) => token.index);
const words = rawWords.map((w) => w.replace(TOKEN_PUNCTUATION_RE, "").toLowerCase());
+ // Triggers are matched against the transcript as spoken: CJK normalization
+ // both splits a trigger that contains the name and manufactures the word
+ // boundaries a glued-together one lacks, so ranges taken from `source` would
+ // miss real triggers and invent absent ones. Candidate spans map back instead.
+ const originAt = normalized
+ ? (index: number) => normalized.origin[index]
+ : (index: number) => index;
+ const triggerRanges = findSnippetTriggerRanges(rangeSource, snippets);
const maxEdits = maxEditsForLength(nameLower.length);
// STT may split the name across tokens ("open whispr") or mishear it, so
@@ -143,16 +225,23 @@ function locateAgentAddress(
const maxSpan = Math.max(2, detectionName.split(/\s+/).length);
for (let i = 0; i < words.length; i++) {
+ const cueBefore = i > 0 && (VOCATIVE_CUES.has(words[i - 1]) || localizedCues.has(words[i - 1]));
let joined = "";
for (let span = 0; span < maxSpan && i + span < words.length; span++) {
joined += words[i + span];
if (Math.abs(joined.length - nameLower.length) > maxEdits) continue;
if (
levenshteinDistance(joined, nameLower) <= maxEdits &&
+ // A cue names the agent outright, so it outranks a trigger the words
+ // happen to span; without one the trigger the user configured wins.
+ (cueBefore ||
+ !insideTrigger(
+ originAt(wordStarts[i]),
+ originAt(wordStarts[i + span] + rawWords[i + span].length - 1) + 1,
+ triggerRanges
+ )) &&
isAddressedAt(i, words, rawWords, localizedCues)
) {
- const cueBefore =
- i > 0 && (VOCATIVE_CUES.has(words[i - 1]) || localizedCues.has(words[i - 1]));
const nameEnd = i + span + 1;
const addressEnd = SEPARATE_ADDRESS_PUNCTUATION.has(rawWords[nameEnd])
? nameEnd + 1
@@ -165,8 +254,13 @@ function locateAgentAddress(
return null;
}
-export function detectAgentName(transcript: string, agentName: string, language?: string): boolean {
- return locateAgentAddress(transcript, agentName, language) !== null;
+export function detectAgentName(
+ transcript: string,
+ agentName: string,
+ language?: string,
+ snippets?: Snippet[] | null
+): boolean {
+ return locateAgentAddress(transcript, agentName, language, snippets) !== null;
}
/**
@@ -178,9 +272,10 @@ export function detectAgentName(transcript: string, agentName: string, language?
export function stripAgentAddress(
transcript: string,
agentName: string,
- language?: string
+ language?: string,
+ snippets?: Snippet[] | null
): string {
- const address = locateAgentAddress(transcript, agentName, language);
+ const address = locateAgentAddress(transcript, agentName, language, snippets);
if (!address) return transcript;
const { rawWords, start, end } = address;
const remaining = [...rawWords.slice(0, start), ...rawWords.slice(end)].join(" ").trim();
diff --git a/src/helpers/audioManager.js b/src/helpers/audioManager.js
index 9ff3cce1f..5f38dba19 100644
--- a/src/helpers/audioManager.js
+++ b/src/helpers/audioManager.js
@@ -218,7 +218,9 @@ function resolveReasoningRoute(
agentReachable: agent.reachable,
// A translation recording never routes to the agent, so skip the scan.
agentInvoked:
- !translationRequested && !!agentName && detectAgentName(text, agentName, wakeWordLanguage),
+ !translationRequested &&
+ !!agentName &&
+ detectAgentName(text, agentName, wakeWordLanguage, settings.snippets),
voiceAgentRequested,
translationRequested,
translationReachable: translation.reachable,
@@ -301,8 +303,10 @@ function resolveReasoningRoute(
// reachable; standalone commands resolve the same scope again in the
// panel and report their own configuration problems in-conversation.
selectionEditReachable: agent.reachable,
- // Detection and stripping must resolve auto-language identically.
+ // Detection and stripping must read the transcript identically, so both
+ // inputs ride the route rather than being re-read after the await.
wakeWordLanguage,
+ snippets: settings.snippets,
// The panel re-decides attach/drop for its own request, so carry the
// raw screenshot past this attach gate for that path.
...(screenContext ? { rawScreenContext: screenContext } : {}),
@@ -2622,12 +2626,14 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);
{ selectedContext, selectedText, deliverySessionId } = {}
) {
this.assertAgentAllowedByPolicy();
+ const settings = getSettings();
const command = this.voiceAgentRequested
? text
: stripAgentAddress(
text,
agentName,
- config?.wakeWordLanguage ?? resolveWakeWordLanguage(getSettings())
+ config?.wakeWordLanguage ?? resolveWakeWordLanguage(settings),
+ config?.snippets ?? settings.snippets
);
const transcript = selectedText === undefined ? command : `${command}\n\n"${selectedText}"`;
this._bankAssistantDirective(transcript, config, { selectedContext, deliverySessionId });
diff --git a/src/utils/snippets.ts b/src/utils/snippets.ts
index 8572c6d53..c07186e55 100644
--- a/src/utils/snippets.ts
+++ b/src/utils/snippets.ts
@@ -11,6 +11,13 @@ interface SnippetMatcher {
replacements: Map<string, string>;
}
+export interface SnippetTriggerRange {
+ /** Index of the trigger's first character. */
+ start: number;
+ /** Index one past the trigger's last character. */
+ end: number;
+}
+
let cachedSnippets: Snippet[] | null = null;
let cachedMatcher: SnippetMatcher | null = null;
@@ -50,29 +57,63 @@ function buildMatcher(snippets: Snippet[]): SnippetMatcher | null {
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[] | null): string {
- if (!text || !Array.isArray(snippets) || snippets.length === 0) return text;
+// Memoized against the snippets array reference (the settings store replaces
+// the array on every change).
+function getMatcher(snippets?: Snippet[] | null): SnippetMatcher | null {
+ if (!Array.isArray(snippets) || snippets.length === 0) return null;
if (snippets !== cachedSnippets) {
cachedSnippets = snippets;
cachedMatcher = buildMatcher(snippets);
}
- if (!cachedMatcher) return text;
- const { regex, replacements } = cachedMatcher;
+ return cachedMatcher;
+}
+
+// The pattern case-folds the Unicode way (/iu) while the keys are toLowerCase'd,
+// so a match is not proof of a replacement: "[ıI]mza" matches a plain "imza",
+// which is no key at all. Both callers resolve through here, so a reported range
+// always means an expansion — wake-word suppression depends on it.
+function resolveReplacement(match: string, replacements: Map<string, string>): string | undefined {
+ const folded = foldCapitalIDot(match);
+ return (
+ replacements.get(folded.toLowerCase()) ??
+ // An uppercase I can be capital dotless ı as well as English i.
+ replacements.get(folded.replace(/I/g, "ı").toLowerCase())
+ );
+}
+
+/**
+ * Character ranges of every trigger occurrence, matched against `text` exactly
+ * as given so the offsets index that same string. Wake-word detection uses
+ * these to ignore an agent name that only appears because it opens a trigger
+ * the user chose, such as "openwhispr review" (see `agentDetection`).
+ */
+export function findSnippetTriggerRanges(
+ text: string,
+ snippets?: Snippet[] | null
+): SnippetTriggerRange[] {
+ if (!text) return [];
+ const matcher = getMatcher(snippets);
+ if (!matcher) return [];
+ return [...text.matchAll(matcher.regex)]
+ .filter((match) => resolveReplacement(match[0], matcher.replacements) !== undefined)
+ .map((match) => ({
+ start: match.index,
+ end: match.index + match[0].length,
+ }));
+}
+
+/**
+ * Replace every spoken trigger with its saved text in a single pass.
+ */
+export function expandSnippets(text: string, snippets?: Snippet[] | null): string {
+ if (!text) return text;
+ const matcher = getMatcher(snippets);
+ if (!matcher) return text;
+ const { regex, replacements } = matcher;
// NFC so a decomposed "I" + U+0307 in the transcript recombines into İ.
- return text.normalize("NFC").replace(regex, (match) => {
- const folded = foldCapitalIDot(match);
- return (
- replacements.get(folded.toLowerCase()) ??
- // An uppercase I can be capital dotless ı as well as English i.
- replacements.get(folded.replace(/I/g, "ı").toLowerCase()) ??
- match
- );
- });
+ return text
+ .normalize("NFC")
+ .replace(regex, (match) => resolveReplacement(match, replacements) ?? match);
}
/**
diff --git a/test/helpers/agentDetection.test.js b/test/helpers/agentDetection.test.js
index 198dcc1d6..b60b5d3c4 100644
--- a/test/helpers/agentDetection.test.js
+++ b/test/helpers/agentDetection.test.js
@@ -253,3 +253,150 @@ test("every locale's advertised wake phrase triggers detection in its language",
);
}
});
+
+// A snippet trigger is a phrase the snippet feature owns. When it happens to
+// start with the agent name ("openwhispr review"), the wake-word scan used to
+// read it as an address and hijack an ordinary dictation into the agent.
+test("a name inside a snippet trigger is not an address", async () => {
+ const { detectAgentName } = await load();
+ const snippets = [{ trigger: "openwhispr review", replacement: "Review the PR" }];
+
+ assert.equal(
+ detectAgentName("openwhispr review this PR", "OpenWhispr", undefined, snippets),
+ false
+ );
+ assert.equal(
+ detectAgentName("That's done. openwhispr review this PR", "OpenWhispr", undefined, snippets),
+ false
+ );
+});
+
+test("a real address still counts when the dictation also uses a snippet trigger", async () => {
+ const { detectAgentName } = await load();
+ const snippets = [{ trigger: "openwhispr review", replacement: "Review the PR" }];
+
+ assert.equal(
+ detectAgentName(
+ "Hey OpenWhispr, run openwhispr review on PR 5",
+ "OpenWhispr",
+ undefined,
+ snippets
+ ),
+ true
+ );
+});
+
+test("stripAgentAddress removes the real address, not the snippet trigger", async () => {
+ const { stripAgentAddress } = await load();
+ const snippets = [{ trigger: "openwhispr review", replacement: "Review the PR" }];
+
+ assert.equal(
+ stripAgentAddress(
+ "openwhispr review. OpenWhispr summarize it",
+ "OpenWhispr",
+ undefined,
+ snippets
+ ),
+ "openwhispr review. summarize it"
+ );
+ assert.equal(
+ stripAgentAddress("openwhispr review this PR", "OpenWhispr", undefined, snippets),
+ "openwhispr review this PR",
+ "no address left once the trigger is excluded"
+ );
+});
+
+test("characterization: a trigger equal to the agent name shadows the bare wake word", async () => {
+ const { detectAgentName } = await load();
+ // Excluding trigger spans has a cost: a snippet whose trigger is the bare
+ // agent name shadows the wake word whenever it is spoken without a cue.
+ // Expanding the snippet the user explicitly configured is the better of the
+ // two, but flip this deliberately (e.g. by warning about the collision when a
+ // snippet is saved).
+ const snippets = [{ trigger: "Jarvis", replacement: "J.A.R.V.I.S." }];
+
+ assert.equal(detectAgentName("Jarvis take a note", "Jarvis", undefined, snippets), false);
+ // A cue still reaches the agent, so the wake word is never wholly unreachable.
+ assert.equal(detectAgentName("Hey Jarvis take a note", "Jarvis", undefined, snippets), true);
+});
+
+test("characterization: a decomposed trigger falls back to firing the agent", async () => {
+ const { detectAgentName } = await load();
+ // Range-finding matches the transcript exactly as given, because the offsets
+ // have to index the string the locator tokenizes; expandSnippets normalizes to
+ // NFC first. A decomposed trigger therefore stays invisible here and keeps the
+ // pre-fix behavior — the safe direction, since it never suppresses a real
+ // wake word.
+ const snippets = [{ trigger: "İmza", replacement: "Best regards" }];
+
+ assert.equal(detectAgentName("İmza send it".normalize("NFD"), "İmza", undefined, snippets), true);
+});
+
+// A candidate window spans up to maxSpan tokens so STT splitting the name
+// ("open whispr") still matches. Only a window the trigger fully contains is
+// the trigger being spoken; one that merely clips a trigger is a real address.
+test("a trigger clipping part of a split name does not suppress the address", async () => {
+ const { detectAgentName, stripAgentAddress } = await load();
+ const snippets = [{ trigger: "open", replacement: "OPEN" }];
+
+ assert.equal(
+ detectAgentName("open whispr summarize this", "OpenWhispr", undefined, snippets),
+ true
+ );
+ assert.equal(
+ stripAgentAddress("open whispr summarize this", "OpenWhispr", undefined, snippets),
+ "summarize this"
+ );
+});
+
+// "Hey" before the name is the same evidence of address the wake word already
+// relies on, and the two failures are not symmetric: a wrongly-opened panel is
+// visible and dismissable, while a wrongly-expanded snippet types the user's
+// command into their document. The cue wins.
+test("an explicit cue outranks a trigger the address happens to span", async () => {
+ const { detectAgentName, stripAgentAddress } = await load();
+ const snippets = [{ trigger: "openwhispr review", replacement: "Review the PR" }];
+
+ assert.equal(
+ detectAgentName("Hey OpenWhispr review this PR", "OpenWhispr", undefined, snippets),
+ true
+ );
+ assert.equal(
+ stripAgentAddress("Hey OpenWhispr review this PR", "OpenWhispr", undefined, snippets),
+ "review this PR"
+ );
+ // No cue, so the trigger still wins — the reported bug stays fixed.
+ assert.equal(
+ detectAgentName("openwhispr review this PR", "OpenWhispr", undefined, snippets),
+ false
+ );
+});
+
+// Dictation set to auto with a provider that reports no language falls back to
+// the UI language, so an English transcript reaches the CJK branch whenever the
+// app is in Japanese or Chinese. The trigger exclusion has to survive it.
+test("a name inside a snippet trigger is not an address under CJK normalization", async () => {
+ const { detectAgentName } = await load();
+ const snippets = [{ trigger: "openwhispr review", replacement: "Review the PR" }];
+
+ for (const language of ["ja", "zh", "zh-CN", "zh-TW"]) {
+ assert.equal(
+ detectAgentName("openwhispr review this PR", "OpenWhispr", language, snippets),
+ false,
+ language
+ );
+ }
+});
+
+// Japanese runs the words together, so a bare-name trigger cannot match the
+// transcript the user actually spoke. Normalization splits the name out with
+// spaces for cue matching, and those spaces must not manufacture the word
+// boundaries that would make the trigger match — suppressing the wake word for
+// a snippet that then never expands costs the user both.
+test("CJK normalization does not invent a trigger the transcript never had", async () => {
+ const { detectAgentName } = await load();
+ const snippets = [{ trigger: "Jarvis", replacement: "J.A.R.V.I.S." }];
+
+ assert.equal(detectAgentName("Jarvis明日の予定は", "Jarvis", "ja", snippets), true);
+ assert.equal(detectAgentName("Jarvis总结这条笔记", "Jarvis", "zh", snippets), true);
+});
diff --git a/test/helpers/audioManagerWakeWordLanguage.test.js b/test/helpers/audioManagerWakeWordLanguage.test.js
index cba4ebde3..c7c82f9a4 100644
--- a/test/helpers/audioManagerWakeWordLanguage.test.js
+++ b/test/helpers/audioManagerWakeWordLanguage.test.js
@@ -331,3 +331,94 @@ test("streaming auto-language routing detects and strips Arabic with an English
assert.equal(completions[0]?.assistantConversation?.transcript, "لخّص هذه الملاحظة");
});
+
+// Snippet triggers are phrases the user reserves for expansion, and they are
+// free to start one with the agent's own name ("jarvis review"). Routing runs
+// on the raw transcript — expansion happens later, in the renderer — so without
+// trigger-aware detection the wake-word scan reads the leading name as an
+// address and sends an ordinary dictation to the agent.
+const snippetSettings = {
+ preferredLanguage: "en",
+ useCleanupModel: true,
+ cleanupCloudMode: "byok",
+ cleanupDisableThinking: false,
+ customDictionary: [],
+ snippets: [{ trigger: "jarvis review", replacement: "Review the PR below." }],
+};
+
+const snippetAudioBlob = {
+ type: "audio/webm",
+ size: 1024,
+ arrayBuffer: async () => new ArrayBuffer(8),
+};
+
+test("a name inside a snippet trigger does not route to the agent", async (t) => {
+ const { window, setSettings, createManager } = await loadAudioManager(t);
+
+ setSettings(snippetSettings);
+ window.electronAPI.cloudTranscribe = async () => ({
+ success: true,
+ text: "jarvis review this PR",
+ sttLanguage: "en",
+ });
+
+ const result = await createManager().processWithOpenWhisprCloud(snippetAudioBlob);
+
+ assert.equal(result.text, "cleanup output");
+});
+
+test("a real address still routes to the agent when a trigger is also spoken", async (t) => {
+ const { window, setSettings, createManager } = await loadAudioManager(t);
+
+ setSettings(snippetSettings);
+ window.electronAPI.cloudTranscribe = async () => ({
+ success: true,
+ text: "Hey Jarvis, run jarvis review on PR 5",
+ sttLanguage: "en",
+ });
+
+ const result = await createManager().processWithOpenWhisprCloud(snippetAudioBlob);
+
+ assert.equal(result.text, "agent output");
+});
+
+test("the banked agent command drops the address, not the snippet trigger", async (t) => {
+ const { window, setSettings, createBankingManager } = await loadAudioManager(t);
+
+ setSettings(snippetSettings);
+ window.electronAPI.cloudTranscribe = async () => ({
+ success: true,
+ text: "jarvis review. Jarvis summarize it",
+ sttLanguage: "en",
+ });
+
+ const manager = createBankingManager();
+ await manager.processWithOpenWhisprCloud(snippetAudioBlob);
+
+ assert.equal(manager.pendingAssistantConversation?.transcript, "jarvis review. summarize it");
+});
+
+// Routing and stripping are separated by the selection-capture await. Re-reading
+// the store there lets a snippet edit — a Control Panel save, the assistant's
+// update_snippets tool, the startup SQLite sync — land between them, so the
+// address is spliced out of a different reading of the transcript than the one
+// that chose the route.
+test("a snippets edit between routing and stripping cannot desync them", async (t) => {
+ const { window, setSettings, createBankingManager } = await loadAudioManager(t);
+
+ setSettings(snippetSettings);
+ window.electronAPI.cloudTranscribe = async () => ({
+ success: true,
+ text: "jarvis review. Jarvis summarize it",
+ sttLanguage: "en",
+ });
+
+ const manager = createBankingManager();
+ manager.consumeSelectionCapture = async () => {
+ setSettings({ ...snippetSettings, snippets: [] });
+ return null;
+ };
+ await manager.processWithOpenWhisprCloud(snippetAudioBlob);
+
+ assert.equal(manager.pendingAssistantConversation?.transcript, "jarvis review. summarize it");
+});
diff --git a/test/utils/snippets.test.js b/test/utils/snippets.test.js
index c8c55c8b0..29154c796 100644
--- a/test/utils/snippets.test.js
+++ b/test/utils/snippets.test.js
@@ -1,7 +1,11 @@
const test = require("node:test");
const assert = require("node:assert/strict");
-const { expandSnippets, getDictionaryHintWords } = require("../../src/utils/snippets.ts");
+const {
+ expandSnippets,
+ findSnippetTriggerRanges,
+ getDictionaryHintWords,
+} = require("../../src/utils/snippets.ts");
test("expands a trigger containing Turkish capital İ", () => {
const snippets = [{ trigger: "İmza", replacement: "Best regards,\nUmut" }];
@@ -129,3 +133,28 @@ test("getDictionaryHintWords combines dictionary words and snippet triggers safe
"zoom link",
]);
});
+
+test("findSnippetTriggerRanges reports where each trigger occurs", () => {
+ const snippets = [{ trigger: "openwhispr review", replacement: "Review the PR" }];
+
+ assert.deepEqual(findSnippetTriggerRanges("openwhispr review this PR", snippets), [
+ { start: 0, end: 17 },
+ ]);
+ assert.deepEqual(findSnippetTriggerRanges("please openwhispr review it", snippets), [
+ { start: 7, end: 24 },
+ ]);
+ assert.deepEqual(findSnippetTriggerRanges("nothing to expand here", snippets), []);
+ assert.deepEqual(findSnippetTriggerRanges("openwhispr review", null), []);
+});
+
+// Wake-word suppression keys off these ranges, so a range that expandSnippets
+// will not actually replace costs the user both the wake word and the snippet.
+// The matcher folds case the Unicode way (/iu) while the replacement lookup
+// uses toLowerCase(); Turkish dotless ı is where the two part company, since
+// the pattern's [ıI] matches a plain "i" that is not a Map key.
+test("findSnippetTriggerRanges reports only ranges expandSnippets will replace", () => {
+ const snippets = [{ trigger: "ımza", replacement: "Saygılarımla" }];
+
+ assert.equal(expandSnippets("imza raporu hazırla", snippets), "imza raporu hazırla");
+ assert.deepEqual(findSnippetTriggerRanges("imza raporu hazırla", snippets), []);
+});