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(linux): prevent target detection from delaying dictation (#1945)
Idris Gadie7a39295cbf8
diff --git a/resources/linux-fast-paste.c b/resources/linux-fast-paste.cindex 64af68bd6..e8d6180ad 100644--- a/resources/linux-fast-paste.c+++ b/resources/linux-fast-paste.c@@ -25,6 +25,14 @@#ifdef HAVE_ATSPI#include <atspi/atspi.h>++/* libatspi gives every application it hasn't seen yet 15s to answer, and every+ * application is new to this short-lived process. One peer that stops+ * answering (xdg-desktop-portal-gtk stuck at its fd limit, #1944) then stalls+ * the whole walk past the caller's kill. Bound every call instead, so the walk+ * skips that peer, still reaches the focused window, and stays inside the+ * app's 1.2s selection and 2s target budgets. */+#define ATSPI_CALL_TIMEOUT_MS 500#endif/* Paste key sequence. SHIFT_INSERT is the universal Linux paste shortcut —@@ -402,8 +410,14 @@ static int check_parent_terminal(Display *dpy, Window win) {}#ifdef HAVE_ATSPI+static int init_atspi(void) {+ int status = atspi_init();+ atspi_set_timeout(ATSPI_CALL_TIMEOUT_MS, -1);+ return status;+}+static int detect_terminal_atspi(void) {- atspi_init();+ if (init_atspi() != 0) return -1;AtspiAccessible *desktop = atspi_get_desktop(0);if (!desktop) return -1;@@ -494,6 +508,7 @@ static int atspi_active_pid(AtspiAccessible *app) {}static int print_atspi_target(void) {+ if (init_atspi() != 0) return 1;AtspiAccessible *app = NULL;AtspiAccessible *win = find_active_atspi_window(&app);int pid = app ? atspi_active_pid(app) : 0;@@ -505,6 +520,7 @@ static int print_atspi_target(void) {}static int print_atspi_selection(void) {+ if (init_atspi() != 0) return 1;AtspiAccessible *app = NULL;AtspiAccessible *win = find_active_atspi_window(&app);int pid = app ? atspi_active_pid(app) : 0;diff --git a/scripts/build-linux-fast-paste.js b/scripts/build-linux-fast-paste.jsindex a0e055d62..3e115148b 100755--- a/scripts/build-linux-fast-paste.js+++ b/scripts/build-linux-fast-paste.js@@ -107,9 +107,12 @@ function getAtspiFlags() {stdio: "pipe",});if (cflags.status === 0 && libs.status === 0) {+ // atspi-2.pc lists gobject-2.0 under Requires.private, so plain --libs+ // omits -lgobject-2.0; add it explicitly for --as-needed linkers.return [...cflags.stdout.toString().trim().split(/\s+/),...libs.stdout.toString().trim().split(/\s+/),+ "-lgobject-2.0",].filter(Boolean);}} catch {}diff --git a/src/helpers/ipcHandlers.js b/src/helpers/ipcHandlers.jsindex 155f53d95..4ee3fe753 100644--- a/src/helpers/ipcHandlers.js+++ b/src/helpers/ipcHandlers.js@@ -1520,8 +1520,11 @@ class IPCHandlers {});ipcMain.handle("capture-dictation-target", async () => {+ // Recording start awaits this handler, so the Linux/Windows window probe+ // runs in the background: a stalled AT-SPI peer would otherwise hold the+ // microphone for seconds (#1944). Its consumers wait for it themselves.+ void this.selectionManager?.captureTarget?.();const pid = (await this.textEditMonitor?.captureTargetPid?.()) ?? null;- await this.selectionManager?.captureTarget?.();return { success: true, pid };});diff --git a/src/helpers/selectionManager.js b/src/helpers/selectionManager.jsindex e0bfb25e1..e2b366fac 100644--- a/src/helpers/selectionManager.js+++ b/src/helpers/selectionManager.js@@ -11,6 +11,8 @@ const MAX_SELECTION_EDIT_CODE_POINTS = 6000;const COPY_TIMEOUT_MS = 1200;const CLIPBOARD_POLL_MS = 20;const ATSPI_TARGET_TIMEOUT_MS = 2000;+const TARGET_CAPTURE_FRESHNESS_MS = 250;+const ATSPI_COOLDOWN_MS = 2000;// Editors that copy the whole current line when Ctrl+C (⌘C on macOS) lands with// an empty selection (VS Code's editor.emptySelectionClipboard, Scintilla,@@ -61,19 +63,20 @@ function runFile(command, args, options = {}) {function runSpawn(command, args, options = {}) {return new Promise((resolve) => {+ const { timeout = COPY_TIMEOUT_MS, ...spawnOptions } = options;const child = spawn(command, args, {stdio: ["ignore", "pipe", "pipe"],windowsHide: true,- ...options,+ ...spawnOptions,});let stdout = "";let stderr = "";let settled = false;- const finish = (success) => {+ const finish = (success, timedOut = false) => {if (settled) return;settled = true;clearTimeout(timer);- resolve({ success, stdout, stderr });+ resolve({ success, timedOut, stdout, stderr });};child.stdout?.on("data", (chunk) => (stdout += chunk.toString()));child.stderr?.on("data", (chunk) => (stderr += chunk.toString()));@@ -84,8 +87,8 @@ function runSpawn(command, args, options = {}) {child.on("close", (code) => finish(code === 0));const timer = setTimeout(() => {child.kill("SIGKILL");- finish(false);- }, options.timeout || COPY_TIMEOUT_MS);+ finish(false, true);+ }, timeout);});}@@ -109,10 +112,22 @@ class SelectionManager {this.sessions = new Map();this.lastTarget = null;this._captureTargetPromise = null;+ this._lastTargetCaptureAt = 0;+ this._atspiCooldownUntil = 0;+ this._atspiProbeGeneration = 0;}- async captureTarget() {+ async captureTarget({ force = false } = {}) {if (this.platform === "darwin") return;+ if (!force) {+ if (this._captureTargetPromise) return this._captureTargetPromise;+ if (+ this.lastTarget !== null &&+ this.now() - this._lastTargetCaptureAt < TARGET_CAPTURE_FRESHNESS_MS+ ) {+ return;+ }+ }this.lastTarget = null;const probe = this._probeTarget();this._captureTargetPromise = probe;@@ -121,6 +136,7 @@ class SelectionManager {// only the latest probe's result may land in lastTarget.if (this._captureTargetPromise === probe) {this.lastTarget = target;+ this._lastTargetCaptureAt = this.now();this._captureTargetPromise = null;}}@@ -622,8 +638,16 @@ class SelectionManager {async _readLinuxAtspiSelection(binary, expectedTarget) {if (!binary) return { status: "unavailable", code: "copy_helper_unavailable" };+ if (this.now() < this._atspiCooldownUntil) {+ return { status: "unavailable", code: "accessibility_unavailable" };+ }+ const generation = ++this._atspiProbeGeneration;const result = await runSpawn(binary, ["--atspi-selection"], { timeout: COPY_TIMEOUT_MS });+ if (result.timedOut && generation === this._atspiProbeGeneration) {+ this._atspiCooldownUntil = this.now() + ATSPI_COOLDOWN_MS;+ debugLogger.warn("AT-SPI selection probe timed out", { cooldownMs: ATSPI_COOLDOWN_MS });+ }if (!result.success) return { status: "unavailable", code: "accessibility_unavailable" };const selected = result.stdout.match(/^ATSPI_SELECTED\s+(\d+)\s+([A-Za-z0-9+/=]+)$/m);@@ -652,7 +676,8 @@ class SelectionManager {// On native Wayland, xdotool can report a stale XWayland window. Prefer// AT-SPI when available so the target and selected text come from the// compositor's actual focused accessibility object.- if (this.clipboardManager._isWayland?.()) {+ const isWayland = this.clipboardManager._isWayland?.() === true;+ if (isWayland) {const atspiTarget = await this._getLinuxAtspiTarget();if (atspiTarget) return atspiTarget;}@@ -698,15 +723,21 @@ class SelectionManager {}}- return this._getLinuxAtspiTarget();+ return isWayland ? null : this._getLinuxAtspiTarget();}async _getLinuxAtspiTarget() {+ if (this.now() < this._atspiCooldownUntil) return null;const binary = this.clipboardManager.resolveLinuxFastPasteBinary();if (!binary) return null;+ const generation = ++this._atspiProbeGeneration;const result = await runSpawn(binary, ["--atspi-target"], {timeout: ATSPI_TARGET_TIMEOUT_MS,});+ if (result.timedOut && generation === this._atspiProbeGeneration) {+ this._atspiCooldownUntil = this.now() + ATSPI_COOLDOWN_MS;+ debugLogger.warn("AT-SPI target probe timed out", { cooldownMs: ATSPI_COOLDOWN_MS });+ }const match = result.stdout.match(/^TARGET\s+ATSPI\s+(\d+)$/m);return result.success && match ? { kind: "atspi-pid", id: match[1] } : null;}diff --git a/src/helpers/windowManager.js b/src/helpers/windowManager.jsindex 4c663ca4b..af226a0b9 100644--- a/src/helpers/windowManager.js+++ b/src/helpers/windowManager.js@@ -936,7 +936,7 @@ class WindowManager {// sites in main.js; a stop-press capture resolves the same frontmost// app, since NSWorkspace ignores the overlay panel.const targetPidPromise = this.textEditMonitor?.captureTargetPid?.();- void this.selectionManager?.captureTarget?.();+ void this.selectionManager?.captureTarget?.({ force: !isStarting });if (!isStarting) {this._mainWindowPlacementCoordinator.cancelPending();}diff --git a/test/helpers/captureDictationTargetIpc.test.js b/test/helpers/captureDictationTargetIpc.test.jsnew file mode 100644index 000000000..e467c2b7a--- /dev/null+++ b/test/helpers/captureDictationTargetIpc.test.js@@ -0,0 +1,115 @@+const test = require("node:test");+const assert = require("node:assert/strict");+const Module = require("node:module");+const { deferred } = require("./harness/deferred");++const handlersModulePath = require.resolve("../../src/helpers/ipcHandlers");+const originalLoad = Module._load;+const handlers = new Map();++const electronStub = {+ app: {+ getPath: () => "/tmp",+ getName: () => "test",+ getVersion: () => "0.0.0",+ isPackaged: false,+ on: () => {},+ requestSingleInstanceLock: () => true,+ },+ ipcMain: {+ handle: (channel, fn) => handlers.set(channel, fn),+ on: () => {},+ removeHandler: () => {},+ },+ net: { fetch: async () => ({ ok: true, status: 200, json: async () => ({}) }) },+ BrowserWindow: class BrowserWindow {+ static getAllWindows() {+ return [];+ }+ static fromWebContents() {+ return null;+ }+ },+ shell: {},+ dialog: {},+ screen: { getPrimaryDisplay: () => ({ workAreaSize: { width: 0, height: 0 } }) },+ systemPreferences: { getMediaAccessStatus: () => "granted" },+ session: { fromPartition: () => ({}) },+ clipboard: {},+ nativeImage: {},+ globalShortcut: {},+ utilityProcess: {},+ MessageChannelMain: class {},+};++Module._load = function loadWithElectronStub(request, parent, isMain) {+ if (request === "electron") return electronStub;+ if (parent?.filename === handlersModulePath && request === "./debugLogger") {+ return new Proxy({}, { get: () => () => {} });+ }+ return originalLoad.call(this, request, parent, isMain);+};++function anything() {+ return new Proxy(function () {}, {+ get: (_target, property) => {+ if (property === Symbol.toPrimitive || property === "toString") return () => "";+ if (property === "then") return undefined;+ return anything();+ },+ apply: () => anything(),+ });+}++let target;+test.before(() => {+ delete require.cache[handlersModulePath];+ const IPCHandlers = require(handlersModulePath);+ const Ctor = IPCHandlers.default || IPCHandlers;+ target = { textEditMonitor: null, selectionManager: null };+ Ctor.prototype.setupHandlers.call(+ new Proxy(target, {+ get: (value, property) => (property in value ? value[property] : anything()),+ })+ );+ assert.ok(+ handlers.get("capture-dictation-target"),+ "capture-dictation-target must be registered"+ );+});++test.after(() => {+ Module._load = originalLoad;+});++// Recording start awaits this handler (#1944): a stalled Linux AT-SPI or Windows+// window probe must not hold it, while the macOS frontmost-PID read still must.+test("capture-dictation-target awaits the target PID but not the window probe", async () => {+ const probe = deferred();+ const pidRead = deferred();+ let probeStarted = false;+ target.selectionManager = {+ captureTarget: () => {+ probeStarted = true;+ return probe.promise;+ },+ };+ target.textEditMonitor = { captureTargetPid: () => pidRead.promise };++ let settled = false;+ const pending = handlers+ .get("capture-dictation-target")()+ .then((result) => {+ settled = true;+ return result;+ });+ await new Promise((resolve) => setImmediate(resolve));+ assert.equal(probeStarted, true);+ assert.equal(settled, false, "the handler must wait for the target PID");++ pidRead.resolve(4242);+ await new Promise((resolve) => setImmediate(resolve));+ assert.equal(settled, true, "the handler must not wait for the window probe");+ probe.resolve(null);+ assert.deepEqual(await pending, { success: true, pid: 4242 });+});diff --git a/test/helpers/selectionManager.test.js b/test/helpers/selectionManager.test.jsindex 7960847f0..3c669056c 100644--- a/test/helpers/selectionManager.test.js+++ b/test/helpers/selectionManager.test.js@@ -511,7 +511,57 @@ test("captureSelectedText awaits an in-flight target probe before reading lastTaassert.equal(result.text, "picked");});-test("a superseded probe never overwrites the newer probe's target", async () => {+test("start target captures share in-flight and recent work", async () => {+ let now = 1000;+ let calls = 0;+ const resolvers = [];+ const manager = new SelectionManager({+ clipboardManager: {},+ textEditMonitor: {},+ platform: "linux",+ now: () => now,+ });+ manager._probeTarget = () => {+ calls += 1;+ return new Promise((resolve) => resolvers.push(resolve));+ };++ const first = manager.captureTarget();+ const joined = manager.captureTarget();+ assert.equal(calls, 1);+ resolvers[0]({ kind: "atspi-pid", id: "1" });+ await Promise.all([first, joined]);++ const reused = manager.captureTarget();+ assert.equal(calls, 1);+ await reused;++ now += 250;+ const refreshed = manager.captureTarget();+ assert.equal(calls, 2);+ resolvers[1]({ kind: "atspi-pid", id: "2" });+ await refreshed;+});++test("a failed target probe is retried rather than reused", async () => {+ let calls = 0;+ const manager = new SelectionManager({+ clipboardManager: {},+ textEditMonitor: {},+ platform: "linux",+ now: () => 1000,+ });+ manager._probeTarget = async () => {+ calls += 1;+ return null;+ };++ await manager.captureTarget();+ await manager.captureTarget();+ assert.equal(calls, 2);+});++test("a forced probe stays fresh and older work cannot overwrite it", async () => {const clipboardManager = { runClipboardOperation: (operation) => operation() };const manager = new SelectionManager({clipboardManager,@@ -523,7 +573,7 @@ test("a superseded probe never overwrites the newer probe's target", async () =>manager._getLinuxTarget = () => new Promise((resolve) => resolvers.push(resolve));const first = manager.captureTarget();- const second = manager.captureTarget();+ const second = manager.captureTarget({ force: true });resolvers[1]({ kind: "atspi-pid", id: "2" });await second;resolvers[0]({ kind: "atspi-pid", id: "1" });@@ -532,6 +582,142 @@ test("a superseded probe never overwrites the newer probe's target", async () =>assert.deepEqual(manager.lastTarget, { kind: "atspi-pid", id: "2" });});+test("Wayland target lookup attempts AT-SPI once", async () => {+ const spawnCalls = [];+ const SpawningSelectionManager = loadSelectionManager({+ spawn: (command, args) => {+ spawnCalls.push({ command, args });+ const child = new EventEmitter();+ child.stdout = new EventEmitter();+ child.stderr = new EventEmitter();+ child.kill = () => {};+ process.nextTick(() => child.emit("close", 1));+ return child;+ },+ });+ const manager = new SpawningSelectionManager({+ clipboardManager: {+ _isWayland: () => true,+ commandExists: () => false,+ resolveLinuxFastPasteBinary: () => "/tmp/linux-fast-paste",+ },+ platform: "linux",+ now: () => 1000,+ });++ assert.equal(await manager._getLinuxTarget(), null);+ assert.equal(await manager._getLinuxTarget(), null);+ assert.deepEqual(spawnCalls, [+ { command: "/tmp/linux-fast-paste", args: ["--atspi-target"] },+ { command: "/tmp/linux-fast-paste", args: ["--atspi-target"] },+ ]);+});++test("an AT-SPI timeout opens a cooldown and retries after it expires", async (t) => {+ t.mock.timers.enable({ apis: ["setTimeout"] });+ let now = 1000;+ let spawns = 0;+ let kills = 0;+ const SpawningSelectionManager = loadSelectionManager({+ spawn: () => {+ spawns += 1;+ const child = new EventEmitter();+ child.stdout = new EventEmitter();+ child.stderr = new EventEmitter();+ child.kill = () => {+ kills += 1;+ };+ return child;+ },+ });+ const manager = new SpawningSelectionManager({+ clipboardManager: {+ resolveLinuxFastPasteBinary: () => "/tmp/linux-fast-paste",+ },+ platform: "linux",+ now: () => now,+ });++ const first = manager._getLinuxAtspiTarget();+ t.mock.timers.tick(2000);+ assert.equal(await first, null);+ assert.equal(spawns, 1);+ assert.equal(kills, 1);++ const cooledTarget = manager._getLinuxAtspiTarget();+ assert.equal(spawns, 1, "a target probe must not spawn during the cooldown");+ assert.equal(await cooledTarget, null);+ const cooledSelection = manager._readLinuxAtspiSelection("/tmp/linux-fast-paste", {+ kind: "atspi-pid",+ id: "42",+ });+ assert.equal(spawns, 1, "a selection read must not spawn during the cooldown");+ assert.equal((await cooledSelection).code, "accessibility_unavailable");++ now += 2000;+ const retry = manager._getLinuxAtspiTarget();+ t.mock.timers.tick(2000);+ assert.equal(await retry, null);+ assert.equal(spawns, 2);+ assert.equal(kills, 2);++ now += 2000;+ const selection = manager._readLinuxAtspiSelection("/tmp/linux-fast-paste", {+ kind: "atspi-pid",+ id: "42",+ });+ t.mock.timers.tick(1200);+ assert.equal((await selection).status, "unavailable");+ assert.equal(spawns, 3);+ assert.equal(kills, 3);+ const cooledBySelection = manager._getLinuxAtspiTarget();+ assert.equal(spawns, 3, "a selection timeout must cool down target probes too");+ assert.equal(await cooledBySelection, null);+});++test("older AT-SPI timeouts cannot cool down a newer successful probe", async (t) => {+ t.mock.timers.enable({ apis: ["setTimeout"] });+ let spawns = 0;+ const SpawningSelectionManager = loadSelectionManager({+ spawn: () => {+ spawns += 1;+ const child = new EventEmitter();+ child.stdout = new EventEmitter();+ child.stderr = new EventEmitter();+ child.kill = () => {};+ if (spawns >= 3) {+ process.nextTick(() => {+ child.stdout.emit("data", "TARGET ATSPI 42\n");+ child.emit("close", 0);+ });+ }+ return child;+ },+ });+ const manager = new SpawningSelectionManager({+ clipboardManager: {+ resolveLinuxFastPasteBinary: () => "/tmp/linux-fast-paste",+ },+ platform: "linux",+ now: () => 1000,+ });++ const olderTarget = manager._getLinuxAtspiTarget();+ const olderSelection = manager._readLinuxAtspiSelection("/tmp/linux-fast-paste", {+ kind: "atspi-pid",+ id: "42",+ });+ const newer = manager._getLinuxAtspiTarget();+ assert.deepEqual(await newer, { kind: "atspi-pid", id: "42" });+ t.mock.timers.tick(2000);+ assert.equal(await olderTarget, null);+ assert.equal((await olderSelection).status, "unavailable");++ const next = manager._getLinuxAtspiTarget();+ assert.equal(spawns, 4, "neither older timeout may open a cooldown");+ assert.deepEqual(await next, { kind: "atspi-pid", id: "42" });+});+// The Windows paste path restores the window captured at record start (#859).// getWinTarget 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.diff --git a/test/helpers/windowManagerMeetingNotification.test.js b/test/helpers/windowManagerMeetingNotification.test.jsindex 216c177c6..3ce3d8f64 100644--- a/test/helpers/windowManagerMeetingNotification.test.js+++ b/test/helpers/windowManagerMeetingNotification.test.js@@ -345,6 +345,26 @@ test("push-to-talk dictation follows the companion pill's availability", () => {assert.deepEqual(rendererChannels, ["prepare-dictation", "start-dictation"]);});+test("a stop press probes the target again instead of reusing the start press's", () => {+ const manager = createNormalWindowManager();+ const captures = [];+ manager.mainWindow = { isDestroyed: () => false, webContents: { send: () => undefined } };+ manager.hotkeyManager = {+ isInListeningMode: () => false,+ unregisterAll: () => undefined,+ };+ manager.textEditMonitor = { captureTargetPid: () => Promise.resolve(null) };+ manager.selectionManager = { captureTarget: (options) => captures.push(options) };+ manager.showDictationPanel = () => undefined;+ manager.sendPrepareDictation = () => undefined;++ manager.sendToggleDictation();+ manager.setDictationLifecycleState("recording");+ manager.sendToggleDictation();++ assert.deepEqual(captures, [{ force: false }, { force: true }]);+});+test("window manager starts fail-closed and suppresses normal-app popup surfaces", async () => {const manager = new WindowManager();