Voice-to-text dictation app with local (Nvidia Parakeet/Whisper) and cloud models (BYOK). Privacy-first and available cross-platform.
JavaScript aianthropiccross-platformgeminigroqlinuxmacosnvidiaopen-sourceopenaiparakeetspeech-to-texttranscribewhisperwindows
fix: Edit highlighted text in place with voice agent commands
Chadpihaf4eb545940ee
diff --git a/preload.js b/preload.jsindex ae63418c8..b40f9b4cf 100644--- a/preload.js+++ b/preload.js@@ -50,6 +50,7 @@ contextBridge.exposeInMainWorld("electronAPI", {ipcRenderer.invoke("replace-selected-text", sessionId, text, options),hideWindow: () => ipcRenderer.invoke("hide-window"),showDictationPanel: () => ipcRenderer.invoke("show-dictation-panel"),+ captureDictationTarget: () => ipcRenderer.invoke("capture-dictation-target"),onToggleDictation: registerListener("toggle-dictation", (callback) => () => callback()),onToggleVoiceAgent: registerListener("toggle-voice-agent", (callback) => () => callback()),onToggleTranslation: registerListener("toggle-translation", (callback) => () => callback()),diff --git a/resources/macos-text-monitor.swift b/resources/macos-text-monitor.swiftindex 255a33b1e..9dbef7f1e 100644--- a/resources/macos-text-monitor.swift+++ b/resources/macos-text-monitor.swift@@ -51,19 +51,26 @@ func observerCallback(}// Usage: macos-text-monitor <pid>-guard CommandLine.arguments.count >= 2,- let targetPid = Int32(CommandLine.arguments[1]),+// macos-text-monitor --selected-text <pid>+let selectionReadMode = CommandLine.arguments.count >= 3 &&+ CommandLine.arguments[1] == "--selected-text"+let pidArgumentIndex = selectionReadMode ? 2 : 1++guard CommandLine.arguments.count > pidArgumentIndex,+ let targetPid = Int32(CommandLine.arguments[pidArgumentIndex]),targetPid > 0 else {- writeError("Usage: macos-text-monitor <pid>")+ writeError("Usage: macos-text-monitor [--selected-text] <pid>")writeOutput("NO_ELEMENT")exit(1)}monitoredPid = targetPid-// Read original text from stdin+// Read original text from stdin (monitoring mode only). Selection reads are+// spawned via execFile, which keeps stdin open without writing — blocking on+// readLine there would hang until the caller's timeout kills the process.var originalText = ""-if let line = readLine(strippingNewline: true) {+if !selectionReadMode, let line = readLine(strippingNewline: true) {originalText = line}@@ -101,6 +108,36 @@ guard let resolvedElement = focusedElement else {exit(1)}+// Selection capture is a short-lived, read-only mode used before an AI edit.+// It deliberately uses the same AX client as the monitor so a packaged app's+// trusted native helper does not need to rely on System Events automation.+if selectionReadMode {+ var selectionValue: AnyObject?+ let selectionResult = AXUIElementCopyAttributeValue(+ resolvedElement,+ kAXSelectedTextAttribute as CFString,+ &selectionValue+ )++ if selectionResult == .success, let selection = selectionValue as? String {+ if selection.isEmpty {+ writeOutput("NONE:")+ } else {+ writeTextOutput("SELECTED", selection)+ }+ exit(0)+ }++ if selectionResult == .noValue || selectionResult == .attributeUnsupported {+ writeOutput("NONE:")+ exit(0)+ }++ writeError("Cannot read selected text for PID \(monitoredPid) (error: \(selectionResult.rawValue))")+ writeOutput("UNAVAILABLE:")+ exit(1)+}+monitoredElement = resolvedElementwriteError("Monitoring element in PID \(monitoredPid)")diff --git a/src/helpers/dictationAgentInference.js b/src/helpers/dictationAgentInference.jsindex 5468277c8..95956e39f 100644--- a/src/helpers/dictationAgentInference.js+++ b/src/helpers/dictationAgentInference.js@@ -1,4 +1,7 @@-import { resolveDictationAgentReachability } from "./dictationRouting.js";+import {+ resolveDictationAgentProvider,+ resolveDictationAgentReachability,+} from "./dictationRouting.js";// The dictation agent's inference scope, shared by the dictation route in// audioManager and the Prompt Studio test tab so a prompt test hits the same@@ -11,9 +14,11 @@ export function resolveDictationAgentInference(settings, { isCloudAgent = falseconst model = settings.dictationAgentModel?.trim() || "";const isSelfHosted =settings.dictationAgentMode === "self-hosted" && !!settings.dictationAgentRemoteUrl?.trim();- const provider = isCloudAgent- ? "openwhispr"- : settings.dictationAgentProvider?.trim() || undefined;+ const provider = resolveDictationAgentProvider({+ isCloudAgent,+ dictationAgentMode: settings.dictationAgentMode,+ dictationAgentProvider: settings.dictationAgentProvider,+ });const isCustom = settings.dictationAgentMode === "providers" && provider === "custom";return {diff --git a/src/helpers/dictationRouting.js b/src/helpers/dictationRouting.jsindex 1a7fc48d6..3a1070764 100644--- a/src/helpers/dictationRouting.js+++ b/src/helpers/dictationRouting.js@@ -27,6 +27,20 @@ export function resolveDictationTranslationReachability({return (translationModel?.trim()?.length ?? 0) > 0;}+// Maps the dictation agent's stored provider to a ReasoningService provider id.+// In local mode the store holds the model picker's brand group ("qwen",+// "llama", ...), which is UI state, not an inference provider — route it to+// "local" so PROVIDER_REGISTRY can resolve it.+export function resolveDictationAgentProvider({+ isCloudAgent,+ dictationAgentMode,+ dictationAgentProvider,+}) {+ if (isCloudAgent) return "openwhispr";+ if (dictationAgentMode === "local") return "local";+ return dictationAgentProvider?.trim() || undefined;+}+// Decides which reasoning path ("translation" | "agent" | "cleanup" | "skip")// a finished dictation takes. A recording started via the voice agent hotkey// always takes the agent path — no wake word needed — and never falls back todiff --git a/src/helpers/ipcHandlers.js b/src/helpers/ipcHandlers.jsindex 6290453d4..b08f7d654 100644--- a/src/helpers/ipcHandlers.js+++ b/src/helpers/ipcHandlers.js@@ -1021,6 +1021,12 @@ class IPCHandlers {this.windowManager.showDictationPanel();});+ ipcMain.handle("capture-dictation-target", async () => {+ const pid = (await this.textEditMonitor?.captureTargetPid?.()) ?? null;+ await this.selectionManager?.captureTarget?.();+ return { success: true, pid };+ });+ipcMain.handle("force-stop-dictation", () => {if (this.windowManager?.forceStopMacCompoundPush) {this.windowManager.forceStopMacCompoundPush("manual");@@ -2275,7 +2281,7 @@ class IPCHandlers {// too slow for the paste hot path.const textToPaste = applySmartSpacing({ text, mode: "append" });- const result = await this.clipboardManager.pasteText(textToPaste, {+ await this.clipboardManager.pasteText(textToPaste, {...options,webContents: event.sender,});@@ -2296,7 +2302,11 @@ class IPCHandlers {}}, 500);}- return result;+ // ClipboardManager returns `restoreComplete` so main-process callers can+ // serialize subsequent clipboard work behind its delayed restore. A+ // Promise cannot cross Electron's IPC boundary, though, and renderer+ // callers only need to know that the paste was accepted.+ return { success: true };});ipcMain.handle("check-accessibility-permission", async (_event, silent = false) => {diff --git a/src/helpers/llamaServer.js b/src/helpers/llamaServer.jsindex a4a6222ac..fe0f5c9ae 100644--- a/src/helpers/llamaServer.js+++ b/src/helpers/llamaServer.js@@ -92,7 +92,11 @@ class LlamaServerManager {if (cpuBin) paths.cpu = cpuBin;}- this.cachedServerBinaryPaths = paths;+ // Only cache hits: a miss may be transient (binary downloaded after+ // startup), and caching it would require an app restart to recover.+ if (Object.keys(paths).length > 0) {+ this.cachedServerBinaryPaths = paths;+ }return paths;}diff --git a/src/helpers/selectionManager.js b/src/helpers/selectionManager.jsindex 216bce601..484688d19 100644--- a/src/helpers/selectionManager.js+++ b/src/helpers/selectionManager.js@@ -4,9 +4,37 @@ const debugLogger = require("./debugLogger");const SESSION_TTL_MS = 5 * 60 * 1000;const MAX_SELECTION_EDIT_CODE_POINTS = 6000;+// Ceiling for one synthetic-copy round trip. A no-selection agent command+// pays this in full, and replaceSelectedText spends a second round trip+// re-verifying — the accepted cost of failing closed rather than pasting blind.const COPY_TIMEOUT_MS = 1200;const CLIPBOARD_POLL_MS = 20;+// Editors that copy the whole current line when Ctrl+C lands with an empty+// selection (VS Code's editor.emptySelectionClipboard, Scintilla, JetBrains,+// Visual Studio), making a bare caret look like a selection to the+// synthetic-copy capture. Matched against the target's exe name and window class.+const LINE_COPY_EDITOR_SIGNATURES = [+ "code", // VS Code and forks (VSCodium, code-oss)+ "cursor",+ "windsurf",+ "notepad++",+ "sublime",+ "jetbrains",+ "idea64",+ "pycharm",+ "webstorm",+ "phpstorm",+ "rider64",+ "clion",+ "goland",+ "rubymine",+ "datagrip",+ "dataspell",+ "studio64", // Android Studio+ "devenv", // Visual Studio+];+function runFile(command, args, options = {}) {return new Promise((resolve) => {execFile(@@ -80,7 +108,15 @@ class SelectionManager {}const result = await runSpawn(binary, ["--detect-only"], { timeout: 700 });const match = result.stdout.match(/TARGET\s+(\S+)/);- this.lastTarget = result.success && match ? { kind: "win-hwnd", id: match[1] } : null;+ this.lastTarget =+ result.success && match+ ? {+ kind: "win-hwnd",+ id: match[1],+ windowClass: result.stdout.match(/^WINDOW_CLASS (.+)$/m)?.[1]?.trim() || null,+ exeName: result.stdout.match(/^EXE_NAME (.+)$/m)?.[1]?.trim() || null,+ }+ : null;return;}if (this.platform === "linux") {@@ -190,9 +226,6 @@ class SelectionManager {if (!pid || !this.textEditMonitor?.getSelectedText) {return { status: "unavailable", code: "target_unavailable" };}- if (expectedTarget && expectedTarget.pid !== pid) {- return { status: "target_changed" };- }const frontmostPid = await this.textEditMonitor._readFrontmostPid?.();if (frontmostPid && frontmostPid !== pid) {return { status: "target_changed" };@@ -273,7 +306,9 @@ class SelectionManager {}if (target.kind === "x11-window" && this.clipboardManager.commandExists("xdotool")) {- const chord = await this._getLinuxCopyChord(target.id);+ const chord = this.clipboardManager.isLinuxTerminalWindowClass(target.windowClass)+ ? "ctrl+shift+c"+ : "ctrl+c";const result = await runFile("xdotool",["windowactivate", "--sync", target.id, "key", chord],@@ -325,7 +360,14 @@ class SelectionManager {if (this.clipboardManager.commandExists("xdotool") && process.env.DISPLAY) {const result = await runFile("xdotool", ["getactivewindow"], { timeout: 500 });const id = result.stdout.trim();- if (result.success && id) return { kind: "x11-window", id };+ if (result.success && id) {+ const classResult = await runFile("xdotool", ["getwindowclassname", id], { timeout: 500 });+ return {+ kind: "x11-window",+ id,+ windowClass: classResult.success ? classResult.stdout.trim().toLowerCase() : null,+ };+ }}if (this.clipboardManager.commandExists("kdotool")) {@@ -367,13 +409,6 @@ class SelectionManager {return result.success && match ? { kind: "atspi-pid", id: match[1] } : null;}- async _getLinuxCopyChord(windowId) {- const result = await runFile("xdotool", ["getwindowclassname", windowId], { timeout: 500 });- return this.clipboardManager.isLinuxTerminalWindowClass(result.stdout)- ? "ctrl+shift+c"- : "ctrl+c";- }-async _captureViaClipboard(sendCopy, expectedTarget) {const original = this.clipboardManager._saveClipboard();const beforeWrite = this.clipboardManager._readClipboardTextAll();@@ -381,7 +416,9 @@ class SelectionManager {this.clipboardManager._writeClipboardTextAll(sentinel);// A clipboard side the sentinel write didn't reach (KDE desyncs X11 from// Wayland) still holds pre-copy content; snapshot it so stale text can't- // be mistaken for the copied selection.+ // be mistaken for the copied selection. Known limitation: a clipboard that+ // already held exactly the selected text reads as "no selection", and the+ // command falls back to standalone dictation.const baseline = new Set([...beforeWrite,...this.clipboardManager._readClipboardTextAll(),@@ -412,9 +449,22 @@ class SelectionManager {if (copiedText === null) {return { status: "none", target: copyResult.target };}+ // A line copy from an empty-selection Ctrl+C is exactly one line with a+ // trailing terminator; treat that shape from a known line-copy editor as+ // "no selection" so a bare caret never gets its line rewritten. Proper+ // fix: a real selection read (UIA TextPattern), like --atspi-selection.+ if (/^[^\n]*\r?\n$/.test(copiedText) && this._isLineCopyEditor(expectedTarget)) {+ return { status: "none", target: copyResult.target };+ }return { status: "selected", text: copiedText, target: copyResult.target };}+ _isLineCopyEditor(target) {+ const signature = `${target?.exeName || ""} ${target?.windowClass || ""}`.toLowerCase();+ if (!signature.trim()) return false;+ return LINE_COPY_EDITOR_SIGNATURES.some((editor) => signature.includes(editor));+ }+_restoreClipboardIfOurs(original, writtenTexts, baseline = new Set()) {const written = writtenTexts.filter((text) => typeof text === "string" && text.length > 0);try {diff --git a/src/helpers/textEditMonitor.js b/src/helpers/textEditMonitor.jsindex b4f032ee2..c3cdd7f9f 100644--- a/src/helpers/textEditMonitor.js+++ b/src/helpers/textEditMonitor.js@@ -10,6 +10,11 @@ const INITIAL_QUERY_RETRIES = 4; // Retry if AXValue is empty (paste not yet proconst INITIAL_QUERY_RETRY_DELAY_MS = 300;const ACTIVATE_CONFIRM_RETRIES = 6; // Poll the frontmost app until activation landsconst ACTIVATE_CONFIRM_DELAY_MS = 25;+// One dictation triggers target captures from several call sites (hotkey press,+// toggle path, recording start) within a few hundred ms; reuse the result+// across that burst. Kept short so back-to-back dictations in different apps+// still get a fresh capture.+const TARGET_CAPTURE_FRESHNESS_MS = 250;// Monitoring is strictly read-only: never write AXEnhancedUserInterface (or any// AX attribute) on the target app to force its accessibility tree. Flipping that@@ -99,6 +104,8 @@ class TextEditMonitor extends EventEmitter {this._lastValue = null;this._stdoutBuffer = "";this.lastTargetPid = null;+ this._captureTargetPromise = null;+ this._lastCaptureAt = 0;}/**@@ -106,14 +113,31 @@ class TextEditMonitor extends EventEmitter {* Must be called at hotkey press time, BEFORE showDictationPanel()/mainWindow.show().* NSWorkspace.frontmostApplication correctly identifies the key window owner,* ignoring panel-type windows like the OpenWhispr overlay.+ *+ * Resolves with the captured PID (or null). At most one lookup runs at a+ * time: concurrent calls share the in-flight lookup, so an older lookup can+ * never overwrite a newer target, and a just-captured result is reused+ * briefly so the press-time and recording-start captures of one dictation+ * cost a single osascript spawn instead of several.*/captureTargetPid() {- if (process.platform !== "darwin") return;+ if (process.platform !== "darwin") return Promise.resolve(null);+ if (this._captureTargetPromise) return this._captureTargetPromise;+ if (+ this.lastTargetPid !== null &&+ Date.now() - this._lastCaptureAt < TARGET_CAPTURE_FRESHNESS_MS+ ) {+ return Promise.resolve(this.lastTargetPid);+ }this.lastTargetPid = null;- this._readFrontmostPid().then((pid) => {+ this._captureTargetPromise = this._readFrontmostPid().then((pid) => {+ this._captureTargetPromise = null;+ this._lastCaptureAt = Date.now();this.lastTargetPid = pid;debugLogger.debug("[TextEditMonitor] Captured target PID", { pid });+ return pid;});+ return this._captureTargetPromise;}/**@@ -195,29 +219,74 @@ class TextEditMonitor extends EventEmitter {return;}- execFile(- "osascript",- ["-e", MACOS_AX_SELECTED_TEXT_SCRIPT(pid)],- { timeout: timeoutMs },- (err, stdout) => {- if (err) {- resolve({ state: "unavailable" });- return;+ const resolved = this.resolveBinary();+ if (resolved) {+ execFile(+ resolved.command,+ [...resolved.args, "--selected-text", String(pid)],+ { timeout: timeoutMs },+ (error, stdout, stderr) => {+ const output = stdout.replace(/\n$/, "");+ if (output === "NONE:") {+ resolve({ state: "none" });+ return;+ }+ if (output.startsWith("SELECTED_B64:")) {+ try {+ resolve({+ state: "selected",+ text: Buffer.from(output.slice("SELECTED_B64:".length), "base64").toString("utf8"),+ });+ return;+ } catch (decodeError) {+ debugLogger.debug("[TextEditMonitor] Failed to decode native selected text", {+ error: decodeError.message,+ });+ }+ }+ if (output.startsWith("SELECTED:")) {+ resolve({ state: "selected", text: output.slice("SELECTED:".length) });+ return;+ }++ debugLogger.debug("[TextEditMonitor] Native selected-text read unavailable; trying AppleScript", {+ pid,+ error: error?.message || null,+ stderr: stderr?.trim() || null,+ });+ this._getSelectedTextViaAppleScript(pid, timeoutMs, resolve);}+ );+ return;+ }- const output = stdout.replace(/\n$/, "");- if (output === "NONE:") {- resolve({ state: "none" });- } else if (output.startsWith("SELECTED:")) {- resolve({ state: "selected", text: output.slice("SELECTED:".length) });- } else {- resolve({ state: "unavailable" });- }- }- );+ this._getSelectedTextViaAppleScript(pid, timeoutMs, resolve);});}+ _getSelectedTextViaAppleScript(pid, timeoutMs, resolve) {+ execFile(+ "osascript",+ ["-e", MACOS_AX_SELECTED_TEXT_SCRIPT(pid)],+ { timeout: timeoutMs },+ (err, stdout) => {+ if (err) {+ resolve({ state: "unavailable" });+ return;+ }++ const output = stdout.replace(/\n$/, "");+ if (output === "NONE:") {+ resolve({ state: "none" });+ } else if (output.startsWith("SELECTED:")) {+ resolve({ state: "selected", text: output.slice("SELECTED:".length) });+ } else {+ resolve({ state: "unavailable" });+ }+ }+ );+ }+/*** macOS: read the char before the cursor in the focused text field, used by* paste-time smart spacing. Resolves to { state: "ok", char } | { state:diff --git a/src/helpers/windowManager.js b/src/helpers/windowManager.jsindex d1ae5cfd8..cc8897edf 100644--- a/src/helpers/windowManager.js+++ b/src/helpers/windowManager.js@@ -455,13 +455,16 @@ class WindowManager {return;}if (this.mainWindow && !this.mainWindow.isDestroyed()) {- // Capture the paste target and any selection on the leading (start) edge,+ // Capture the paste target and any selection on every toggle press,// before the overlay steals focus — the paste can't refocus the target- // otherwise (#668). Covers both dictation and voice-agent toggle paths.- if (!this._isDictatingToggle) {- if (this.textEditMonitor) this.textEditMonitor.captureTargetPid();- void this.selectionManager?.captureTarget?.();- }+ // otherwise (#668). The renderer owns the real recording state and may+ // decline a toggle (mic error, silence gate, Esc cancel), so gating this+ // on _isDictatingToggle desyncs and leaves a stale target from a+ // previous app. Press-time capture matches the dictation hotkey call+ // sites in main.js; a stop-press capture resolves the same frontmost+ // app, since NSWorkspace ignores the overlay panel.+ if (this.textEditMonitor) this.textEditMonitor.captureTargetPid();+ void this.selectionManager?.captureTarget?.();this.showDictationPanel();this.mainWindow.webContents.send(channel);this._isDictatingToggle = !this._isDictatingToggle;diff --git a/src/hooks/useAudioRecording.js b/src/hooks/useAudioRecording.jsindex d1f5e4759..c1b2b23fa 100644--- a/src/hooks/useAudioRecording.js+++ b/src/hooks/useAudioRecording.js@@ -42,6 +42,16 @@ export const useAudioRecording = (toast, options = {}) => {const currentState = audioManagerRef.current.getState();if (currentState.isRecording || currentState.isProcessing) return false;+ // The floating dictation panel is non-focusable, so the foreground app is+ // still the user's actual editing target here. Refresh it for recordings+ // started from the panel itself as well as from global hotkeys; otherwise+ // paste can reactivate a stale target from the preceding dictation.+ try {+ await window.electronAPI.captureDictationTarget?.();+ } catch (error) {+ logger.warn("Failed to refresh dictation target", { error: error?.message });+ }+audioManagerRef.current.setVoiceAgentRequested(voiceAgentRequested);audioManagerRef.current.setTranslationRequested(translationRequested);diff --git a/src/types/electron.ts b/src/types/electron.tsindex 20a3110ba..b3dd927c2 100644--- a/src/types/electron.ts+++ b/src/types/electron.ts@@ -755,6 +755,7 @@ declare global {}>;hideWindow: () => Promise<void>;showDictationPanel: () => Promise<void>;+ captureDictationTarget?: () => Promise<{ success: boolean; pid: number | null }>;onToggleDictation: (callback: () => void) => () => void;onToggleVoiceAgent?: (callback: () => void) => () => void;onToggleTranslation?: (callback: () => void) => () => void;diff --git a/test/helpers/dictationRouting.test.js b/test/helpers/dictationRouting.test.jsindex dfa8c9be7..7c9d4aba1 100644--- a/test/helpers/dictationRouting.test.js+++ b/test/helpers/dictationRouting.test.js@@ -341,3 +341,57 @@ test("translation needs a model on model-required providers", async () => {true);});++test("cloud agent always resolves the openwhispr provider", async () => {+ const { resolveDictationAgentProvider } = await load();++ assert.equal(+ resolveDictationAgentProvider({+ isCloudAgent: true,+ dictationAgentMode: "openwhispr",+ dictationAgentProvider: "anthropic",+ }),+ "openwhispr"+ );+});++test("local mode resolves the local provider, not the stored brand group", async () => {+ const { resolveDictationAgentProvider } = await load();++ // The local model picker stores its brand group ("qwen", "llama", ...) in+ // dictationAgentProvider; ReasoningService only knows "local".+ assert.equal(+ resolveDictationAgentProvider({+ isCloudAgent: false,+ dictationAgentMode: "local",+ dictationAgentProvider: "qwen",+ }),+ "local"+ );+});++test("BYOK providers mode passes the stored provider through", async () => {+ const { resolveDictationAgentProvider } = await load();++ assert.equal(+ resolveDictationAgentProvider({+ isCloudAgent: false,+ dictationAgentMode: "providers",+ dictationAgentProvider: "anthropic",+ }),+ "anthropic"+ );+});++test("blank stored provider resolves to undefined outside local mode", async () => {+ const { resolveDictationAgentProvider } = await load();++ assert.equal(+ resolveDictationAgentProvider({+ isCloudAgent: false,+ dictationAgentMode: "providers",+ dictationAgentProvider: " ",+ }),+ undefined+ );+});diff --git a/test/helpers/selectionManager.test.js b/test/helpers/selectionManager.test.jsindex 8a73886f5..647556e70 100644--- a/test/helpers/selectionManager.test.js+++ b/test/helpers/selectionManager.test.js@@ -177,6 +177,58 @@ test("a copy that replaces the sentinel is captured and the clipboard restored",assert.equal(writes.at(-1), "user clipboard");});+// A line copy (one line + trailing terminator) from an empty-selection Ctrl+C+// in editors like VS Code must never be mistaken for a real selection.+const VSCODE_TARGET = { kind: "x11-window", id: "7", windowClass: "code" };++function makeLineCopyHarness(copiedText) {+ let polled = false;+ return makeCaptureHarness({+ readClipboard: (written) => {+ if (written.length === 0) return ["user clipboard"];+ if (!polled) {+ polled = true;+ return [written[0]];+ }+ return [copiedText, written[0]];+ },+ });+}++test("a line copy from an empty selection in a line-copy editor reads as no selection", async () => {+ const { manager, writes } = makeLineCopyHarness("const x = 1;\r\n");+ const result = await manager._captureViaClipboard(+ async () => ({ success: true, target: VSCODE_TARGET }),+ VSCODE_TARGET+ );++ assert.equal(result.status, "none");+ assert.equal(writes.at(-1), "user clipboard");+});++test("a multi-line selection in a line-copy editor is still captured", async () => {+ const { manager } = makeLineCopyHarness("first line\nsecond line\n");+ const result = await manager._captureViaClipboard(+ async () => ({ success: true, target: VSCODE_TARGET }),+ VSCODE_TARGET+ );++ assert.equal(result.status, "selected");+ assert.equal(result.text, "first line\nsecond line\n");+});++test("a trailing-newline selection outside line-copy editors is still captured", async () => {+ const { manager } = makeLineCopyHarness("whole line\n");+ const firefoxTarget = { kind: "x11-window", id: "7", windowClass: "org.mozilla.firefox" };+ const result = await manager._captureViaClipboard(+ async () => ({ success: true, target: firefoxTarget }),+ firefoxTarget+ );++ assert.equal(result.status, "selected");+ assert.equal(result.text, "whole line\n");+});+test("does not overwrite a clipboard value copied while capture is in flight", async () => {let userCopied = false;const { manager, writes } = makeCaptureHarness({diff --git a/test/helpers/textEditMonitorCaptureTarget.test.js b/test/helpers/textEditMonitorCaptureTarget.test.jsnew file mode 100644index 000000000..ff06329ea--- /dev/null+++ b/test/helpers/textEditMonitorCaptureTarget.test.js@@ -0,0 +1,71 @@+const test = require("node:test");+const assert = require("node:assert/strict");++const TextEditMonitor = require("../../src/helpers/textEditMonitor");++const darwinOnly = { skip: process.platform !== "darwin" };++function stubFrontmostPid(monitor, pid) {+ let invocations = 0;+ let release;+ const gate = new Promise((resolve) => {+ release = () => resolve(pid);+ });+ monitor._readFrontmostPid = () => {+ invocations += 1;+ return gate;+ };+ return { release, count: () => invocations };+}++test("concurrent captures share one frontmost lookup", darwinOnly, async () => {+ const m = new TextEditMonitor();+ const lookup = stubFrontmostPid(m, 4242);++ const first = m.captureTargetPid();+ const second = m.captureTargetPid();+ lookup.release();++ assert.deepEqual(await Promise.all([first, second]), [4242, 4242]);+ assert.equal(lookup.count(), 1);+ assert.equal(m.lastTargetPid, 4242);+});++test("a just-completed capture is reused instead of respawning osascript", darwinOnly, async () => {+ const m = new TextEditMonitor();+ const lookup = stubFrontmostPid(m, 4242);++ const first = m.captureTargetPid();+ lookup.release();+ await first;++ assert.equal(await m.captureTargetPid(), 4242);+ assert.equal(lookup.count(), 1);+});++test("a failed capture is retried, not reused", darwinOnly, async () => {+ const m = new TextEditMonitor();+ let invocations = 0;+ m._readFrontmostPid = () => {+ invocations += 1;+ return Promise.resolve(invocations === 1 ? null : 4242);+ };++ assert.equal(await m.captureTargetPid(), null);+ assert.equal(await m.captureTargetPid(), 4242);+ assert.equal(invocations, 2);+});++test("captures refresh once the reuse window has passed", darwinOnly, async () => {+ const m = new TextEditMonitor();+ let invocations = 0;+ m._readFrontmostPid = () => {+ invocations += 1;+ return Promise.resolve(invocations === 1 ? 1111 : 2222);+ };++ assert.equal(await m.captureTargetPid(), 1111);+ m._lastCaptureAt = Date.now() - 10_000;+ assert.equal(await m.captureTargetPid(), 2222);+ assert.equal(m.lastTargetPid, 2222);+});