Skip to content

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

fix(paste): wait for held modifier keys before injecting a paste on Linux (#2207)

void01d28384e56a
diff --git a/CLAUDE.md b/CLAUDE.md
index 30ea6c359..b0232436c 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -62,6 +62,7 @@ OpenWhispr is an Electron-based desktop dictation application that uses whisper.
- macOS: AppleScript-based paste with accessibility permission check
- Windows: PowerShell SendKeys with nircmd.exe fallback
- Linux: compositor-aware Wayland paste (Hyprland sendshortcut, wlroots wtype, GNOME/KDE portal keysyms) with native uinput/XTest and system-tool fallbacks
+ - Linux: before any paste or selection-copy chord, `linux-fast-paste --capabilities --await-modifier-release <ms>` waits for physically held modifiers to be released (XKB state on X11, `EVIOCGKEY` on Wayland; `unknown` without `/dev/input` access pastes as before). A chord injected into held keys arrives as a different shortcut, and a virtual device cannot release another device's key (#2113). Still held after 1.5 s → not pasted, `reason: "modifiers-held"`, and the renderer shows the dictation-error pill with the transcript on the clipboard; a selection edit blocked the same way reports `code: "modifiers_held"` and gets the same pill (the assistant caret paste reports the same code, for logs only). `ydotoold`'s virtual keyboard is ignored, since an interrupted chord can leave its modifier down, and an unreadable key state is logged once per session. The wait runs before `pasteLinux` detects the target window, and a selection copy that had to wait looks the target up again, since focus can move while a key is held: a fresh capture then runs the command on its own (`focus_moved`), and a revalidated session declines as `target_changed`. Retry on a modifiers-held pill pastes the kept transcript again rather than recording again (the macOS/Windows push force-stop pill keeps its record-again Retry, since neither platform waits for held keys), ignores clicks while its paste is pending, and never dismisses a newer pill. `useAudioRecording` keeps the pill in processing until the paste attempt settles (the audio manager settles before the paste starts), but never reports that to main, which drops dictation hotkeys while processing; a paste held back after the next dictation started leaves the transcript on the clipboard without a pill. The helper measures its wait on `CLOCK_MONOTONIC`, since the JS watchdog kills it at timeout + 1 s
- **database.js**: SQLite operations for transcription history
- **debugLogger.js**: Debug logging system with file output
- **devServerManager.js**: Vite dev server integration
diff --git a/resources/linux-fast-paste.c b/resources/linux-fast-paste.c
index 8279899ed..64af68bd6 100644
--- a/resources/linux-fast-paste.c
+++ b/resources/linux-fast-paste.c
@@ -6,16 +6,20 @@
#include <X11/Xlib.h>
#include <X11/Xatom.h>
#include <X11/Xutil.h>
+#include <X11/XKBlib.h>
#include <X11/extensions/XTest.h>
#include <X11/extensions/shape.h>
#include <X11/keysym.h>
+#include <dirent.h>
+#include <fcntl.h>
+#include <linux/input.h>
#include <math.h>
+#include <sys/ioctl.h>
+#include <time.h>
#include <unistd.h>
#ifdef HAVE_UINPUT
#include <linux/uinput.h>
-#include <linux/input.h>
-#include <fcntl.h>
#include <errno.h>
#endif
@@ -843,6 +847,128 @@ static int serve_input_region(Window window)
return 0;
}
+/* A paste or copy chord injected while the user still physically holds a
+ * modifier (the rest of a push-to-talk chord, or a tap hotkey still down when a
+ * fast transcript lands) reaches the target as a different shortcut, and the
+ * text is lost (#2113). Releasing the key on the user's behalf is not possible:
+ * the kernel drops a key-up from a virtual device that never pressed that key.
+ * So wait for the user to let go instead. */
+#define MODIFIER_POLL_MS 10
+/* Lets the compositor process the physical release before the chord arrives. */
+#define MODIFIER_SETTLE_MS 30
+#define MAX_KEYBOARDS 64
+#define KEY_BITS_SIZE (KEY_MAX / 8 + 1)
+
+typedef enum {
+ MODIFIERS_RELEASED = 0,
+ MODIFIERS_HELD = 1,
+ MODIFIERS_UNKNOWN = 2,
+} modifier_state_t;
+
+static const int modifier_keys[] = {
+ KEY_LEFTCTRL, KEY_RIGHTCTRL, KEY_LEFTSHIFT, KEY_RIGHTSHIFT,
+ KEY_LEFTALT, KEY_RIGHTALT, KEY_LEFTMETA, KEY_RIGHTMETA,
+};
+
+static int test_key_bit(const unsigned char *bits, int code) {
+ return (bits[code / 8] >> (code % 8)) & 1;
+}
+
+/* ydotoold's virtual keyboard can keep a modifier down after an interrupted
+ * chord. That is not the user's hand, so it must not hold every paste back.
+ * The name is the same in ydotool 0.1.x and 1.0.x. */
+#define YDOTOOLD_DEVICE_NAME "ydotoold virtual device"
+
+/* The KEY_A test from linux-key-listener.c: EV_KEY devices with a KEY_A bit. */
+static int open_keyboards(int *fds) {
+ DIR *dir = opendir("/dev/input");
+ if (!dir) return 0;
+
+ int count = 0;
+ struct dirent *ent;
+ while ((ent = readdir(dir)) && count < MAX_KEYBOARDS) {
+ if (strncmp(ent->d_name, "event", 5) != 0) continue;
+
+ char path[512];
+ snprintf(path, sizeof(path), "/dev/input/%s", ent->d_name);
+ int fd = open(path, O_RDONLY | O_NONBLOCK);
+ if (fd < 0) continue;
+
+ unsigned char key_bits[KEY_BITS_SIZE] = { 0 };
+ char name[128] = "";
+ ioctl(fd, EVIOCGNAME(sizeof(name) - 1), name);
+ if (ioctl(fd, EVIOCGBIT(EV_KEY, sizeof(key_bits)), key_bits) < 0 ||
+ !test_key_bit(key_bits, KEY_A) || strcmp(name, YDOTOOLD_DEVICE_NAME) == 0) {
+ close(fd);
+ continue;
+ }
+ fds[count++] = fd;
+ }
+ closedir(dir);
+ return count;
+}
+
+static modifier_state_t evdev_modifier_state(const int *fds, int count) {
+ for (int i = 0; i < count; i++) {
+ unsigned char keys[KEY_BITS_SIZE] = { 0 };
+ if (ioctl(fds[i], EVIOCGKEY(sizeof(keys)), keys) < 0) continue;
+ for (size_t k = 0; k < sizeof(modifier_keys) / sizeof(modifier_keys[0]); k++) {
+ if (test_key_bit(keys, modifier_keys[k])) return MODIFIERS_HELD;
+ }
+ }
+ return MODIFIERS_RELEASED;
+}
+
+/* base_mods only counts keys that are down, so a locked Caps Lock or Num Lock
+ * never reads as held. A server whose state cannot be read is unknown, not
+ * released: the caller must know the wait was blind. */
+static modifier_state_t x11_modifier_state(Display *display) {
+ XkbStateRec state;
+ if (XkbGetState(display, XkbUseCoreKbd, &state) != Success) return MODIFIERS_UNKNOWN;
+ return state.base_mods != 0 ? MODIFIERS_HELD : MODIFIERS_RELEASED;
+}
+
+/* Mirrors getLinuxSessionInfo() in src/helpers/linuxSession.js. XWayland only
+ * tracks keys while one of its own windows has focus, so the X server is trusted
+ * on an X11 session only; Wayland reads the kernel's key state, which needs the
+ * same /dev/input access as push-to-talk. */
+static int is_wayland_session(void) {
+ const char *session_type = getenv("XDG_SESSION_TYPE");
+ return (session_type && strcasecmp(session_type, "wayland") == 0) ||
+ getenv("WAYLAND_DISPLAY") != NULL;
+}
+
+static long monotonic_ms(void) {
+ struct timespec now;
+ clock_gettime(CLOCK_MONOTONIC, &now);
+ return now.tv_sec * 1000L + now.tv_nsec / 1000000L;
+}
+
+static modifier_state_t await_modifier_release(int timeout_ms, int *waited_ms) {
+ Display *display = is_wayland_session() ? NULL : XOpenDisplay(NULL);
+ int fds[MAX_KEYBOARDS];
+ int count = display ? 0 : open_keyboards(fds);
+ *waited_ms = 0;
+ if (!display && count == 0) return MODIFIERS_UNKNOWN;
+
+ /* Measured on the clock, not by counting sleeps: usleep overshoots under
+ * load, and the caller kills a helper that runs past timeout + 1s. */
+ long started_at = monotonic_ms();
+ modifier_state_t state;
+ while ((state = display ? x11_modifier_state(display) : evdev_modifier_state(fds, count)) ==
+ MODIFIERS_HELD &&
+ *waited_ms < timeout_ms) {
+ usleep(MODIFIER_POLL_MS * 1000);
+ *waited_ms = (int)(monotonic_ms() - started_at);
+ }
+
+ if (display) XCloseDisplay(display);
+ for (int i = 0; i < count; i++) close(fds[i]);
+
+ if (state == MODIFIERS_RELEASED && *waited_ms > 0) usleep(MODIFIER_SETTLE_MS * 1000);
+ return state;
+}
+
int main(int argc, char *argv[]) {
int force_terminal = 0;
int force_shift_insert = 0;
@@ -854,6 +980,7 @@ int main(int argc, char *argv[]) {
int input_region_server = 0;
int atspi_target_only = 0;
int atspi_selection = 0;
+ int modifier_wait_ms = -1;
const char *restore_token = NULL;
Window target_window = None;
@@ -882,15 +1009,25 @@ int main(int argc, char *argv[]) {
restore_token = argv[++i];
} else if (strcmp(argv[i], "--window") == 0 && i + 1 < argc) {
target_window = (Window)strtoul(argv[++i], NULL, 0);
+ } else if (strcmp(argv[i], "--await-modifier-release") == 0 && i + 1 < argc) {
+ modifier_wait_ms = atoi(argv[++i]);
}
}
- /* --capabilities makes older binaries exit harmlessly instead of pasting
- * when they encounter the new server flag. */
+ /* Callers pair these flags with --capabilities, so an older binary that
+ * ignores them prints its capabilities and exits instead of pasting. */
if (input_region_server) return serve_input_region(target_window);
+ if (modifier_wait_ms >= 0) {
+ static const char *state_names[] = { "released", "held", "unknown" };
+ int waited_ms;
+ modifier_state_t state = await_modifier_release(modifier_wait_ms, &waited_ms);
+ printf("MODIFIERS %s %d\n", state_names[state], waited_ms);
+ return 0;
+ }
+
if (capabilities_only) {
- printf("paste-v1 selection-copy-v1 target-window-v1");
+ printf("paste-v1 selection-copy-v1 target-window-v1 modifier-wait-v1");
#ifdef HAVE_GIO
printf(" portal-keysym-v1");
#endif
diff --git a/src/helpers/audioManager.js b/src/helpers/audioManager.js
index bbcae6eee..b7a265497 100644
--- a/src/helpers/audioManager.js
+++ b/src/helpers/audioManager.js
@@ -4080,9 +4080,12 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);
clipboardCopied: true,
transcript: text,
});
- return false;
+ return { pasted: false };
}
- return result?.pasted === true;
+ return {
+ pasted: result?.pasted === true,
+ ...(result?.reason ? { reason: result.reason } : {}),
+ };
} catch (error) {
const message =
error?.message ??
@@ -4093,7 +4096,7 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);
// Keep the platform's guidance, without Electron's IPC wrapper around it.
description: message.replace(/^Error invoking remote method '[^']+': (?:\w*Error: )?/, ""),
});
- return false;
+ return { pasted: false };
}
}
diff --git a/src/helpers/clipboard.js b/src/helpers/clipboard.js
index 7b1a8a342..71d576abc 100644
--- a/src/helpers/clipboard.js
+++ b/src/helpers/clipboard.js
@@ -21,6 +21,12 @@ const PASTE_DELAYS = {
linux: 50,
};
+// How long a Linux paste or copy waits for the user to let go of held modifiers
+// before giving up and leaving the text on the clipboard. Covers someone still
+// resting on the rest of a push-to-talk chord; a key held on purpose past this
+// surfaces as an unpasted transcript instead of an indefinite wait.
+const MODIFIER_RELEASE_WAIT_MS = 1500;
+
const RESTORE_DELAYS = {
darwin: 450,
win32_nircmd: 500,
@@ -683,6 +689,65 @@ class ClipboardManager {
}
}
+ // A paste or copy chord injected while the user still holds a modifier reaches
+ // the target as a different shortcut (Super+Ctrl+V), and the text is lost.
+ // Resolves { state, waitedMs }: "released" (waitedMs > 0 when it had to wait),
+ // "held" once the wait runs out, or "unknown" when the key state can't be read,
+ // in which case the caller proceeds as it always has.
+ _awaitModifierRelease() {
+ const unknown = { state: "unknown", waitedMs: 0 };
+ const binary = this.resolveLinuxFastPasteBinary();
+ if (!binary) return Promise.resolve(unknown);
+
+ return new Promise((resolve) => {
+ // --capabilities comes first so an older binary that doesn't know the wait
+ // flag prints its capabilities and exits instead of falling through to a paste.
+ const proc = spawn(binary, [
+ "--capabilities",
+ "--await-modifier-release",
+ String(MODIFIER_RELEASE_WAIT_MS),
+ ]);
+ let stdout = "";
+ let timedOut = false;
+ const timeoutId = setTimeout(() => {
+ timedOut = true;
+ killProcess(proc, "SIGKILL");
+ resolve(unknown);
+ }, MODIFIER_RELEASE_WAIT_MS + 1000);
+
+ proc.stdout?.on("data", (data) => {
+ stdout += data.toString();
+ });
+
+ proc.on("close", () => {
+ if (timedOut) return;
+ clearTimeout(timeoutId);
+ const [, state = "unknown", waitedMs = "0"] =
+ stdout.match(/^MODIFIERS (released|held|unknown) (\d+)$/m) || [];
+ if (state === "held" || Number(waitedMs) > 0) {
+ debugLogger.info("Waited for held modifier keys", { state, waitedMs }, "clipboard");
+ }
+ // "unknown" (no /dev/input access on Wayland, or a helper too old for the
+ // flag) means the wait is inert; say so once so support can tell it apart
+ // from a genuine "released".
+ if (state === "unknown" && !this._modifierStateUnreadableLogged) {
+ this._modifierStateUnreadableLogged = true;
+ debugLogger.info(
+ "Modifier key state unreadable, pasting without waiting",
+ { isWayland: getLinuxSessionInfo().isWayland, helperOutput: stdout.trim() },
+ "clipboard"
+ );
+ }
+ resolve({ state, waitedMs: Number(waitedMs) });
+ });
+
+ proc.on("error", () => {
+ clearTimeout(timeoutId);
+ resolve(unknown);
+ });
+ });
+ }
+
_runLinuxPasteCommand(command, args, label, { expectedOutput } = {}) {
return new Promise((resolve, reject) => {
debugLogger.debug("Attempting Linux paste command", { command, args, label }, "clipboard");
@@ -1534,6 +1599,16 @@ class ClipboardManager {
}
};
+ // Every tool below injects a chord, so wait here once for held modifiers. The
+ // text is already on the clipboard; returning before a restore is scheduled
+ // keeps it there for a manual paste. The wait comes before target detection:
+ // focus can move while a key is held, and the chord must suit the window the
+ // paste will actually reach.
+ if ((await this._awaitModifierRelease()).state === "held") {
+ this.safeLog("⌨️ Modifier keys still held, leaving the text on the clipboard");
+ return { pasted: false, reason: "modifiers-held", restoreComplete: Promise.resolve() };
+ }
+
const targetWindowId = preDetectTargetWindow();
let detectedWindowClass = preDetectWindowClass(targetWindowId);
diff --git a/src/helpers/ipcHandlers.js b/src/helpers/ipcHandlers.js
index 2f02c4691..f886c0384 100644
--- a/src/helpers/ipcHandlers.js
+++ b/src/helpers/ipcHandlers.js
@@ -3078,8 +3078,13 @@ class IPCHandlers {
// Promise cannot cross Electron's IPC boundary, though, and renderer
// callers need to know whether text was pasted, but not the delayed
// clipboard restoration promise. Successful platform paths predate the
- // explicit `pasted` outcome; only the clipboard-only fallback sets false.
- return { success: true, pasted };
+ // explicit `pasted` outcome; only the clipboard-only fallback and a paste
+ // held back for still-held modifiers (which carries a `reason`) set false.
+ return {
+ success: true,
+ pasted,
+ ...(pasteResult?.reason ? { reason: pasteResult.reason } : {}),
+ };
});
ipcMain.handle("check-accessibility-permission", async (_event, silent = false) => {
diff --git a/src/helpers/selectionEditing.js b/src/helpers/selectionEditing.js
index f783b772a..0d95dcac9 100644
--- a/src/helpers/selectionEditing.js
+++ b/src/helpers/selectionEditing.js
@@ -30,15 +30,18 @@ const STANDALONE_CAPTURE_CODES = new Set([
// macOS: neither the accessibility tree nor a synthetic copy could inspect the
// app, so a selection is neither readable nor ruled out.
"accessibility_unavailable",
+ // Linux: keys still held past the wait block the copy, so the same holds.
+ "modifiers_held",
+ // Linux: focus moved while those keys were held, so the window the command
+ // is about was never checked (a target_changed status).
+ "focus_moved",
]);
export function getSelectionCaptureDisposition(capture) {
if (capture?.status === "editable") return "caret";
if (!capture || capture.status === "none") return "standalone";
if (capture.status === "selected") return "selection";
- if (capture.status === "unavailable" && STANDALONE_CAPTURE_CODES.has(capture.code)) {
- return "standalone";
- }
+ if (STANDALONE_CAPTURE_CODES.has(capture.code)) return "standalone";
return capture.status === "target_changed" ? "changed" : "unavailable";
}
diff --git a/src/helpers/selectionManager.js b/src/helpers/selectionManager.js
index c31f1529e..e0bfb25e1 100644
--- a/src/helpers/selectionManager.js
+++ b/src/helpers/selectionManager.js
@@ -89,6 +89,12 @@ function runSpawn(command, args, options = {}) {
});
}
+// Keys still held past the modifier wait (#2113) get their own code, so the
+// renderer can say so instead of blaming permissions or a changed target.
+function heldBackCode(fallback, { code, reason } = {}) {
+ return code === "modifiers_held" || reason === "modifiers-held" ? "modifiers_held" : fallback;
+}
+
class SelectionManager {
constructor({
clipboardManager,
@@ -232,7 +238,7 @@ class SelectionManager {
return { success: false, code: "target_changed" };
}
if (current.status === "unavailable") {
- return { success: false, code: "selection_unavailable" };
+ return { success: false, code: heldBackCode("selection_unavailable", current) };
}
if (current.status !== "selected" || current.text !== session.text) {
return { success: false, code: "selection_changed" };
@@ -245,7 +251,7 @@ class SelectionManager {
});
await pasteResult?.restoreComplete;
if (pasteResult?.pasted === false) {
- return { success: false, code: "paste_failed" };
+ return { success: false, code: heldBackCode("paste_failed", pasteResult) };
}
return { success: true };
} catch (error) {
@@ -279,7 +285,7 @@ class SelectionManager {
const current = await this._readCurrentSelection(session.target, { probeEditable: true });
if (current.status !== "editable") {
- return this._declineAssistantPaste("target_changed", {
+ return this._declineAssistantPaste(heldBackCode("target_changed", current), {
sessionFound: true,
sessionKind: "caret",
probeStatus: current.status,
@@ -295,7 +301,7 @@ class SelectionManager {
});
await pasteResult?.restoreComplete;
if (pasteResult?.pasted === false) {
- return this._declineAssistantPaste("paste_failed", {
+ return this._declineAssistantPaste(heldBackCode("paste_failed", pasteResult), {
sessionFound: true,
sessionKind: "caret",
probeStatus: "editable",
@@ -451,6 +457,21 @@ class SelectionManager {
);
}
+ // Capture runs right after the voice assistant hotkey press, so its keys are
+ // often still down; a Ctrl+C sent into them copies nothing.
+ const modifiers = await this.clipboardManager._awaitModifierRelease();
+ if (modifiers.state === "held") {
+ return { status: "unavailable", code: "modifiers_held" };
+ }
+ // The checks above approved the window focused before the wait. If focus
+ // moved while a key was held, the chord would reach an unchecked window,
+ // and a plain Ctrl+C in a terminal interrupts whatever is running there.
+ // `focus_moved` lets a fresh capture run the command on its own; a session
+ // being revalidated still declines as a changed target.
+ if (modifiers.waitedMs > 0 && !this._sameTarget(await this._getLinuxTarget(), target)) {
+ return { status: "target_changed", code: "focus_moved" };
+ }
+
const capture = await this._captureViaClipboard(async () => {
if (binary) {
if (target.kind === "x11-window") {
diff --git a/src/hooks/useAudioRecording.js b/src/hooks/useAudioRecording.js
index b63ef2239..3d0b653b3 100644
--- a/src/hooks/useAudioRecording.js
+++ b/src/hooks/useAudioRecording.js
@@ -40,6 +40,12 @@ export const useAudioRecording = (toast, options = {}) => {
const { t } = useTranslation();
const [isRecording, setIsRecording] = useState(false);
const [isProcessing, setIsProcessing] = useState(false);
+ // The audio manager settles processing before the transcript is pasted; the
+ // hook keeps the pill in processing until the paste attempt has settled (a
+ // Linux paste can wait up to 1.5 s for held modifier keys). Main is never told:
+ // it drops dictation hotkeys while processing, and the next dictation may start
+ // while a paste is still waiting.
+ const [isPasting, setIsPasting] = useState(false);
const [isStreaming, setIsStreaming] = useState(false);
const [isAssistantVoice, setIsAssistantVoice] = useState(false);
const [isPreparing, setIsPreparing] = useState(false);
@@ -55,6 +61,7 @@ export const useAudioRecording = (toast, options = {}) => {
const preparationGenerationRef = useRef(0);
const dictationErrorGenerationRef = useRef(0);
const wasRecordingRef = useRef(false);
+ const pastesInFlightRef = useRef(0);
const wasMicUnavailableRef = useRef(false);
const demoKindRef = useRef("dictation");
const onDemoEventRef = useRef(options.onDemoEvent);
@@ -344,6 +351,8 @@ export const useAudioRecording = (toast, options = {}) => {
audioManagerRef.current?.streamingPartialText
).trim() || fallback.trim();
+ // `onRetry` replaces the default Retry (a new recording) for a pill whose
+ // transcript is already kept and only needs delivering again.
const showDictationError = ({
title,
description,
@@ -351,13 +360,14 @@ export const useAudioRecording = (toast, options = {}) => {
duration,
code,
settingsLaunchFailed = false,
+ onRetry,
}) => {
const errorGeneration = ++dictationErrorGenerationRef.current;
+ const isCurrent = () => errorGeneration === dictationErrorGenerationRef.current;
const recoverAssistant = Boolean(audioManagerRef.current?.voiceAgentRequested);
onDictationError?.({ recoverAssistant });
if (code === "ACCESSIBILITY_PERMISSION_REQUIRED") {
let settingsOpening = false;
- const isCurrent = () => errorGeneration === dictationErrorGenerationRef.current;
const actions = [
{
label: t("hooks.audioRecording.pastePermission.openSettings"),
@@ -436,12 +446,25 @@ export const useAudioRecording = (toast, options = {}) => {
return;
}
const recoverableTranscript = getRecoverableTranscript(transcript);
+ // A retried paste can wait on held keys with no visible progress, so a
+ // second click is ignored until it settles, and a paste that lands after
+ // a newer pill or recording leaves that one alone.
+ let retrying = false;
+ const retry = async () => {
+ if (retrying || !isCurrent()) return;
+ retrying = true;
+ try {
+ if ((await onRetry()) && isCurrent()) dismissDictationError?.();
+ } finally {
+ retrying = false;
+ }
+ };
const actions = [
{
label: t("common.retry"),
icon: "retry",
dismissOnClick: false,
- onClick: () => performStartRecording(lastStartOptionsRef.current),
+ onClick: onRetry ? retry : () => performStartRecording(lastStartOptionsRef.current),
},
];
@@ -723,37 +746,119 @@ export const useAudioRecording = (toast, options = {}) => {
}
};
- 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");
+ const pasteOptions = {
+ restoreClipboard: !keepTranscriptionInClipboard,
+ allowClipboardFallback: isAccessibilitySkipped(),
+ };
+
+ const whilePasting = async (attempt) => {
+ pastesInFlightRef.current += 1;
+ setIsPasting(true);
+ try {
+ return await attempt();
+ } finally {
+ pastesInFlightRef.current -= 1;
+ if (pastesInFlightRef.current === 0) setIsPasting(false);
+ }
+ };
+
+ // A paste held back because keys were still down keeps the transcript
+ // and says why it did not land. `onRetry`, when given, replaces the
+ // pill's record-again Retry. `generation` is the pill
+ // generation when the attempt began: if the next dictation started while
+ // it waited, that recording owns the pill (and would dismiss this one at
+ // once) and its live preview, so the transcript only stays on the clipboard.
+ const reportHeldBackPaste = async (
+ delivery,
+ { title, description, descriptionClipboardFailed, onRetry },
+ generation = dictationErrorGenerationRef.current
+ ) => {
+ const keptInClipboard = await keepInClipboard(delivery);
+ if (generation !== dictationErrorGenerationRef.current) {
+ logger.info(
+ "Held-back paste kept on the clipboard behind a newer dictation",
+ { delivery, keptInClipboard },
+ "clipboard"
+ );
+ return;
+ }
window.electronAPI?.hideDictationPreview?.();
showDictationError({
- title: t("hooks.audioRecording.pushForceStopped.title"),
+ 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"
- ),
+ description: keptInClipboard ? description : descriptionClipboardFailed,
transcript: result.rawText ?? result.text,
+ onRetry,
+ });
+ };
+
+ const pasteTranscript = async () => {
+ const generation = dictationErrorGenerationRef.current;
+ const pasteOutcome = await whilePasting(() =>
+ audioManagerRef.current.safePaste(result.text, {
+ ...(isStreaming ? { fromStreaming: true } : {}),
+ ...pasteOptions,
+ })
+ );
+ if (pasteOutcome.reason === "modifiers-held") {
+ await reportHeldBackPaste(
+ "modifiers-held",
+ {
+ title: t("hooks.audioRecording.modifiersHeld.title"),
+ description: t("hooks.audioRecording.modifiersHeld.description"),
+ descriptionClipboardFailed: t(
+ "hooks.audioRecording.modifiersHeld.descriptionClipboardFailed"
+ ),
+ // The modifier wait runs again, so the kept text is safe to re-paste.
+ onRetry: pasteTranscript,
+ },
+ generation
+ );
+ }
+ return pasteOutcome.pasted;
+ };
+
+ 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. Only macOS
+ // and Windows force-stop, and neither waits for held modifiers, so
+ // Retry records again rather than pasting.
+ await reportHeldBackPaste("push-force-stopped", {
+ title: t("hooks.audioRecording.pushForceStopped.title"),
+ description: t("hooks.audioRecording.pushForceStopped.description"),
+ descriptionClipboardFailed: t(
+ "hooks.audioRecording.pushForceStopped.descriptionClipboardFailed"
+ ),
});
} else if (autoPasteEnabled && !result.assistantConversation) {
const pasteStart = performance.now();
let pasteSucceeded = true;
if (result.selectionEdit?.sessionId) {
- const replacement = await window.electronAPI?.replaceSelectedText?.(
- result.selectionEdit.sessionId,
- result.text,
- {
- restoreClipboard: !keepTranscriptionInClipboard,
- allowClipboardFallback: isAccessibilitySkipped(),
- }
+ const generation = dictationErrorGenerationRef.current;
+ const replacement = await whilePasting(() =>
+ window.electronAPI?.replaceSelectedText?.(
+ result.selectionEdit.sessionId,
+ result.text,
+ pasteOptions
+ )
);
pasteSucceeded = replacement?.success === true;
- if (!pasteSucceeded) {
+ if (replacement?.code === "modifiers_held") {
+ await reportHeldBackPaste(
+ "selection-edit-modifiers-held",
+ {
+ title: t("hooks.audioRecording.selectionEditing.notAppliedTitle"),
+ description: t("hooks.audioRecording.selectionEditing.modifiersHeld"),
+ descriptionClipboardFailed: t(
+ "hooks.audioRecording.selectionEditing.modifiersHeldClipboardFailed"
+ ),
+ onRetry: pasteTranscript,
+ },
+ generation
+ );
+ } else if (!pasteSucceeded) {
window.electronAPI?.hideDictationPreview?.();
if (keepTranscriptionInClipboard) {
await keepInClipboard("selection-edit-fallback");
@@ -767,11 +872,7 @@ export const useAudioRecording = (toast, options = {}) => {
});
}
} else {
- pasteSucceeded = await audioManagerRef.current.safePaste(result.text, {
- ...(isStreaming ? { fromStreaming: true } : {}),
- restoreClipboard: !keepTranscriptionInClipboard,
- allowClipboardFallback: isAccessibilitySkipped(),
- });
+ pasteSucceeded = await pasteTranscript();
}
logger.info(
"Paste timing",
@@ -1020,7 +1121,7 @@ export const useAudioRecording = (toast, options = {}) => {
voiceAgentRequested = false,
translationRequested = false,
} = {}) => {
- if (!isRecording && !isProcessing) {
+ if (!isRecording && !isProcessing && !isPasting) {
await performStartRecording({ voiceAgentRequested, translationRequested });
} else if (isRecording) {
await performStopRecording();
@@ -1029,7 +1130,9 @@ export const useAudioRecording = (toast, options = {}) => {
return {
isRecording,
- isProcessing,
+ // A paste still waiting when the next recording starts must not paint that
+ // recording's pill as processing.
+ isProcessing: isProcessing || (isPasting && !isRecording),
isStreaming,
isAssistantVoice,
isPreparing,
diff --git a/src/locales/ar/translation.json b/src/locales/ar/translation.json
index 2b19aaae7..fd9da7467 100644
--- a/src/locales/ar/translation.json
+++ b/src/locales/ar/translation.json
@@ -62,6 +62,8 @@
"changed": "تم تغيير النص المحدد أو التطبيق المستهدف أثناء قيام OpenWhispr بالمعالجة. لم يتم استبدال أي شيء.",
"expired": "استغرق تعديل التحديد وقتًا طويلًا وانتهت صلاحيته. حدد النص وحاول مرة أخرى.",
"pasteFailed": "قام OpenWhispr بإنشاء التعديل ولكنه لم يتمكن من استبدال النص المحدد.",
+ "modifiersHeld": "أنشأ OpenWhispr التعديل، لكن مفتاح تعديل (مثل Ctrl أو Shift) كان لا يزال مضغوطًا، لذلك لم يتم تطبيقه. التعديل موجود في الحافظة.",
+ "modifiersHeldClipboardFailed": "أنشأ OpenWhispr التعديل، لكن مفتاح تعديل (مثل Ctrl أو Shift) كان لا يزال مضغوطًا، لذلك لم يتم تطبيقه، ولم يتمكن من نسخه إلى الحافظة أيضًا.",
"unavailable": "لم يتمكن OpenWhispr من قراءة النص المحدد بأمان. تحقق من أذونات إمكانية الوصول أو أتمتة الإدخال وحاول مرة أخرى.",
"tooLarge": "التحديد كبير جدًا بحيث لا يمكن تعديله بأمان. حدد 6,000 حرف أو أقل.",
"reasoningFailed": "لم يتمكن الذكاء الاصطناعي من إكمال تعديل التحديد. لم يتم تغيير نصك الأصلي."
@@ -71,6 +73,11 @@
"description": "توقف الإملاء بينما كان مفتاح الاختصار لا يزال مضغوطًا، لذلك لم يتم لصق النص. نصك المفرَّغ موجود في الحافظة.",
"descriptionClipboardFailed": "توقف الإملاء بينما كان مفتاح الاختصار لا يزال مضغوطًا، لذلك لم يتم لصق النص، ولم يمكن نسخه إلى الحافظة أيضًا."
},
+ "modifiersHeld": {
+ "title": "لم يتم لصق النص المفرَّغ",
+ "description": "كان مفتاح تعديل (مثل Ctrl أو Shift) لا يزال مضغوطًا، لذلك لم يتم لصق النص. نصك المفرَّغ موجود في الحافظة.",
+ "descriptionClipboardFailed": "كان مفتاح تعديل (مثل Ctrl أو Shift) لا يزال مضغوطًا، لذلك لم يتم لصق النص، ولم يمكن نسخه إلى الحافظة أيضًا."
+ },
"pastePermission": {
"title": "السماح باللصق التلقائي",
"description": "فعّل OpenWhispr في إعدادات النظام ← الخصوصية والأمن ← تسهيلات الاستخدام.",
diff --git a/src/locales/de/translation.json b/src/locales/de/translation.json
index ab96a91fb..d70b7b7af 100644
--- a/src/locales/de/translation.json
+++ b/src/locales/de/translation.json
@@ -937,11 +937,18 @@
"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."
},
+ "modifiersHeld": {
+ "title": "Transkription nicht eingefügt",
+ "description": "Eine Sondertaste (z. B. Strg oder Umschalt) war noch gedrückt, daher wurde der Text nicht eingefügt. Deine Transkription befindet sich in der Zwischenablage.",
+ "descriptionClipboardFailed": "Eine Sondertaste (z. B. Strg oder Umschalt) war noch gedrückt. 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.",
"expired": "Die Auswahlbearbeitung ist abgelaufen. Wähle den Text erneut aus und versuche es noch einmal.",
"pasteFailed": "OpenWhispr hat die Bearbeitung erstellt, konnte den ausgewählten Text aber nicht ersetzen.",
+ "modifiersHeld": "OpenWhispr hat die Bearbeitung erstellt, aber eine Sondertaste (z. B. Strg oder Umschalt) war noch gedrückt, daher wurde sie nicht angewendet. Die Bearbeitung befindet sich in der Zwischenablage.",
+ "modifiersHeldClipboardFailed": "OpenWhispr hat die Bearbeitung erstellt, aber eine Sondertaste (z. B. Strg oder Umschalt) war noch gedrückt, daher wurde sie nicht angewendet und konnte auch nicht in die Zwischenablage kopiert werden.",
"unavailable": "OpenWhispr konnte den ausgewählten Text nicht sicher lesen. Prüfe die Bedienungshilfen oder Eingabeautomatisierung.",
"tooLarge": "Die Auswahl ist zu groß. Wähle höchstens 6.000 Zeichen aus.",
"reasoningFailed": "Die KI konnte die Auswahlbearbeitung nicht abschließen. Dein ursprünglicher Text wurde nicht geändert."
diff --git a/src/locales/en/translation.json b/src/locales/en/translation.json
index 3ef96d276..5a74b4f12 100644
--- a/src/locales/en/translation.json
+++ b/src/locales/en/translation.json
@@ -937,11 +937,18 @@
"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."
},
+ "modifiersHeld": {
+ "title": "Transcription not pasted",
+ "description": "A modifier key (like Ctrl or Shift) was still held down, so the text was not pasted. Your transcription is on the clipboard.",
+ "descriptionClipboardFailed": "A modifier key (like Ctrl or Shift) was still held down, 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.",
"expired": "The selection edit took too long and expired. Select the text and try again.",
"pasteFailed": "OpenWhispr generated the edit but could not replace the selected text.",
+ "modifiersHeld": "OpenWhispr generated the edit, but a modifier key (like Ctrl or Shift) was still held down, so it was not applied. The edit is on the clipboard.",
+ "modifiersHeldClipboardFailed": "OpenWhispr generated the edit, but a modifier key (like Ctrl or Shift) was still held down, so it was not applied, and it could not be copied to the clipboard either.",
"unavailable": "OpenWhispr could not safely read the selected text. Check accessibility or input automation permissions and try again.",
"tooLarge": "The selection is too large to edit safely. Select 6,000 characters or fewer.",
"reasoningFailed": "The AI could not complete the selection edit. Your original text was not changed."
diff --git a/src/locales/es/translation.json b/src/locales/es/translation.json
index 40d71e337..9ca45391d 100644
--- a/src/locales/es/translation.json
+++ b/src/locales/es/translation.json
@@ -937,11 +937,18 @@
"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."
},
+ "modifiersHeld": {
+ "title": "Transcripción no pegada",
+ "description": "Una tecla modificadora (como Ctrl o Mayús) seguía pulsada, así que el texto no se pegó. Tu transcripción está en el portapapeles.",
+ "descriptionClipboardFailed": "Una tecla modificadora (como Ctrl o Mayús) 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.",
"expired": "La edición caducó. Selecciona el texto e inténtalo de nuevo.",
"pasteFailed": "OpenWhispr generó la edición, pero no pudo reemplazar el texto seleccionado.",
+ "modifiersHeld": "OpenWhispr generó la edición, pero una tecla modificadora (como Ctrl o Mayús) seguía pulsada, así que no se aplicó. La edición está en el portapapeles.",
+ "modifiersHeldClipboardFailed": "OpenWhispr generó la edición, pero una tecla modificadora (como Ctrl o Mayús) seguía pulsada, así que no se aplicó, y tampoco se pudo copiar al portapapeles.",
"unavailable": "OpenWhispr no pudo leer de forma segura el texto seleccionado. Revisa los permisos de accesibilidad o automatización.",
"tooLarge": "La selección es demasiado grande. Selecciona 6.000 caracteres o menos.",
"reasoningFailed": "La IA no pudo completar la edición. El texto original no se modificó."
diff --git a/src/locales/fr/translation.json b/src/locales/fr/translation.json
index a2e751494..663cae5db 100644
--- a/src/locales/fr/translation.json
+++ b/src/locales/fr/translation.json
@@ -937,11 +937,18 @@
"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."
},
+ "modifiersHeld": {
+ "title": "Transcription non collée",
+ "description": "Une touche de modification (comme Ctrl ou Maj) était encore enfoncée, le texte n'a donc pas été collé. Votre transcription est dans le presse-papiers.",
+ "descriptionClipboardFailed": "Une touche de modification (comme Ctrl ou Maj) était encore enfoncée : 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é.",
"expired": "La modification a expiré. Sélectionnez de nouveau le texte et réessayez.",
"pasteFailed": "OpenWhispr a généré la modification, mais n’a pas pu remplacer le texte sélectionné.",
+ "modifiersHeld": "OpenWhispr a généré la modification, mais une touche de modification (comme Ctrl ou Maj) était encore enfoncée, elle n'a donc pas été appliquée. La modification est dans le presse-papiers.",
+ "modifiersHeldClipboardFailed": "OpenWhispr a généré la modification, mais une touche de modification (comme Ctrl ou Maj) était encore enfoncée, elle n'a donc pas été appliquée, et elle n'a pas pu être copiée dans le presse-papiers non plus.",
"unavailable": "OpenWhispr n’a pas pu lire la sélection en toute sécurité. Vérifiez les autorisations d’accessibilité ou d’automatisation.",
"tooLarge": "La sélection est trop grande. Sélectionnez au maximum 6 000 caractères.",
"reasoningFailed": "L’IA n’a pas pu terminer la modification. Le texte d’origine n’a pas été modifié."
diff --git a/src/locales/it/translation.json b/src/locales/it/translation.json
index 5bf72d42f..cccf600e6 100644
--- a/src/locales/it/translation.json
+++ b/src/locales/it/translation.json
@@ -937,11 +937,18 @@
"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."
},
+ "modifiersHeld": {
+ "title": "Trascrizione non incollata",
+ "description": "Un tasto modificatore (come Ctrl o Maiusc) era ancora premuto, quindi il testo non è stato incollato. La trascrizione è negli appunti.",
+ "descriptionClipboardFailed": "Un tasto modificatore (come Ctrl o Maiusc) 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.",
"expired": "La modifica è scaduta. Seleziona di nuovo il testo e riprova.",
"pasteFailed": "OpenWhispr ha generato la modifica, ma non ha potuto sostituire il testo selezionato.",
+ "modifiersHeld": "OpenWhispr ha generato la modifica, ma un tasto modificatore (come Ctrl o Maiusc) era ancora premuto, quindi non è stata applicata. La modifica è negli appunti.",
+ "modifiersHeldClipboardFailed": "OpenWhispr ha generato la modifica, ma un tasto modificatore (come Ctrl o Maiusc) era ancora premuto, quindi non è stata applicata e non è stato possibile copiarla negli appunti.",
"unavailable": "OpenWhispr non ha potuto leggere in sicurezza il testo selezionato. Controlla i permessi di accessibilità o automazione.",
"tooLarge": "La selezione è troppo grande. Seleziona al massimo 6.000 caratteri.",
"reasoningFailed": "L’IA non ha potuto completare la modifica. Il testo originale non è stato cambiato."
diff --git a/src/locales/ja/translation.json b/src/locales/ja/translation.json
index e6bcd5235..ed6ca1205 100644
--- a/src/locales/ja/translation.json
+++ b/src/locales/ja/translation.json
@@ -937,11 +937,18 @@
"description": "ホットキーが押されたままディクテーションが終了したため、テキストは貼り付けられませんでした。文字起こしはクリップボードにあります。",
"descriptionClipboardFailed": "ホットキーが押されたままディクテーションが終了したため、テキストは貼り付けられず、クリップボードにもコピーできませんでした。"
},
+ "modifiersHeld": {
+ "title": "文字起こしは貼り付けられませんでした",
+ "description": "修飾キー(Ctrl や Shift など)が押されたままだったため、テキストは貼り付けられませんでした。文字起こしはクリップボードにあります。",
+ "descriptionClipboardFailed": "修飾キー(Ctrl や Shift など)が押されたままだったため、テキストは貼り付けられず、クリップボードにもコピーできませんでした。"
+ },
"selectionEditing": {
"notAppliedTitle": "選択範囲の編集を適用できませんでした",
"changed": "処理中に選択したテキストまたは対象アプリが変更されました。置換は行われていません。",
"expired": "選択範囲の編集が期限切れになりました。テキストを選択し直して再試行してください。",
"pasteFailed": "OpenWhispr は編集を生成しましたが、選択したテキストを置換できませんでした。",
+ "modifiersHeld": "OpenWhispr は編集を生成しましたが、修飾キー(Ctrl や Shift など)が押されたままだったため、適用されませんでした。編集内容はクリップボードにあります。",
+ "modifiersHeldClipboardFailed": "OpenWhispr は編集を生成しましたが、修飾キー(Ctrl や Shift など)が押されたままだったため、適用されず、クリップボードにもコピーできませんでした。",
"unavailable": "OpenWhispr は選択したテキストを安全に読み取れませんでした。アクセシビリティまたは入力自動化の権限を確認してください。",
"tooLarge": "選択範囲が大きすぎます。6,000文字以内を選択してください。",
"reasoningFailed": "AI は選択範囲の編集を完了できませんでした。元のテキストは変更されていません。"
diff --git a/src/locales/pt/translation.json b/src/locales/pt/translation.json
index 21566dd4a..0cfa62d87 100644
--- a/src/locales/pt/translation.json
+++ b/src/locales/pt/translation.json
@@ -916,11 +916,18 @@
"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."
},
+ "modifiersHeld": {
+ "title": "Transcrição não colada",
+ "description": "Uma tecla modificadora (como Ctrl ou Shift) ainda estava pressionada, por isso o texto não foi colado. Sua transcrição está na área de transferência.",
+ "descriptionClipboardFailed": "Uma tecla modificadora (como Ctrl ou Shift) 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.",
"expired": "A edição expirou. Selecione o texto novamente e tente de novo.",
"pasteFailed": "O OpenWhispr gerou a edição, mas não conseguiu substituir o texto selecionado.",
+ "modifiersHeld": "O OpenWhispr gerou a edição, mas uma tecla modificadora (como Ctrl ou Shift) ainda estava pressionada, por isso ela não foi aplicada. A edição está na área de transferência.",
+ "modifiersHeldClipboardFailed": "O OpenWhispr gerou a edição, mas uma tecla modificadora (como Ctrl ou Shift) ainda estava pressionada, por isso ela não foi aplicada e também não foi possível copiá-la para a área de transferência.",
"unavailable": "O OpenWhispr não conseguiu ler o texto selecionado com segurança. Verifique as permissões de acessibilidade ou automação.",
"tooLarge": "A seleção é muito grande. Selecione no máximo 6.000 caracteres.",
"reasoningFailed": "A IA não conseguiu concluir a edição. O texto original não foi alterado."
diff --git a/src/locales/ru/translation.json b/src/locales/ru/translation.json
index 7209f95ed..1c4093db0 100644
--- a/src/locales/ru/translation.json
+++ b/src/locales/ru/translation.json
@@ -937,11 +937,18 @@
"description": "Диктовка остановилась, пока клавиша была зажата, поэтому текст не был вставлен. Расшифровка находится в буфере обмена.",
"descriptionClipboardFailed": "Диктовка остановилась, пока клавиша была зажата: текст не был вставлен и его также не удалось скопировать в буфер обмена."
},
+ "modifiersHeld": {
+ "title": "Расшифровка не вставлена",
+ "description": "Клавиша-модификатор (например, Ctrl или Shift) была зажата, поэтому текст не был вставлен. Расшифровка находится в буфере обмена.",
+ "descriptionClipboardFailed": "Клавиша-модификатор (например, Ctrl или Shift) была зажата: текст не был вставлен и его также не удалось скопировать в буфер обмена."
+ },
"selectionEditing": {
"notAppliedTitle": "Изменение выделения не применено",
"changed": "Выделенный текст или целевое приложение изменились во время обработки. Текст не был заменён.",
"expired": "Время изменения истекло. Выделите текст заново и повторите попытку.",
"pasteFailed": "OpenWhispr создал изменение, но не смог заменить выделенный текст.",
+ "modifiersHeld": "OpenWhispr создал изменение, но клавиша-модификатор (например, Ctrl или Shift) была зажата, поэтому оно не было применено. Изменение находится в буфере обмена.",
+ "modifiersHeldClipboardFailed": "OpenWhispr создал изменение, но клавиша-модификатор (например, Ctrl или Shift) была зажата, поэтому оно не было применено, и скопировать его в буфер обмена также не удалось.",
"unavailable": "OpenWhispr не смог безопасно прочитать выделенный текст. Проверьте разрешения специальных возможностей или автоматизации ввода.",
"tooLarge": "Выделение слишком большое. Выберите не более 6 000 символов.",
"reasoningFailed": "ИИ не смог завершить изменение. Исходный текст не был изменён."
diff --git a/src/locales/zh-CN/translation.json b/src/locales/zh-CN/translation.json
index 97dd6b373..4c5ee45f6 100644
--- a/src/locales/zh-CN/translation.json
+++ b/src/locales/zh-CN/translation.json
@@ -937,11 +937,18 @@
"description": "听写停止时快捷键仍处于按下状态,因此未粘贴文本。转录内容已复制到剪贴板。",
"descriptionClipboardFailed": "听写停止时快捷键仍处于按下状态,因此未粘贴文本,也无法复制到剪贴板。"
},
+ "modifiersHeld": {
+ "title": "转录内容未粘贴",
+ "description": "修饰键(如 Ctrl 或 Shift)仍处于按下状态,因此未粘贴文本。转录内容已复制到剪贴板。",
+ "descriptionClipboardFailed": "修饰键(如 Ctrl 或 Shift)仍处于按下状态,因此未粘贴文本,也无法复制到剪贴板。"
+ },
"selectionEditing": {
"notAppliedTitle": "未应用选中文本编辑",
"changed": "处理期间,选中的文本或目标应用已发生变化。未替换任何内容。",
"expired": "选中文本编辑已过期。请重新选择文本后再试。",
"pasteFailed": "OpenWhispr 已生成编辑结果,但无法替换选中的文本。",
+ "modifiersHeld": "OpenWhispr 已生成编辑结果,但修饰键(如 Ctrl 或 Shift)仍处于按下状态,因此未应用。编辑结果已复制到剪贴板。",
+ "modifiersHeldClipboardFailed": "OpenWhispr 已生成编辑结果,但修饰键(如 Ctrl 或 Shift)仍处于按下状态,因此未应用,也无法复制到剪贴板。",
"unavailable": "OpenWhispr 无法安全读取选中的文本。请检查辅助功能或输入自动化权限。",
"tooLarge": "选中的内容过长。请选择不超过 6,000 个字符。",
"reasoningFailed": "AI 无法完成选中文本编辑。原始文本未被更改。"
diff --git a/src/locales/zh-TW/translation.json b/src/locales/zh-TW/translation.json
index 3a9e215c8..2f1cf6f75 100644
--- a/src/locales/zh-TW/translation.json
+++ b/src/locales/zh-TW/translation.json
@@ -937,11 +937,18 @@
"description": "聽寫停止時快捷鍵仍處於按住狀態,因此未貼上文字。轉錄內容已複製到剪貼簿。",
"descriptionClipboardFailed": "聽寫停止時快捷鍵仍處於按住狀態,因此未貼上文字,也無法複製到剪貼簿。"
},
+ "modifiersHeld": {
+ "title": "轉錄內容未貼上",
+ "description": "修飾鍵(如 Ctrl 或 Shift)仍處於按住狀態,因此未貼上文字。轉錄內容已複製到剪貼簿。",
+ "descriptionClipboardFailed": "修飾鍵(如 Ctrl 或 Shift)仍處於按住狀態,因此未貼上文字,也無法複製到剪貼簿。"
+ },
"selectionEditing": {
"notAppliedTitle": "未套用選取文字編輯",
"changed": "處理期間,選取的文字或目標應用程式已變更。未取代任何內容。",
"expired": "選取文字編輯已逾時。請重新選取文字後再試。",
"pasteFailed": "OpenWhispr 已產生編輯結果,但無法取代選取的文字。",
+ "modifiersHeld": "OpenWhispr 已產生編輯結果,但修飾鍵(如 Ctrl 或 Shift)仍處於按住狀態,因此未套用。編輯結果已複製到剪貼簿。",
+ "modifiersHeldClipboardFailed": "OpenWhispr 已產生編輯結果,但修飾鍵(如 Ctrl 或 Shift)仍處於按住狀態,因此未套用,也無法複製到剪貼簿。",
"unavailable": "OpenWhispr 無法安全讀取選取的文字。請檢查輔助使用或輸入自動化權限。",
"tooLarge": "選取內容過長。請選取不超過 6,000 個字元。",
"reasoningFailed": "AI 無法完成選取文字編輯。原始文字未被變更。"
diff --git a/src/types/electron.ts b/src/types/electron.ts
index 0625a13b4..b1a910e36 100644
--- a/src/types/electron.ts
+++ b/src/types/electron.ts
@@ -1158,7 +1158,7 @@ declare global {
allowClipboardFallback?: boolean;
}
) => Promise<
- | { success: true; pasted: boolean }
+ | { success: true; pasted: boolean; reason?: "modifiers-held" }
| {
success: false;
pasted: false;
@@ -1199,6 +1199,7 @@ declare global {
| "selection_unavailable"
| "selection_changed"
| "paste_failed"
+ | "modifiers_held"
| "selection_manager_unavailable";
error?: string;
}>;
@@ -1213,6 +1214,7 @@ declare global {
| "session_expired"
| "target_changed"
| "paste_failed"
+ | "modifiers_held"
| "selection_manager_unavailable";
error?: string;
}>;
diff --git a/test/helpers/audioManagerAssistantDirective.test.js b/test/helpers/audioManagerAssistantDirective.test.js
index 4209b48e6..42d151467 100644
--- a/test/helpers/audioManagerAssistantDirective.test.js
+++ b/test/helpers/audioManagerAssistantDirective.test.js
@@ -290,6 +290,28 @@ test("an ambiguous capture with no dictation editor goes to the panel as a plain
assert.equal(manager.pendingAssistantConversation.transcript, "summarize this");
});
+// Focus moved while the voice assistant hotkey's keys were still held (#2113),
+// so the window the command is about was never checked. That is no selection to
+// edit, not a failed edit: the command still runs in the panel.
+test("a capture whose focus moved during the modifier wait runs as a panel command", async (t) => {
+ const { createManager } = await loadAudioManager(t, {
+ cachePrefix: "openwhispr-assistant-focus-moved-",
+ settingsKey: "__assistantFocusMovedSettings",
+ });
+ const { manager, modelCalls } = managerWithCapture(createManager, {
+ status: "target_changed",
+ code: "focus_moved",
+ });
+
+ const result = await manager.processAgentCommand("summarize this", "gpt", "Aria", {
+ selectionEditReachable: true,
+ });
+
+ assert.equal(result, "summarize this");
+ assert.equal(manager.pendingAssistantConversation.transcript, "summarize this");
+ assert.equal(modelCalls.length, 0, "the dictation-agent model must not run");
+});
+
test("a selection with the dictation agent reachable keeps the in-place edit path", async (t) => {
const { createManager } = await loadAudioManager(t, {
cachePrefix: "openwhispr-assistant-sel-reachable-",
diff --git a/test/helpers/audioManagerCleanupFallback.test.js b/test/helpers/audioManagerCleanupFallback.test.js
index df95f9781..5cfda12ff 100644
--- a/test/helpers/audioManagerCleanupFallback.test.js
+++ b/test/helpers/audioManagerCleanupFallback.test.js
@@ -183,7 +183,7 @@ test("a truncated cleanup inside the translation chain still reports the failure
});
});
-test("safePaste returns false when the preload reports that no text was pasted", async (t) => {
+test("safePaste reports not pasted when the preload reports that no text was pasted", async (t) => {
const { createManager, window } = await loadAudioManager(t, {
cachePrefix: "openwhispr-audio-cleanup-paste-outcome-",
settingsKey: "__audioCleanupPasteOutcomeSettings",
@@ -193,10 +193,12 @@ test("safePaste returns false when the preload reports that no text was pasted",
});
window.electronAPI.pasteText = async () => ({ success: true, pasted: false });
- assert.equal(await manager.safePaste("onboarding transcript"), false);
+ assert.deepEqual(await manager.safePaste("onboarding transcript"), {
+ pasted: false,
+ });
});
-test("safePaste returns true only when the preload reports a completed paste", async (t) => {
+test("safePaste reports pasted only when the preload reports a completed paste", async (t) => {
const { createManager, window } = await loadAudioManager(t, {
cachePrefix: "openwhispr-audio-cleanup-paste-success-",
settingsKey: "__audioCleanupPasteSuccessSettings",
@@ -206,7 +208,31 @@ test("safePaste returns true only when the preload reports a completed paste", a
});
window.electronAPI.pasteText = async () => ({ success: true, pasted: true });
- assert.equal(await manager.safePaste("completed transcript"), true);
+ assert.deepEqual(await manager.safePaste("completed transcript"), {
+ pasted: true,
+ });
+});
+
+// The hook tells a paste held back for still-held modifiers apart from an
+// ordinary clipboard-only fallback by this reason, so it must survive safePaste.
+test("safePaste passes through why a paste was held back", async (t) => {
+ const { createManager, window } = await loadAudioManager(t, {
+ cachePrefix: "openwhispr-audio-cleanup-paste-held-",
+ settingsKey: "__audioCleanupPasteHeldSettings",
+ });
+ const manager = createManager({
+ onError: () => assert.fail("a held-back paste is not a paste error"),
+ });
+ window.electronAPI.pasteText = async () => ({
+ success: true,
+ pasted: false,
+ reason: "modifiers-held",
+ });
+
+ assert.deepEqual(await manager.safePaste("held transcript"), {
+ pasted: false,
+ reason: "modifiers-held",
+ });
});
test("translation cleanup failures survive successful and skipped translation for post-paste warnings", async (t) => {
diff --git a/test/helpers/audioManagerPasteRecovery.test.js b/test/helpers/audioManagerPasteRecovery.test.js
index 6b63a8cf3..e4060c07a 100644
--- a/test/helpers/audioManagerPasteRecovery.test.js
+++ b/test/helpers/audioManagerPasteRecovery.test.js
@@ -24,7 +24,7 @@ test("safePaste preserves exact final text only for confirmed permission recover
clipboardCopied: true,
};
};
- assert.equal(await manager.safePaste(text, options), false);
+ assert.deepEqual(await manager.safePaste(text, options), { pasted: false });
assert.deepEqual(calls, [[text, options]]);
assert.deepEqual(errors, [
{
@@ -38,13 +38,13 @@ test("safePaste preserves exact final text only for confirmed permission recover
for (const pasted of [true, false]) {
errors.length = 0;
window.electronAPI.pasteText = async () => ({ success: true, pasted });
- assert.equal(await manager.safePaste(text), pasted);
+ assert.deepEqual(await manager.safePaste(text), { pasted });
assert.deepEqual(errors, []);
}
window.electronAPI.pasteText = async () => {
throw new Error("accessibility in an unrelated error");
};
- assert.equal(await manager.safePaste(text), false);
+ assert.deepEqual(await manager.safePaste(text), { pasted: false });
assert.deepEqual(errors, [
{
title: "Paste Error",
@@ -59,7 +59,7 @@ test("safePaste preserves exact final text only for confirmed permission recover
"Error invoking remote method 'paste-text': Error: Please install xdotool or paste manually with Ctrl+V."
);
};
- assert.equal(await manager.safePaste(text), false);
+ assert.deepEqual(await manager.safePaste(text), { pasted: false });
assert.equal(errors[0].description, "Please install xdotool or paste manually with Ctrl+V.");
window.electronAPI.pasteText = async () => {
diff --git a/test/helpers/clipboardRestore.test.js b/test/helpers/clipboardRestore.test.js
index d82a17648..3f73a79ed 100644
--- a/test/helpers/clipboardRestore.test.js
+++ b/test/helpers/clipboardRestore.test.js
@@ -63,7 +63,10 @@ const clipboardModulePath = require.resolve("../../src/helpers/clipboard");
const originalLoad = Module._load;
-function loadClipboardManager({ spawn, accessibility = true } = {}) {
+// The held-modifier wait spawns the fast-paste binary ahead of every Linux paste.
+// Tests that pin the paste chain's spawn sequence see it as already released;
+// the wait itself is covered by tests that load with `realModifierWait`.
+function loadClipboardManager({ spawn, accessibility = true, realModifierWait = false } = {}) {
delete require.cache[clipboardModulePath];
Module._load = function loadWithMocks(request, parent, isMain) {
@@ -82,7 +85,14 @@ function loadClipboardManager({ spawn, accessibility = true } = {}) {
};
try {
- return require("../../src/helpers/clipboard");
+ const LoadedClipboardManager = require("../../src/helpers/clipboard");
+ if (!realModifierWait) {
+ LoadedClipboardManager.prototype._awaitModifierRelease = async () => ({
+ state: "released",
+ waitedMs: 0,
+ });
+ }
+ return LoadedClipboardManager;
} finally {
Module._load = originalLoad;
}
@@ -731,6 +741,229 @@ test("XWayland fallback remains reachable after native Wayland failure", async (
);
});
+const MODIFIER_WAIT_CALL = {
+ command: "/tmp/linux-fast-paste",
+ args: ["--capabilities", "--await-modifier-release", "1500"],
+};
+
+// A chord injected into still-held modifiers reaches the target as a different
+// shortcut (#2113), so every paste tool — not only the fast-paste binary — waits.
+for (const [desktop, commandExists, injector] of [
+ ["Sway", (command) => command === "wtype", "wtype"],
+ ["GNOME", () => false, "/tmp/linux-fast-paste"],
+]) {
+ test(`${desktop} waits for held modifiers before ${injector} injects the paste`, async () => {
+ const spawnCalls = [];
+ const TestClipboardManager = loadClipboardManager({
+ spawn: createSpawn(spawnCalls, [0, 0], { stdout: ["MODIFIERS released 120\n"] }),
+ realModifierWait: true,
+ });
+ const manager = new TestClipboardManager();
+ manager.commandExists = commandExists;
+ manager.resolveLinuxFastPasteBinary = () => "/tmp/linux-fast-paste";
+ manager._readPortalToken = () => null;
+
+ const result = await withWaylandEnvironment(desktop, () => manager.pasteLinux(null));
+
+ assert.deepEqual(spawnCalls[0], MODIFIER_WAIT_CALL);
+ assert.deepEqual(
+ spawnCalls.slice(1).map((call) => call.command),
+ [injector]
+ );
+ assert.notEqual(result.pasted, false);
+ });
+}
+
+test("modifiers still held leave the text on the clipboard without injecting", async () => {
+ const spawnCalls = [];
+ const TestClipboardManager = loadClipboardManager({
+ spawn: createSpawn(spawnCalls, [0], { stdout: ["MODIFIERS held 1500\n"] }),
+ realModifierWait: true,
+ });
+ const manager = new TestClipboardManager();
+ let restoreScheduled = false;
+ manager.commandExists = (command) => command === "wtype";
+ manager.resolveLinuxFastPasteBinary = () => "/tmp/linux-fast-paste";
+ manager._restoreClipboardAfterDelay = async () => {
+ restoreScheduled = true;
+ };
+
+ const result = await withWaylandEnvironment("Sway", () =>
+ manager.pasteLinux({ type: "text", data: "previous clipboard" })
+ );
+
+ assert.deepEqual(spawnCalls, [MODIFIER_WAIT_CALL]);
+ assert.equal(result.pasted, false);
+ assert.equal(result.reason, "modifiers-held");
+ assert.equal(restoreScheduled, false, "the transcript stays on the clipboard");
+});
+
+// The wait can outlast a focus change (the user switches to a terminal while
+// still holding a key), so the chord is chosen for the window focused once the
+// keys are up — the one it will actually reach.
+test("the paste target is detected after the modifier wait", async () => {
+ const spawnCalls = [];
+ const TestClipboardManager = loadClipboardManager({
+ spawn: createSpawn(spawnCalls, [0], { stdout: ["MODIFIERS released 400\n"] }),
+ realModifierWait: true,
+ });
+ const manager = new TestClipboardManager();
+ const dispatched = [];
+ manager.commandExists = (command) => command === "hyprctl";
+ manager.resolveLinuxFastPasteBinary = () => "/tmp/linux-fast-paste";
+ manager._detectHyprlandWindowClass = () => (spawnCalls.length > 0 ? "kitty" : "gedit");
+ manager._runLinuxPasteCommand = async (command, args) => dispatched.push(args.at(-1));
+ manager._restoreClipboardAfterDelay = async () => {};
+
+ await withWaylandEnvironment("Hyprland", () => manager.pasteLinux(null));
+
+ assert.deepEqual(spawnCalls, [MODIFIER_WAIT_CALL]);
+ assert.match(dispatched[0], /mods = "CTRL SHIFT", key = "V"/);
+});
+
+// "unknown" (a Wayland session without /dev/input access) and the capabilities
+// line an older binary prints for the unknown flag both mean the state can't be
+// read, which must paste exactly as before.
+for (const [label, output] of [
+ ["an unreadable key state", "MODIFIERS unknown 0\n"],
+ ["an older binary", "paste-v1 selection-copy-v1 target-window-v1\n"],
+]) {
+ test(`${label} still pastes`, async () => {
+ const spawnCalls = [];
+ const TestClipboardManager = loadClipboardManager({
+ spawn: createSpawn(spawnCalls, [0, 0], { stdout: [output] }),
+ realModifierWait: true,
+ });
+ const manager = new TestClipboardManager();
+ manager.commandExists = (command) => command === "wtype";
+ manager.resolveLinuxFastPasteBinary = () => "/tmp/linux-fast-paste";
+
+ await withWaylandEnvironment("Sway", () => manager.pasteLinux(null));
+
+ assert.deepEqual(
+ spawnCalls.map((call) => call.command),
+ ["/tmp/linux-fast-paste", "wtype"]
+ );
+ });
+}
+
+// The helper can only hang if the X server or an evdev read stalls, but a hung
+// wait must never hang the paste: the watchdog kills it and pastes as before.
+test("a hung modifier wait is killed after the watchdog budget, reads as unknown, and ignores its late answer", async (t) => {
+ t.mock.timers.enable({ apis: ["setTimeout"] });
+ const debugLogger = require("../../src/helpers/debugLogger");
+ const info = t.mock.method(debugLogger, "info");
+ const kills = [];
+ let hungProcess;
+ const TestClipboardManager = loadClipboardManager({
+ spawn: () => {
+ hungProcess = new EventEmitter();
+ hungProcess.stdout = new EventEmitter();
+ hungProcess.stderr = new EventEmitter();
+ hungProcess.exitCode = null;
+ hungProcess.kill = (signal) => kills.push(signal);
+ return hungProcess;
+ },
+ realModifierWait: true,
+ });
+ const manager = new TestClipboardManager();
+ manager.resolveLinuxFastPasteBinary = () => "/tmp/linux-fast-paste";
+
+ let state = null;
+ const wait = manager._awaitModifierRelease().then((resolved) => {
+ state = resolved.state;
+ });
+ t.mock.timers.tick(2499);
+ await Promise.resolve();
+ assert.equal(state, null, "the wait budget plus a second of slack is honored");
+ assert.deepEqual(kills, []);
+
+ t.mock.timers.tick(1);
+ await wait;
+ assert.equal(state, "unknown");
+ assert.deepEqual(kills, ["SIGKILL"]);
+
+ hungProcess.stdout.emit("data", "MODIFIERS held 1500\n");
+ hungProcess.emit("close", null);
+ assert.equal(
+ info.mock.calls.filter((call) => call.arguments[0] === "Waited for held modifier keys").length,
+ 0,
+ "a killed helper's late output is not logged as a wait"
+ );
+});
+
+// Without /dev/input access on Wayland the helper answers "unknown" and the fix
+// is inert; the log must say so once, or support cannot tell that from "released".
+test("an unreadable modifier state is logged once per session", async (t) => {
+ const debugLogger = require("../../src/helpers/debugLogger");
+ const info = t.mock.method(debugLogger, "info");
+ const TestClipboardManager = loadClipboardManager({
+ spawn: createSpawn([], [0, 0, 0, 0], {
+ stdout: ["MODIFIERS unknown 0\n", "", "MODIFIERS unknown 0\n", ""],
+ }),
+ realModifierWait: true,
+ });
+ const manager = new TestClipboardManager();
+ manager.commandExists = (command) => command === "wtype";
+ manager.resolveLinuxFastPasteBinary = () => "/tmp/linux-fast-paste";
+
+ await withWaylandEnvironment("Sway", async () => {
+ await manager.pasteLinux(null);
+ await manager.pasteLinux(null);
+ });
+
+ const unreadable = info.mock.calls.filter(
+ (call) => call.arguments[0] === "Modifier key state unreadable, pasting without waiting"
+ );
+ assert.equal(unreadable.length, 1);
+ assert.deepEqual(unreadable[0].arguments[1], {
+ isWayland: true,
+ helperOutput: "MODIFIERS unknown 0",
+ });
+ assert.equal(unreadable[0].arguments[2], "clipboard");
+});
+
+test(
+ "a modifier wait whose helper fails to spawn reads as unknown",
+ { timeout: 5000 },
+ async (t) => {
+ // Frozen timers: only the spawn error itself may settle the wait, not the watchdog.
+ t.mock.timers.enable({ apis: ["setTimeout"] });
+ const TestClipboardManager = loadClipboardManager({
+ spawn: () => {
+ const failedProcess = new EventEmitter();
+ failedProcess.stdout = new EventEmitter();
+ failedProcess.stderr = new EventEmitter();
+ process.nextTick(() => failedProcess.emit("error", new Error("ENOENT")));
+ return failedProcess;
+ },
+ realModifierWait: true,
+ });
+ const manager = new TestClipboardManager();
+ manager.resolveLinuxFastPasteBinary = () => "/tmp/linux-fast-paste";
+
+ assert.deepEqual(await manager._awaitModifierRelease(), { state: "unknown", waitedMs: 0 });
+ }
+);
+
+test("without the fast-paste binary the paste chain is unchanged", async () => {
+ const spawnCalls = [];
+ const TestClipboardManager = loadClipboardManager({
+ spawn: createSuccessfulSpawn(spawnCalls),
+ realModifierWait: true,
+ });
+ const manager = new TestClipboardManager();
+ manager.commandExists = (command) => command === "wtype";
+ manager.resolveLinuxFastPasteBinary = () => null;
+
+ await withWaylandEnvironment("Sway", () => manager.pasteLinux(null));
+
+ assert.deepEqual(
+ spawnCalls.map((call) => call.command),
+ ["wtype"]
+ );
+});
+
test("pasteMacOS restores clipboard after the short macOS delay on successful fast paste", async () => {
const spawnCalls = [];
const TestClipboardManager = loadClipboardManager({
diff --git a/test/helpers/ipcPasteOutcome.test.js b/test/helpers/ipcPasteOutcome.test.js
index 29074b42c..ec6a8da17 100644
--- a/test/helpers/ipcPasteOutcome.test.js
+++ b/test/helpers/ipcPasteOutcome.test.js
@@ -126,6 +126,17 @@ test("paste-text preserves a clipboard-only fallback as not pasted", async () =>
assert.deepEqual(result, { success: true, pasted: false });
});
+test("paste-text tells the renderer why a paste was held back", async () => {
+ target.windowManager = { isOnboardingDemoActive: () => false };
+ target.clipboardManager = {
+ pasteText: async () => ({ pasted: false, reason: "modifiers-held" }),
+ };
+
+ const result = await handlers.get("paste-text")({ sender: { id: 1 } }, "held transcript");
+
+ assert.deepEqual(result, { success: true, pasted: false, reason: "modifiers-held" });
+});
+
test("paste-text does not schedule AutoLearn monitoring after a clipboard-only fallback", async (t) => {
const originalSetTimeout = global.setTimeout;
t.after(() => {
diff --git a/test/helpers/linuxInputRegionNative.test.js b/test/helpers/linuxInputRegionNative.test.js
index 2d5e92068..503ac3601 100644
--- a/test/helpers/linuxInputRegionNative.test.js
+++ b/test/helpers/linuxInputRegionNative.test.js
@@ -1,84 +1,13 @@
const test = require("node:test");
const assert = require("node:assert/strict");
-const fs = require("node:fs");
-const os = require("node:os");
-const path = require("node:path");
-const { spawn, spawnSync } = require("node:child_process");
-const { once } = require("node:events");
-const { createInterface } = require("node:readline");
+const { runLinuxFastPasteFixture } = require("../lib/linuxFastPasteFixture");
test(
"native input regions scale, clip and route clicks without changing the visible window",
{ skip: process.platform !== "linux", timeout: 30_000 },
async (t) => {
- const temporaryDirectory = fs.mkdtempSync(path.join(os.tmpdir(), "openwhispr-input-region-"));
- let xvfb;
- t.after(async () => {
- if (xvfb && xvfb.exitCode === null && xvfb.signalCode === null) {
- const closed = once(xvfb, "close");
- xvfb.kill("SIGKILL");
- await closed;
- }
- fs.rmSync(temporaryDirectory, { recursive: true, force: true });
- });
-
- const xvfbCheck = spawnSync("Xvfb", ["-help"], { encoding: "utf8", timeout: 5000 });
- if (xvfbCheck.error?.code === "ENOENT") return t.skip("Xvfb is not installed");
- assert.ifError(xvfbCheck.error);
- const libraries = ["-lX11", "-lXtst", "-lXext", "-lm"];
- const prerequisites = spawnSync(
- "gcc",
- ["-x", "c", "-", "-o", path.join(temporaryDirectory, "prerequisites"), ...libraries],
- {
- input:
- "#include <X11/Xlib.h>\n#include <X11/extensions/XTest.h>\n#include <X11/extensions/shape.h>\nint main(void) { return 0; }\n",
- encoding: "utf8",
- timeout: 10_000,
- }
- );
- if (prerequisites.error?.code === "ENOENT") return t.skip("gcc is not installed");
- assert.ifError(prerequisites.error);
- if (prerequisites.status !== 0)
- return t.skip("X11, Xtst or Xext development libraries unavailable");
-
- const root = path.resolve(__dirname, "../..");
- const helper = path.join(temporaryDirectory, "linux-fast-paste");
- const fixture = path.join(temporaryDirectory, "input-region-fixture");
- for (const [source, output] of [
- [path.join(root, "resources/linux-fast-paste.c"), helper],
- [path.join(root, "test/native/linuxInputRegion.c"), fixture],
- ]) {
- const compiled = spawnSync("gcc", [source, "-o", output, ...libraries], {
- encoding: "utf8",
- timeout: 10_000,
- });
- assert.ifError(compiled.error);
- assert.equal(compiled.status, 0, compiled.stderr);
- }
-
- // Xvfb selects a free display itself; never send fixture input to the
- // developer's DISPLAY or assume that a hardcoded display number is unused.
- xvfb = spawn("Xvfb", ["-displayfd", "3", "-screen", "0", "1024x768x24", "-nolisten", "tcp"], {
- env: { ...process.env, DISPLAY: "" },
- stdio: ["ignore", "ignore", "pipe", "pipe"],
- });
- let displayErrors = "";
- xvfb.stderr.on("data", (chunk) => {
- displayErrors += chunk;
- });
- await once(xvfb, "spawn");
- const displayLines = createInterface({ input: xvfb.stdio[3] });
- t.after(() => displayLines.close());
- const [displayNumber] = await once(displayLines, "line", { signal: AbortSignal.timeout(5000) });
- assert.match(displayNumber, /^\d+$/, displayErrors);
-
- const result = spawnSync(fixture, [helper], {
- env: { ...process.env, DISPLAY: `:${displayNumber}` },
- encoding: "utf8",
- timeout: 10_000,
- });
- assert.ifError(result.error);
- assert.equal(result.status, 0, result.stderr || displayErrors);
+ const result = await runLinuxFastPasteFixture(t, "linuxInputRegion");
+ if (!result) return;
assert.match(result.stdout, /input region native checks passed/);
}
);
diff --git a/test/helpers/linuxModifierGateNative.test.js b/test/helpers/linuxModifierGateNative.test.js
new file mode 100644
index 000000000..ff2e53354
--- /dev/null
+++ b/test/helpers/linuxModifierGateNative.test.js
@@ -0,0 +1,47 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+const fs = require("node:fs");
+const { runLinuxFastPasteFixture } = require("../lib/linuxFastPasteFixture");
+
+// The modifier gate must read the key state the X server reports on an X11
+// session, so strip anything that would make the helper treat this as Wayland.
+const X11_SESSION_ENV = { ...process.env, XDG_SESSION_TYPE: "x11", WAYLAND_DISPLAY: undefined };
+const WAYLAND_SESSION_ENV = { ...process.env, XDG_SESSION_TYPE: "wayland" };
+
+function uinputUnavailable() {
+ try {
+ fs.accessSync("/dev/uinput", fs.constants.W_OK);
+ return false;
+ } catch {
+ return "/dev/uinput is not writable";
+ }
+}
+
+test(
+ "native modifier gate waits for a held modifier, ignores locked ones, and reports an unreadable XKB state as unknown",
+ { skip: process.platform !== "linux" && "Linux only", timeout: 30_000 },
+ async (t) => {
+ const result = await runLinuxFastPasteFixture(t, "linuxModifierGate", {
+ env: X11_SESSION_ENV,
+ sharedLibraries: ["xkbUnavailable"],
+ });
+ if (!result) return;
+ assert.match(result.stdout, /modifier gate native checks passed/);
+ }
+);
+
+// The Wayland side reads /dev/input, which is what push-to-talk users run on.
+test(
+ "native evdev modifier gate sees a held key on a keyboard and ignores ydotoold's virtual one",
+ {
+ skip: (process.platform !== "linux" && "Linux only") || uinputUnavailable(),
+ timeout: 30_000,
+ },
+ async (t) => {
+ const result = await runLinuxFastPasteFixture(t, "linuxModifierGateEvdev", {
+ env: WAYLAND_SESSION_ENV,
+ });
+ if (!result) return;
+ assert.match(result.stdout, /evdev modifier gate native checks passed/);
+ }
+);
diff --git a/test/helpers/selectionEditing.test.js b/test/helpers/selectionEditing.test.js
index 22e4b5e9b..4f3c248a8 100644
--- a/test/helpers/selectionEditing.test.js
+++ b/test/helpers/selectionEditing.test.js
@@ -43,6 +43,17 @@ test("builds a structured prompt that keeps instruction and selection separate",
getSelectionCaptureDisposition({ status: "unavailable", code: "accessibility_unavailable" }),
"standalone"
);
+ // Keys held past the modifier wait (#2113) block the copy the same way.
+ assert.equal(
+ getSelectionCaptureDisposition({ status: "unavailable", code: "modifiers_held" }),
+ "standalone"
+ );
+ // Focus moved during that wait, so the new window was never checked: the
+ // command runs on its own rather than failing as a changed selection.
+ assert.equal(
+ getSelectionCaptureDisposition({ status: "target_changed", code: "focus_moved" }),
+ "standalone"
+ );
assert.equal(getSelectionCaptureDisposition({ status: "target_changed" }), "changed");
assert.equal(
getSelectionCaptureDisposition({ status: "unavailable", code: "copy_failed" }),
diff --git a/test/helpers/selectionManager.test.js b/test/helpers/selectionManager.test.js
index 03f0c7524..7960847f0 100644
--- a/test/helpers/selectionManager.test.js
+++ b/test/helpers/selectionManager.test.js
@@ -260,6 +260,65 @@ test("does not paste when the selection changed", async () => {
assert.equal(pastes.length, 0);
});
+// Keys still held past the modifier wait (#2113) block the edit at two points.
+// Both must say so: "selection_unavailable" sends the user to permissions
+// settings and "paste_failed" hides that the edit is on the clipboard.
+test("a replacement blocked by held modifiers at revalidation reports modifiers_held", async () => {
+ const { manager, pastes } = makeHarness({ selections: ["original"] });
+ const capture = await manager.captureSelectedText();
+ manager._readCurrentSelection = async () => ({ status: "unavailable", code: "modifiers_held" });
+
+ assert.deepEqual(await manager.replaceSelectedText(capture.sessionId, "improved"), {
+ success: false,
+ code: "modifiers_held",
+ });
+ assert.equal(pastes.length, 0);
+});
+
+test("a replacement whose paste was held back for modifiers reports modifiers_held", async () => {
+ const { manager, pastes } = makeHarness({
+ selections: ["original", "original"],
+ pasteResult: { restoreComplete: Promise.resolve(), pasted: false, reason: "modifiers-held" },
+ });
+ const capture = await manager.captureSelectedText();
+
+ assert.deepEqual(await manager.replaceSelectedText(capture.sessionId, "improved"), {
+ success: false,
+ code: "modifiers_held",
+ });
+ assert.equal(pastes.length, 1);
+});
+
+// The assistant's caret paste is blocked the same two ways. The renderer only
+// reads `success`, so this code is for logs and support rather than UI.
+test("an assistant caret paste held back by modifier keys reports modifiers_held", async () => {
+ const { manager } = makeHarness({
+ selections: [
+ { state: "none", editable: true },
+ { state: "none", editable: true },
+ ],
+ pasteResult: { restoreComplete: Promise.resolve(), pasted: false, reason: "modifiers-held" },
+ });
+ const capture = await manager.captureSelectedText({ probeEditable: true });
+
+ assert.deepEqual(await manager.pasteAtCapturedTarget(capture.sessionId, "Agent response"), {
+ success: false,
+ code: "modifiers_held",
+ });
+});
+
+test("a caret re-read blocked by held modifier keys reports modifiers_held", async () => {
+ const { manager, pastes } = makeHarness({ selections: [{ state: "none", editable: true }] });
+ const capture = await manager.captureSelectedText({ probeEditable: true });
+ manager._readCurrentSelection = async () => ({ status: "unavailable", code: "modifiers_held" });
+
+ assert.deepEqual(await manager.pasteAtCapturedTarget(capture.sessionId, "Agent response"), {
+ success: false,
+ code: "modifiers_held",
+ });
+ assert.equal(pastes.length, 0);
+});
+
test("selection sessions are single-use", async () => {
const { manager } = makeHarness({ selections: ["original", "original", "original"] });
const capture = await manager.captureSelectedText();
@@ -591,6 +650,123 @@ test("a terminal target reads as no selection", async () => {
assert.deepEqual(result.target, terminalTarget);
});
+// Capture runs right after the voice assistant hotkey press, while its keys are
+// often still down. A Ctrl+C sent into them copies nothing, so capture waits for
+// the release and fails closed when the keys stay held.
+for (const [modifiers, expectCopy] of [
+ ["held", false],
+ ["released", true],
+ ["unknown", true],
+]) {
+ test(`Linux selection capture ${expectCopy ? "copies" : "sends no copy"} when modifiers are ${modifiers}`, async () => {
+ let copyAttempts = 0;
+ const manager = new SelectionManager({
+ clipboardManager: {
+ runClipboardOperation: (operation) => operation(),
+ isLinuxTerminalWindowClass: () => false,
+ resolveLinuxFastPasteBinary: () => "/tmp/linux-fast-paste",
+ _awaitModifierRelease: async () => ({ state: modifiers, waitedMs: 0 }),
+ },
+ textEditMonitor: {},
+ platform: "linux",
+ now: () => 1000,
+ });
+ const target = { kind: "x11-window", id: "7", windowClass: "org.gnome.texteditor" };
+ manager._getLinuxTarget = async () => target;
+ manager._captureViaClipboard = async () => {
+ copyAttempts += 1;
+ return { status: "none", target };
+ };
+
+ const result = await manager._readLinuxSelection(null);
+
+ assert.equal(copyAttempts, expectCopy ? 1 : 0);
+ assert.deepEqual(
+ result,
+ expectCopy ? { status: "none", target } : { status: "unavailable", code: "modifiers_held" }
+ );
+ });
+}
+
+// The target was classified before the wait. If focus moved while the keys were
+// held (say, to a terminal), a copy chord would reach a window nobody checked:
+// a plain Ctrl+C there interrupts whatever is running.
+for (const [waitedMs, focusMoved, expectCopy] of [
+ [400, true, false],
+ [400, false, true],
+ [0, true, true],
+]) {
+ test(`Linux selection capture ${expectCopy ? "copies" : "sends no copy"} after a ${waitedMs} ms wait when focus ${focusMoved ? "moved" : "stayed"}`, async () => {
+ let copyAttempts = 0;
+ let targetReads = 0;
+ const manager = new SelectionManager({
+ clipboardManager: {
+ runClipboardOperation: (operation) => operation(),
+ isLinuxTerminalWindowClass: (windowClass) => windowClass === "konsole",
+ resolveLinuxFastPasteBinary: () => "/tmp/linux-fast-paste",
+ _awaitModifierRelease: async () => ({ state: "released", waitedMs }),
+ },
+ textEditMonitor: {},
+ platform: "linux",
+ now: () => 1000,
+ });
+ const target = { kind: "kde-window", id: "7", windowClass: "kate" };
+ const terminal = { kind: "kde-window", id: "9", windowClass: "konsole" };
+ manager._getLinuxTarget = async () => {
+ targetReads += 1;
+ return targetReads > 1 && focusMoved ? terminal : target;
+ };
+ manager._captureViaClipboard = async () => {
+ copyAttempts += 1;
+ return { status: "none", target };
+ };
+
+ const result = await manager._readLinuxSelection(null);
+
+ assert.equal(copyAttempts, expectCopy ? 1 : 0);
+ assert.equal(targetReads, waitedMs > 0 ? 2 : 1, "only a real wait pays for a second lookup");
+ if (!expectCopy) assert.deepEqual(result, { status: "target_changed", code: "focus_moved" });
+ });
+}
+
+// A capture that saw focus move runs the command on its own (nothing was
+// checked), but a session being revalidated has a real target to protect: the
+// selection edit or caret delivery is declined as a changed target.
+test("a Linux session revalidation declines when focus moved during the modifier wait", async () => {
+ let targetReads = 0;
+ let pastes = 0;
+ const manager = new SelectionManager({
+ clipboardManager: {
+ runClipboardOperation: (operation) => operation(),
+ isLinuxTerminalWindowClass: () => false,
+ resolveLinuxFastPasteBinary: () => "/tmp/linux-fast-paste",
+ _awaitModifierRelease: async () => ({ state: "released", waitedMs: 400 }),
+ _pasteText: async () => {
+ pastes += 1;
+ return { pasted: true };
+ },
+ },
+ textEditMonitor: {},
+ platform: "linux",
+ now: () => 1000,
+ });
+ const target = { kind: "kde-window", id: "7", windowClass: "kate" };
+ const other = { kind: "kde-window", id: "9", windowClass: "konsole" };
+ manager._getLinuxTarget = async () => (++targetReads % 2 === 0 ? other : target);
+ manager.sessions.set("edit", { kind: "selection", text: "old", target, expiresAt: 2000 });
+ manager.sessions.set("caret", { kind: "caret", target, expiresAt: 2000 });
+
+ assert.deepEqual(await manager.replaceSelectedText("edit", "new"), {
+ success: false,
+ code: "target_changed",
+ });
+ assert.deepEqual(await manager.pasteAtCapturedTarget("caret", "answer"), {
+ success: false,
+ code: "target_changed",
+ });
+ assert.equal(pastes, 0);
+});
+
// macOS accessibility never resolves a focused element in Chromium browsers, so
// a synthetic ⌘C is the only way to tell a real selection from an empty field.
function makeMacClipboardHarness({ copyOutput = "COPY_OK 42 Dia", copied = null } = {}) {
diff --git a/test/helpers/useAudioRecordingCleanupFallback.test.js b/test/helpers/useAudioRecordingCleanupFallback.test.js
index 39702dae4..dc66fc70b 100644
--- a/test/helpers/useAudioRecordingCleanupFallback.test.js
+++ b/test/helpers/useAudioRecordingCleanupFallback.test.js
@@ -22,7 +22,7 @@ export default class FakeAudioManager {
shouldUseStreaming() { return false; }
async safePaste() {
this.pasteCalls += 1;
- return globalThis.__cleanupFallbackPasteOutcome?.pasted === true;
+ return { pasted: globalThis.__cleanupFallbackPasteOutcome?.pasted === true };
}
async saveTranscription() { return true; }
cleanup() {}
diff --git a/test/helpers/useAudioRecordingForceStop.test.js b/test/helpers/useAudioRecordingForceStop.test.js
index 091ad92c4..5440bb9d5 100644
--- a/test/helpers/useAudioRecordingForceStop.test.js
+++ b/test/helpers/useAudioRecordingForceStop.test.js
@@ -26,6 +26,7 @@ export default class FakeAudioManager {
setAssistantSelectionContext() {}
setTranslationRequested() {}
startRecording() {
+ globalThis.__forceStopStarts += 1;
return Promise.resolve(true);
}
complete(result) {
@@ -33,7 +34,7 @@ export default class FakeAudioManager {
}
async safePaste(text, options) {
globalThis.__forceStopPastes.push({ text, options });
- return true;
+ return globalThis.__forceStopPasteOutcome;
}
saveTranscription() {
return Promise.resolve(true);
@@ -41,6 +42,9 @@ export default class FakeAudioManager {
shouldUseStreaming() {
return false;
}
+ getRecordingAudioLevel() {
+ return 0;
+ }
isSttConfigStale() {
return false;
}
@@ -76,14 +80,26 @@ export const useTranslation = () => ({ t: translate });
const NOOP = () => {};
-async function mountHarness(t, { settings, writeClipboard } = {}) {
+async function mountHarness(
+ t,
+ {
+ settings,
+ writeClipboard,
+ pasteOutcome = { pasted: true },
+ replaceOutcome = { success: true },
+ } = {}
+) {
let root = null;
t.after(async () => {
if (root) await React.act(async () => root.unmount());
});
const clipboardWrites = [];
+ const replacements = [];
+ const lifecycle = [];
const toasts = [];
+ const dismissals = [];
+ let previewHides = 0;
let forceStopListener = null;
const noopDispose = () => () => {};
@@ -101,14 +117,20 @@ async function mountHarness(t, { settings, writeClipboard } = {}) {
forceStopListener = callback;
return () => {};
},
- dictationLifecycleStateChanged: NOOP,
+ dictationLifecycleStateChanged: (state) => lifecycle.push(state),
completeDictationPreview: NOOP,
- hideDictationPreview: NOOP,
+ hideDictationPreview: () => {
+ previewHides += 1;
+ },
setScreenContextEnabled: NOOP,
async writeClipboard(text) {
clipboardWrites.push(text);
return writeClipboard ? writeClipboard(text) : { success: true };
},
+ async replaceSelectedText(sessionId, text, options) {
+ replacements.push({ sessionId, text, options });
+ return replaceOutcome;
+ },
},
},
});
@@ -125,6 +147,8 @@ async function mountHarness(t, { settings, writeClipboard } = {}) {
...settings,
};
globalThis.__forceStopPastes = [];
+ globalThis.__forceStopPasteOutcome = pasteOutcome;
+ globalThis.__forceStopStarts = 0;
const vite = await createRendererServer(t, {
cachePrefix: "openwhispr-audio-recording-force-stop-",
@@ -140,11 +164,12 @@ async function mountHarness(t, { settings, writeClipboard } = {}) {
const { useAudioRecording } = await vite.ssrLoadModule("/hooks/useAudioRecording.js");
const api = {};
+ // Stable like the app's ToastProvider callback: a new identity per render
+ // would re-run the hook's mount effect on every state change.
+ const pushToast = (entry) => toasts.push(entry);
+ const dismissDictationError = () => dismissals.push(toasts.length);
function Harness() {
- Object.assign(
- api,
- useAudioRecording((entry) => toasts.push(entry), { onDemoEvent: NOOP })
- );
+ Object.assign(api, useAudioRecording(pushToast, { onDemoEvent: NOOP, dismissDictationError }));
return null;
}
@@ -154,9 +179,24 @@ async function mountHarness(t, { settings, writeClipboard } = {}) {
});
return {
+ api,
clipboardWrites,
+ lifecycle,
pastes: globalThis.__forceStopPastes,
+ replacements,
toasts,
+ dismissals,
+ previewHides: () => previewHides,
+ recordingStarts: () => globalThis.__forceStopStarts,
+ setRecording: async (isRecording) => {
+ await React.act(async () =>
+ globalThis.__forceStopAudioManager.callbacks.onStateChange({
+ isRecording,
+ isProcessing: false,
+ isStreaming: false,
+ })
+ );
+ },
forceStop: async (reason) => {
assert.ok(forceStopListener, "the hook must subscribe to dictation-force-stopped");
await React.act(async () => forceStopListener({ reason }));
@@ -164,9 +204,11 @@ async function mountHarness(t, { settings, writeClipboard } = {}) {
startRecording: async () => {
await React.act(async () => api.startRecording());
},
- complete: async (result) => {
+ // `detach` returns while the paste is still in flight, for tests that
+ // observe the hook mid-paste.
+ complete: async (result, { detach = false } = {}) => {
await React.act(async () => {
- await globalThis.__forceStopAudioManager.complete({
+ const completion = globalThis.__forceStopAudioManager.complete({
success: true,
text: "held too long",
rawText: "held too long",
@@ -174,11 +216,19 @@ async function mountHarness(t, { settings, writeClipboard } = {}) {
source: "openai",
...result,
});
+ if (!detach) await completion;
+ });
+ },
+ flush: async () => {
+ await React.act(async () => {
+ await new Promise((resolve) => setTimeout(resolve, 0));
});
},
};
}
+const retryAction = (toast) => toast.actions.find((action) => action.label === "common.retry");
+
const errorToasts = (harness) =>
harness.toasts.filter((entry) => entry.presentation === "dictation-error");
@@ -208,6 +258,225 @@ for (const reason of ["timeout", "reset"]) {
});
}
+// Modifiers still down when the paste was due (#2113): the main process held the
+// paste back, so the transcript must be surfaced exactly like a forced stop.
+test("a paste held back for still-held modifiers keeps the transcript", async (t) => {
+ const harness = await mountHarness(t, {
+ pasteOutcome: { pasted: false, reason: "modifiers-held" },
+ });
+
+ await harness.complete();
+
+ assert.equal(harness.pastes.length, 1, "the paste was attempted, then held back");
+ assert.deepEqual(harness.clipboardWrites, ["held too long"]);
+ const [toast] = errorToasts(harness);
+ assert.ok(toast, "the transcript is surfaced, not dropped");
+ assert.equal(toast.title, "hooks.audioRecording.modifiersHeld.title");
+ assert.equal(toast.description, "hooks.audioRecording.modifiersHeld.description");
+ assert.ok(
+ toast.actions.some(
+ (action) => action.label === "hooks.audioRecording.errorActions.viewTranscript"
+ ),
+ "the pill must carry the transcript so it stays recoverable"
+ );
+});
+
+// A macOS clipboard-only fallback (accessibility skipped) is also "not pasted",
+// but it is expected and carries no reason, so it must stay silent.
+test("a clipboard-only fallback without a reason raises no error", async (t) => {
+ const harness = await mountHarness(t, { pasteOutcome: { pasted: false } });
+
+ await harness.complete();
+
+ assert.deepEqual(harness.clipboardWrites, []);
+ assert.deepEqual(errorToasts(harness), []);
+});
+
+// A selection edit is blocked by held keys at two points (revalidation and
+// the paste itself); both arrive as `modifiers_held`, which must not read as a
+// permissions problem, and the edit must be kept like any held-back paste.
+test("a selection edit held back for still-held modifiers keeps the edit and says why", async (t) => {
+ const harness = await mountHarness(t, {
+ replaceOutcome: { success: false, code: "modifiers_held" },
+ });
+
+ await harness.complete({ selectionEdit: { sessionId: "selection-1" } });
+
+ assert.equal(harness.replacements.length, 1);
+ assert.deepEqual(harness.pastes, [], "the edit is not pasted blindly");
+ assert.deepEqual(harness.clipboardWrites, ["held too long"]);
+ const [toast] = errorToasts(harness);
+ assert.equal(toast.title, "hooks.audioRecording.selectionEditing.notAppliedTitle");
+ assert.equal(toast.description, "hooks.audioRecording.selectionEditing.modifiersHeld");
+});
+
+test("a held-back selection edit whose clipboard write fails is not described as a success", async (t) => {
+ const harness = await mountHarness(t, {
+ writeClipboard: () => ({ success: false }),
+ replaceOutcome: { success: false, code: "modifiers_held" },
+ });
+
+ await harness.complete({ selectionEdit: { sessionId: "selection-1" } });
+
+ const [toast] = errorToasts(harness);
+ assert.equal(
+ toast.description,
+ "hooks.audioRecording.selectionEditing.modifiersHeldClipboardFailed"
+ );
+});
+
+// The transcript is already on the clipboard; what the user wants back is the
+// paste, not another recording.
+test("retrying a held-back paste pastes again instead of recording again", async (t) => {
+ const harness = await mountHarness(t, {
+ pasteOutcome: { pasted: false, reason: "modifiers-held" },
+ });
+ await harness.complete();
+ const [toast] = errorToasts(harness);
+
+ globalThis.__forceStopPasteOutcome = { pasted: true };
+ await React.act(async () => retryAction(toast).onClick());
+
+ assert.equal(harness.pastes.length, 2);
+ assert.deepEqual(harness.pastes[1].options, harness.pastes[0].options);
+ assert.equal(harness.recordingStarts(), 0);
+ assert.equal(errorToasts(harness).length, 1, "a paste that landed raises no new pill");
+});
+
+test("retrying a held-back paste while the keys are still held shows the pill again", async (t) => {
+ const harness = await mountHarness(t, {
+ pasteOutcome: { pasted: false, reason: "modifiers-held" },
+ });
+ await harness.complete();
+ const [toast] = errorToasts(harness);
+
+ await React.act(async () => retryAction(toast).onClick());
+
+ assert.equal(harness.pastes.length, 2);
+ assert.equal(harness.recordingStarts(), 0);
+ assert.equal(errorToasts(harness).length, 2);
+});
+
+// Force stops come only from macOS and Windows push-to-talk, which have no
+// modifier wait: a pasting Retry clicked while the keys are still down would
+// inject exactly the chord the pill exists to prevent. Retry records again.
+test("retrying a force-stopped push records again instead of pasting", async (t) => {
+ const harness = await mountHarness(t);
+ await harness.forceStop("timeout");
+ await harness.complete();
+ const [toast] = errorToasts(harness);
+
+ await React.act(async () => retryAction(toast).onClick());
+
+ assert.deepEqual(harness.pastes, []);
+ assert.equal(harness.recordingStarts(), 1);
+});
+
+function deferredPaste() {
+ let settle;
+ const outcome = new Promise((resolve) => {
+ settle = resolve;
+ });
+ return { outcome, settle: (value) => React.act(async () => settle(value)) };
+}
+
+// The audio manager settles processing before the paste starts, so the pill
+// would sit idle while the modifier wait runs (up to 1.5 s): the hook keeps the
+// pill processing until the paste attempt settles. It must not report that to
+// main, which drops dictation hotkeys while processing — the user could not
+// start the next dictation during every paste.
+test("the pill stays processing during a paste without holding back hotkeys", async (t) => {
+ const paste = deferredPaste();
+ const harness = await mountHarness(t, { pasteOutcome: paste.outcome });
+
+ await harness.complete(undefined, { detach: true });
+ assert.equal(harness.api.isProcessing, true);
+ assert.ok(!harness.lifecycle.includes("processing"), "main keeps accepting hotkeys");
+
+ await paste.settle({ pasted: true });
+ await harness.flush();
+ assert.equal(harness.api.isProcessing, false);
+});
+
+// Holding Ctrl and pressing the rest of the chord again starts the next
+// dictation while the previous paste is still waiting on that Ctrl. The held-back
+// transcript stays on the clipboard, but its pill must not land on top of the new
+// recording (which dismisses it at once) or hide that recording's live preview.
+test("a paste held back after the next recording started keeps the transcript quietly", async (t) => {
+ const paste = deferredPaste();
+ const harness = await mountHarness(t, { pasteOutcome: paste.outcome });
+ await harness.complete(undefined, { detach: true });
+
+ await harness.startRecording();
+ await harness.setRecording(true);
+ assert.equal(harness.recordingStarts(), 1);
+ assert.equal(harness.api.isProcessing, false, "the new recording owns the pill");
+ const hidesBefore = harness.previewHides();
+
+ await paste.settle({ pasted: false, reason: "modifiers-held" });
+ await harness.flush();
+
+ assert.deepEqual(harness.clipboardWrites, ["held too long"]);
+ assert.deepEqual(errorToasts(harness), []);
+ assert.equal(harness.previewHides(), hidesBefore, "the live preview is left alone");
+ assert.equal(harness.lifecycle.at(-1), "recording");
+});
+
+// Retry shows no progress while the paste waits on held keys, so a second click
+// is likely; it must not queue a second paste of the same text.
+test("a double-clicked Retry pastes once", async (t) => {
+ const harness = await mountHarness(t, {
+ pasteOutcome: { pasted: false, reason: "modifiers-held" },
+ });
+ await harness.complete();
+ const [toast] = errorToasts(harness);
+
+ const paste = deferredPaste();
+ globalThis.__forceStopPasteOutcome = paste.outcome;
+ const retry = retryAction(toast);
+ const dismissalsBefore = harness.dismissals.length;
+ await React.act(async () => {
+ void retry.onClick();
+ void retry.onClick();
+ });
+ await paste.settle({ pasted: true });
+ await harness.flush();
+
+ assert.equal(harness.pastes.length, 2, "the first attempt plus one retry");
+ assert.equal(
+ harness.dismissals.length - dismissalsBefore,
+ 1,
+ "the landed retry closes its pill once"
+ );
+});
+
+test("a Retry that lands after a newer pill leaves that pill alone", async (t) => {
+ const harness = await mountHarness(t, {
+ pasteOutcome: { pasted: false, reason: "modifiers-held" },
+ });
+ await harness.complete();
+ const [toast] = errorToasts(harness);
+
+ const paste = deferredPaste();
+ globalThis.__forceStopPasteOutcome = paste.outcome;
+ await React.act(async () => {
+ void retryAction(toast).onClick();
+ });
+ await harness.forceStop("timeout");
+ await harness.complete({ text: "newer", rawText: "newer" });
+ assert.equal(errorToasts(harness).length, 2, "a newer pill is showing");
+ const dismissalsBefore = harness.dismissals.length;
+
+ await paste.settle({ pasted: true });
+ await harness.flush();
+
+ assert.equal(
+ harness.dismissals.length,
+ dismissalsBefore,
+ "the stale Retry must not close the newer pill"
+ );
+});
+
test("an ordinary dictation still pastes", async (t) => {
const harness = await mountHarness(t);
@@ -286,4 +555,20 @@ for (const [label, writeClipboard] of [
"hooks.audioRecording.pushForceStopped.descriptionClipboardFailed"
);
});
+
+ test(`a held-back paste whose clipboard write ${label} is not described as a success`, async (t) => {
+ const harness = await mountHarness(t, {
+ writeClipboard,
+ pasteOutcome: { pasted: false, reason: "modifiers-held" },
+ });
+
+ await harness.complete();
+
+ const [toast] = errorToasts(harness);
+ assert.ok(toast, "the transcript is still surfaced");
+ assert.equal(
+ toast.description,
+ "hooks.audioRecording.modifiersHeld.descriptionClipboardFailed"
+ );
+ });
}
diff --git a/test/helpers/useAudioRecordingPasteRecovery.test.js b/test/helpers/useAudioRecordingPasteRecovery.test.js
index 7032c5815..69ec1bf5e 100644
--- a/test/helpers/useAudioRecordingPasteRecovery.test.js
+++ b/test/helpers/useAudioRecordingPasteRecovery.test.js
@@ -74,7 +74,7 @@ async function mount(t) {
setAssistantSelectionContext() {}
setTranslationRequested() {}
async startRecording() { this.starts+=1; return true; }
- async safePaste(text) { this.callbacks.onError({title:"Paste Error",code:"ACCESSIBILITY_PERMISSION_REQUIRED",clipboardCopied:true,transcript:text}); return false; }
+ async safePaste(text) { this.callbacks.onError({title:"Paste Error",code:"ACCESSIBILITY_PERMISSION_REQUIRED",clipboardCopied:true,transcript:text}); return { pasted:false }; }
async saveTranscription() { this.saves+=1; return true; }
cleanup() {}
}`,
diff --git a/test/lib/linuxFastPasteFixture.js b/test/lib/linuxFastPasteFixture.js
new file mode 100644
index 000000000..f066e9762
--- /dev/null
+++ b/test/lib/linuxFastPasteFixture.js
@@ -0,0 +1,112 @@
+const assert = require("node:assert/strict");
+const fs = require("node:fs");
+const os = require("node:os");
+const path = require("node:path");
+const { spawn, spawnSync } = require("node:child_process");
+const { once } = require("node:events");
+const { createInterface } = require("node:readline");
+
+const ROOT = path.resolve(__dirname, "../..");
+const LIBRARIES = ["-lX11", "-lXtst", "-lXext", "-lm"];
+
+// Compiles resources/linux-fast-paste.c and test/native/<fixtureName>.c, then runs
+// the fixture against the helper on a private Xvfb display. Returns the fixture's
+// spawnSync result, or null once the test is skipped because Xvfb, gcc or the X11
+// development libraries are missing.
+async function runLinuxFastPasteFixture(
+ t,
+ fixtureName,
+ { env = process.env, sharedLibraries = [] } = {}
+) {
+ const temporaryDirectory = fs.mkdtempSync(path.join(os.tmpdir(), "openwhispr-fast-paste-"));
+ let xvfb;
+ t.after(async () => {
+ if (xvfb && xvfb.exitCode === null && xvfb.signalCode === null) {
+ const closed = once(xvfb, "close");
+ xvfb.kill("SIGKILL");
+ await closed;
+ }
+ fs.rmSync(temporaryDirectory, { recursive: true, force: true });
+ });
+
+ const xvfbCheck = spawnSync("Xvfb", ["-help"], { encoding: "utf8", timeout: 5000 });
+ if (xvfbCheck.error?.code === "ENOENT") {
+ t.skip("Xvfb is not installed");
+ return null;
+ }
+ assert.ifError(xvfbCheck.error);
+ const prerequisites = spawnSync(
+ "gcc",
+ ["-x", "c", "-", "-o", path.join(temporaryDirectory, "prerequisites"), ...LIBRARIES],
+ {
+ input:
+ "#include <X11/Xlib.h>\n#include <X11/extensions/XTest.h>\n#include <X11/extensions/shape.h>\nint main(void) { return 0; }\n",
+ encoding: "utf8",
+ timeout: 10_000,
+ }
+ );
+ if (prerequisites.error?.code === "ENOENT") {
+ t.skip("gcc is not installed");
+ return null;
+ }
+ assert.ifError(prerequisites.error);
+ if (prerequisites.status !== 0) {
+ t.skip("X11, Xtst or Xext development libraries unavailable");
+ return null;
+ }
+
+ const helper = path.join(temporaryDirectory, "linux-fast-paste");
+ const fixture = path.join(temporaryDirectory, fixtureName);
+ for (const [source, output] of [
+ [path.join(ROOT, "resources/linux-fast-paste.c"), helper],
+ [path.join(ROOT, "test/native", `${fixtureName}.c`), fixture],
+ ]) {
+ const compiled = spawnSync("gcc", [source, "-o", output, ...LIBRARIES], {
+ encoding: "utf8",
+ timeout: 10_000,
+ });
+ assert.ifError(compiled.error);
+ assert.equal(compiled.status, 0, compiled.stderr);
+ }
+
+ // Shared objects the fixture may LD_PRELOAD into the helper to stand in for a
+ // library that fails; their paths follow the helper on the fixture's argv.
+ const preloads = sharedLibraries.map((name) => {
+ const output = path.join(temporaryDirectory, `${name}.so`);
+ const compiled = spawnSync(
+ "gcc",
+ ["-shared", "-fPIC", path.join(ROOT, "test/native", `${name}.c`), "-o", output],
+ { encoding: "utf8", timeout: 10_000 }
+ );
+ assert.ifError(compiled.error);
+ assert.equal(compiled.status, 0, compiled.stderr);
+ return output;
+ });
+
+ // Xvfb selects a free display itself; never send fixture input to the
+ // developer's DISPLAY or assume that a hardcoded display number is unused.
+ xvfb = spawn("Xvfb", ["-displayfd", "3", "-screen", "0", "1024x768x24", "-nolisten", "tcp"], {
+ env: { ...process.env, DISPLAY: "" },
+ stdio: ["ignore", "ignore", "pipe", "pipe"],
+ });
+ let displayErrors = "";
+ xvfb.stderr.on("data", (chunk) => {
+ displayErrors += chunk;
+ });
+ await once(xvfb, "spawn");
+ const displayLines = createInterface({ input: xvfb.stdio[3] });
+ t.after(() => displayLines.close());
+ const [displayNumber] = await once(displayLines, "line", { signal: AbortSignal.timeout(5000) });
+ assert.match(displayNumber, /^\d+$/, displayErrors);
+
+ const result = spawnSync(fixture, [helper, ...preloads], {
+ env: { ...env, DISPLAY: `:${displayNumber}` },
+ encoding: "utf8",
+ timeout: 10_000,
+ });
+ assert.ifError(result.error);
+ assert.equal(result.status, 0, result.stderr || displayErrors);
+ return result;
+}
+
+module.exports = { runLinuxFastPasteFixture };
diff --git a/test/native/linuxModifierGate.c b/test/native/linuxModifierGate.c
new file mode 100644
index 000000000..9912c3d05
--- /dev/null
+++ b/test/native/linuxModifierGate.c
@@ -0,0 +1,108 @@
+#include <X11/Xlib.h>
+#include <X11/extensions/XTest.h>
+#include <X11/keysym.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <time.h>
+#include <unistd.h>
+
+/* XTest keys are released when the client that pressed them disconnects, so the
+ * fixture keeps its connection open while the helper reads the key state. */
+static Display *display;
+static char command[1024];
+
+static void require(int condition, const char *message)
+{
+ if (condition) return;
+ fprintf(stderr, "%s\n", message);
+ exit(1);
+}
+
+static void set_key(KeySym keysym, Bool pressed)
+{
+ XTestFakeKeyEvent(display, XKeysymToKeycode(display, keysym), pressed, CurrentTime);
+ XSync(display, False);
+}
+
+static FILE *start_wait(const char *helper, int timeout_ms)
+{
+ snprintf(command, sizeof(command), "'%s' --capabilities --await-modifier-release %d",
+ helper, timeout_ms);
+ FILE *output = popen(command, "r");
+ require(output != NULL, "cannot start helper");
+ return output;
+}
+
+static long now_ms(void)
+{
+ struct timespec now;
+ clock_gettime(CLOCK_MONOTONIC, &now);
+ return now.tv_sec * 1000L + now.tv_nsec / 1000000L;
+}
+
+static int finish_wait(FILE *output, const char *expected_state, int min_waited_ms,
+ int max_waited_ms)
+{
+ char state[32];
+ int waited_ms = -1;
+ int fields = fscanf(output, "MODIFIERS %31s %d", state, &waited_ms);
+ require(pclose(output) == 0, "helper exited with an error");
+ require(fields == 2, "helper did not report a modifier state");
+ if (strcmp(state, expected_state) != 0 || waited_ms < min_waited_ms ||
+ waited_ms > max_waited_ms) {
+ fprintf(stderr, "expected %s after %d-%dms, got %s after %dms\n", expected_state,
+ min_waited_ms, max_waited_ms, state, waited_ms);
+ exit(1);
+ }
+ return waited_ms;
+}
+
+int main(int argc, char **argv)
+{
+ require(argc >= 2, "usage: linuxModifierGate <linux-fast-paste> [xkb-unavailable.so]");
+ display = XOpenDisplay(NULL);
+ require(display != NULL, "cannot open display");
+ const char *helper = argv[1];
+
+ finish_wait(start_wait(helper, 1000), "released", 0, 0);
+
+ set_key(XK_Control_L, True);
+ finish_wait(start_wait(helper, 100), "held", 100, 1000);
+
+ /* The reported wait must be wall-clock time: the JS caller kills the helper
+ * at timeout + 1s, and a wait that counts sleeps instead of time runs past
+ * that on a loaded machine, so the paste would go ahead into the held key. */
+ long started_at = now_ms();
+ int waited_ms = finish_wait(start_wait(helper, 2000), "held", 2000, 2100);
+ long overshoot_ms = now_ms() - started_at - waited_ms;
+ if (overshoot_ms < 0 || overshoot_ms > 100) {
+ fprintf(stderr, "helper reported %dms but ran %ldms longer than that\n", waited_ms,
+ overshoot_ms);
+ exit(1);
+ }
+
+ FILE *output = start_wait(helper, 3000);
+ usleep(200000);
+ set_key(XK_Control_L, False);
+ finish_wait(output, "released", 150, 1000);
+
+ /* A locked Caps Lock is not a key being held. */
+ set_key(XK_Caps_Lock, True);
+ set_key(XK_Caps_Lock, False);
+ finish_wait(start_wait(helper, 1000), "released", 0, 0);
+ set_key(XK_Caps_Lock, True);
+ set_key(XK_Caps_Lock, False);
+
+ /* An X server whose XKB state cannot be read is "unknown", never "released":
+ * the caller must know the wait was blind. */
+ if (argc >= 3) {
+ setenv("LD_PRELOAD", argv[2], 1);
+ finish_wait(start_wait(helper, 1000), "unknown", 0, 0);
+ unsetenv("LD_PRELOAD");
+ }
+
+ XCloseDisplay(display);
+ printf("modifier gate native checks passed\n");
+ return 0;
+}
diff --git a/test/native/linuxModifierGateEvdev.c b/test/native/linuxModifierGateEvdev.c
new file mode 100644
index 000000000..d5aa4a307
--- /dev/null
+++ b/test/native/linuxModifierGateEvdev.c
@@ -0,0 +1,151 @@
+#include <dirent.h>
+#include <fcntl.h>
+#include <linux/uinput.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/ioctl.h>
+#include <sys/stat.h>
+#include <sys/sysmacros.h>
+#include <unistd.h>
+
+/* Drives the Wayland (evdev) side of --await-modifier-release with uinput
+ * keyboards, which the helper reads exactly like physical ones. */
+static char command[1024];
+static const char *helper;
+
+typedef struct {
+ int fd;
+ char node[64];
+ int created_node;
+} keyboard_t;
+
+static void require(int condition, const char *message)
+{
+ if (condition) return;
+ fprintf(stderr, "%s\n", message);
+ exit(1);
+}
+
+/* Without udev (containers), a new device's event node never appears under
+ * /dev/input, so create it from sysfs when it is missing. */
+static void ensure_event_node(keyboard_t *keyboard)
+{
+ char sysname[64];
+ require(ioctl(keyboard->fd, UI_GET_SYSNAME(sizeof(sysname)), sysname) >= 0,
+ "UI_GET_SYSNAME failed");
+ char class_path[128];
+ snprintf(class_path, sizeof(class_path), "/sys/class/input/%s", sysname);
+ DIR *dir = opendir(class_path);
+ require(dir != NULL, "cannot read the device's sysfs entry");
+ char event[32] = "";
+ struct dirent *ent;
+ while ((ent = readdir(dir))) {
+ if (strncmp(ent->d_name, "event", 5) == 0) {
+ snprintf(event, sizeof(event), "%s", ent->d_name);
+ break;
+ }
+ }
+ closedir(dir);
+ require(event[0] != '\0', "device has no event node");
+ snprintf(keyboard->node, sizeof(keyboard->node), "/dev/input/%s", event);
+ if (access(keyboard->node, F_OK) == 0) return;
+
+ char dev_path[192];
+ snprintf(dev_path, sizeof(dev_path), "%s/%s/dev", class_path, event);
+ FILE *dev = fopen(dev_path, "r");
+ require(dev != NULL, "cannot read the event node's device numbers");
+ unsigned int major_number, minor_number;
+ require(fscanf(dev, "%u:%u", &major_number, &minor_number) == 2, "malformed device numbers");
+ fclose(dev);
+ mkdir("/dev/input", 0755);
+ require(mknod(keyboard->node, S_IFCHR | 0600, makedev(major_number, minor_number)) == 0,
+ "cannot create the event node");
+ keyboard->created_node = 1;
+}
+
+static keyboard_t create_keyboard(const char *name)
+{
+ keyboard_t keyboard = { .fd = open("/dev/uinput", O_WRONLY | O_NONBLOCK) };
+ require(keyboard.fd >= 0, "cannot open /dev/uinput");
+ ioctl(keyboard.fd, UI_SET_EVBIT, EV_KEY);
+ ioctl(keyboard.fd, UI_SET_KEYBIT, KEY_A);
+ ioctl(keyboard.fd, UI_SET_KEYBIT, KEY_LEFTCTRL);
+ struct uinput_setup setup;
+ memset(&setup, 0, sizeof(setup));
+ setup.id.bustype = BUS_VIRTUAL;
+ snprintf(setup.name, sizeof(setup.name), "%s", name);
+ require(ioctl(keyboard.fd, UI_DEV_SETUP, &setup) == 0, "UI_DEV_SETUP failed");
+ require(ioctl(keyboard.fd, UI_DEV_CREATE) == 0, "UI_DEV_CREATE failed");
+ usleep(100000);
+ ensure_event_node(&keyboard);
+ return keyboard;
+}
+
+static void destroy_keyboard(keyboard_t *keyboard)
+{
+ ioctl(keyboard->fd, UI_DEV_DESTROY);
+ close(keyboard->fd);
+ if (keyboard->created_node) unlink(keyboard->node);
+}
+
+static void set_ctrl(const keyboard_t *keyboard, int pressed)
+{
+ struct input_event events[2];
+ memset(events, 0, sizeof(events));
+ events[0].type = EV_KEY;
+ events[0].code = KEY_LEFTCTRL;
+ events[0].value = pressed;
+ events[1].type = EV_SYN;
+ events[1].code = SYN_REPORT;
+ require(write(keyboard->fd, events, sizeof(events)) == sizeof(events), "cannot write key event");
+ usleep(50000);
+}
+
+static FILE *start_wait(int timeout_ms)
+{
+ snprintf(command, sizeof(command), "'%s' --capabilities --await-modifier-release %d",
+ helper, timeout_ms);
+ FILE *output = popen(command, "r");
+ require(output != NULL, "cannot start helper");
+ return output;
+}
+
+static void finish_wait(FILE *output, const char *expected_state, int min_waited_ms,
+ int max_waited_ms)
+{
+ char state[32];
+ int waited_ms = -1;
+ int fields = fscanf(output, "MODIFIERS %31s %d", state, &waited_ms);
+ require(pclose(output) == 0, "helper exited with an error");
+ require(fields == 2, "helper did not report a modifier state");
+ if (strcmp(state, expected_state) != 0 || waited_ms < min_waited_ms ||
+ waited_ms > max_waited_ms) {
+ fprintf(stderr, "expected %s after %d-%dms, got %s after %dms\n", expected_state,
+ min_waited_ms, max_waited_ms, state, waited_ms);
+ exit(1);
+ }
+}
+
+int main(int argc, char **argv)
+{
+ require(argc == 2, "usage: linuxModifierGateEvdev <linux-fast-paste>");
+ helper = argv[1];
+
+ keyboard_t keyboard = create_keyboard("Fixture Keyboard");
+ set_ctrl(&keyboard, 1);
+ finish_wait(start_wait(100), "held", 100, 1000);
+ set_ctrl(&keyboard, 0);
+ finish_wait(start_wait(1000), "released", 0, 0);
+
+ /* ydotoold's virtual keyboard can keep a modifier down after an interrupted
+ * chord. That is not the user's hand, so it must not hold every paste back. */
+ keyboard_t ydotoold = create_keyboard("ydotoold virtual device");
+ set_ctrl(&ydotoold, 1);
+ finish_wait(start_wait(100), "released", 0, 0);
+
+ destroy_keyboard(&ydotoold);
+ destroy_keyboard(&keyboard);
+ printf("evdev modifier gate native checks passed\n");
+ return 0;
+}
diff --git a/test/native/xkbUnavailable.c b/test/native/xkbUnavailable.c
new file mode 100644
index 000000000..8128ad131
--- /dev/null
+++ b/test/native/xkbUnavailable.c
@@ -0,0 +1,11 @@
+#include <X11/XKBlib.h>
+
+/* Preloaded into the helper to stand in for an X server whose XKB state cannot
+ * be queried: every XkbGetState call fails. */
+int XkbGetState(Display *display, unsigned int device_spec, XkbStatePtr state)
+{
+ (void)display;
+ (void)device_spec;
+ (void)state;
+ return BadAccess;
+}