Voice-to-text dictation app with local (Nvidia Parakeet/Whisper) and cloud models (BYOK). Privacy-first and available cross-platform.
JavaScript aianthropiccross-platformgeminigroqlinuxmacosnvidiaopen-sourceopenaiparakeetspeech-to-texttranscribewhisperwindows
fix(paste): reliably focus target app before pasting on macOS (#1000)
Gabriel Stein8a88d93781b1
diff --git a/electron-builder.json b/electron-builder.jsonindex 8406fed20..5bd53c3c3 100644--- a/electron-builder.json+++ b/electron-builder.json@@ -121,6 +121,7 @@"windows-fast-paste*","all-MiniLM-L6-v2/**/*","diarization-models/**/*",+ "whisper-vad/**/*","*.dylib","*.dll","*.so*"diff --git a/src/helpers/ipcHandlers.js b/src/helpers/ipcHandlers.jsindex d42426546..9b6bfab63 100644--- a/src/helpers/ipcHandlers.js+++ b/src/helpers/ipcHandlers.js@@ -1578,23 +1578,11 @@ class IPCHandlers {}}- // Smart spacing (#856): macOS reads the preceding char via Accessibility- // and prepends a space when needed; Windows/Linux (and macOS when the- // read fails) append a trailing space instead — the next paste then- // sees a leading space and self-corrects.- let mode = "append";- let precedingChar;- if (process.platform === "darwin" && activated && this.textEditMonitor) {- const ax = await this.textEditMonitor.getPrecedingChar(targetPid);- if (ax.state === "ok") {- mode = "prepend";- precedingChar = ax.char;- } else if (ax.state === "start") {- mode = "prepend";- precedingChar = "";- }- }- const textToPaste = applySmartSpacing({ text, mode, precedingChar });+ // Smart spacing (#856): append a trailing space so the next paste's leading+ // space self-corrects the gap. macOS prepend-mode (getPrecedingChar) is+ // intentionally skipped here — its Accessibility read costs hundreds of ms,+ // too slow for the paste hot path.+ const textToPaste = applySmartSpacing({ text, mode: "append" });const result = await this.clipboardManager.pasteText(textToPaste, {...options,diff --git a/src/helpers/textEditMonitor.js b/src/helpers/textEditMonitor.jsindex 22ca6f94f..1eb4872b7 100644--- a/src/helpers/textEditMonitor.js+++ b/src/helpers/textEditMonitor.js@@ -8,6 +8,8 @@ const POLL_INTERVAL_MS = 500;const INITIAL_QUERY_DELAY_MS = 500; // Wait for paste to settle in target appconst INITIAL_QUERY_RETRIES = 4; // Retry if AXValue is empty (paste not yet processed)const INITIAL_QUERY_RETRY_DELAY_MS = 300;+const ACTIVATE_CONFIRM_RETRIES = 6; // Poll the frontmost app until activation lands+const ACTIVATE_CONFIRM_DELAY_MS = 25;// AppleScript to enable AXEnhancedUserInterface on the target app.// Chromium-based apps (Chrome, Electron, VS Code, Slack, etc.) don't build their@@ -94,47 +96,75 @@ class TextEditMonitor extends EventEmitter {*/captureTargetPid() {if (process.platform !== "darwin") return;- const script =- 'ObjC.import("AppKit"); $.NSWorkspace.sharedWorkspace.frontmostApplication.processIdentifier';- execFile("osascript", ["-l", "JavaScript", "-e", script], { timeout: 2000 }, (err, stdout) => {- if (err) {- this.lastTargetPid = null;- } else {- const pid = parseInt(stdout.trim(), 10);- this.lastTargetPid = isNaN(pid) ? null : pid;- }- debugLogger.debug("[TextEditMonitor] Captured target PID", { pid: this.lastTargetPid });+ this._readFrontmostPid().then((pid) => {+ this.lastTargetPid = pid;+ debugLogger.debug("[TextEditMonitor] Captured target PID", { pid });});}/**- * macOS: bring the captured target app to the front before pasting.- * More reliable than hide()'s implicit hand-off for Chromium apps (#668).+ * macOS: resolve the frontmost app's PID, or null if it can't be read.*/- activateTargetPid() {+ _readFrontmostPid() {return new Promise((resolve) => {- if (process.platform !== "darwin" || !this.lastTargetPid) {- resolve(false);+ if (process.platform !== "darwin") {+ resolve(null);return;}- const pid = this.lastTargetPid;const script =- `ObjC.import("AppKit"); ` +- `const app = $.NSRunningApplication.runningApplicationWithProcessIdentifier(${pid}); ` +- `if (app.isNil) { "not_found" } else { app.activateWithOptions(2); "ok" }`;- execFile(- "osascript",- ["-l", "JavaScript", "-e", script],- { timeout: 1000 },- (err, stdout) => {- const ok = !err && stdout.trim() === "ok";- debugLogger.debug("[TextEditMonitor] Activated target PID", { pid, ok });- resolve(ok);+ 'ObjC.import("AppKit"); $.NSWorkspace.sharedWorkspace.frontmostApplication.processIdentifier';+ execFile("osascript", ["-l", "JavaScript", "-e", script], { timeout: 2000 }, (err, stdout) => {+ const pid = err ? NaN : parseInt(stdout.trim(), 10);+ resolve(isNaN(pid) ? null : pid);+ });+ });+ }++ /**+ * macOS: request activation of the app with the given PID, bringing all its+ * windows forward (AllWindows|IgnoringOtherApps) so one becomes key. Scans+ * runningApplications because NSRunningApplication's PID lookup returns nil under JXA.+ */+ _activateApp(pid) {+ return new Promise((resolve) => {+ const script = `+ ObjC.import("AppKit");+ const apps = $.NSWorkspace.sharedWorkspace.runningApplications;+ for (let i = 0; i < apps.count; i++) {+ const a = apps.objectAtIndex(i);+ if (a.processIdentifier === ${pid}) { a.activateWithOptions(3); break; }}- );+ `;+ execFile("osascript", ["-l", "JavaScript", "-e", script], { timeout: 2000 }, () => resolve());});}+ /**+ * macOS: make the captured target app frontmost before pasting, so the global+ * Cmd+V lands in its focused field (#668). Resolves true once the target is+ * confirmed frontmost. If it is already frontmost we do nothing: re-activating+ * an already-active Chromium app (e.g. Claude Desktop) drops its field's first+ * responder — the focus loss this fixes — and skipping also avoids a needless+ * activation round-trip. Otherwise we activate and poll until the OS reports the+ * target frontmost, the macOS analogue of Linux's `xdotool windowactivate --sync`.+ */+ async activateTargetPid() {+ if (process.platform !== "darwin" || !this.lastTargetPid) return false;+ const pid = this.lastTargetPid;+ if ((await this._readFrontmostPid()) === pid) return true;++ await this._activateApp(pid);+ for (let i = 0; i < ACTIVATE_CONFIRM_RETRIES; i++) {+ await new Promise((resolve) => setTimeout(resolve, ACTIVATE_CONFIRM_DELAY_MS));+ if ((await this._readFrontmostPid()) === pid) {+ debugLogger.debug("[TextEditMonitor] Activated target PID", { pid });+ return true;+ }+ }+ debugLogger.debug("[TextEditMonitor] Target did not become frontmost", { pid });+ return false;+ }+/*** macOS: read the char before the cursor in the focused text field, used by* paste-time smart spacing. Resolves to { state: "ok", char } | { state:diff --git a/src/helpers/windowManager.js b/src/helpers/windowManager.jsindex 7d9d2dfde..0fe1e3ea7 100644--- a/src/helpers/windowManager.js+++ b/src/helpers/windowManager.js@@ -457,6 +457,10 @@ class WindowManager {}sendToggleVoiceAgent() {+ // The voice-agent hotkeys, unlike the dictation paths, don't capture the+ // target PID at their call sites, so capture here or the paste can't+ // refocus the target (#668).+ if (this.textEditMonitor) this.textEditMonitor.captureTargetPid();this._sendDictationToggle("toggle-voice-agent");}diff --git a/test/helpers/textEditMonitorPrecedingChar.test.js b/test/helpers/textEditMonitorPrecedingChar.test.jsindex aa3b7581e..8744fe757 100644--- a/test/helpers/textEditMonitorPrecedingChar.test.js+++ b/test/helpers/textEditMonitorPrecedingChar.test.js@@ -19,3 +19,21 @@ test("getPrecedingChar returns unknown when the AX read fails or hangs", async (assert.equal(result.state, "unknown");assert.ok(Date.now() - start < 3000);});++test("activateTargetPid resolves false when no target PID was captured", async () => {+ const m = new TextEditMonitor();+ m.lastTargetPid = null;+ assert.equal(await m.activateTargetPid(), false);+});++test("activateTargetPid resolves false for an unmapped PID", async () => {+ const m = new TextEditMonitor();+ // Non-darwin short-circuits; darwin can't make a non-existent PID frontmost,+ // so the confirm poll times out. Both resolve quickly to false rather than+ // reporting a target that was never frontmost as active.+ m.lastTargetPid = 99999999;+ const start = Date.now();+ const result = await m.activateTargetPid();+ assert.equal(result, false);+ assert.ok(Date.now() - start < 3000);+});