Skip to content

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

feat(paste): smart spacing around dictated text (#856) (#868)

Gabriel Stein5968b17f3c07
diff --git a/src/helpers/ipcHandlers.js b/src/helpers/ipcHandlers.js
index 18e3ff72f..353c73138 100644
--- a/src/helpers/ipcHandlers.js
+++ b/src/helpers/ipcHandlers.js
@@ -15,6 +15,7 @@ const OpenAIRealtimeStreaming = require("./openaiRealtimeStreaming");
const AudioStorageManager = require("./audioStorage");
const liveSpeakerIdentifier = require("./liveSpeakerIdentifier");
const MeetingEchoLeakDetector = require("./meetingEchoLeakDetector");
+const { applySmartSpacing } = require("./smartSpacing");
const {
transcriptsOverlap,
transcriptsLooselyOverlap,
@@ -1465,7 +1466,26 @@ class IPCHandlers {
await new Promise((resolve) => setTimeout(resolve, 80));
}
}
- const result = await this.clipboardManager.pasteText(text, {
+
+ // Smart spacing (#856): macOS reads the preceding char via Accessibility
+ // and prepends a space when needed; Windows/Linux (and macOS when the
+ // read fails) append a trailing space instead — the next paste then
+ // sees a leading space and self-corrects.
+ let mode = "append";
+ let precedingChar;
+ if (process.platform === "darwin" && activated && this.textEditMonitor) {
+ const ax = await this.textEditMonitor.getPrecedingChar(targetPid);
+ if (ax.state === "ok") {
+ mode = "prepend";
+ precedingChar = ax.char;
+ } else if (ax.state === "start") {
+ mode = "prepend";
+ precedingChar = "";
+ }
+ }
+ const textToPaste = applySmartSpacing({ text, mode, precedingChar });
+
+ const result = await this.clipboardManager.pasteText(textToPaste, {
...options,
webContents: event.sender,
});
diff --git a/src/helpers/smartSpacing.js b/src/helpers/smartSpacing.js
new file mode 100644
index 000000000..3e1dfbeb9
--- /dev/null
+++ b/src/helpers/smartSpacing.js
@@ -0,0 +1,29 @@
+// Pure spacing rules applied between previously-typed text and a paste.
+// "prepend" mode needs the char before the cursor (read via Accessibility on
+// macOS); "append" mode is the platform-agnostic fallback.
+
+const OPENING_CHARS = new Set([" ", "\t", "\n", "\r", "(", "[", "{", "<", '"', "'", "`", "“", "‘"]);
+const LEADING_PUNCTUATION = new Set([",", ".", "!", "?", ";", ":", ")", "]", "}", "%", "”", "’"]);
+
+function applySmartSpacing({ text, mode, precedingChar }) {
+ if (typeof text !== "string" || text.length === 0) return text;
+ if (mode === "prepend") return applyPrepend(text, precedingChar);
+ if (mode === "append") return applyAppend(text);
+ return text;
+}
+
+function applyPrepend(text, precedingChar) {
+ if (precedingChar == null || precedingChar === "") return text;
+ if (/^\s/.test(text)) return text;
+ if (OPENING_CHARS.has(precedingChar)) return text;
+ // Don't separate prior text from closing punctuation: "Hello" + ", world".
+ if (LEADING_PUNCTUATION.has(text[0])) return text;
+ return " " + text;
+}
+
+function applyAppend(text) {
+ if (/\s$/.test(text)) return text;
+ return text + " ";
+}
+
+module.exports = { applySmartSpacing };
diff --git a/src/helpers/textEditMonitor.js b/src/helpers/textEditMonitor.js
index cbcb75ece..22ca6f94f 100644
--- a/src/helpers/textEditMonitor.js
+++ b/src/helpers/textEditMonitor.js
@@ -21,6 +21,37 @@ const MACOS_AX_ENABLE_SCRIPT = (pid) =>
`\tend try\n` +
`end tell`;
+// Returns the character before the cursor for smart-spacing. Output protocol:
+// "OK:X" — preceding char is X
+// "START:" — cursor at field start, no preceding char
+// "" — unknown / read failed (caller falls back to append-mode spacing)
+// AppleScript `character N` is 1-indexed; AXSelectedTextRange.location is
+// 0-indexed, so the char at offset (loc-1) is `character loc`.
+const MACOS_AX_PRECEDING_CHAR_SCRIPT = (pid) =>
+ `tell application "System Events"\n` +
+ `\tset targetProc to first application process whose unix id is ${pid}\n` +
+ `\tset focAttr to value of attribute "AXFocusedUIElement" of targetProc\n` +
+ `\tif focAttr is missing value then return ""\n` +
+ `\tset theVal to ""\n` +
+ `\ttry\n` +
+ `\t\tset theVal to value of attribute "AXValue" of focAttr\n` +
+ `\t\tif theVal is missing value then set theVal to ""\n` +
+ `\tend try\n` +
+ `\tset loc to -1\n` +
+ `\ttry\n` +
+ `\t\tset sel to value of attribute "AXSelectedTextRange" of focAttr\n` +
+ `\t\ttry\n` +
+ `\t\t\tset loc to item 1 of sel\n` +
+ `\t\tend try\n` +
+ `\tend try\n` +
+ `\tif loc is -1 then return ""\n` +
+ `\tif loc < 1 then return "START:"\n` +
+ `\tif (length of theVal) is 0 then return "START:"\n` +
+ `\tif loc > (length of theVal) then set loc to length of theVal\n` +
+ `\tif loc < 1 then return "START:"\n` +
+ `\treturn "OK:" & (character loc of theVal)\n` +
+ `end tell`;
+
// AppleScript to read the focused text field value from a specific app by PID.
// Using PID avoids the problem where the Electron overlay is "frontmost".
// Tries AXValue first, then falls back to AXStringForRange for apps that
@@ -104,6 +135,38 @@ class TextEditMonitor extends EventEmitter {
});
}
+ /**
+ * macOS: read the char before the cursor in the focused text field, used by
+ * paste-time smart spacing. Resolves to { state: "ok", char } | { state:
+ * "start" } | { state: "unknown" }. Tight timeout so paste latency is
+ * unaffected; on "unknown" the caller falls back to append-mode spacing.
+ */
+ getPrecedingChar(pid, timeoutMs = 400) {
+ return new Promise((resolve) => {
+ if (process.platform !== "darwin" || !pid) {
+ resolve({ state: "unknown" });
+ return;
+ }
+ const script = MACOS_AX_PRECEDING_CHAR_SCRIPT(pid);
+ execFile("osascript", ["-e", script], { timeout: timeoutMs }, (err, stdout) => {
+ if (err) {
+ resolve({ state: "unknown" });
+ return;
+ }
+ const out = stdout.replace(/\n$/, "");
+ if (out === "START:") {
+ resolve({ state: "start" });
+ return;
+ }
+ if (out.startsWith("OK:")) {
+ resolve({ state: "ok", char: out.slice(3) });
+ return;
+ }
+ resolve({ state: "unknown" });
+ });
+ });
+ }
+
/**
* Start monitoring the focused text field for edits after a paste.
* Kills any existing monitor before starting a new one.
diff --git a/test/helpers/smartSpacing.test.js b/test/helpers/smartSpacing.test.js
new file mode 100644
index 000000000..2bb7330ed
--- /dev/null
+++ b/test/helpers/smartSpacing.test.js
@@ -0,0 +1,123 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+
+const { applySmartSpacing } = require("../../src/helpers/smartSpacing");
+
+const prepend = (text, precedingChar) =>
+ applySmartSpacing({ text, mode: "prepend", precedingChar });
+
+const append = (text) => applySmartSpacing({ text, mode: "append" });
+
+test("prepend: adds space after a regular letter", () => {
+ assert.equal(prepend("hello", "d"), " hello");
+});
+
+test("prepend: adds space after a digit", () => {
+ assert.equal(prepend("dollars", "5"), " dollars");
+});
+
+test("prepend: no space at field start (empty precedingChar)", () => {
+ assert.equal(prepend("hello", ""), "hello");
+});
+
+test("prepend: no space when precedingChar is null/undefined", () => {
+ assert.equal(prepend("hello", null), "hello");
+ assert.equal(prepend("hello", undefined), "hello");
+});
+
+test("prepend: no space after existing whitespace", () => {
+ assert.equal(prepend("hello", " "), "hello");
+ assert.equal(prepend("hello", "\t"), "hello");
+ assert.equal(prepend("hello", "\n"), "hello");
+});
+
+test("prepend: no space after opening brackets", () => {
+ assert.equal(prepend("hello", "("), "hello");
+ assert.equal(prepend("hello", "["), "hello");
+ assert.equal(prepend("hello", "{"), "hello");
+ assert.equal(prepend("hello", "<"), "hello");
+});
+
+test("prepend: no space after opening quotes", () => {
+ assert.equal(prepend("hello", '"'), "hello");
+ assert.equal(prepend("hello", "'"), "hello");
+ assert.equal(prepend("hello", "`"), "hello");
+ assert.equal(prepend("hello", "“"), "hello");
+});
+
+test("prepend: no space when transcript already starts with whitespace", () => {
+ assert.equal(prepend(" hello", "d"), " hello");
+ assert.equal(prepend("\nhello", "d"), "\nhello");
+});
+
+test("prepend: no space when transcript starts with closing punctuation", () => {
+ // "Hello" + ", world" → "Hello, world" (not "Hello , world")
+ assert.equal(prepend(", world", "o"), ", world");
+ assert.equal(prepend(". Period.", "o"), ". Period.");
+ assert.equal(prepend("! exclamation", "o"), "! exclamation");
+ assert.equal(prepend("? question", "o"), "? question");
+ assert.equal(prepend("; semicolon", "o"), "; semicolon");
+ assert.equal(prepend(": colon", "o"), ": colon");
+ assert.equal(prepend(") close paren", "o"), ") close paren");
+});
+
+test("prepend: adds space when preceding char is sentence punctuation (no space yet)", () => {
+ assert.equal(prepend("World", "."), " World");
+ assert.equal(prepend("World", "!"), " World");
+ assert.equal(prepend("World", "?"), " World");
+});
+
+test("prepend: no space when preceding is whitespace, even after period+space sequence", () => {
+ assert.equal(prepend("World", " "), "World");
+});
+
+test("prepend: handles unicode preceding chars", () => {
+ assert.equal(prepend("hello", "д"), " hello");
+});
+
+test("prepend: handles empty transcript", () => {
+ assert.equal(prepend("", "a"), "");
+});
+
+test("append: adds trailing space to normal text", () => {
+ assert.equal(append("hello"), "hello ");
+});
+
+test("append: adds trailing space after punctuation", () => {
+ assert.equal(append("hello."), "hello. ");
+ assert.equal(append("hello!"), "hello! ");
+});
+
+test("append: does not double-up when text already ends with whitespace", () => {
+ assert.equal(append("hello "), "hello ");
+ assert.equal(append("hello\n"), "hello\n");
+ assert.equal(append("hello\t"), "hello\t");
+});
+
+test("append: handles empty transcript", () => {
+ assert.equal(append(""), "");
+});
+
+test("returns text unchanged for unknown mode", () => {
+ assert.equal(applySmartSpacing({ text: "hello", mode: "noop" }), "hello");
+});
+
+test("returns text unchanged for non-string input", () => {
+ assert.equal(applySmartSpacing({ text: null, mode: "append" }), null);
+ assert.equal(applySmartSpacing({ text: undefined, mode: "append" }), undefined);
+});
+
+test("integration: typical dictation flow", () => {
+ // Field starts empty: "" → "Hello there"
+ assert.equal(prepend("Hello there.", ""), "Hello there.");
+
+ // After append fallback, next paste's preceding char is " "
+ // Field: "Hello there. " → user dictates again
+ assert.equal(prepend("How are you?", " "), "How are you?");
+
+ // No fallback was used; preceding char is "."
+ assert.equal(prepend("How are you?", "."), " How are you?");
+
+ // User dictates a closing tag: "(" → "first part)"
+ assert.equal(prepend("first part)", "("), "first part)");
+});
diff --git a/test/helpers/textEditMonitorPrecedingChar.test.js b/test/helpers/textEditMonitorPrecedingChar.test.js
new file mode 100644
index 000000000..aa3b7581e
--- /dev/null
+++ b/test/helpers/textEditMonitorPrecedingChar.test.js
@@ -0,0 +1,21 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+
+const TextEditMonitor = require("../../src/helpers/textEditMonitor");
+
+test("getPrecedingChar resolves to unknown for missing pid", async () => {
+ const m = new TextEditMonitor();
+ for (const pid of [null, undefined, 0]) {
+ assert.deepEqual(await m.getPrecedingChar(pid), { state: "unknown" });
+ }
+});
+
+test("getPrecedingChar returns unknown when the AX read fails or hangs", async () => {
+ const m = new TextEditMonitor();
+ // Non-darwin short-circuits without shelling out; darwin errors out on an
+ // unmapped PID. Both paths must resolve quickly with state "unknown".
+ const start = Date.now();
+ const result = await m.getPrecedingChar(99999999, 1500);
+ assert.equal(result.state, "unknown");
+ assert.ok(Date.now() - start < 3000);
+});