Skip to content

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

fix(ptt): keep the transcript when a push is force-stopped mid-hold (#2102)

voidf64ea02aab61
diff --git a/preload.js b/preload.js
index 53134e757..9c0f0d7af 100644
--- a/preload.js
+++ b/preload.js
@@ -97,6 +97,10 @@ contextBridge.exposeInMainWorld("electronAPI", {
(callback) => () => callback()
),
onCancelDictation: registerListener("cancel-dictation", (callback) => () => callback()),
+ onDictationForceStopped: registerListener(
+ "dictation-force-stopped",
+ (callback) => (_event, payload) => callback(payload)
+ ),
micWarmHoldChanged: (active) => ipcRenderer.send("mic-warm-hold-changed", active),
dictationLifecycleStateChanged: (state, inputKind) =>
ipcRenderer.send("dictation-lifecycle-state-changed", state, inputKind),
diff --git a/src/helpers/linuxKeyManager.js b/src/helpers/linuxKeyManager.js
index 025f8db97..4a3e074ab 100644
--- a/src/helpers/linuxKeyManager.js
+++ b/src/helpers/linuxKeyManager.js
@@ -4,17 +4,19 @@ const EventEmitter = require("events");
const fs = require("fs");
const debugLogger = require("./debugLogger");
-// Force a key-up if the native listener never reports one (e.g. a missed release
-// while another window had focus), so a held key can't get stuck recording.
-const WATCHDOG_MS = 30000;
-
+// Key state comes from an evdev reader (resources/linux-key-listener.c) that reads
+// /dev/input directly, so it observes KEY_UP regardless of which window has focus
+// and cannot miss a release. The ceiling for a genuinely stuck key is
+// MAX_PUSH_DURATION_MS in windowManager, which owns push state; enforcing one here
+// too would end the push by synthesizing a release, making a forced stop
+// indistinguishable from the user letting go.
class LinuxKeyManager extends EventEmitter {
constructor() {
super();
this.isSupported = process.platform === "linux";
this.hasReportedError = false;
this.hasReportedUnavailable = false;
- this.listeners = new Map(); // key string -> { child, watchdog }
+ this.listeners = new Map(); // key string -> { child }
}
/**
@@ -56,7 +58,7 @@ class LinuxKeyManager extends EventEmitter {
}
this.hasReportedError = false;
- const entry = { child, watchdog: null };
+ const entry = { child };
this.listeners.set(key, entry);
debugLogger.debug("[LinuxKeyManager] Starting key listener", { key, binaryPath: listenerPath });
@@ -107,7 +109,6 @@ class LinuxKeyManager extends EventEmitter {
const entry = this.listeners.get(key);
if (!entry) return;
this.listeners.delete(key);
- if (entry.watchdog) clearTimeout(entry.watchdog);
debugLogger.debug("[LinuxKeyManager] Stopping key listener", { key });
try {
entry.child.kill();
@@ -131,28 +132,12 @@ class LinuxKeyManager extends EventEmitter {
if (line === "KEY_DOWN") {
debugLogger.debug("[LinuxKeyManager] KEY_DOWN detected", { key });
- const entry = this.listeners.get(key);
- if (entry) {
- if (entry.watchdog) clearTimeout(entry.watchdog);
- entry.watchdog = setTimeout(() => {
- debugLogger.warn("[LinuxKeyManager] Watchdog: no KEY_UP within 30s, forcing release", {
- key,
- });
- entry.watchdog = null;
- this.emit("key-up", key);
- }, WATCHDOG_MS);
- }
this.emit("key-down", key);
return;
}
if (line === "KEY_UP") {
debugLogger.debug("[LinuxKeyManager] KEY_UP detected", { key });
- const entry = this.listeners.get(key);
- if (entry?.watchdog) {
- clearTimeout(entry.watchdog);
- entry.watchdog = null;
- }
this.emit("key-up", key);
return;
}
diff --git a/src/helpers/windowManager.js b/src/helpers/windowManager.js
index c1ecf8ec2..d51916e44 100644
--- a/src/helpers/windowManager.js
+++ b/src/helpers/windowManager.js
@@ -693,6 +693,16 @@ class WindowManager {
}
}
+ // A push that ends without a physical release leaves the trigger keys down, so
+ // an injected paste shortcut lands in a modifier state the target app cannot
+ // interpret and the transcript is lost. Tell the renderer to hold the text
+ // back instead of pasting it.
+ _notifyPushForceStopped(reason) {
+ if (this.mainWindow && !this.mainWindow.isDestroyed()) {
+ this.mainWindow.webContents.send("dictation-force-stopped", { reason });
+ }
+ }
+
forceStopMacCompoundPush(reason = "manual") {
if (!this.macCompoundPushState) {
return;
@@ -705,15 +715,13 @@ class WindowManager {
const wasRecording = this.macCompoundPushState.isRecording;
this.macCompoundPushState = null;
+ this._notifyPushForceStopped(reason);
+
if (wasRecording) {
this.sendStopDictation();
} else {
this.sendCancelDictationPreparation();
- }
- this.hideDictationPanel();
-
- if (this.mainWindow && !this.mainWindow.isDestroyed()) {
- this.mainWindow.webContents.send("compound-ptt-force-stopped", { reason });
+ this.hideDictationPanel();
}
}
@@ -775,7 +783,7 @@ class WindowManager {
const safetyTimeoutId = setTimeout(() => {
if (!this.winPushState || this.winPushState.downTime !== downTime) return;
debugLogger.warn("Native PTT safety timeout", undefined, "ptt");
- this.handleWindowsPushKeyUp();
+ this.handleWindowsPushKeyUp(undefined, { reason: "timeout" });
}, MAX_PUSH_DURATION_MS);
this.winPushState = {
@@ -798,9 +806,11 @@ class WindowManager {
}, MIN_HOLD_DURATION_MS);
}
- // With several dictation hotkeys bound, only the key that started the push
- // may stop it; called without a key to force-stop (resetWindowsPushState).
- handleWindowsPushKeyUp(key) {
+ // With several dictation hotkeys bound, only the key that started the push may
+ // stop it; called without a key to force-stop. "release" is the user letting
+ // go; every other reason ends a push whose trigger keys are still physically
+ // down, which the renderer must know before it pastes.
+ handleWindowsPushKeyUp(key, { reason = "release" } = {}) {
if (!this.winPushState?.active) {
return;
}
@@ -815,6 +825,8 @@ class WindowManager {
const wasRecording = this.winPushState.isRecording;
this.winPushState = null;
+ if (reason !== "release") this._notifyPushForceStopped(reason);
+
if (wasRecording) {
this.sendStopDictation();
} else {
@@ -828,7 +840,7 @@ class WindowManager {
return;
}
- this.handleWindowsPushKeyUp();
+ this.handleWindowsPushKeyUp(undefined, { reason: "reset" });
}
_isOnboardingInputAllowed(inputKind) {
diff --git a/src/hooks/useAudioRecording.js b/src/hooks/useAudioRecording.js
index 4d70f49e5..964b42dd1 100644
--- a/src/hooks/useAudioRecording.js
+++ b/src/hooks/useAudioRecording.js
@@ -50,6 +50,7 @@ export const useAudioRecording = (toast, options = {}) => {
const audioManagerRef = useRef(null);
const startLockRef = useRef(false);
const stopRequestedDuringStartRef = useRef(false);
+ const pushForceStoppedRef = useRef(false);
const stopLockRef = useRef(false);
const preparationGenerationRef = useRef(0);
const wasRecordingRef = useRef(false);
@@ -114,6 +115,7 @@ export const useAudioRecording = (toast, options = {}) => {
lastStartOptionsRef.current = { voiceAgentRequested, translationRequested };
startLockRef.current = true;
stopRequestedDuringStartRef.current = false;
+ pushForceStoppedRef.current = false;
let recordingStarted = false;
try {
if (!audioManagerRef.current) return false;
@@ -582,16 +584,35 @@ export const useAudioRecording = (toast, options = {}) => {
if (clipboardResult?.success === false) {
throw new Error("clipboard-write-failed");
}
+ return true;
} catch (error) {
logger.warn(
"Failed to keep transcription in clipboard",
{ delivery, error: error?.message },
"clipboard"
);
+ return false;
}
};
- if (autoPasteEnabled && !result.assistantConversation) {
+ if (pushForceStoppedRef.current && autoPasteEnabled && !result.assistantConversation) {
+ // The push hit its safety ceiling while the trigger keys were still
+ // down. Injecting the paste shortcut into those held modifiers is
+ // what silently loses the transcript, so keep it instead.
+ const keptInClipboard = await keepInClipboard("push-force-stopped");
+ window.electronAPI?.hideDictationPreview?.();
+ showDictationError({
+ title: t("hooks.audioRecording.pushForceStopped.title"),
+ // Never promise a clipboard that rejected the write; the transcript
+ // action on this pill is the recovery path either way.
+ description: t(
+ keptInClipboard
+ ? "hooks.audioRecording.pushForceStopped.description"
+ : "hooks.audioRecording.pushForceStopped.descriptionClipboardFailed"
+ ),
+ transcript: result.rawText ?? result.text,
+ });
+ } else if (autoPasteEnabled && !result.assistantConversation) {
const pasteStart = performance.now();
let pasteSucceeded = true;
if (result.selectionEdit?.sessionId) {
@@ -778,6 +799,14 @@ export const useAudioRecording = (toast, options = {}) => {
onToggle?.();
});
+ const disposeForceStopped = window.electronAPI.onDictationForceStopped?.((payload) => {
+ // Listed rather than negated: a future renderer-initiated stop would not
+ // leave the keys down, and must not be swept in here.
+ if (payload?.reason === "timeout" || payload?.reason === "reset") {
+ pushForceStoppedRef.current = true;
+ }
+ });
+
// Cleanup
return () => {
reportLifecycle("idle");
@@ -789,6 +818,7 @@ export const useAudioRecording = (toast, options = {}) => {
disposePrepare?.();
disposeCancelPreparation?.();
disposeStop?.();
+ disposeForceStopped?.();
if (audioManagerRef.current) {
audioManagerRef.current.cleanup();
}
diff --git a/src/locales/de/translation.json b/src/locales/de/translation.json
index 73efcdb3a..5f7dfb90f 100644
--- a/src/locales/de/translation.json
+++ b/src/locales/de/translation.json
@@ -916,6 +916,11 @@
"failedTitle": "Übersetzung fehlgeschlagen",
"failedDescription": "Der Originaltext wurde eingefügt. Du kannst es im Verlauf erneut versuchen."
},
+ "pushForceStopped": {
+ "title": "Transkription nicht eingefügt",
+ "description": "Das Diktat wurde beendet, während die Taste noch gedrückt war, daher wurde der Text nicht eingefügt. Deine Transkription befindet sich in der Zwischenablage.",
+ "descriptionClipboardFailed": "Das Diktat wurde beendet, während die Taste noch gedrückt war. Der Text wurde nicht eingefügt und konnte auch nicht in die Zwischenablage kopiert werden."
+ },
"selectionEditing": {
"notAppliedTitle": "Auswahlbearbeitung nicht angewendet",
"changed": "Der ausgewählte Text oder die Ziel-App wurde während der Verarbeitung geändert. Es wurde nichts ersetzt.",
diff --git a/src/locales/en/translation.json b/src/locales/en/translation.json
index ebe4e404d..b7b62e39a 100644
--- a/src/locales/en/translation.json
+++ b/src/locales/en/translation.json
@@ -916,6 +916,11 @@
"failedTitle": "Translation failed",
"failedDescription": "The original text was pasted. You can retry it from History."
},
+ "pushForceStopped": {
+ "title": "Transcription not pasted",
+ "description": "Dictation stopped while the hotkey was still held, so the text was not pasted. Your transcription is on the clipboard.",
+ "descriptionClipboardFailed": "Dictation stopped while the hotkey was still held, so the text was not pasted, and it could not be copied to the clipboard either."
+ },
"selectionEditing": {
"notAppliedTitle": "Selection edit not applied",
"changed": "The selected text or target app changed while OpenWhispr was processing. Nothing was replaced.",
diff --git a/src/locales/es/translation.json b/src/locales/es/translation.json
index 7d0cc100c..be25b91d4 100644
--- a/src/locales/es/translation.json
+++ b/src/locales/es/translation.json
@@ -916,6 +916,11 @@
"failedTitle": "La traducción falló",
"failedDescription": "Se pegó el texto original. Puedes reintentarlo desde el Historial."
},
+ "pushForceStopped": {
+ "title": "Transcripción no pegada",
+ "description": "El dictado se detuvo mientras la tecla seguía pulsada, así que el texto no se pegó. Tu transcripción está en el portapapeles.",
+ "descriptionClipboardFailed": "El dictado se detuvo mientras la tecla seguía pulsada, así que el texto no se pegó y tampoco se pudo copiar al portapapeles."
+ },
"selectionEditing": {
"notAppliedTitle": "Edición de selección no aplicada",
"changed": "El texto seleccionado o la aplicación de destino cambió durante el procesamiento. No se reemplazó nada.",
diff --git a/src/locales/fr/translation.json b/src/locales/fr/translation.json
index 72469dd3d..61fc6b656 100644
--- a/src/locales/fr/translation.json
+++ b/src/locales/fr/translation.json
@@ -916,6 +916,11 @@
"failedTitle": "Échec de la traduction",
"failedDescription": "Le texte original a été collé. Vous pouvez réessayer depuis l'Historique."
},
+ "pushForceStopped": {
+ "title": "Transcription non collée",
+ "description": "La dictée s'est arrêtée alors que le raccourci était encore enfoncé, le texte n'a donc pas été collé. Votre transcription est dans le presse-papiers.",
+ "descriptionClipboardFailed": "La dictée s'est arrêtée alors que le raccourci était encore enfoncé : le texte n'a pas été collé et n'a pas pu être copié dans le presse-papiers non plus."
+ },
"selectionEditing": {
"notAppliedTitle": "Modification de la sélection non appliquée",
"changed": "Le texte sélectionné ou l’application cible a changé pendant le traitement. Rien n’a été remplacé.",
diff --git a/src/locales/it/translation.json b/src/locales/it/translation.json
index 9a50ecb96..5b9f60b31 100644
--- a/src/locales/it/translation.json
+++ b/src/locales/it/translation.json
@@ -916,6 +916,11 @@
"failedTitle": "Traduzione non riuscita",
"failedDescription": "È stato incollato il testo originale. Puoi riprovare dalla History."
},
+ "pushForceStopped": {
+ "title": "Trascrizione non incollata",
+ "description": "La dettatura si è interrotta mentre il tasto era ancora premuto, quindi il testo non è stato incollato. La trascrizione è negli appunti.",
+ "descriptionClipboardFailed": "La dettatura si è interrotta mentre il tasto era ancora premuto: il testo non è stato incollato e non è stato possibile copiarlo negli appunti."
+ },
"selectionEditing": {
"notAppliedTitle": "Modifica della selezione non applicata",
"changed": "Il testo selezionato o l’app di destinazione è cambiato durante l’elaborazione. Non è stato sostituito nulla.",
diff --git a/src/locales/ja/translation.json b/src/locales/ja/translation.json
index 18799094f..563a488b1 100644
--- a/src/locales/ja/translation.json
+++ b/src/locales/ja/translation.json
@@ -916,6 +916,11 @@
"failedTitle": "翻訳に失敗しました",
"failedDescription": "元のテキストが貼り付けられました。履歴から再試行できます。"
},
+ "pushForceStopped": {
+ "title": "文字起こしは貼り付けられませんでした",
+ "description": "ホットキーが押されたままディクテーションが終了したため、テキストは貼り付けられませんでした。文字起こしはクリップボードにあります。",
+ "descriptionClipboardFailed": "ホットキーが押されたままディクテーションが終了したため、テキストは貼り付けられず、クリップボードにもコピーできませんでした。"
+ },
"selectionEditing": {
"notAppliedTitle": "選択範囲の編集を適用できませんでした",
"changed": "処理中に選択したテキストまたは対象アプリが変更されました。置換は行われていません。",
diff --git a/src/locales/pt/translation.json b/src/locales/pt/translation.json
index bf206dc4f..c45c68660 100644
--- a/src/locales/pt/translation.json
+++ b/src/locales/pt/translation.json
@@ -895,6 +895,11 @@
"failedTitle": "Falha na tradução",
"failedDescription": "O texto original foi colado. Você pode tentar novamente pelo Histórico."
},
+ "pushForceStopped": {
+ "title": "Transcrição não colada",
+ "description": "O ditado parou enquanto a tecla ainda estava pressionada, por isso o texto não foi colado. Sua transcrição está na área de transferência.",
+ "descriptionClipboardFailed": "O ditado parou enquanto a tecla ainda estava pressionada, por isso o texto não foi colado e também não foi possível copiá-lo para a área de transferência."
+ },
"selectionEditing": {
"notAppliedTitle": "Edição da seleção não aplicada",
"changed": "O texto selecionado ou o aplicativo de destino mudou durante o processamento. Nada foi substituído.",
diff --git a/src/locales/ru/translation.json b/src/locales/ru/translation.json
index 24c1b6801..5277c418e 100644
--- a/src/locales/ru/translation.json
+++ b/src/locales/ru/translation.json
@@ -916,6 +916,11 @@
"failedTitle": "Не удалось выполнить перевод",
"failedDescription": "Вставлен исходный текст. Вы можете повторить попытку в Истории."
},
+ "pushForceStopped": {
+ "title": "Расшифровка не вставлена",
+ "description": "Диктовка остановилась, пока клавиша была зажата, поэтому текст не был вставлен. Расшифровка находится в буфере обмена.",
+ "descriptionClipboardFailed": "Диктовка остановилась, пока клавиша была зажата: текст не был вставлен и его также не удалось скопировать в буфер обмена."
+ },
"selectionEditing": {
"notAppliedTitle": "Изменение выделения не применено",
"changed": "Выделенный текст или целевое приложение изменились во время обработки. Текст не был заменён.",
diff --git a/src/locales/zh-CN/translation.json b/src/locales/zh-CN/translation.json
index 38f84d69e..5baba30e1 100644
--- a/src/locales/zh-CN/translation.json
+++ b/src/locales/zh-CN/translation.json
@@ -916,6 +916,11 @@
"failedTitle": "翻译失败",
"failedDescription": "已粘贴原始文本。你可以在历史记录中重试。"
},
+ "pushForceStopped": {
+ "title": "转录内容未粘贴",
+ "description": "听写停止时快捷键仍处于按下状态,因此未粘贴文本。转录内容已复制到剪贴板。",
+ "descriptionClipboardFailed": "听写停止时快捷键仍处于按下状态,因此未粘贴文本,也无法复制到剪贴板。"
+ },
"selectionEditing": {
"notAppliedTitle": "未应用选中文本编辑",
"changed": "处理期间,选中的文本或目标应用已发生变化。未替换任何内容。",
diff --git a/src/locales/zh-TW/translation.json b/src/locales/zh-TW/translation.json
index d960c4a02..4498520d5 100644
--- a/src/locales/zh-TW/translation.json
+++ b/src/locales/zh-TW/translation.json
@@ -916,6 +916,11 @@
"failedTitle": "翻譯失敗",
"failedDescription": "已貼上原始文字。你可以在歷史記錄中重試。"
},
+ "pushForceStopped": {
+ "title": "轉錄內容未貼上",
+ "description": "聽寫停止時快捷鍵仍處於按住狀態,因此未貼上文字。轉錄內容已複製到剪貼簿。",
+ "descriptionClipboardFailed": "聽寫停止時快捷鍵仍處於按住狀態,因此未貼上文字,也無法複製到剪貼簿。"
+ },
"selectionEditing": {
"notAppliedTitle": "未套用選取文字編輯",
"changed": "處理期間,選取的文字或目標應用程式已變更。未取代任何內容。",
diff --git a/src/types/electron.ts b/src/types/electron.ts
index 7f26905d5..2a66e085a 100644
--- a/src/types/electron.ts
+++ b/src/types/electron.ts
@@ -1160,6 +1160,9 @@ declare global {
) => () => void;
onCancelDictationPreparation?: (callback: () => void) => () => void;
onCancelDictation?: (callback: () => void) => () => void;
+ onDictationForceStopped?: (
+ callback: (payload?: { reason?: "timeout" | "reset" | "manual" }) => void
+ ) => () => void;
micWarmHoldChanged?: (active: boolean) => void;
dictationLifecycleStateChanged: (
state: "idle" | "preparing" | "recording" | "processing",
diff --git a/test/helpers/linuxKeyManager.test.js b/test/helpers/linuxKeyManager.test.js
new file mode 100644
index 000000000..6573580ce
--- /dev/null
+++ b/test/helpers/linuxKeyManager.test.js
@@ -0,0 +1,135 @@
+const test = require("node:test");
+const { afterEach } = require("node:test");
+const assert = require("node:assert/strict");
+const Module = require("node:module");
+const { EventEmitter } = require("node:events");
+const childProcess = require("node:child_process");
+
+const managerModulePath = require.resolve("../../src/helpers/linuxKeyManager");
+const originalLoad = Module._load;
+const originalPlatform = process.platform;
+
+function setPlatform(platform) {
+ Object.defineProperty(process, "platform", { value: platform, configurable: true });
+}
+
+function makeChild() {
+ const child = new EventEmitter();
+ child.stdout = Object.assign(new EventEmitter(), { setEncoding() {} });
+ child.stderr = Object.assign(new EventEmitter(), { setEncoding() {} });
+ child.kill = () => {
+ child.killed = true;
+ };
+ return child;
+}
+
+// Drives the real setKeys path with a stubbed listener binary, so the tests
+// exercise the same wiring production uses rather than poking listener state.
+function loadManager() {
+ delete require.cache[managerModulePath];
+ setPlatform("linux");
+
+ const spawnCalls = [];
+ const spawn = (command, args) => {
+ const child = makeChild();
+ spawnCalls.push({ command, args, child });
+ return child;
+ };
+
+ Module._load = function loadWithMocks(request, parent, isMain) {
+ if (request === "./debugLogger") {
+ return { info() {}, warn() {}, debug() {}, error() {} };
+ }
+ if (request === "child_process") {
+ return { ...childProcess, spawn };
+ }
+ if (request === "fs") {
+ return { statSync: () => ({ isFile: () => true }) };
+ }
+ return originalLoad(request, parent, isMain);
+ };
+
+ try {
+ const LinuxKeyManager = require(managerModulePath);
+ return { LinuxKeyManager, spawnCalls };
+ } finally {
+ Module._load = originalLoad;
+ }
+}
+
+function startWatching(key = "Control+Space") {
+ const { LinuxKeyManager, spawnCalls } = loadManager();
+ const manager = new LinuxKeyManager();
+ manager.setKeys([key]);
+ assert.equal(spawnCalls.length, 1, "one listener process per watched key");
+
+ const events = [];
+ manager.on("key-down", (k) => events.push(`down:${k}`));
+ manager.on("key-up", (k) => events.push(`up:${k}`));
+
+ return { manager, events, child: spawnCalls[0].child };
+}
+
+afterEach(() => {
+ Module._load = originalLoad;
+ setPlatform(originalPlatform);
+});
+
+// Regression pin for #1594 / #2047. A watchdog here used to synthesize a release
+// (at 30s, later 5min), which both truncated long holds and made a forced stop
+// indistinguishable from the user letting go. The ceiling belongs to
+// windowManager's MAX_PUSH_DURATION_MS, which can report that it forced the stop.
+test("a held key is never released by this listener, however long it is held", (t) => {
+ t.mock.timers.enable({ apis: ["setTimeout"] });
+ t.after(() => t.mock.timers.reset());
+
+ const { events, child } = startWatching();
+ child.stdout.emit("data", "KEY_DOWN\n");
+
+ t.mock.timers.tick(30_000);
+ assert.deepEqual(events, ["down:Control+Space"], "no release at the old 30s watchdog");
+
+ t.mock.timers.tick(300_000);
+ assert.deepEqual(events, ["down:Control+Space"], "no release at the push-to-talk ceiling");
+
+ t.mock.timers.tick(3_600_000);
+ assert.deepEqual(events, ["down:Control+Space"], "no release an hour in");
+});
+
+test("a physical release is relayed, and nothing follows it", (t) => {
+ t.mock.timers.enable({ apis: ["setTimeout"] });
+ t.after(() => t.mock.timers.reset());
+
+ const { events, child } = startWatching();
+ child.stdout.emit("data", "KEY_DOWN\n");
+ t.mock.timers.tick(45_000);
+ child.stdout.emit("data", "KEY_UP\n");
+
+ assert.deepEqual(events, ["down:Control+Space", "up:Control+Space"]);
+
+ t.mock.timers.tick(3_600_000);
+ assert.deepEqual(
+ events,
+ ["down:Control+Space", "up:Control+Space"],
+ "no synthetic extra release"
+ );
+});
+
+test("events split across stdout chunks are still relayed once each", () => {
+ const { events, child } = startWatching();
+
+ child.stdout.emit("data", "KEY_DO");
+ child.stdout.emit("data", "WN\nKEY_");
+ child.stdout.emit("data", "UP\n");
+
+ assert.deepEqual(events, ["down:Control+Space", "up:Control+Space"]);
+});
+
+test("dropping a key kills its listener process and stops tracking it", () => {
+ const { manager, child } = startWatching();
+
+ manager.setKeys([]);
+
+ assert.equal(child.killed, true);
+ assert.equal(manager.listeners.size, 0);
+});
diff --git a/test/helpers/pushToTalkForceStop.test.js b/test/helpers/pushToTalkForceStop.test.js
new file mode 100644
index 000000000..ddf50223d
--- /dev/null
+++ b/test/helpers/pushToTalkForceStop.test.js
@@ -0,0 +1,199 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+const Module = require("node:module");
+
+// WindowManager pulls in electron and its sibling managers at require time; only
+// the pieces the push-to-talk state machine touches need to behave.
+const originalLoad = Module._load;
+Module._load = function loadWindowManagerWithStubs(request, parent, isMain) {
+ if (request === "electron") {
+ return {
+ app: { on: () => undefined },
+ screen: { on: () => undefined, getPrimaryDisplay: () => ({}) },
+ BrowserWindow: class {},
+ Menu: {},
+ shell: {},
+ dialog: {},
+ };
+ }
+ if (request === "./debugLogger") {
+ return { warn: () => undefined, debug: () => undefined, log: () => undefined };
+ }
+ if (request === "./hotkeyManager") {
+ const FakeHotkeyManager = class {};
+ FakeHotkeyManager.isGlobeLikeHotkey = () => false;
+ return FakeHotkeyManager;
+ }
+ if (request === "./dragManager") return class {};
+ if (request === "./menuManager") return {};
+ if (request === "./devServerManager") {
+ return {
+ DEV_SERVER_PORT: 5173,
+ DEV_SERVER_URL: "http://localhost:5173",
+ getAppFilePath: () => ({ path: "/app/index.html", query: {} }),
+ waitForDevServer: async () => undefined,
+ };
+ }
+ if (request === "./dockManager") return {};
+ if (request === "./i18nMain") return { i18nMain: { t: (key) => key } };
+ if (request === "./windowConfig") {
+ return {
+ MAIN_WINDOW_CONFIG: {},
+ CONTROL_PANEL_CONFIG: {},
+ NOTIFICATION_WINDOW_CONFIG: {},
+ AUTO_END_NOTIFICATION_WINDOW_SIZE: { width: 620, height: 116 },
+ getMeetingNotificationWindowSize: () => ({ width: 392, height: 92 }),
+ WINDOW_SIZES: { BASE: { width: 96, height: 96 } },
+ ONBOARDING_WINDOW_SIZES: { COMPACT: {}, EXPANDED: {} },
+ WindowPositionUtil: {
+ setupAlwaysOnTop: () => undefined,
+ clampToWorkArea: (b) => b,
+ getMainWindowPosition: () => ({ x: 0, y: 0 }),
+ getNotificationPosition: () => ({ x: 0, y: 0 }),
+ },
+ fitAssistantWindowToWorkArea: (s) => s,
+ fitAssistantContentWindowToWorkArea: (h) => ({ width: 466, height: h }),
+ fitDictationErrorWindowToWorkArea: (s) => s,
+ fitDictationErrorContentWindowToWorkArea: (h) => ({ width: 466, height: h }),
+ resolveHorizontalWindowDirection: () => "right",
+ };
+ }
+ return originalLoad.call(this, request, parent, isMain);
+};
+const WindowManager = require("../../src/helpers/windowManager");
+Module._load = originalLoad;
+
+// Returns the manager plus the channels it pushed to the renderer, in order.
+function makeManager() {
+ const sent = [];
+ const manager = new WindowManager();
+ manager.hotkeyManager = { isInListeningMode: () => false };
+ // Before mainWindow is attached, so its own teardown sends stay out of `sent`.
+ manager.setOnboardingActive(false);
+ manager.mainWindow = {
+ isDestroyed: () => false,
+ webContents: { send: (channel, payload) => sent.push({ channel, payload }) },
+ };
+ manager.showDictationPanel = () => undefined;
+ manager.isDictationProcessing = () => false;
+ const hides = [];
+ manager.hideDictationPanel = () => hides.push(true);
+ return {
+ manager,
+ sent,
+ hides,
+ channels: () => sent.map((entry) => entry.channel),
+ };
+}
+
+function startPush(t) {
+ const harness = makeManager();
+ harness.manager.startWindowsPushToTalk("Control+Space");
+ t.mock.timers.tick(150); // MIN_HOLD_DURATION_MS — recording actually begins
+ assert.deepEqual(harness.channels(), ["prepare-dictation", "start-dictation"]);
+ return harness;
+}
+
+test("a physical release stops dictation without reporting a forced stop", (t) => {
+ t.mock.timers.enable({ apis: ["setTimeout"] });
+ t.after(() => t.mock.timers.reset());
+
+ const { manager, channels } = startPush(t);
+ manager.handleWindowsPushKeyUp("Control+Space");
+
+ assert.deepEqual(channels(), ["prepare-dictation", "start-dictation", "stop-dictation"]);
+});
+
+// The safety ceiling ends the push while the trigger keys are still physically
+// down. The renderer has to know, or it pastes into those held modifiers and the
+// transcript is lost with no error (#2047).
+test("the safety ceiling reports a forced stop before the stop it causes", (t) => {
+ t.mock.timers.enable({ apis: ["setTimeout"] });
+ t.after(() => t.mock.timers.reset());
+
+ const { sent, channels } = startPush(t);
+ t.mock.timers.tick(300_000); // MAX_PUSH_DURATION_MS
+
+ assert.deepEqual(channels(), [
+ "prepare-dictation",
+ "start-dictation",
+ "dictation-force-stopped",
+ "stop-dictation",
+ ]);
+ assert.deepEqual(sent.at(-2).payload, { reason: "timeout" });
+});
+
+// Driven through the real ceiling rather than by calling forceStop directly, so
+// the "timeout" argument at the timer itself stays pinned.
+test("the macOS compound ceiling reports a forced stop on the same channel", (t) => {
+ t.mock.timers.enable({ apis: ["setTimeout"] });
+ t.after(() => t.mock.timers.reset());
+
+ const harness = makeManager();
+ harness.manager.startMacCompoundPushToTalk("Control+Option");
+ t.mock.timers.tick(150);
+ assert.deepEqual(harness.channels(), ["prepare-dictation", "start-dictation"]);
+
+ t.mock.timers.tick(300_000);
+
+ assert.deepEqual(harness.channels(), [
+ "prepare-dictation",
+ "start-dictation",
+ "dictation-force-stopped",
+ "stop-dictation",
+ ]);
+ assert.deepEqual(harness.sent.at(-2).payload, { reason: "timeout" });
+});
+
+// The transcript arrives seconds after the stop and is surfaced by a toast inside
+// this window, so hiding it here would render the recovery pill invisibly.
+test("a forced stop leaves the window up for the transcript still being processed", (t) => {
+ t.mock.timers.enable({ apis: ["setTimeout"] });
+ t.after(() => t.mock.timers.reset());
+
+ const mac = makeManager();
+ mac.manager.startMacCompoundPushToTalk("Control+Option");
+ t.mock.timers.tick(150);
+ t.mock.timers.tick(300_000);
+ assert.deepEqual(mac.hides, [], "macOS compound");
+
+ const win = startPush(t);
+ t.mock.timers.tick(300_000);
+ assert.deepEqual(win.hides, [], "windows/linux");
+});
+
+// The complementary half: with nothing being transcribed there is no pill to
+// keep the window open for, so it still goes away.
+test("a forced stop before recording began still hides the window", (t) => {
+ t.mock.timers.enable({ apis: ["setTimeout"] });
+ t.after(() => t.mock.timers.reset());
+
+ const mac = makeManager();
+ mac.manager.startMacCompoundPushToTalk("Control+Option");
+ t.mock.timers.tick(100); // still inside MIN_HOLD_DURATION_MS
+ mac.manager.forceStopMacCompoundPush("timeout");
+
+ assert.deepEqual(mac.channels(), [
+ "prepare-dictation",
+ "dictation-force-stopped",
+ "cancel-dictation-preparation",
+ ]);
+ assert.deepEqual(mac.hides, [true]);
+});
+
+// Changing the hotkey or activation mode mid-push ends it without a release too.
+test("a settings-driven reset reports a forced stop, not a release", (t) => {
+ t.mock.timers.enable({ apis: ["setTimeout"] });
+ t.after(() => t.mock.timers.reset());
+
+ const { manager, sent, channels } = startPush(t);
+ manager.resetWindowsPushState();
+
+ assert.deepEqual(channels(), [
+ "prepare-dictation",
+ "start-dictation",
+ "dictation-force-stopped",
+ "stop-dictation",
+ ]);
+ assert.deepEqual(sent.at(-2).payload, { reason: "reset" });
+});
diff --git a/test/helpers/useAudioRecordingForceStop.test.js b/test/helpers/useAudioRecordingForceStop.test.js
new file mode 100644
index 000000000..95d42d87d
--- /dev/null
+++ b/test/helpers/useAudioRecordingForceStop.test.js
@@ -0,0 +1,286 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+const React = require("react");
+const { createRoot } = require("react-dom/client");
+const {
+ createRendererServer,
+ installBrowserGlobals,
+ installHookDom,
+} = require("../lib/rendererTestHarness");
+
+const FAKE_AUDIO_MANAGER_SOURCE = `
+export default class FakeAudioManager {
+ constructor() {
+ this.voiceAgentRequested = false;
+ this.translationRequested = false;
+ this.sttConfig = {};
+ globalThis.__forceStopAudioManager = this;
+ }
+ getState() {
+ return {};
+ }
+ setCallbacks(callbacks) {
+ this.callbacks = callbacks;
+ }
+ setVoiceAgentRequested() {}
+ setAssistantSelectionContext() {}
+ setTranslationRequested() {}
+ startRecording() {
+ return Promise.resolve(true);
+ }
+ complete(result) {
+ return this.callbacks.onTranscriptionComplete(result);
+ }
+ async safePaste(text, options) {
+ globalThis.__forceStopPastes.push({ text, options });
+ return true;
+ }
+ saveTranscription() {
+ return Promise.resolve(true);
+ }
+ shouldUseStreaming() {
+ return false;
+ }
+ cleanup() {}
+}
+`;
+
+const SETTINGS_STORE_SOURCE = `
+export const getSettings = () => globalThis.__forceStopSettings;
+`;
+
+const POLICY_STORE_SOURCE = `
+export const usePolicyStore = {
+ // An unknown status fails closed at the policy gate, which would make the
+ // second dictation bail before it reaches AudioManager at all.
+ getState: () => ({ status: "unmanaged" }),
+ subscribe: () => () => {},
+};
+`;
+
+const LOGGER_SOURCE = `
+const noop = () => {};
+export default {
+ trace: noop, debug: noop, info: noop, warn: noop, error: noop, fatal: noop,
+ logReasoning: noop,
+};
+`;
+
+const TRANSLATION_SOURCE = `
+const translate = (key) => key;
+export const useTranslation = () => ({ t: translate });
+`;
+
+const NOOP = () => {};
+
+async function mountHarness(t, { settings, writeClipboard } = {}) {
+ let root = null;
+ t.after(async () => {
+ if (root) await React.act(async () => root.unmount());
+ });
+
+ const clipboardWrites = [];
+ const toasts = [];
+ let forceStopListener = null;
+ const noopDispose = () => () => {};
+
+ installBrowserGlobals(t, {
+ window: {
+ electronAPI: {
+ onToggleDictation: noopDispose,
+ onToggleVoiceAgent: noopDispose,
+ onToggleTranslation: noopDispose,
+ onStartDictation: noopDispose,
+ onPrepareDictation: noopDispose,
+ onCancelDictationPreparation: noopDispose,
+ onStopDictation: noopDispose,
+ onDictationForceStopped: (callback) => {
+ forceStopListener = callback;
+ return () => {};
+ },
+ dictationLifecycleStateChanged: NOOP,
+ completeDictationPreview: NOOP,
+ hideDictationPreview: NOOP,
+ setScreenContextEnabled: NOOP,
+ async writeClipboard(text) {
+ clipboardWrites.push(text);
+ return writeClipboard ? writeClipboard(text) : { success: true };
+ },
+ },
+ },
+ });
+ const container = installHookDom(t);
+
+ globalThis.__forceStopSettings = {
+ autoPasteEnabled: true,
+ keepTranscriptionInClipboard: false,
+ showTranscriptionPreview: false,
+ snippets: [],
+ useLocalWhisper: false,
+ pauseMediaOnDictation: false,
+ voiceAgentScreenContext: false,
+ ...settings,
+ };
+ globalThis.__forceStopPastes = [];
+
+ const vite = await createRendererServer(t, {
+ cachePrefix: "openwhispr-audio-recording-force-stop-",
+ noExternal: ["react-i18next"],
+ mockModules: {
+ "/helpers/audioManager": FAKE_AUDIO_MANAGER_SOURCE,
+ "/stores/settingsStore": SETTINGS_STORE_SOURCE,
+ "/stores/policyStore": POLICY_STORE_SOURCE,
+ "/utils/logger": LOGGER_SOURCE,
+ "react-i18next": TRANSLATION_SOURCE,
+ },
+ });
+ const { useAudioRecording } = await vite.ssrLoadModule("/hooks/useAudioRecording.js");
+
+ const api = {};
+ function Harness() {
+ Object.assign(
+ api,
+ useAudioRecording((entry) => toasts.push(entry), { onDemoEvent: NOOP })
+ );
+ return null;
+ }
+
+ root = createRoot(container);
+ await React.act(async () => {
+ root.render(React.createElement(Harness));
+ });
+
+ return {
+ clipboardWrites,
+ pastes: globalThis.__forceStopPastes,
+ toasts,
+ forceStop: async (reason) => {
+ assert.ok(forceStopListener, "the hook must subscribe to dictation-force-stopped");
+ await React.act(async () => forceStopListener({ reason }));
+ },
+ startRecording: async () => {
+ await React.act(async () => api.startRecording());
+ },
+ complete: async (result) => {
+ await React.act(async () => {
+ await globalThis.__forceStopAudioManager.complete({
+ success: true,
+ text: "held too long",
+ rawText: "held too long",
+ clientTranscriptionId: "force-stop",
+ source: "openai",
+ ...result,
+ });
+ });
+ },
+ };
+}
+
+const errorToasts = (harness) =>
+ harness.toasts.filter((entry) => entry.presentation === "dictation-error");
+
+// The whole point of the fix: the trigger keys are still down, so the paste
+// shortcut must not be injected, and the transcript must stay recoverable.
+for (const reason of ["timeout", "reset"]) {
+ test(`a push force-stopped by "${reason}" keeps the transcript instead of pasting it`, async (t) => {
+ const harness = await mountHarness(t);
+
+ await harness.forceStop(reason);
+ await harness.complete();
+
+ assert.deepEqual(harness.pastes, [], "nothing may be injected into held keys");
+ assert.deepEqual(harness.clipboardWrites, ["held too long"]);
+ const [toast] = errorToasts(harness);
+ assert.ok(toast, "the transcript is surfaced, not dropped");
+ assert.equal(toast.description, "hooks.audioRecording.pushForceStopped.description");
+ // A batch transcription has no streaming text, so the pill's transcript
+ // argument is the only thing that can produce this action — and it is the
+ // sole in-app recovery when the clipboard write is the part that failed.
+ assert.ok(
+ toast.actions.some(
+ (action) => action.label === "hooks.audioRecording.errorActions.viewTranscript"
+ ),
+ "the pill must carry the transcript so it stays recoverable"
+ );
+ });
+}
+
+test("an ordinary dictation still pastes", async (t) => {
+ const harness = await mountHarness(t);
+
+ await harness.complete();
+
+ assert.equal(harness.pastes.length, 1);
+ assert.deepEqual(harness.clipboardWrites, []);
+ assert.deepEqual(errorToasts(harness), []);
+});
+
+// With auto-paste off nothing was going to be injected, so there is no loss to
+// report — and overriding keepTranscriptionInClipboard would clobber a clipboard
+// the user asked to leave alone.
+test("a force stop is inert when auto-paste is disabled", async (t) => {
+ const harness = await mountHarness(t, { settings: { autoPasteEnabled: false } });
+
+ await harness.forceStop("timeout");
+ await harness.complete();
+
+ assert.deepEqual(harness.pastes, []);
+ assert.deepEqual(harness.clipboardWrites, [], "keepTranscriptionInClipboard is off");
+ assert.deepEqual(errorToasts(harness), [], "no paste was lost, so no error");
+});
+
+// The latch is per-recording. If it survived, every later dictation in the
+// session would stop pasting and dump onto the clipboard instead.
+test("the latch does not leak into the next dictation", async (t) => {
+ const harness = await mountHarness(t);
+
+ await harness.forceStop("timeout");
+ await harness.complete();
+ assert.deepEqual(harness.pastes, [], "the force-stopped one is held back");
+
+ await harness.startRecording();
+ await harness.complete();
+
+ assert.equal(harness.pastes.length, 1, "the next dictation pastes normally");
+ assert.equal(errorToasts(harness).length, 1, "no second error pill");
+});
+
+// Only reasons that leave the keys down may suppress a paste. A stop the
+// renderer asked for itself must not be swept in.
+test("a reason that is not a forced key-down stop does not latch", async (t) => {
+ const harness = await mountHarness(t);
+
+ await harness.forceStop("manual");
+ await harness.complete();
+
+ assert.equal(harness.pastes.length, 1, "a manual stop still pastes");
+ assert.deepEqual(harness.clipboardWrites, []);
+ assert.deepEqual(errorToasts(harness), []);
+});
+
+// The pill must not promise a clipboard that rejected the write — the transcript
+// action on it is the recovery path either way.
+for (const [label, writeClipboard] of [
+ ["reports failure", async () => ({ success: false })],
+ [
+ "throws",
+ async () => {
+ throw new Error("clipboard unavailable");
+ },
+ ],
+]) {
+ test(`a clipboard write that ${label} is not described as a success`, async (t) => {
+ const harness = await mountHarness(t, { writeClipboard });
+
+ await harness.forceStop("timeout");
+ await harness.complete();
+
+ assert.deepEqual(harness.pastes, [], "still nothing injected into held keys");
+ const [toast] = errorToasts(harness);
+ assert.ok(toast, "the transcript is still surfaced");
+ assert.equal(
+ toast.description,
+ "hooks.audioRecording.pushForceStopped.descriptionClipboardFailed"
+ );
+ });
+}