Skip to content

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

fix(windows): restore the captured target window before pasting — fixes #859

Gabriel Steinde9e335a89a7
diff --git a/resources/windows-fast-paste.c b/resources/windows-fast-paste.c
index 67bf3f138..9d522e5a6 100644
--- a/resources/windows-fast-paste.c
+++ b/resources/windows-fast-paste.c
@@ -10,6 +10,13 @@
* 1. Window class name (fast, works for native terminals)
* 2. Executable name (fallback, catches Electron-based terminals like Termius)
*
+ * Focus restore (issue #859): the caller captures the target window handle at
+ * record start (the hex "TARGET %p" line that --detect-only prints), then
+ * passes it back as --restore-window <hwnd> at paste time. We re-activate that
+ * window before sending the keystroke so dictation lands in the field the user
+ * was in, even when something stole the foreground during transcription. This
+ * mirrors the macOS PID capture/activate path and the Linux --window path.
+ *
* Compile with: cl /O2 windows-fast-paste.c /Fe:windows-fast-paste.exe user32.lib
* Or with MinGW: gcc -O2 windows-fast-paste.c -o windows-fast-paste.exe -luser32
*/
@@ -17,6 +24,8 @@
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <stdio.h>
+#include <stdlib.h>
+#include <stdint.h>
#include <string.h>
static const char* TERMINAL_CLASSES[] = {
@@ -144,6 +153,45 @@ static int SendPasteNormal(void) {
return (sent == 4) ? 0 : 1;
}
+/* Bring a captured target window back to the foreground before pasting.
+ SetForegroundWindow alone is blocked by Windows' foreground lock when the
+ calling process isn't the current foreground owner, so we attach this
+ thread's input queue to both the current foreground thread and the target
+ thread first — the standard workaround, and what nircmd's "win activate"
+ does internally. Returns TRUE if the target ended up foreground. */
+static BOOL RestoreForegroundWindow(HWND target) {
+ if (!target || !IsWindow(target)) return FALSE;
+
+ if (GetForegroundWindow() == target) return TRUE;
+
+ if (IsIconic(target)) {
+ ShowWindow(target, SW_RESTORE);
+ }
+
+ HWND fg = GetForegroundWindow();
+ DWORD thisThread = GetCurrentThreadId();
+ DWORD targetThread = GetWindowThreadProcessId(target, NULL);
+ DWORD fgThread = fg ? GetWindowThreadProcessId(fg, NULL) : 0;
+
+ BOOL attachedTarget = FALSE;
+ BOOL attachedFg = FALSE;
+ if (targetThread && targetThread != thisThread) {
+ attachedTarget = AttachThreadInput(thisThread, targetThread, TRUE);
+ }
+ if (fgThread && fgThread != thisThread && fgThread != targetThread) {
+ attachedFg = AttachThreadInput(thisThread, fgThread, TRUE);
+ }
+
+ BringWindowToTop(target);
+ BOOL ok = SetForegroundWindow(target);
+ SetFocus(target);
+
+ if (attachedFg) AttachThreadInput(thisThread, fgThread, FALSE);
+ if (attachedTarget) AttachThreadInput(thisThread, targetThread, FALSE);
+
+ return ok && GetForegroundWindow() == target;
+}
+
static int SendPasteTerminal(void) {
INPUT inputs[6];
ZeroMemory(inputs, sizeof(inputs));
@@ -189,6 +237,7 @@ int main(int argc, char* argv[]) {
BOOL detectOnly = FALSE;
BOOL copyMode = FALSE;
BOOL capabilitiesOnly = FALSE;
+ HWND restoreWindow = NULL;
for (int i = 1; i < argc; i++) {
if (strcmp(argv[i], "--detect-only") == 0) {
@@ -197,14 +246,25 @@ int main(int argc, char* argv[]) {
copyMode = TRUE;
} else if (strcmp(argv[i], "--capabilities") == 0) {
capabilitiesOnly = TRUE;
+ } else if (strcmp(argv[i], "--restore-window") == 0 && i + 1 < argc) {
+ /* Base 16: the handle comes back exactly as --detect-only printed
+ it with "TARGET %p" (hex, with or without an 0x prefix). */
+ restoreWindow = (HWND)(uintptr_t)strtoull(argv[++i], NULL, 16);
}
}
if (capabilitiesOnly) {
- printf("paste-v1 selection-copy-v1 target-identity-v1\n");
+ printf("paste-v1 selection-copy-v1 target-identity-v1 focus-restore-v1\n");
return 0;
}
+ /* Restore the captured target to the foreground before pasting. If it is
+ gone or can't be restored we fall through to whatever is foreground now,
+ which is the pre-#859 behavior. */
+ if (restoreWindow && RestoreForegroundWindow(restoreWindow)) {
+ Sleep(20);
+ }
+
HWND hwnd = GetForegroundWindow();
if (!hwnd) {
fprintf(stderr, "ERROR: No foreground window found\n");
diff --git a/src/helpers/clipboard.js b/src/helpers/clipboard.js
index 42ccd6737..4a550243d 100644
--- a/src/helpers/clipboard.js
+++ b/src/helpers/clipboard.js
@@ -943,7 +943,10 @@ class ClipboardManager {
const nircmdPath = this.getNircmdPath();
method = nircmdPath ? "nircmd" : "powershell";
}
- pasteResult = await this.pasteWindows(originalClipboard, { expectedClipboardText: text });
+ pasteResult = await this.pasteWindows(originalClipboard, {
+ expectedClipboardText: text,
+ targetWindow: options.targetWindow,
+ });
} else {
pasteResult = await this.pasteLinux(originalClipboard, {
...options,
@@ -1125,9 +1128,17 @@ class ClipboardManager {
let hasTimedOut = false;
const startTime = Date.now();
- this.safeLog("⚡ Windows fast-paste starting");
+ // Restore the window captured at record start (#859) so the paste lands
+ // where the user was dictating even if focus drifted during
+ // transcription. The hex handle comes from --detect-only's TARGET line
+ // via selectionManager. An older cached binary ignores the unknown flag
+ // and pastes into the current foreground — the pre-fix behavior.
+ const args =
+ options.targetWindow != null ? ["--restore-window", String(options.targetWindow)] : [];
+
+ this.safeLog("⚡ Windows fast-paste starting", { targetWindow: options.targetWindow });
- const pasteProcess = spawn(fastPastePath, [], {
+ const pasteProcess = spawn(fastPastePath, args, {
stdio: ["ignore", "pipe", "pipe"],
windowsHide: true,
});
diff --git a/src/helpers/ipcHandlers.js b/src/helpers/ipcHandlers.js
index 00df09ea5..db5aab3b4 100644
--- a/src/helpers/ipcHandlers.js
+++ b/src/helpers/ipcHandlers.js
@@ -2461,9 +2461,19 @@ class IPCHandlers {
// too slow for the paste hot path.
const textToPaste = applySmartSpacing({ text, mode: "append" });
+ // Windows: restore the foreground window captured at record start so the
+ // paste lands in the field the user was dictating into, not wherever focus
+ // drifted during transcription (#859). macOS handles this via
+ // activateTargetPid above; Linux re-detects the target inside pasteLinux.
+ const targetWindow =
+ process.platform === "win32"
+ ? ((await this.selectionManager?.getWinTargetHwnd?.()) ?? null)
+ : null;
+
await this.clipboardManager.pasteText(textToPaste, {
...options,
webContents: event.sender,
+ targetWindow,
});
debugLogger.debug("[AutoLearn] Paste completed", {
autoLearnEnabled: this._autoLearnEnabled,
diff --git a/src/helpers/selectionManager.js b/src/helpers/selectionManager.js
index d7c0e6dcd..603b184a5 100644
--- a/src/helpers/selectionManager.js
+++ b/src/helpers/selectionManager.js
@@ -143,6 +143,17 @@ class SelectionManager {
return null;
}
+ // The Windows foreground window captured at record start, for the paste path
+ // to restore before Ctrl+V lands (#859). Waits out an in-flight probe for the
+ // same reason captureSelectedText does: the stop-press probe can still be
+ // running when fast transcription reaches the paste.
+ async getWinTargetHwnd() {
+ while (this._captureTargetPromise) {
+ await this._captureTargetPromise;
+ }
+ return this.lastTarget?.kind === "win-hwnd" ? this.lastTarget.id : null;
+ }
+
async captureSelectedText() {
return this.clipboardManager.runClipboardOperation(async () => {
// captureTarget() fires on every toggle press, including stop. Fast
diff --git a/test/helpers/clipboardRestore.test.js b/test/helpers/clipboardRestore.test.js
index c58b65f94..2ec5fa23b 100644
--- a/test/helpers/clipboardRestore.test.js
+++ b/test/helpers/clipboardRestore.test.js
@@ -247,6 +247,47 @@ test("pasteText waits for prior clipboard restoration before starting the next p
assert.deepEqual(events, ["start:first", "end:first", "start:second", "end:second"]);
});
+test("pasteWithFastPaste passes --restore-window <hwnd> when targetWindow is set (#859)", async () => {
+ const spawnCalls = [];
+ const TestClipboardManager = loadClipboardManager({
+ spawn: createSuccessfulSpawn(spawnCalls),
+ });
+ const manager = new TestClipboardManager();
+ manager._restoreClipboardAfterDelay = () => Promise.resolve();
+
+ const result = await manager.pasteWithFastPaste(
+ "/tmp/windows-fast-paste.exe",
+ { type: "text", data: "previous clipboard" },
+ // Hex id: the binary prints "TARGET %p" (hex) from --detect-only and parses
+ // --restore-window with strtoull base 16, so the handle stays hex end to end.
+ { expectedClipboardText: "dictated text", targetWindow: "1A2B3C" }
+ );
+ await result.restoreComplete;
+
+ assert.equal(spawnCalls.length, 1);
+ assert.equal(spawnCalls[0].command, "/tmp/windows-fast-paste.exe");
+ assert.deepEqual(spawnCalls[0].args, ["--restore-window", "1A2B3C"]);
+});
+
+test("pasteWithFastPaste sends no args when nothing was captured", async () => {
+ const spawnCalls = [];
+ const TestClipboardManager = loadClipboardManager({
+ spawn: createSuccessfulSpawn(spawnCalls),
+ });
+ const manager = new TestClipboardManager();
+ manager._restoreClipboardAfterDelay = () => Promise.resolve();
+
+ const result = await manager.pasteWithFastPaste(
+ "/tmp/windows-fast-paste.exe",
+ { type: "text", data: "previous clipboard" },
+ { expectedClipboardText: "dictated text" }
+ );
+ await result.restoreComplete;
+
+ assert.equal(spawnCalls.length, 1);
+ assert.deepEqual(spawnCalls[0].args, []);
+});
+
test("Hyprland paste uses the current symbolic shortcut dispatcher", async () => {
const spawnCalls = [];
const TestClipboardManager = loadClipboardManager({
diff --git a/test/helpers/selectionManager.test.js b/test/helpers/selectionManager.test.js
index c47eec771..4dd367375 100644
--- a/test/helpers/selectionManager.test.js
+++ b/test/helpers/selectionManager.test.js
@@ -1,16 +1,21 @@
const test = 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 selectionManagerPath = require.resolve("../../src/helpers/selectionManager");
const originalLoad = Module._load;
-function loadSelectionManager() {
+function loadSelectionManager({ spawn } = {}) {
delete require.cache[selectionManagerPath];
Module._load = function loadWithElectronMock(request, parent, isMain) {
if (request === "electron") {
return { clipboard: { readText: () => "", writeText: () => {} } };
}
+ if (request === "child_process" && spawn) {
+ return { ...childProcess, spawn };
+ }
return originalLoad.call(this, request, parent, isMain);
};
try {
@@ -296,6 +301,75 @@ test("a superseded probe never overwrites the newer probe's target", async () =>
assert.deepEqual(manager.lastTarget, { kind: "atspi-pid", id: "2" });
});
+// The Windows paste path restores the window captured at record start (#859).
+// getWinTargetHwnd hands the paste that HWND exactly as --detect-only printed
+// it ("TARGET %p", hex) so the binary's base-16 --restore-window parse round-trips.
+test("getWinTargetHwnd returns the hex HWND a win32 probe captured (#859)", async () => {
+ const spawnCalls = [];
+ const SpawningSelectionManager = loadSelectionManager({
+ spawn: (command, args) => {
+ spawnCalls.push({ command, args });
+ const probe = new EventEmitter();
+ probe.stdout = new EventEmitter();
+ probe.stderr = new EventEmitter();
+ process.nextTick(() => {
+ probe.stdout.emit(
+ "data",
+ "TARGET 00001A2B\nWINDOW_CLASS Chrome_WidgetWin_1\nIS_TERMINAL false\n"
+ );
+ probe.emit("close", 0);
+ });
+ return probe;
+ },
+ });
+ const manager = new SpawningSelectionManager({
+ clipboardManager: { resolveWindowsFastPasteBinary: () => "/tmp/windows-fast-paste.exe" },
+ textEditMonitor: {},
+ platform: "win32",
+ now: () => 1000,
+ });
+
+ await manager.captureTarget();
+
+ assert.deepEqual(spawnCalls, [
+ { command: "/tmp/windows-fast-paste.exe", args: ["--detect-only"] },
+ ]);
+ assert.equal(await manager.getWinTargetHwnd(), "00001A2B");
+});
+
+// captureTarget() nulls lastTarget while its probe runs; a paste racing the
+// stop-press probe must wait for the answer instead of restoring nothing.
+test("getWinTargetHwnd waits for an in-flight probe before answering", async () => {
+ const manager = new SelectionManager({
+ clipboardManager: {},
+ textEditMonitor: {},
+ platform: "win32",
+ now: () => 1000,
+ });
+ let resolveProbe;
+ manager._probeTarget = () => new Promise((resolve) => (resolveProbe = resolve));
+
+ const probe = manager.captureTarget();
+ const pending = manager.getWinTargetHwnd();
+ resolveProbe({ kind: "win-hwnd", id: "0000F00D" });
+ await probe;
+
+ assert.equal(await pending, "0000F00D");
+});
+
+test("getWinTargetHwnd is null without a capture or with a non-Windows target", async () => {
+ const manager = new SelectionManager({
+ clipboardManager: {},
+ textEditMonitor: {},
+ platform: "linux",
+ now: () => 1000,
+ });
+ assert.equal(await manager.getWinTargetHwnd(), null);
+
+ manager.lastTarget = { kind: "x11-window", id: "7" };
+ assert.equal(await manager.getWinTargetHwnd(), null);
+});
+
// Replacement text typed into a shell executes on its embedded newlines, so a
// terminal target must read as no selection (standalone dictation), not as an
// editable selection.