Skip to content

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

Auto-learn correction monitoring (#327)

Gabriel Steine866126b6fc0
diff --git a/.github/workflows/build-and-notarize.yml b/.github/workflows/build-and-notarize.yml
index 09974e6c1..ed1d77422 100644
--- a/.github/workflows/build-and-notarize.yml
+++ b/.github/workflows/build-and-notarize.yml
@@ -61,7 +61,7 @@ jobs:
- name: Install Linux build and packaging dependencies
run: |
sudo apt-get update
- sudo apt-get install -y rpm libx11-dev libxtst-dev
+ sudo apt-get install -y rpm libx11-dev libxtst-dev libatspi2.0-dev libglib2.0-dev
- name: Build Application
run: npm run build:linux -- --publish never
diff --git a/.github/workflows/build-linux-text-monitor.yml b/.github/workflows/build-linux-text-monitor.yml
new file mode 100644
index 000000000..fae3d3b77
--- /dev/null
+++ b/.github/workflows/build-linux-text-monitor.yml
@@ -0,0 +1,62 @@
+name: Build Linux Text Monitor
+
+on:
+ push:
+ paths:
+ - 'resources/linux-text-monitor.c'
+ - '.github/workflows/build-linux-text-monitor.yml'
+ branches:
+ - main
+ workflow_dispatch:
+ inputs:
+ version:
+ description: 'Version tag (e.g., 1.0.0)'
+ required: false
+ default: '1.0.0'
+ type: string
+
+permissions:
+ contents: write
+
+jobs:
+ build:
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+
+ - name: Install dependencies
+ run: |
+ sudo apt-get update && sudo apt-get install -y libatspi2.0-dev libglib2.0-dev pkg-config
+
+ - name: Compile Linux Text Monitor
+ run: |
+ gcc -O2 resources/linux-text-monitor.c -o linux-text-monitor $(pkg-config --cflags --libs atspi-2)
+
+ - name: Verify binary
+ run: |
+ file linux-text-monitor
+ test -f linux-text-monitor || { echo "Binary not found"; exit 1; }
+
+ - name: Create tar.gz archive
+ run: |
+ tar -czf linux-text-monitor-linux-x64.tar.gz linux-text-monitor
+
+ - name: Upload artifact
+ uses: actions/upload-artifact@v4
+ with:
+ name: linux-text-monitor
+ path: linux-text-monitor-linux-x64.tar.gz
+
+ - name: Create or update release
+ uses: softprops/action-gh-release@v2
+ with:
+ tag_name: linux-text-monitor-v${{ inputs.version || '1.0.0' }}
+ name: Linux Text Monitor v${{ inputs.version || '1.0.0' }}
+ body: |
+ Prebuilt Linux text monitor binary for auto-learn correction monitoring.
+
+ This binary uses AT-SPI2 to detect text field changes after paste.
+ files: linux-text-monitor-linux-x64.tar.gz
+ make_latest: false
+ env:
+ GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
diff --git a/.github/workflows/build-windows-text-monitor.yml b/.github/workflows/build-windows-text-monitor.yml
new file mode 100644
index 000000000..e11daf063
--- /dev/null
+++ b/.github/workflows/build-windows-text-monitor.yml
@@ -0,0 +1,72 @@
+name: Build Windows Text Monitor
+
+on:
+ push:
+ paths:
+ - 'resources/windows-text-monitor.c'
+ - '.github/workflows/build-windows-text-monitor.yml'
+ branches:
+ - main
+ workflow_dispatch:
+ inputs:
+ version:
+ description: 'Version tag (e.g., 1.0.0)'
+ required: false
+ default: '1.0.0'
+ type: string
+
+permissions:
+ contents: write
+
+jobs:
+ build:
+ runs-on: windows-latest
+ steps:
+ - uses: actions/checkout@v4
+
+ - name: Setup MSVC
+ uses: microsoft/setup-msbuild@v2
+
+ - name: Setup MSVC environment
+ uses: ilammy/msvc-dev-cmd@v1
+
+ - name: Compile Windows Text Monitor
+ run: |
+ cl /O2 /nologo resources/windows-text-monitor.c /Fe:windows-text-monitor.exe ole32.lib oleaut32.lib
+ shell: cmd
+
+ - name: Verify binary
+ run: |
+ if (Test-Path "windows-text-monitor.exe") {
+ Write-Host "Binary built successfully"
+ Get-Item "windows-text-monitor.exe" | Select-Object Name, Length
+ } else {
+ Write-Error "Binary not found"
+ exit 1
+ }
+ shell: pwsh
+
+ - name: Create zip archive
+ run: |
+ Compress-Archive -Path windows-text-monitor.exe -DestinationPath windows-text-monitor-win32-x64.zip
+ shell: pwsh
+
+ - name: Upload artifact
+ uses: actions/upload-artifact@v4
+ with:
+ name: windows-text-monitor
+ path: windows-text-monitor-win32-x64.zip
+
+ - name: Create or update release
+ uses: softprops/action-gh-release@v2
+ with:
+ tag_name: windows-text-monitor-v${{ inputs.version || '1.0.0' }}
+ name: Windows Text Monitor v${{ inputs.version || '1.0.0' }}
+ body: |
+ Prebuilt Windows text monitor binary for auto-learn correction monitoring.
+
+ This binary uses Windows UI Automation to detect text field changes after paste.
+ files: windows-text-monitor-win32-x64.zip
+ make_latest: false
+ env:
+ GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
diff --git a/electron-builder.json b/electron-builder.json
index 130827c52..6923e33c4 100644
--- a/electron-builder.json
+++ b/electron-builder.json
@@ -87,7 +87,9 @@
"src/assets/**/*",
"resources/bin/macos-globe-listener",
"resources/bin/macos-fast-paste",
+ "resources/bin/macos-text-monitor",
"resources/bin/linux-fast-paste",
+ "resources/bin/linux-text-monitor",
{
"from": "resources/bin/",
"to": "bin/",
@@ -97,6 +99,7 @@
"llama-server-*",
"sherpa-onnx-*",
"windows-key-listener*",
+ "windows-text-monitor*",
"windows-fast-paste*",
"*.dylib",
"*.dll",
diff --git a/main.js b/main.js
index 5b5723496..ad90157d5 100644
--- a/main.js
+++ b/main.js
@@ -164,6 +164,7 @@ const UpdateManager = require("./src/updater");
const GlobeKeyManager = require("./src/helpers/globeKeyManager");
const DevServerManager = require("./src/helpers/devServerManager");
const WindowsKeyManager = require("./src/helpers/windowsKeyManager");
+const TextEditMonitor = require("./src/helpers/textEditMonitor");
const WhisperCudaManager = require("./src/helpers/whisperCudaManager");
const { i18nMain, changeLanguage } = require("./src/helpers/i18nMain");
@@ -180,7 +181,9 @@ let trayManager = null;
let updateManager = null;
let globeKeyManager = null;
let windowsKeyManager = null;
+let textEditMonitor = null;
let whisperCudaManager = null;
+let ipcHandlers = null;
let globeKeyAlertShown = false;
let authBridgeServer = null;
@@ -245,9 +248,11 @@ function initializeCoreManagers() {
parakeetManager = new ParakeetManager();
updateManager = new UpdateManager();
windowsKeyManager = new WindowsKeyManager();
+ textEditMonitor = new TextEditMonitor();
+ windowManager.textEditMonitor = textEditMonitor;
// IPC handlers must be registered before window content loads
- new IPCHandlers({
+ ipcHandlers = new IPCHandlers({
environmentManager,
databaseManager,
clipboardManager,
@@ -256,6 +261,7 @@ function initializeCoreManagers() {
windowManager,
updateManager,
windowsKeyManager,
+ textEditMonitor,
whisperCudaManager,
getTrayManager: () => trayManager,
});
@@ -551,6 +557,8 @@ async function startApp() {
// Handle dictation if Globe is the current hotkey
if (currentHotkey === "GLOBE") {
if (mainWindowLive) {
+ // Capture target app PID BEFORE showing the overlay
+ if (textEditMonitor) textEditMonitor.captureTargetPid();
const activationMode = windowManager.getActivationMode();
if (activationMode === "push") {
const now = Date.now();
@@ -624,6 +632,7 @@ async function startApp() {
if (!isLiveWindow(windowManager.mainWindow)) return;
const activationMode = windowManager.getActivationMode();
+ if (textEditMonitor) textEditMonitor.captureTargetPid();
if (activationMode === "push") {
const now = Date.now();
if (now - rightModLastStopTime < POST_STOP_COOLDOWN_MS) return;
@@ -916,6 +925,12 @@ if (gotSingleInstanceLock) {
if (windowsKeyManager) {
windowsKeyManager.stop();
}
+ if (ipcHandlers) {
+ ipcHandlers._cleanupTextEditMonitor();
+ }
+ if (textEditMonitor) {
+ textEditMonitor.stopMonitoring();
+ }
if (updateManager) {
updateManager.cleanup();
}
diff --git a/package.json b/package.json
index 06b0ba6ef..73bcc348b 100644
--- a/package.json
+++ b/package.json
@@ -8,9 +8,10 @@
"compile:globe": "node scripts/build-globe-listener.js",
"compile:fast-paste": "node scripts/build-macos-fast-paste.js",
"compile:winkeys": "node scripts/build-windows-key-listener.js",
+ "compile:text-monitor": "node scripts/build-text-monitor.js",
"compile:winpaste": "node scripts/build-windows-fast-paste.js",
"compile:linux-paste": "node scripts/build-linux-fast-paste.js",
- "compile:native": "npm run compile:globe && npm run compile:fast-paste && npm run compile:winkeys && npm run compile:winpaste && npm run compile:linux-paste",
+ "compile:native": "npm run compile:globe && npm run compile:fast-paste && npm run compile:winkeys && npm run compile:winpaste && npm run compile:linux-paste && npm run compile:text-monitor",
"prestart": "npm run compile:native",
"start": "electron .",
"predev": "npm run compile:native",
diff --git a/preload.js b/preload.js
index db9736420..f8ece6a88 100644
--- a/preload.js
+++ b/preload.js
@@ -38,6 +38,18 @@ contextBridge.exposeInMainWorld("electronAPI", {
// Dictionary functions
getDictionary: () => ipcRenderer.invoke("db-get-dictionary"),
setDictionary: (words) => ipcRenderer.invoke("db-set-dictionary", words),
+ onDictionaryUpdated: (callback) => {
+ const listener = (_event, words) => callback?.(words);
+ ipcRenderer.on("dictionary-updated", listener);
+ return () => ipcRenderer.removeListener("dictionary-updated", listener);
+ },
+ setAutoLearnEnabled: (enabled) => ipcRenderer.send("auto-learn-changed", enabled),
+ onCorrectionsLearned: (callback) => {
+ const listener = (_event, words) => callback?.(words);
+ ipcRenderer.on("corrections-learned", listener);
+ return () => ipcRenderer.removeListener("corrections-learned", listener);
+ },
+ undoLearnedCorrections: (words) => ipcRenderer.invoke("undo-learned-corrections", words),
// Note functions
saveNote: (title, content, noteType, sourceFile, audioDuration, folderId) =>
diff --git a/resources/linux-text-monitor.c b/resources/linux-text-monitor.c
new file mode 100644
index 000000000..fde5dee78
--- /dev/null
+++ b/resources/linux-text-monitor.c
@@ -0,0 +1,252 @@
+/**
+ * Linux Text Edit Monitor
+ *
+ * Uses AT-SPI2 to monitor the focused text field for value changes.
+ * Outputs "CHANGED:<value>" to stdout when the text changes.
+ * Exits after a timeout or on receiving a termination signal.
+ *
+ * Protocol (stdout):
+ * INITIAL_VALUE:<text> - Initial text field value
+ * INITIAL_VALUE_B64:<base64> - Initial text field value (multiline)
+ * CHANGED:<text> - Text field value after a change
+ * CHANGED_B64:<base64> - Text field value after a change (multiline)
+ * NO_ELEMENT - Could not get focused element
+ * NO_VALUE - Focused element has no text value
+ *
+ * Input (stdin):
+ * First line: original pasted text (informational)
+ *
+ * Compile:
+ * gcc -O2 linux-text-monitor.c -o linux-text-monitor $(pkg-config --cflags --libs atspi-2)
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <signal.h>
+#include <time.h>
+#include <unistd.h>
+#include <atspi/atspi.h>
+
+#define TIMEOUT_SECONDS 30
+#define POLL_INTERVAL_MS 500
+#define MAX_OUTPUT_CHARS 10240
+
+static volatile sig_atomic_t running = 1;
+static const char BASE64_TABLE[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
+
+static void signal_handler(int sig) {
+ (void)sig;
+ running = 0;
+}
+
+static char *base64_encode(const unsigned char *data, size_t len) {
+ size_t out_len = 4 * ((len + 2) / 3);
+ char *out = (char *)malloc(out_len + 1);
+ if (!out) return NULL;
+
+ size_t i = 0, j = 0;
+ while (i < len) {
+ unsigned int octet_a = i < len ? data[i++] : 0;
+ unsigned int octet_b = i < len ? data[i++] : 0;
+ unsigned int octet_c = i < len ? data[i++] : 0;
+ unsigned int triple = (octet_a << 16) | (octet_b << 8) | octet_c;
+
+ out[j++] = BASE64_TABLE[(triple >> 18) & 0x3F];
+ out[j++] = BASE64_TABLE[(triple >> 12) & 0x3F];
+ out[j++] = BASE64_TABLE[(triple >> 6) & 0x3F];
+ out[j++] = BASE64_TABLE[triple & 0x3F];
+ }
+
+ if (len % 3 == 1) {
+ out[out_len - 1] = '=';
+ out[out_len - 2] = '=';
+ } else if (len % 3 == 2) {
+ out[out_len - 1] = '=';
+ }
+
+ out[out_len] = '\0';
+ return out;
+}
+
+static void print_text_output(const char *name, const char *value) {
+ if (!value) return;
+
+ size_t len = strlen(value);
+ size_t limit = len < MAX_OUTPUT_CHARS ? len : MAX_OUTPUT_CHARS;
+
+ if (memchr(value, '\n', limit) || memchr(value, '\r', limit)) {
+ char *encoded = base64_encode((const unsigned char *)value, limit);
+ if (!encoded) return;
+ printf("%s_B64:%s\n", name, encoded);
+ fflush(stdout);
+ free(encoded);
+ return;
+ }
+
+ printf("%s:%.*s\n", name, (int)limit, value);
+ fflush(stdout);
+}
+
+static AtspiAccessible *find_focused(AtspiAccessible *accessible) {
+ GError *error = NULL;
+
+ AtspiStateSet *states = atspi_accessible_get_state_set(accessible);
+ if (states) {
+ if (atspi_state_set_contains(states, ATSPI_STATE_FOCUSED)) {
+ g_object_unref(states);
+ return g_object_ref(accessible);
+ }
+ g_object_unref(states);
+ }
+
+ int count = atspi_accessible_get_child_count(accessible, &error);
+ if (error) {
+ g_error_free(error);
+ return NULL;
+ }
+
+ for (int i = 0; i < count; i++) {
+ AtspiAccessible *child = atspi_accessible_get_child_at_index(accessible, i, &error);
+ if (error) {
+ g_error_free(error);
+ error = NULL;
+ continue;
+ }
+ if (!child) continue;
+
+ AtspiAccessible *result = find_focused(child);
+ g_object_unref(child);
+ if (result) return result;
+ }
+
+ return NULL;
+}
+
+static char *read_text_value(AtspiText *text_iface) {
+ GError *error = NULL;
+
+ int char_count = atspi_text_get_character_count(text_iface, &error);
+ if (error) {
+ g_error_free(error);
+ return NULL;
+ }
+ if (char_count <= 0) return NULL;
+
+ int limit = char_count < MAX_OUTPUT_CHARS ? char_count : MAX_OUTPUT_CHARS;
+ char *value = atspi_text_get_text(text_iface, 0, limit, &error);
+ if (error) {
+ g_error_free(error);
+ return NULL;
+ }
+
+ return value;
+}
+
+int main(void) {
+ signal(SIGTERM, signal_handler);
+ signal(SIGINT, signal_handler);
+
+ /* Read original text from stdin (consume but don't use) */
+ char stdin_buf[4096];
+ if (fgets(stdin_buf, sizeof(stdin_buf), stdin)) {
+ /* consumed */
+ }
+
+ int init_result = atspi_init();
+ if (init_result != 0 && init_result != 1) {
+ printf("NO_ELEMENT\n");
+ fflush(stdout);
+ return 1;
+ }
+
+ GError *error = NULL;
+ AtspiAccessible *desktop = atspi_get_desktop(0);
+ if (!desktop) {
+ printf("NO_ELEMENT\n");
+ fflush(stdout);
+ return 1;
+ }
+
+ /* Search for focused element across all applications */
+ AtspiAccessible *focused = NULL;
+ int app_count = atspi_accessible_get_child_count(desktop, &error);
+ if (error) {
+ g_error_free(error);
+ error = NULL;
+ app_count = 0;
+ }
+
+ for (int i = 0; i < app_count && !focused; i++) {
+ AtspiAccessible *app = atspi_accessible_get_child_at_index(desktop, i, &error);
+ if (error) {
+ g_error_free(error);
+ error = NULL;
+ continue;
+ }
+ if (!app) continue;
+
+ focused = find_focused(app);
+ g_object_unref(app);
+ }
+
+ g_object_unref(desktop);
+
+ if (!focused) {
+ printf("NO_ELEMENT\n");
+ fflush(stdout);
+ return 1;
+ }
+
+ /* Get the Text interface */
+ AtspiText *text_iface = atspi_accessible_get_text_iface(focused);
+ if (!text_iface) {
+ printf("NO_VALUE\n");
+ fflush(stdout);
+ g_object_unref(focused);
+ return 0;
+ }
+
+ /* Read initial value */
+ char *last_value = read_text_value(text_iface);
+ if (!last_value) {
+ printf("NO_VALUE\n");
+ fflush(stdout);
+ g_object_unref(text_iface);
+ g_object_unref(focused);
+ return 0;
+ }
+
+ print_text_output("INITIAL_VALUE", last_value);
+
+ /* Poll for changes */
+ struct timespec start;
+ clock_gettime(CLOCK_MONOTONIC, &start);
+
+ while (running) {
+ struct timespec now;
+ clock_gettime(CLOCK_MONOTONIC, &now);
+ long elapsed_ms = (now.tv_sec - start.tv_sec) * 1000 +
+ (now.tv_nsec - start.tv_nsec) / 1000000;
+ if (elapsed_ms >= TIMEOUT_SECONDS * 1000) break;
+
+ usleep(POLL_INTERVAL_MS * 1000);
+
+ char *current_value = read_text_value(text_iface);
+ if (!current_value) continue;
+
+ if (strcmp(current_value, last_value) != 0) {
+ print_text_output("CHANGED", current_value);
+ g_free(last_value);
+ last_value = current_value;
+ } else {
+ g_free(current_value);
+ }
+ }
+
+ g_free(last_value);
+ g_object_unref(text_iface);
+ g_object_unref(focused);
+
+ return 0;
+}
diff --git a/resources/linux-text-monitor.py b/resources/linux-text-monitor.py
new file mode 100644
index 000000000..82c36f575
--- /dev/null
+++ b/resources/linux-text-monitor.py
@@ -0,0 +1,166 @@
+#!/usr/bin/env python3
+"""
+Linux Text Edit Monitor
+
+Uses AT-SPI2 to monitor the focused text field for changes.
+Outputs "CHANGED:<value>" to stdout when the text changes.
+Exits after a timeout or on receiving SIGTERM.
+
+Protocol (stdout):
+ INITIAL_VALUE:<text> - Initial text field value
+ INITIAL_VALUE_B64:<base64> - Initial text field value (multiline)
+ CHANGED:<text> - Text field value after a change
+ CHANGED_B64:<base64> - Text field value after a change (multiline)
+ NO_ELEMENT - Could not get focused element
+ NO_VALUE - Focused element has no text value
+
+Input (stdin):
+ First line: original pasted text (informational)
+
+Requires: python3-atspi / pyatspi (gi.repository.Atspi)
+"""
+
+import sys
+import signal
+import threading
+import base64
+
+TIMEOUT_SECONDS = 30
+MAX_OUTPUT_CHARS = 10240
+
+try:
+ import gi
+ gi.require_version("Atspi", "2.0")
+ from gi.repository import Atspi, GLib
+ HAS_ATSPI = True
+except (ImportError, ValueError):
+ HAS_ATSPI = False
+
+
+def _find_focused(accessible):
+ """Recursively find the focused accessible element."""
+ try:
+ state_set = accessible.get_state_set()
+ if state_set.contains(Atspi.StateType.FOCUSED):
+ return accessible
+ for i in range(accessible.get_child_count()):
+ child = accessible.get_child_at_index(i)
+ if child is None:
+ continue
+ result = _find_focused(child)
+ if result is not None:
+ return result
+ except Exception:
+ pass
+ return None
+
+
+def _emit_text(prefix, value):
+ truncated = value[:MAX_OUTPUT_CHARS]
+ if "\n" in truncated or "\r" in truncated:
+ encoded = base64.b64encode(truncated.encode("utf-8")).decode("ascii")
+ print(f"{prefix}_B64:{encoded}", flush=True)
+ else:
+ print(f"{prefix}:{truncated}", flush=True)
+
+
+def main():
+ # Read original text from stdin (consume but don't use in this binary)
+ try:
+ sys.stdin.readline()
+ except Exception:
+ pass
+
+ if not HAS_ATSPI:
+ print("NO_ELEMENT", flush=True)
+ sys.exit(1)
+
+ Atspi.init()
+
+ # Get the focused accessible element
+ desktop = Atspi.get_desktop(0)
+ focused = None
+
+ # Search for the focused element across all applications
+ for i in range(desktop.get_child_count()):
+ try:
+ app = desktop.get_child_at_index(i)
+ if app is None:
+ continue
+ focused = _find_focused(app)
+ if focused is not None:
+ break
+ except Exception:
+ continue
+
+ if focused is None:
+ print("NO_ELEMENT", flush=True)
+ sys.exit(1)
+
+ # Check if the element supports the Text interface
+ try:
+ text_iface = focused.get_text_iface()
+ if text_iface is None:
+ print("NO_VALUE", flush=True)
+ sys.exit(0)
+ except Exception:
+ print("NO_VALUE", flush=True)
+ sys.exit(0)
+
+ # Read initial value
+ try:
+ char_count = text_iface.get_character_count()
+ initial_value = text_iface.get_text(0, min(char_count, MAX_OUTPUT_CHARS))
+ _emit_text("INITIAL_VALUE", initial_value)
+ except Exception:
+ print("NO_VALUE", flush=True)
+ sys.exit(0)
+
+ # Set up event listener for text changes
+ last_value = [initial_value]
+ loop = GLib.MainLoop()
+
+ def on_text_changed(event):
+ try:
+ source = event.source
+ ti = source.get_text_iface()
+ if ti is None:
+ return
+ cc = ti.get_character_count()
+ new_value = ti.get_text(0, min(cc, MAX_OUTPUT_CHARS))
+ if new_value != last_value[0]:
+ last_value[0] = new_value
+ _emit_text("CHANGED", new_value)
+ except Exception:
+ pass
+
+ Atspi.EventListener.register_from_callback(
+ on_text_changed, "object:text-changed:insert"
+ )
+ Atspi.EventListener.register_from_callback(
+ on_text_changed, "object:text-changed:delete"
+ )
+
+ # Set up timeout
+ def timeout_handler():
+ loop.quit()
+ timer = threading.Timer(TIMEOUT_SECONDS, timeout_handler)
+ timer.daemon = True
+ timer.start()
+
+ # Handle SIGTERM
+ def sigterm_handler(signum, frame):
+ loop.quit()
+ signal.signal(signal.SIGTERM, sigterm_handler)
+ signal.signal(signal.SIGINT, sigterm_handler)
+
+ try:
+ loop.run()
+ except KeyboardInterrupt:
+ pass
+
+ timer.cancel()
+
+
+if __name__ == "__main__":
+ main()
diff --git a/resources/macos-text-monitor.swift b/resources/macos-text-monitor.swift
new file mode 100644
index 000000000..255a33b1e
--- /dev/null
+++ b/resources/macos-text-monitor.swift
@@ -0,0 +1,160 @@
+import Cocoa
+import Foundation
+import Darwin
+
+let TIMEOUT_SECONDS: Double = 30.0
+let MAX_OUTPUT_BYTES = 10240
+let MAX_BASE64_SOURCE_CHARS = 7000
+
+var monitoredElement: AXUIElement?
+var observer: AXObserver?
+var monitoredPid: pid_t = 0
+
+func writeOutput(_ message: String) {
+ FileHandle.standardOutput.write((message + "\n").data(using: .utf8)!)
+ fflush(stdout)
+}
+
+func writeError(_ message: String) {
+ FileHandle.standardError.write((message + "\n").data(using: .utf8)!)
+}
+
+func writeTextOutput(_ prefix: String, _ value: String) {
+ let truncated = String(value.prefix(MAX_OUTPUT_BYTES))
+ if truncated.contains("\n") || truncated.contains("\r") {
+ let capped = String(truncated.prefix(MAX_BASE64_SOURCE_CHARS))
+ let encoded = Data(capped.utf8).base64EncodedString()
+ writeOutput("\(prefix)_B64:\(encoded)")
+ return
+ }
+
+ writeOutput("\(prefix):\(truncated)")
+}
+
+func readCurrentValue() -> String? {
+ guard let element = monitoredElement else { return nil }
+ var value: AnyObject?
+ let result = AXUIElementCopyAttributeValue(element, kAXValueAttribute as CFString, &value)
+ guard result == .success, let str = value as? String else { return nil }
+ return str
+}
+
+func observerCallback(
+ _ observer: AXObserver,
+ _ element: AXUIElement,
+ _ notification: CFString,
+ _ refcon: UnsafeMutableRawPointer?
+) {
+ if let value = readCurrentValue() {
+ writeTextOutput("CHANGED", value)
+ }
+}
+
+// Usage: macos-text-monitor <pid>
+guard CommandLine.arguments.count >= 2,
+ let targetPid = Int32(CommandLine.arguments[1]),
+ targetPid > 0 else {
+ writeError("Usage: macos-text-monitor <pid>")
+ writeOutput("NO_ELEMENT")
+ exit(1)
+}
+
+monitoredPid = targetPid
+
+// Read original text from stdin
+var originalText = ""
+if let line = readLine(strippingNewline: true) {
+ originalText = line
+}
+
+// Target the specific application by PID (passed from the Electron host
+// which captures it BEFORE the overlay steals focus).
+let appElement = AXUIElementCreateApplication(monitoredPid)
+let maxRetries = 5
+var focusedElement: AXUIElement? = nil
+
+for attempt in 1...maxRetries {
+ var elementValue: AnyObject?
+ let elementResult = AXUIElementCopyAttributeValue(
+ appElement,
+ kAXFocusedUIElementAttribute as CFString,
+ &elementValue
+ )
+
+ if elementResult == .success, let element = elementValue {
+ focusedElement = (element as! AXUIElement)
+ if attempt > 1 {
+ writeError("Got focused element on attempt \(attempt)")
+ }
+ break
+ } else {
+ writeError("Attempt \(attempt)/\(maxRetries): Cannot get focused element for PID \(monitoredPid) (error: \(elementResult.rawValue))")
+ }
+
+ if attempt < maxRetries {
+ Thread.sleep(forTimeInterval: 0.3)
+ }
+}
+
+guard let resolvedElement = focusedElement else {
+ writeOutput("NO_ELEMENT")
+ exit(1)
+}
+
+monitoredElement = resolvedElement
+writeError("Monitoring element in PID \(monitoredPid)")
+
+// Read initial value
+guard let initialValue = readCurrentValue() else {
+ writeError("Focused element has no text value")
+ writeOutput("NO_VALUE")
+ exit(0)
+}
+
+writeTextOutput("INITIAL_VALUE", initialValue)
+
+// Create AXObserver for the target application's PID
+var createdObserver: AXObserver?
+let observerResult = AXObserverCreate(monitoredPid, observerCallback, &createdObserver)
+
+guard observerResult == .success, let obs = createdObserver else {
+ writeError("Failed to create AXObserver (error: \(observerResult.rawValue))")
+ exit(1)
+}
+
+observer = obs
+
+// Watch for value changes
+let addResult = AXObserverAddNotification(
+ obs,
+ monitoredElement!,
+ kAXValueChangedNotification as CFString,
+ nil
+)
+
+if addResult != .success {
+ writeError("Failed to add notification (error: \(addResult.rawValue))")
+ exit(1)
+}
+
+// Add observer to run loop
+CFRunLoopAddSource(
+ CFRunLoopGetCurrent(),
+ AXObserverGetRunLoopSource(obs),
+ .commonModes
+)
+
+// Schedule auto-exit after timeout
+DispatchQueue.main.asyncAfter(deadline: .now() + TIMEOUT_SECONDS) {
+ CFRunLoopStop(CFRunLoopGetCurrent())
+}
+
+// Handle SIGTERM for clean exit
+let signalSource = DispatchSource.makeSignalSource(signal: SIGTERM, queue: .main)
+signal(SIGTERM, SIG_IGN)
+signalSource.setEventHandler {
+ CFRunLoopStop(CFRunLoopGetCurrent())
+}
+signalSource.resume()
+
+CFRunLoopRun()
diff --git a/resources/windows-text-monitor.c b/resources/windows-text-monitor.c
new file mode 100644
index 000000000..1f9eb5893
--- /dev/null
+++ b/resources/windows-text-monitor.c
@@ -0,0 +1,225 @@
+/**
+ * Windows Text Edit Monitor
+ *
+ * Uses UI Automation to monitor the focused text field for value changes.
+ * Outputs "CHANGED:<value>" to stdout when the text changes.
+ * Exits after a timeout or on receiving a termination signal.
+ *
+ * Protocol (stdout):
+ * INITIAL_VALUE:<text> - Initial text field value
+ * INITIAL_VALUE_B64:<base64> - Initial text field value (multiline)
+ * CHANGED:<text> - Text field value after a change
+ * CHANGED_B64:<base64> - Text field value after a change (multiline)
+ * NO_ELEMENT - Could not get focused element
+ * NO_VALUE - Focused element has no text value
+ *
+ * Input (stdin):
+ * First line: original pasted text (informational)
+ *
+ * Compile:
+ * cl /O2 windows-text-monitor.c /Fe:windows-text-monitor.exe ole32.lib oleaut32.lib
+ * or: gcc -O2 windows-text-monitor.c -o windows-text-monitor.exe -lole32 -loleaut32 -luuid
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <signal.h>
+
+#define COBJMACROS
+#include <windows.h>
+#include <oleauto.h>
+#include <uiautomation.h>
+
+#define TIMEOUT_MS 30000
+#define POLL_INTERVAL_MS 500
+#define MAX_OUTPUT_CHARS 10240
+
+static volatile int running = 1;
+static const char BASE64_TABLE[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
+
+void signal_handler(int sig) {
+ (void)sig;
+ running = 0;
+}
+
+char *base64_encode(const unsigned char *data, size_t len) {
+ size_t out_len = 4 * ((len + 2) / 3);
+ char *out = (char *)malloc(out_len + 1);
+ if (!out) return NULL;
+
+ size_t i = 0, j = 0;
+ while (i < len) {
+ unsigned int octet_a = i < len ? data[i++] : 0;
+ unsigned int octet_b = i < len ? data[i++] : 0;
+ unsigned int octet_c = i < len ? data[i++] : 0;
+ unsigned int triple = (octet_a << 16) | (octet_b << 8) | octet_c;
+
+ out[j++] = BASE64_TABLE[(triple >> 18) & 0x3F];
+ out[j++] = BASE64_TABLE[(triple >> 12) & 0x3F];
+ out[j++] = BASE64_TABLE[(triple >> 6) & 0x3F];
+ out[j++] = BASE64_TABLE[triple & 0x3F];
+ }
+
+ if (len % 3 == 1) {
+ out[out_len - 1] = '=';
+ out[out_len - 2] = '=';
+ } else if (len % 3 == 2) {
+ out[out_len - 1] = '=';
+ }
+
+ out[out_len] = '\0';
+ return out;
+}
+
+void print_text_output(const char *name, const WCHAR *value) {
+ if (!value) return;
+
+ /* Convert wide string to UTF-8 (needed includes the null terminator) */
+ int needed = WideCharToMultiByte(CP_UTF8, 0, value, -1, NULL, 0, NULL, NULL);
+ if (needed <= 0) return;
+
+ char *utf8 = (char *)malloc((size_t)needed);
+ if (!utf8) return;
+
+ int written = WideCharToMultiByte(CP_UTF8, 0, value, -1, utf8, needed, NULL, NULL);
+ if (written <= 0) {
+ free(utf8);
+ return;
+ }
+ utf8[needed - 1] = '\0';
+
+ size_t utf8_len = strlen(utf8);
+ size_t limit = utf8_len < MAX_OUTPUT_CHARS ? utf8_len : MAX_OUTPUT_CHARS;
+
+ if (memchr(utf8, '\n', limit) || memchr(utf8, '\r', limit)) {
+ char *encoded = base64_encode((const unsigned char *)utf8, limit);
+ if (encoded) {
+ printf("%s_B64:%s\n", name, encoded);
+ fflush(stdout);
+ free(encoded);
+ }
+ } else {
+ printf("%s:%.*s\n", name, (int)limit, utf8);
+ fflush(stdout);
+ }
+
+ free(utf8);
+}
+
+int main(void) {
+ signal(SIGTERM, signal_handler);
+ signal(SIGINT, signal_handler);
+
+ /* Read original text from stdin (consume but don't use) */
+ char stdin_buf[4096];
+ if (fgets(stdin_buf, sizeof(stdin_buf), stdin)) {
+ /* consumed */
+ }
+
+ /* Initialize COM */
+ HRESULT hr = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);
+ if (FAILED(hr)) {
+ fprintf(stderr, "CoInitializeEx failed: 0x%lx\n", hr);
+ printf("NO_ELEMENT\n");
+ fflush(stdout);
+ return 1;
+ }
+
+ /* Create UI Automation instance */
+ IUIAutomation *automation = NULL;
+ hr = CoCreateInstance(
+ &CLSID_CUIAutomation, NULL, CLSCTX_INPROC_SERVER,
+ &IID_IUIAutomation, (void **)&automation
+ );
+ if (FAILED(hr) || !automation) {
+ fprintf(stderr, "Failed to create IUIAutomation: 0x%lx\n", hr);
+ printf("NO_ELEMENT\n");
+ fflush(stdout);
+ CoUninitialize();
+ return 1;
+ }
+
+ /* Get the focused element */
+ IUIAutomationElement *focused = NULL;
+ hr = IUIAutomation_GetFocusedElement(automation, &focused);
+ if (FAILED(hr) || !focused) {
+ fprintf(stderr, "Failed to get focused element: 0x%lx\n", hr);
+ printf("NO_ELEMENT\n");
+ fflush(stdout);
+ IUIAutomation_Release(automation);
+ CoUninitialize();
+ return 1;
+ }
+
+ /* Try to get the Value pattern */
+ IUIAutomationValuePattern *valuePattern = NULL;
+ hr = IUIAutomationElement_GetCurrentPatternAs(
+ focused, UIA_ValuePatternId,
+ &IID_IUIAutomationValuePattern, (void **)&valuePattern
+ );
+
+ BSTR lastValue = NULL;
+
+ if (SUCCEEDED(hr) && valuePattern) {
+ /* Read initial value via Value pattern */
+ hr = IUIAutomationValuePattern_get_CurrentValue(valuePattern, &lastValue);
+ if (SUCCEEDED(hr) && lastValue) {
+ print_text_output("INITIAL_VALUE", lastValue);
+ } else {
+ printf("NO_VALUE\n");
+ fflush(stdout);
+ IUIAutomationValuePattern_Release(valuePattern);
+ IUIAutomationElement_Release(focused);
+ IUIAutomation_Release(automation);
+ CoUninitialize();
+ return 0;
+ }
+ } else {
+ /* No Value pattern — try getting the Name property as fallback */
+ BSTR name = NULL;
+ hr = IUIAutomationElement_get_CurrentName(focused, &name);
+ if (SUCCEEDED(hr) && name && SysStringLen(name) > 0) {
+ /* Element has a name but no editable value — not a text field */
+ SysFreeString(name);
+ }
+ printf("NO_VALUE\n");
+ fflush(stdout);
+ IUIAutomationElement_Release(focused);
+ IUIAutomation_Release(automation);
+ CoUninitialize();
+ return 0;
+ }
+
+ /* Poll for value changes */
+ DWORD startTime = GetTickCount();
+
+ while (running) {
+ DWORD elapsed = GetTickCount() - startTime;
+ if (elapsed >= TIMEOUT_MS) break;
+
+ Sleep(POLL_INTERVAL_MS);
+
+ BSTR currentValue = NULL;
+ hr = IUIAutomationValuePattern_get_CurrentValue(valuePattern, &currentValue);
+ if (FAILED(hr) || !currentValue) continue;
+
+ /* Compare with last known value */
+ if (lastValue && wcscmp(currentValue, lastValue) != 0) {
+ print_text_output("CHANGED", currentValue);
+ SysFreeString(lastValue);
+ lastValue = currentValue;
+ } else {
+ SysFreeString(currentValue);
+ }
+ }
+
+ /* Cleanup */
+ if (lastValue) SysFreeString(lastValue);
+ if (valuePattern) IUIAutomationValuePattern_Release(valuePattern);
+ if (focused) IUIAutomationElement_Release(focused);
+ if (automation) IUIAutomation_Release(automation);
+ CoUninitialize();
+
+ return 0;
+}
diff --git a/scripts/build-linux-fast-paste.js b/scripts/build-linux-fast-paste.js
index f9c3d49e9..ca3ebaf4c 100755
--- a/scripts/build-linux-fast-paste.js
+++ b/scripts/build-linux-fast-paste.js
@@ -65,7 +65,10 @@ const uinputAvailable = hasUinputHeaders();
function computeBuildHash() {
const sourceContent = fs.readFileSync(cSource, "utf8");
const flags = uinputAvailable ? "uinput" : "nouinput";
- return crypto.createHash("sha256").update(sourceContent + flags).digest("hex");
+ return crypto
+ .createHash("sha256")
+ .update(sourceContent + flags)
+ .digest("hex");
}
if (!needsBuild && fs.existsSync(outputBinary)) {
@@ -99,14 +102,7 @@ function attemptCompile(command, args) {
});
}
-const compileArgs = [
- "-O2",
- cSource,
- "-o",
- outputBinary,
- "-lX11",
- "-lXtst",
-];
+const compileArgs = ["-O2", cSource, "-o", outputBinary, "-lX11", "-lXtst"];
if (uinputAvailable) {
log("uinput headers found, enabling uinput support");
@@ -122,7 +118,9 @@ if (result.status !== 0) {
}
if (result.status !== 0) {
- console.warn("[linux-fast-paste] Failed to compile Linux fast-paste binary. Install libx11-dev and libxtst-dev to enable native paste. Falling back to system tools.");
+ console.warn(
+ "[linux-fast-paste] Failed to compile Linux fast-paste binary. Install libx11-dev and libxtst-dev to enable native paste. Falling back to system tools."
+ );
process.exit(0);
}
diff --git a/scripts/build-linux-text-monitor.js b/scripts/build-linux-text-monitor.js
new file mode 100644
index 000000000..f789b5cd1
--- /dev/null
+++ b/scripts/build-linux-text-monitor.js
@@ -0,0 +1,210 @@
+#!/usr/bin/env node
+/**
+ * Ensures the Linux text monitor binary is available.
+ *
+ * Strategy:
+ * 1. If binary exists and is up-to-date, do nothing
+ * 2. Try to download prebuilt binary from GitHub releases
+ * 3. Fall back to local compilation if download fails
+ *
+ * This allows developers without AT-SPI2 dev headers to still build the app.
+ */
+
+const { spawnSync } = require("child_process");
+const crypto = require("crypto");
+const fs = require("fs");
+const path = require("path");
+
+const isLinux = process.platform === "linux";
+if (!isLinux) {
+ process.exit(0);
+}
+
+const projectRoot = path.resolve(__dirname, "..");
+const cSource = path.join(projectRoot, "resources", "linux-text-monitor.c");
+const outputDir = path.join(projectRoot, "resources", "bin");
+const outputBinary = path.join(outputDir, "linux-text-monitor");
+const hashFile = path.join(outputDir, ".linux-text-monitor.hash");
+
+function log(message) {
+ console.log(`[linux-text-monitor] ${message}`);
+}
+
+function ensureDir(dirPath) {
+ if (!fs.existsSync(dirPath)) {
+ fs.mkdirSync(dirPath, { recursive: true });
+ }
+}
+
+function isBinaryUpToDate() {
+ if (!fs.existsSync(outputBinary)) {
+ return false;
+ }
+
+ if (!fs.existsSync(cSource)) {
+ return true;
+ }
+
+ try {
+ const binaryStat = fs.statSync(outputBinary);
+ const sourceStat = fs.statSync(cSource);
+ if (binaryStat.mtimeMs < sourceStat.mtimeMs) {
+ return false;
+ }
+ } catch {
+ return false;
+ }
+
+ // Check source + build flags hash
+ try {
+ const pkgFlags = getPkgConfigFlags();
+ const flagStr = pkgFlags ? pkgFlags.join(" ") : "";
+ const sourceContent = fs.readFileSync(cSource, "utf8");
+ const currentHash = crypto
+ .createHash("sha256")
+ .update(sourceContent + flagStr)
+ .digest("hex");
+
+ if (fs.existsSync(hashFile)) {
+ const savedHash = fs.readFileSync(hashFile, "utf8").trim();
+ if (savedHash !== currentHash) {
+ log("Source or build flags changed, rebuild needed");
+ return false;
+ }
+ } else {
+ fs.writeFileSync(hashFile, currentHash);
+ }
+ } catch (err) {
+ log(`Hash check failed: ${err.message}, forcing rebuild`);
+ return false;
+ }
+
+ return true;
+}
+
+async function tryDownload() {
+ log("Attempting to download prebuilt binary...");
+
+ const downloadScript = path.join(__dirname, "download-text-monitor.js");
+ if (!fs.existsSync(downloadScript)) {
+ log("Download script not found, skipping download");
+ return false;
+ }
+
+ const result = spawnSync(process.execPath, [downloadScript, "--force"], {
+ stdio: "inherit",
+ cwd: projectRoot,
+ });
+
+ if (result.status === 0 && fs.existsSync(outputBinary)) {
+ log("Successfully downloaded prebuilt binary");
+ return true;
+ }
+
+ log("Download failed or binary not found after download");
+ return false;
+}
+
+function getPkgConfigFlags() {
+ try {
+ const check = spawnSync("pkg-config", ["--exists", "atspi-2"], {
+ stdio: "pipe",
+ env: process.env,
+ });
+ if (check.status !== 0) return null;
+
+ const result = spawnSync("pkg-config", ["--cflags", "--libs", "atspi-2"], {
+ stdio: ["pipe", "pipe", "pipe"],
+ env: process.env,
+ });
+ if (result.status !== 0) return null;
+
+ return result.stdout.toString().trim().split(/\s+/).filter(Boolean);
+ } catch {
+ return null;
+ }
+}
+
+function attemptCompile(command, args) {
+ log(`Compiling with ${[command, ...args].join(" ")}`);
+ return spawnSync(command, args, {
+ stdio: "inherit",
+ env: process.env,
+ });
+}
+
+function tryCompile() {
+ if (!fs.existsSync(cSource)) {
+ log("C source not found, cannot compile locally");
+ return false;
+ }
+
+ const pkgFlags = getPkgConfigFlags();
+ if (!pkgFlags) {
+ log("AT-SPI2 development headers not found, cannot compile locally");
+ return false;
+ }
+
+ log("Attempting local compilation...");
+
+ const compileArgs = ["-O2", cSource, "-o", outputBinary, ...pkgFlags];
+
+ let result = attemptCompile("gcc", compileArgs);
+ if (result.status !== 0) {
+ result = attemptCompile("cc", compileArgs);
+ }
+
+ if (result.status !== 0) {
+ return false;
+ }
+
+ try {
+ fs.chmodSync(outputBinary, 0o755);
+ } catch (error) {
+ console.warn(`[linux-text-monitor] Unable to set executable permissions: ${error.message}`);
+ }
+
+ try {
+ const sourceContent = fs.readFileSync(cSource, "utf8");
+ const flagStr = pkgFlags.join(" ");
+ const hash = crypto
+ .createHash("sha256")
+ .update(sourceContent + flagStr)
+ .digest("hex");
+ fs.writeFileSync(hashFile, hash);
+ } catch (err) {
+ log(`Warning: Could not save source hash: ${err.message}`);
+ }
+
+ log("Successfully built Linux text monitor binary");
+ return true;
+}
+
+async function main() {
+ ensureDir(outputDir);
+
+ if (isBinaryUpToDate()) {
+ log("Binary is up to date, skipping build");
+ return;
+ }
+
+ const downloaded = await tryDownload();
+ if (downloaded) {
+ return;
+ }
+
+ const compiled = tryCompile();
+ if (compiled) {
+ return;
+ }
+
+ console.warn("[linux-text-monitor] Could not obtain Linux text monitor binary.");
+ console.warn("[linux-text-monitor] Auto-learn correction monitoring will be disabled on Linux.");
+ console.warn(
+ "[linux-text-monitor] To compile locally, install libatspi2.0-dev and libglib2.0-dev. Falling back to Python script."
+ );
+}
+
+main().catch((error) => {
+ console.error("[linux-text-monitor] Unexpected error:", error);
+});
diff --git a/scripts/build-macos-text-monitor.js b/scripts/build-macos-text-monitor.js
new file mode 100644
index 000000000..9b60a9f9e
--- /dev/null
+++ b/scripts/build-macos-text-monitor.js
@@ -0,0 +1,183 @@
+#!/usr/bin/env node
+
+const { spawnSync } = require("child_process");
+const crypto = require("crypto");
+const fs = require("fs");
+const path = require("path");
+
+const isMac = process.platform === "darwin";
+if (!isMac) {
+ process.exit(0);
+}
+
+// Support cross-compilation via --arch flag or TARGET_ARCH env var
+const archIndex = process.argv.indexOf("--arch");
+const targetArch =
+ (archIndex !== -1 && process.argv[archIndex + 1]) || process.env.TARGET_ARCH || process.arch;
+
+const ARCH_TO_TARGET = {
+ arm64: "arm64-apple-macosx11.0",
+ x64: "x86_64-apple-macosx10.15",
+};
+const swiftTarget = ARCH_TO_TARGET[targetArch];
+if (!swiftTarget) {
+ console.error(`[text-monitor] Unsupported architecture: ${targetArch}`);
+ process.exit(1);
+}
+
+const projectRoot = path.resolve(__dirname, "..");
+const swiftSource = path.join(projectRoot, "resources", "macos-text-monitor.swift");
+const outputDir = path.join(projectRoot, "resources", "bin");
+const outputBinary = path.join(outputDir, "macos-text-monitor");
+const hashFile = path.join(outputDir, `.macos-text-monitor.${targetArch}.hash`);
+const moduleCacheDir = path.join(outputDir, ".swift-module-cache");
+
+// Mach-O CPU type constants for architecture verification
+const ARCH_CPU_TYPE = {
+ arm64: 0x0100000c, // CPU_TYPE_ARM64
+ x64: 0x01000007, // CPU_TYPE_X86_64
+};
+
+function log(message) {
+ console.log(`[text-monitor] ${message}`);
+}
+
+function ensureDir(dirPath) {
+ if (!fs.existsSync(dirPath)) {
+ fs.mkdirSync(dirPath, { recursive: true });
+ }
+}
+
+function verifyBinaryArch(binaryPath, expectedArch) {
+ try {
+ const fd = fs.openSync(binaryPath, "r");
+ const header = Buffer.alloc(8);
+ fs.readSync(fd, header, 0, 8, 0);
+ fs.closeSync(fd);
+
+ const magic = header.readUInt32LE(0);
+ if (magic !== 0xfeedfacf) {
+ // Not a 64-bit Mach-O
+ return false;
+ }
+ const cpuType = header.readInt32LE(4);
+ const expectedCpu = ARCH_CPU_TYPE[expectedArch];
+ return cpuType === expectedCpu;
+ } catch {
+ return false;
+ }
+}
+
+if (!fs.existsSync(swiftSource)) {
+ console.error(`[text-monitor] Swift source not found at ${swiftSource}`);
+ process.exit(1);
+}
+
+ensureDir(outputDir);
+ensureDir(moduleCacheDir);
+
+let needsBuild = true;
+if (fs.existsSync(outputBinary)) {
+ // Verify existing binary matches the target architecture
+ if (!verifyBinaryArch(outputBinary, targetArch)) {
+ log(`Existing binary is wrong architecture (expected ${targetArch}), rebuild needed`);
+ needsBuild = true;
+ } else {
+ try {
+ const binaryStat = fs.statSync(outputBinary);
+ const sourceStat = fs.statSync(swiftSource);
+ if (binaryStat.mtimeMs >= sourceStat.mtimeMs) {
+ needsBuild = false;
+ }
+ } catch {
+ needsBuild = true;
+ }
+ }
+}
+
+// Secondary check: compare source hash
+if (!needsBuild && fs.existsSync(outputBinary)) {
+ try {
+ const sourceContent = fs.readFileSync(swiftSource, "utf8");
+ const currentHash = crypto.createHash("sha256").update(sourceContent).digest("hex");
+
+ if (fs.existsSync(hashFile)) {
+ const savedHash = fs.readFileSync(hashFile, "utf8").trim();
+ if (savedHash !== currentHash) {
+ log("Source hash changed, rebuild needed");
+ needsBuild = true;
+ }
+ } else {
+ // No hash file for this architecture — force rebuild to ensure correct arch
+ log(`No hash file for ${targetArch}, rebuild needed`);
+ needsBuild = true;
+ }
+ } catch (err) {
+ log(`Hash check failed: ${err.message}, forcing rebuild`);
+ needsBuild = true;
+ }
+}
+
+if (!needsBuild) {
+ process.exit(0);
+}
+
+function attemptCompile(command, args) {
+ log(`Compiling with ${[command, ...args].join(" ")}`);
+ return spawnSync(command, args, {
+ stdio: "inherit",
+ env: {
+ ...process.env,
+ SWIFT_MODULE_CACHE_PATH: moduleCacheDir,
+ },
+ });
+}
+
+const compileArgs = [
+ swiftSource,
+ "-O",
+ "-target",
+ swiftTarget,
+ "-module-cache-path",
+ moduleCacheDir,
+ "-o",
+ outputBinary,
+];
+
+let result = attemptCompile("xcrun", ["swiftc", ...compileArgs]);
+
+if (result.status !== 0) {
+ result = attemptCompile("swiftc", compileArgs);
+}
+
+if (result.status !== 0) {
+ console.error("[text-monitor] Failed to compile macOS text monitor binary.");
+ process.exit(result.status ?? 1);
+}
+
+try {
+ fs.chmodSync(outputBinary, 0o755);
+} catch (error) {
+ console.warn(`[text-monitor] Unable to set executable permissions: ${error.message}`);
+}
+
+// Verify the compiled binary matches the target architecture
+if (!verifyBinaryArch(outputBinary, targetArch)) {
+ console.error(
+ `[text-monitor] FATAL: Compiled binary architecture does not match target (${targetArch}). ` +
+ `This can happen when cross-compiling without setting TARGET_ARCH env var.`
+ );
+ process.exit(1);
+}
+
+// Save source hash after successful build
+try {
+ const sourceContent = fs.readFileSync(swiftSource, "utf8");
+ const hash = crypto.createHash("sha256").update(sourceContent).digest("hex");
+ fs.writeFileSync(hashFile, hash);
+} catch (err) {
+ // Non-critical, just log
+ log(`Warning: Could not save source hash: ${err.message}`);
+}
+
+log(`Successfully built macOS text monitor binary (${targetArch}).`);
diff --git a/scripts/build-text-monitor.js b/scripts/build-text-monitor.js
new file mode 100644
index 000000000..bd262e85a
--- /dev/null
+++ b/scripts/build-text-monitor.js
@@ -0,0 +1,18 @@
+#!/usr/bin/env node
+
+// macOS uses a native Swift binary compiled from resources/macos-text-monitor.swift.
+// Linux uses a native C binary compiled from resources/linux-text-monitor.c.
+// Windows uses a prebuilt binary downloaded from GitHub releases (or compiled locally).
+const path = require("path");
+const { execFileSync } = require("child_process");
+
+const scripts = {
+ darwin: "build-macos-text-monitor.js",
+ linux: "build-linux-text-monitor.js",
+ win32: "build-windows-text-monitor.js",
+};
+
+const script = scripts[process.platform];
+if (script) {
+ execFileSync("node", [path.join(__dirname, script)], { stdio: "inherit" });
+}
diff --git a/scripts/build-windows-key-listener.js b/scripts/build-windows-key-listener.js
index 942da9e5c..3f222382a 100644
--- a/scripts/build-windows-key-listener.js
+++ b/scripts/build-windows-key-listener.js
@@ -193,7 +193,9 @@ async function main() {
// Neither worked - warn but don't fail
console.warn("[windows-key-listener] Could not obtain Windows key listener binary.");
console.warn("[windows-key-listener] Push-to-Talk on Windows will use fallback mode.");
- console.warn("[windows-key-listener] To compile locally, install Visual Studio Build Tools or MinGW-w64.");
+ console.warn(
+ "[windows-key-listener] To compile locally, install Visual Studio Build Tools or MinGW-w64."
+ );
}
main().catch((error) => {
diff --git a/scripts/build-windows-text-monitor.js b/scripts/build-windows-text-monitor.js
new file mode 100644
index 000000000..16845082d
--- /dev/null
+++ b/scripts/build-windows-text-monitor.js
@@ -0,0 +1,185 @@
+#!/usr/bin/env node
+/**
+ * Ensures the Windows text monitor binary is available.
+ *
+ * Strategy:
+ * 1. If binary exists and is up-to-date, do nothing
+ * 2. Try to download prebuilt binary from GitHub releases
+ * 3. Fall back to local compilation if download fails
+ *
+ * This allows developers without a C compiler to still build the app.
+ */
+
+const { spawnSync } = require("child_process");
+const fs = require("fs");
+const path = require("path");
+
+const isWindows = process.platform === "win32";
+if (!isWindows) {
+ process.exit(0);
+}
+
+const projectRoot = path.resolve(__dirname, "..");
+const cSource = path.join(projectRoot, "resources", "windows-text-monitor.c");
+const outputDir = path.join(projectRoot, "resources", "bin");
+const outputBinary = path.join(outputDir, "windows-text-monitor.exe");
+
+function log(message) {
+ console.log(`[windows-text-monitor] ${message}`);
+}
+
+function ensureDir(dirPath) {
+ if (!fs.existsSync(dirPath)) {
+ fs.mkdirSync(dirPath, { recursive: true });
+ }
+}
+
+function isBinaryUpToDate() {
+ if (!fs.existsSync(outputBinary)) {
+ return false;
+ }
+
+ if (!fs.existsSync(cSource)) {
+ return true;
+ }
+
+ try {
+ const binaryStat = fs.statSync(outputBinary);
+ const sourceStat = fs.statSync(cSource);
+ return binaryStat.mtimeMs >= sourceStat.mtimeMs;
+ } catch {
+ return false;
+ }
+}
+
+async function tryDownload() {
+ log("Attempting to download prebuilt binary...");
+
+ const downloadScript = path.join(__dirname, "download-text-monitor.js");
+ if (!fs.existsSync(downloadScript)) {
+ log("Download script not found, skipping download");
+ return false;
+ }
+
+ const result = spawnSync(process.execPath, [downloadScript, "--force"], {
+ stdio: "inherit",
+ cwd: projectRoot,
+ });
+
+ if (result.status === 0 && fs.existsSync(outputBinary)) {
+ log("Successfully downloaded prebuilt binary");
+ return true;
+ }
+
+ log("Download failed or binary not found after download");
+ return false;
+}
+
+function quotePath(p) {
+ return `"${p.replace(/"/g, '\\"')}"`;
+}
+
+function tryCompile() {
+ if (!fs.existsSync(cSource)) {
+ log("C source not found, cannot compile locally");
+ return false;
+ }
+
+ log("Attempting local compilation...");
+
+ const compilers = [
+ {
+ name: "MSVC",
+ check: { command: "cl", args: [] },
+ useShell: true,
+ getCommand: () =>
+ `cl /O2 /nologo ${quotePath(cSource)} /Fe:${quotePath(outputBinary)} ole32.lib oleaut32.lib`,
+ },
+ {
+ name: "MinGW-w64",
+ check: { command: "gcc", args: ["--version"] },
+ useShell: false,
+ command: "gcc",
+ args: ["-O2", cSource, "-o", outputBinary, "-lole32", "-loleaut32", "-luuid"],
+ },
+ {
+ name: "Clang",
+ check: { command: "clang", args: ["--version"] },
+ useShell: false,
+ command: "clang",
+ args: ["-O2", cSource, "-o", outputBinary, "-lole32", "-loleaut32", "-luuid"],
+ },
+ ];
+
+ for (const compiler of compilers) {
+ log(`Trying ${compiler.name}...`);
+
+ const checkResult = spawnSync(compiler.check.command, compiler.check.args, {
+ stdio: "pipe",
+ shell: true,
+ });
+
+ if (checkResult.status !== 0 && checkResult.error) {
+ log(`${compiler.name} not found, trying next...`);
+ continue;
+ }
+
+ let result;
+ if (compiler.useShell) {
+ const cmd = compiler.getCommand();
+ log(`Compiling with: ${cmd}`);
+ result = spawnSync(cmd, [], {
+ stdio: "inherit",
+ cwd: projectRoot,
+ shell: true,
+ });
+ } else {
+ log(`Compiling with: ${compiler.command} ${compiler.args.join(" ")}`);
+ result = spawnSync(compiler.command, compiler.args, {
+ stdio: "inherit",
+ cwd: projectRoot,
+ shell: false,
+ });
+ }
+
+ if (result.status === 0 && fs.existsSync(outputBinary)) {
+ log(`Successfully built with ${compiler.name}`);
+ return true;
+ }
+
+ log(`${compiler.name} compilation failed, trying next...`);
+ }
+
+ return false;
+}
+
+async function main() {
+ ensureDir(outputDir);
+
+ if (isBinaryUpToDate()) {
+ log("Binary is up to date, skipping build");
+ return;
+ }
+
+ const downloaded = await tryDownload();
+ if (downloaded) {
+ return;
+ }
+
+ const compiled = tryCompile();
+ if (compiled) {
+ return;
+ }
+
+ console.warn("[windows-text-monitor] Could not obtain Windows text monitor binary.");
+ console.warn(
+ "[windows-text-monitor] Auto-learn correction monitoring will be disabled on Windows."
+ );
+ console.warn(
+ "[windows-text-monitor] To compile locally, install Visual Studio Build Tools or MinGW-w64."
+ );
+}
+
+main().catch((error) => {
+ console.error("[windows-text-monitor] Unexpected error:", error);
+});
diff --git a/scripts/download-sherpa-onnx.js b/scripts/download-sherpa-onnx.js
index 772db7a0d..01b62b7b3 100644
--- a/scripts/download-sherpa-onnx.js
+++ b/scripts/download-sherpa-onnx.js
@@ -156,7 +156,11 @@ async function downloadBinary(platformArch, config, isForce = false) {
for (const [baseName, versionedName] of versionedLibs) {
const basePath = path.join(BIN_DIR, baseName);
const versionedPath = path.join(BIN_DIR, versionedName);
- if (fs.existsSync(basePath) && fs.existsSync(versionedPath) && !fs.lstatSync(basePath).isSymbolicLink()) {
+ if (
+ fs.existsSync(basePath) &&
+ fs.existsSync(versionedPath) &&
+ !fs.lstatSync(basePath).isSymbolicLink()
+ ) {
fs.unlinkSync(basePath);
fs.symlinkSync(versionedName, basePath);
console.log(` ${platformArch}: Symlinked ${baseName} -> ${versionedName}`);
@@ -203,10 +207,9 @@ async function main() {
}
// Remove old CLI-style binaries replaced by WS server binaries
- const oldBinaryName =
- args.platformArch.startsWith("win32")
- ? `sherpa-onnx-${args.platformArch}.exe`
- : `sherpa-onnx-${args.platformArch}`;
+ const oldBinaryName = args.platformArch.startsWith("win32")
+ ? `sherpa-onnx-${args.platformArch}.exe`
+ : `sherpa-onnx-${args.platformArch}`;
const oldBinaryPath = path.join(BIN_DIR, oldBinaryName);
if (fs.existsSync(oldBinaryPath)) {
console.log(` Removing old CLI binary: ${oldBinaryName}`);
@@ -234,7 +237,9 @@ async function main() {
});
} else {
console.log("No binaries downloaded yet.");
- console.log(`\nCheck: https://github.com/k2-fsa/sherpa-onnx/releases/tag/v${SHERPA_ONNX_VERSION}`);
+ console.log(
+ `\nCheck: https://github.com/k2-fsa/sherpa-onnx/releases/tag/v${SHERPA_ONNX_VERSION}`
+ );
}
}
diff --git a/scripts/download-text-monitor.js b/scripts/download-text-monitor.js
new file mode 100644
index 000000000..6ebed7533
--- /dev/null
+++ b/scripts/download-text-monitor.js
@@ -0,0 +1,128 @@
+#!/usr/bin/env node
+/**
+ * Downloads prebuilt text monitor binary from GitHub releases.
+ * Selects the correct binary for the current platform (Linux or Windows).
+ *
+ * Usage:
+ * node scripts/download-text-monitor.js [--force]
+ */
+
+const fs = require("fs");
+const path = require("path");
+const {
+ downloadFile,
+ extractArchive,
+ fetchLatestRelease,
+ setExecutable,
+} = require("./lib/download-utils");
+
+const REPO = "OpenWhispr/openwhispr";
+const BIN_DIR = path.join(__dirname, "..", "resources", "bin");
+
+const PLATFORM_CONFIG = {
+ linux: {
+ label: "linux-text-monitor",
+ tagPrefix: "linux-text-monitor-v",
+ archiveName: "linux-text-monitor-linux-x64.tar.gz",
+ binaryName: "linux-text-monitor",
+ versionEnv: "LINUX_TEXT_MONITOR_VERSION",
+ compileHint: "install libatspi2.0-dev and libglib2.0-dev",
+ },
+ win32: {
+ label: "windows-text-monitor",
+ tagPrefix: "windows-text-monitor-v",
+ archiveName: "windows-text-monitor-win32-x64.zip",
+ binaryName: "windows-text-monitor.exe",
+ versionEnv: "WINDOWS_TEXT_MONITOR_VERSION",
+ compileHint: "install Visual Studio Build Tools or MinGW-w64",
+ },
+};
+
+async function main() {
+ const config = PLATFORM_CONFIG[process.platform];
+ if (!config) {
+ console.log(`[text-monitor] Skipping download (unsupported platform: ${process.platform})`);
+ return;
+ }
+
+ const { label, tagPrefix, archiveName, binaryName, versionEnv, compileHint } = config;
+ const versionOverride = process.env[versionEnv] || null;
+ const forceDownload = process.argv.includes("--force");
+ const outputPath = path.join(BIN_DIR, binaryName);
+
+ if (fs.existsSync(outputPath) && !forceDownload) {
+ console.log(`[${label}] Already exists (use --force to re-download)`);
+ console.log(` ${outputPath}`);
+ return;
+ }
+
+ if (versionOverride) {
+ console.log(`\n[${label}] Using pinned version: ${versionOverride}`);
+ } else {
+ console.log(`\n[${label}] Fetching latest release...`);
+ }
+ const tagToFind = versionOverride || tagPrefix;
+ const release = await fetchLatestRelease(REPO, { tagPrefix: tagToFind });
+
+ if (!release) {
+ console.error(`[${label}] Could not find a release matching prefix:`, tagPrefix);
+ console.log(`[${label}] Auto-learn correction monitoring will be disabled`);
+ return;
+ }
+
+ const asset = release.assets.find((a) => a.name === archiveName);
+ if (!asset) {
+ console.error(`[${label}] Release ${release.tag} does not contain ${archiveName}`);
+ console.log(`[${label}] Available assets:`, release.assets.map((a) => a.name).join(", "));
+ return;
+ }
+
+ console.log(`\nDownloading ${label} (${release.tag})...\n`);
+
+ fs.mkdirSync(BIN_DIR, { recursive: true });
+
+ const archivePath = path.join(BIN_DIR, archiveName);
+ console.log(` Downloading from: ${asset.url}`);
+
+ try {
+ await downloadFile(asset.url, archivePath);
+
+ const extractDir = path.join(BIN_DIR, `temp-${label}`);
+ fs.mkdirSync(extractDir, { recursive: true });
+
+ console.log(" Extracting...");
+ await extractArchive(archivePath, extractDir);
+
+ const binaryPath = path.join(extractDir, binaryName);
+ if (fs.existsSync(binaryPath)) {
+ fs.copyFileSync(binaryPath, outputPath);
+ setExecutable(outputPath);
+ console.log(` Extracted to: ${binaryName}`);
+ } else {
+ throw new Error(`Binary not found in archive: ${binaryName}`);
+ }
+
+ fs.rmSync(extractDir, { recursive: true, force: true });
+ if (fs.existsSync(archivePath)) {
+ fs.unlinkSync(archivePath);
+ }
+
+ const stats = fs.statSync(outputPath);
+ console.log(
+ `\n[${label}] Successfully downloaded ${release.tag} (${Math.round(stats.size / 1024)}KB)`
+ );
+ } catch (error) {
+ console.error(`\n[${label}] Download failed: ${error.message}`);
+
+ if (fs.existsSync(archivePath)) {
+ fs.unlinkSync(archivePath);
+ }
+
+ console.log(`[${label}] Auto-learn correction monitoring will be disabled`);
+ console.log(`[${label}] To compile locally, ${compileHint}`);
+ }
+}
+
+main().catch((error) => {
+ console.error("[text-monitor] Unexpected error:", error);
+});
diff --git a/scripts/download-whisper-cpp.js b/scripts/download-whisper-cpp.js
index e42702e07..2e7f01032 100644
--- a/scripts/download-whisper-cpp.js
+++ b/scripts/download-whisper-cpp.js
@@ -95,7 +95,9 @@ async function downloadBinary(platformArch, config, release, isForce = false) {
setExecutable(outputPath);
console.log(` [server] ${platformArch}: Extracted to ${config.outputName}`);
} else {
- console.error(` [server] ${platformArch}: Binary "${config.binaryName}" not found in archive`);
+ console.error(
+ ` [server] ${platformArch}: Binary "${config.binaryName}" not found in archive`
+ );
return false;
}
@@ -138,7 +140,12 @@ async function main() {
}
console.log(`Downloading for target platform (${args.platformArch}):`);
- const ok = await downloadBinary(args.platformArch, BINARIES[args.platformArch], release, args.isForce);
+ const ok = await downloadBinary(
+ args.platformArch,
+ BINARIES[args.platformArch],
+ release,
+ args.isForce
+ );
if (!ok) {
console.error(`Failed to download binaries for ${args.platformArch}`);
process.exitCode = 1;
diff --git a/scripts/download-windows-fast-paste.js b/scripts/download-windows-fast-paste.js
index 4f5a59c20..cc54f8f8a 100644
--- a/scripts/download-windows-fast-paste.js
+++ b/scripts/download-windows-fast-paste.js
@@ -12,7 +12,12 @@
const fs = require("fs");
const path = require("path");
-const { downloadFile, extractZip, fetchLatestRelease, setExecutable } = require("./lib/download-utils");
+const {
+ downloadFile,
+ extractZip,
+ fetchLatestRelease,
+ setExecutable,
+} = require("./lib/download-utils");
const REPO = "OpenWhispr/openwhispr";
const TAG_PREFIX = "windows-fast-paste-v";
@@ -55,7 +60,10 @@ async function main() {
const zipAsset = release.assets.find((a) => a.name === ZIP_NAME);
if (!zipAsset) {
console.error(`[windows-fast-paste] Release ${release.tag} does not contain ${ZIP_NAME}`);
- console.log("[windows-fast-paste] Available assets:", release.assets.map((a) => a.name).join(", "));
+ console.log(
+ "[windows-fast-paste] Available assets:",
+ release.assets.map((a) => a.name).join(", ")
+ );
return;
}
@@ -90,7 +98,9 @@ async function main() {
}
const stats = fs.statSync(outputPath);
- console.log(`\n[windows-fast-paste] Successfully downloaded ${release.tag} (${Math.round(stats.size / 1024)}KB)`);
+ console.log(
+ `\n[windows-fast-paste] Successfully downloaded ${release.tag} (${Math.round(stats.size / 1024)}KB)`
+ );
} catch (error) {
console.error(`\n[windows-fast-paste] Download failed: ${error.message}`);
diff --git a/scripts/download-windows-key-listener.js b/scripts/download-windows-key-listener.js
index 5b806defc..2b60eca07 100644
--- a/scripts/download-windows-key-listener.js
+++ b/scripts/download-windows-key-listener.js
@@ -12,7 +12,12 @@
const fs = require("fs");
const path = require("path");
-const { downloadFile, extractZip, fetchLatestRelease, setExecutable } = require("./lib/download-utils");
+const {
+ downloadFile,
+ extractZip,
+ fetchLatestRelease,
+ setExecutable,
+} = require("./lib/download-utils");
const REPO = "OpenWhispr/openwhispr";
const TAG_PREFIX = "windows-key-listener-v";
@@ -52,7 +57,9 @@ async function main() {
if (!release) {
console.error("[windows-key-listener] Could not find a release matching prefix:", TAG_PREFIX);
- console.log("[windows-key-listener] Push-to-Talk will use fallback mode (compile locally or tap mode)");
+ console.log(
+ "[windows-key-listener] Push-to-Talk will use fallback mode (compile locally or tap mode)"
+ );
return;
}
@@ -60,7 +67,10 @@ async function main() {
const zipAsset = release.assets.find((a) => a.name === ZIP_NAME);
if (!zipAsset) {
console.error(`[windows-key-listener] Release ${release.tag} does not contain ${ZIP_NAME}`);
- console.log("[windows-key-listener] Available assets:", release.assets.map((a) => a.name).join(", "));
+ console.log(
+ "[windows-key-listener] Available assets:",
+ release.assets.map((a) => a.name).join(", ")
+ );
return;
}
@@ -99,7 +109,9 @@ async function main() {
}
const stats = fs.statSync(outputPath);
- console.log(`\n[windows-key-listener] Successfully downloaded ${release.tag} (${Math.round(stats.size / 1024)}KB)`);
+ console.log(
+ `\n[windows-key-listener] Successfully downloaded ${release.tag} (${Math.round(stats.size / 1024)}KB)`
+ );
} catch (error) {
console.error(`\n[windows-key-listener] Download failed: ${error.message}`);
@@ -109,8 +121,12 @@ async function main() {
}
// Don't fail the build - Push-to-Talk can fall back to tap mode
- console.log("[windows-key-listener] Push-to-Talk will use fallback mode (compile locally or tap mode)");
- console.log("[windows-key-listener] To compile locally, install Visual Studio Build Tools or MinGW-w64");
+ console.log(
+ "[windows-key-listener] Push-to-Talk will use fallback mode (compile locally or tap mode)"
+ );
+ console.log(
+ "[windows-key-listener] To compile locally, install Visual Studio Build Tools or MinGW-w64"
+ );
}
}
diff --git a/scripts/run-electron.js b/scripts/run-electron.js
index 5843cea3c..8bb7ae72e 100644
--- a/scripts/run-electron.js
+++ b/scripts/run-electron.js
@@ -5,38 +5,38 @@
* (e.g., when running from Claude Code or other Node.js-based tools).
*/
-const { spawn } = require('child_process');
-const path = require('path');
+const { spawn } = require("child_process");
+const path = require("path");
// Remove ELECTRON_RUN_AS_NODE from environment
delete process.env.ELECTRON_RUN_AS_NODE;
// Get the electron path
-const electronPath = require('electron');
+const electronPath = require("electron");
// Get the app directory (parent of scripts directory)
-const appDir = path.resolve(__dirname, '..');
+const appDir = path.resolve(__dirname, "..");
// Pass through any command line arguments
const args = process.argv.slice(2);
-console.log('[run-electron] Starting Electron with cleaned environment...');
-console.log('[run-electron] Electron path:', electronPath);
-console.log('[run-electron] App dir:', appDir);
-console.log('[run-electron] Args:', args);
+console.log("[run-electron] Starting Electron with cleaned environment...");
+console.log("[run-electron] Electron path:", electronPath);
+console.log("[run-electron] App dir:", appDir);
+console.log("[run-electron] Args:", args);
// Spawn electron with the cleaned environment
const child = spawn(electronPath, [appDir, ...args], {
- stdio: 'inherit',
+ stdio: "inherit",
env: process.env,
cwd: appDir,
});
-child.on('close', (code) => {
+child.on("close", (code) => {
process.exit(code || 0);
});
-child.on('error', (err) => {
- console.error('[run-electron] Failed to start Electron:', err);
+child.on("error", (err) => {
+ console.error("[run-electron] Failed to start Electron:", err);
process.exit(1);
});
diff --git a/src/App.jsx b/src/App.jsx
index 8cb9cedb0..1777a0e07 100644
--- a/src/App.jsx
+++ b/src/App.jsx
@@ -74,7 +74,7 @@ export default function App() {
const [isCommandMenuOpen, setIsCommandMenuOpen] = useState(false);
const commandMenuRef = useRef(null);
const buttonRef = useRef(null);
- const { toast, toastCount } = useToast();
+ const { toast, dismiss, toastCount } = useToast();
const { t } = useTranslation();
const { hotkey } = useHotkey();
const { isDragging, handleMouseDown, handleMouseUp } = useWindowDrag();
@@ -112,11 +112,45 @@ export default function App() {
});
});
+ const unsubscribeCorrections = window.electronAPI?.onCorrectionsLearned?.((words) => {
+ if (words && words.length > 0) {
+ const wordList = words.map((w) => `\u201c${w}\u201d`).join(", ");
+ let toastId;
+ toastId = toast({
+ title: t("app.toasts.addedToDict", { words: wordList }),
+ variant: "success",
+ duration: 6000,
+ action: (
+ <button
+ onClick={async () => {
+ try {
+ const result = await window.electronAPI?.undoLearnedCorrections?.(words);
+ if (result?.success) {
+ dismiss(toastId);
+ }
+ } catch {
+ // silently fail — word stays in dictionary
+ }
+ }}
+ className="text-[10px] font-medium px-2.5 py-1 rounded-sm whitespace-nowrap
+ text-emerald-100/90 hover:text-white
+ bg-emerald-500/15 hover:bg-emerald-500/25
+ border border-emerald-400/20 hover:border-emerald-400/35
+ transition-all duration-150"
+ >
+ {t("app.toasts.undo")}
+ </button>
+ ),
+ });
+ }
+ });
+
return () => {
unsubscribeFallback?.();
unsubscribeFailed?.();
+ unsubscribeCorrections?.();
};
- }, [toast, t]);
+ }, [toast, dismiss, t]);
useEffect(() => {
if (isCommandMenuOpen || toastCount > 0) {
diff --git a/src/components/SettingsPage.tsx b/src/components/SettingsPage.tsx
index 891249474..ebae186e9 100644
--- a/src/components/SettingsPage.tsx
+++ b/src/components/SettingsPage.tsx
@@ -71,7 +71,11 @@ export type SettingsSectionType =
| "transcription"
| "intelligence"
| "privacyData"
- | "system";
+ | "system"
+ | "dictionary"
+ | "aiModels"
+ | "agentConfig"
+ | "prompts";
interface SettingsPageProps {
activeSection?: SettingsSectionType;
@@ -660,6 +664,8 @@ export default function SettingsPage({ activeSection = "general" }: SettingsPage
customReasoningApiKey,
setCustomReasoningApiKey,
setDictationKey,
+ autoLearnCorrections,
+ setAutoLearnCorrections,
updateTranscriptionSettings,
updateReasoningSettings,
cloudTranscriptionMode,
@@ -710,6 +716,65 @@ export default function SettingsPage({ activeSection = "general" }: SettingsPage
useClipboard(showAlertDialog);
const { agentName, setAgentName } = useAgentName();
const [agentNameInput, setAgentNameInput] = useState(agentName);
+ const [newDictionaryWord, setNewDictionaryWord] = useState("");
+
+ const handleAddDictionaryWord = useCallback(() => {
+ const existingWords = new Set(customDictionary.map((w) => w.toLowerCase()));
+ const words = newDictionaryWord
+ .split(",")
+ .map((w) => w.trim())
+ .filter((w) => {
+ const normalized = w.toLowerCase();
+ if (!w || existingWords.has(normalized)) return false;
+ existingWords.add(normalized);
+ return true;
+ });
+ if (words.length > 0) {
+ setCustomDictionary([...customDictionary, ...words]);
+ setNewDictionaryWord("");
+ }
+ }, [newDictionaryWord, customDictionary, setCustomDictionary]);
+
+ const handleRemoveDictionaryWord = useCallback(
+ (word: string) => {
+ if (word === agentName) return;
+ setCustomDictionary(customDictionary.filter((w) => w !== word));
+ },
+ [customDictionary, setCustomDictionary, agentName]
+ );
+
+ const handleSaveAgentName = useCallback(() => {
+ const trimmed = agentNameInput.trim();
+ const previousName = agentName;
+
+ setAgentName(trimmed);
+ setAgentNameInput(trimmed);
+
+ let nextDictionary = customDictionary.filter((w) => w !== previousName);
+ if (trimmed) {
+ const hasName = nextDictionary.some((w) => w.toLowerCase() === trimmed.toLowerCase());
+ if (!hasName) {
+ nextDictionary = [trimmed, ...nextDictionary];
+ }
+ }
+ setCustomDictionary(nextDictionary);
+
+ showAlertDialog({
+ title: t("settingsPage.agentConfig.dialogs.updatedTitle"),
+ description: t("settingsPage.agentConfig.dialogs.updatedDescription", {
+ name: trimmed,
+ }),
+ });
+ }, [
+ agentNameInput,
+ agentName,
+ customDictionary,
+ setAgentName,
+ setCustomDictionary,
+ showAlertDialog,
+ t,
+ ]);
+
const { theme, setTheme } = useTheme();
const usage = useUsage();
const hasShownApproachingToast = useRef(false);
@@ -1794,6 +1859,335 @@ export default function SettingsPage({ activeSection = "general" }: SettingsPage
/>
);
+ case "dictionary":
+ return (
+ <div className="space-y-5">
+ <SectionHeader
+ title={t("settingsPage.dictionary.title")}
+ description={t("settingsPage.dictionary.description")}
+ />
+
+ {/* Add Words */}
+ <SettingsPanel>
+ <SettingsPanelRow>
+ <div className="space-y-2">
+ <p className="text-[12px] font-medium text-foreground">
+ {t("settingsPage.dictionary.addWordOrPhrase")}
+ </p>
+ <div className="flex gap-2">
+ <Input
+ placeholder={t("settingsPage.dictionary.placeholder")}
+ value={newDictionaryWord}
+ onChange={(e) => setNewDictionaryWord(e.target.value)}
+ onKeyDown={(e) => {
+ if (e.key === "Enter") {
+ handleAddDictionaryWord();
+ }
+ }}
+ className="flex-1 h-8 text-[12px]"
+ />
+ <Button
+ onClick={handleAddDictionaryWord}
+ disabled={!newDictionaryWord.trim()}
+ size="sm"
+ className="h-8"
+ >
+ {t("settingsPage.dictionary.add")}
+ </Button>
+ </div>
+ <p className="text-[10px] text-muted-foreground/50">
+ {t("settingsPage.dictionary.pressEnterToAdd")}
+ </p>
+ </div>
+ </SettingsPanelRow>
+ </SettingsPanel>
+
+ {/* Auto-learn from corrections */}
+ <div>
+ <SettingsPanel>
+ <SettingsPanelRow>
+ <div className="flex items-center justify-between w-full">
+ <div>
+ <p className="text-[12px] font-medium text-foreground">
+ {t("settingsPage.dictionary.autoLearnTitle", {
+ defaultValue: "Auto-learn from corrections",
+ })}
+ </p>
+ <p className="text-[10px] text-muted-foreground/50 mt-0.5">
+ {t("settingsPage.dictionary.autoLearnDescription", {
+ defaultValue:
+ "When you correct a transcription in the target app, the corrected word is automatically added to your dictionary.",
+ })}
+ </p>
+ </div>
+ <button
+ onClick={() => setAutoLearnCorrections(!autoLearnCorrections)}
+ className={`relative inline-flex h-5 w-9 shrink-0 items-center rounded-full transition-colors ${
+ autoLearnCorrections ? "bg-primary" : "bg-muted-foreground/20"
+ }`}
+ >
+ <span
+ className={`inline-block h-3.5 w-3.5 transform rounded-full bg-white transition-transform ${
+ autoLearnCorrections ? "translate-x-[18px]" : "translate-x-[3px]"
+ }`}
+ />
+ </button>
+ </div>
+ </SettingsPanelRow>
+ </SettingsPanel>
+ </div>
+
+ {/* Word List */}
+ <div>
+ <div className="flex items-center justify-between mb-2">
+ <p className="text-[12px] font-medium text-foreground">
+ {t("settingsPage.dictionary.yourWords")}
+ {customDictionary.length > 0 && (
+ <span className="ml-1.5 text-muted-foreground/50 font-normal text-[11px]">
+ {customDictionary.length}
+ </span>
+ )}
+ </p>
+ {customDictionary.length > 0 && (
+ <button
+ onClick={() => {
+ showConfirmDialog({
+ title: t("settingsPage.dictionary.clearDictionaryTitle"),
+ description: t("settingsPage.dictionary.clearDictionaryDescription"),
+ confirmText: t("settingsPage.dictionary.clearAll"),
+ variant: "destructive",
+ onConfirm: () =>
+ setCustomDictionary(customDictionary.filter((w) => w === agentName)),
+ });
+ }}
+ className="text-[10px] text-muted-foreground/40 hover:text-destructive transition-colors"
+ >
+ {t("settingsPage.dictionary.clearAll")}
+ </button>
+ )}
+ </div>
+
+ {customDictionary.length > 0 ? (
+ <SettingsPanel>
+ <SettingsPanelRow>
+ <div className="flex flex-wrap gap-1">
+ {customDictionary.map((word) => {
+ const isAgentName = word === agentName;
+ return (
+ <span
+ key={word}
+ className={`group inline-flex items-center gap-0.5 py-0.5 rounded-[5px] text-[11px] border transition-all ${
+ isAgentName
+ ? "pl-2 pr-2 bg-primary/10 dark:bg-primary/15 text-primary border-primary/20 dark:border-primary/30"
+ : "pl-2 pr-1 bg-primary/5 dark:bg-primary/10 text-foreground border-border/30 dark:border-border-subtle hover:border-destructive/40 hover:bg-destructive/5"
+ }`}
+ title={
+ isAgentName
+ ? t("settingsPage.dictionary.agentNameAutoManaged")
+ : undefined
+ }
+ >
+ {word}
+ {!isAgentName && (
+ <button
+ onClick={() => handleRemoveDictionaryWord(word)}
+ className="ml-0.5 p-0.5 rounded-sm text-muted-foreground/40 hover:text-destructive transition-colors"
+ title={t("settingsPage.dictionary.removeWord")}
+ >
+ <svg
+ width="9"
+ height="9"
+ viewBox="0 0 24 24"
+ fill="none"
+ stroke="currentColor"
+ strokeWidth="2.5"
+ strokeLinecap="round"
+ >
+ <path d="M18 6L6 18M6 6l12 12" />
+ </svg>
+ </button>
+ )}
+ </span>
+ );
+ })}
+ </div>
+ </SettingsPanelRow>
+ </SettingsPanel>
+ ) : (
+ <div className="rounded-lg border border-dashed border-border/40 dark:border-border-subtle py-6 flex flex-col items-center justify-center text-center">
+ <p className="text-[11px] text-muted-foreground/50">
+ {t("settingsPage.dictionary.noWords")}
+ </p>
+ <p className="text-[10px] text-muted-foreground/40 mt-0.5">
+ {t("settingsPage.dictionary.wordsAppearHere")}
+ </p>
+ </div>
+ )}
+ </div>
+
+ {/* How it works */}
+ <div>
+ <SectionHeader title={t("settingsPage.dictionary.howItWorksTitle")} />
+ <SettingsPanel>
+ <SettingsPanelRow>
+ <p className="text-[12px] text-muted-foreground leading-relaxed">
+ {t("settingsPage.dictionary.howItWorksDescription")}
+ </p>
+ </SettingsPanelRow>
+ <SettingsPanelRow>
+ <p className="text-[12px] text-muted-foreground leading-relaxed">
+ <span className="font-medium text-foreground">
+ {t("settingsPage.dictionary.tipLabel")}
+ </span>{" "}
+ {t("settingsPage.dictionary.tipDescription")}
+ </p>
+ </SettingsPanelRow>
+ </SettingsPanel>
+ </div>
+ </div>
+ );
+
+ case "aiModels":
+ return (
+ <AiModelsSection
+ isSignedIn={isSignedIn ?? false}
+ cloudReasoningMode={cloudReasoningMode}
+ setCloudReasoningMode={setCloudReasoningMode}
+ useReasoningModel={useReasoningModel}
+ setUseReasoningModel={(value) => {
+ setUseReasoningModel(value);
+ updateReasoningSettings({ useReasoningModel: value });
+ }}
+ reasoningModel={reasoningModel}
+ setReasoningModel={setReasoningModel}
+ reasoningProvider={reasoningProvider}
+ setReasoningProvider={setReasoningProvider}
+ cloudReasoningBaseUrl={cloudReasoningBaseUrl}
+ setCloudReasoningBaseUrl={setCloudReasoningBaseUrl}
+ openaiApiKey={openaiApiKey}
+ setOpenaiApiKey={setOpenaiApiKey}
+ anthropicApiKey={anthropicApiKey}
+ setAnthropicApiKey={setAnthropicApiKey}
+ geminiApiKey={geminiApiKey}
+ setGeminiApiKey={setGeminiApiKey}
+ groqApiKey={groqApiKey}
+ setGroqApiKey={setGroqApiKey}
+ customReasoningApiKey={customReasoningApiKey}
+ setCustomReasoningApiKey={setCustomReasoningApiKey}
+ showAlertDialog={showAlertDialog}
+ toast={toast}
+ />
+ );
+
+ case "agentConfig":
+ return (
+ <div className="space-y-5">
+ <SectionHeader
+ title={t("settingsPage.agentConfig.title")}
+ description={t("settingsPage.agentConfig.description")}
+ />
+
+ {/* Agent Name */}
+ <div>
+ <p className="text-[13px] font-medium text-foreground mb-3">
+ {t("settingsPage.agentConfig.agentName")}
+ </p>
+ <SettingsPanel>
+ <SettingsPanelRow>
+ <div className="space-y-3">
+ <div className="flex gap-2">
+ <Input
+ placeholder={t("settingsPage.agentConfig.placeholder")}
+ value={agentNameInput}
+ onChange={(e) => setAgentNameInput(e.target.value)}
+ className="flex-1 text-center text-base font-mono"
+ />
+ <Button
+ onClick={handleSaveAgentName}
+ disabled={!agentNameInput.trim()}
+ size="sm"
+ >
+ {t("settingsPage.agentConfig.save")}
+ </Button>
+ </div>
+ <p className="text-[11px] text-muted-foreground/60">
+ {t("settingsPage.agentConfig.helper")}
+ </p>
+ </div>
+ </SettingsPanelRow>
+ </SettingsPanel>
+ </div>
+
+ {/* How it works */}
+ <div>
+ <SectionHeader title={t("settingsPage.agentConfig.howItWorksTitle")} />
+ <SettingsPanel>
+ <SettingsPanelRow>
+ <p className="text-[12px] text-muted-foreground leading-relaxed">
+ {t("settingsPage.agentConfig.howItWorksDescription", { agentName })}
+ </p>
+ </SettingsPanelRow>
+ </SettingsPanel>
+ </div>
+
+ {/* Examples */}
+ <div>
+ <SectionHeader title={t("settingsPage.agentConfig.examplesTitle")} />
+ <SettingsPanel>
+ <SettingsPanelRow>
+ <div className="space-y-2.5">
+ {[
+ {
+ input: `Hey ${agentName}, write a formal email about the budget`,
+ mode: t("settingsPage.agentConfig.instructionMode"),
+ },
+ {
+ input: `Hey ${agentName}, make this more professional`,
+ mode: t("settingsPage.agentConfig.instructionMode"),
+ },
+ {
+ input: `Hey ${agentName}, convert this to bullet points`,
+ mode: t("settingsPage.agentConfig.instructionMode"),
+ },
+ {
+ input: t("settingsPage.agentConfig.cleanupExample"),
+ mode: t("settingsPage.agentConfig.cleanupMode"),
+ },
+ ].map((example, i) => (
+ <div key={i} className="flex items-start gap-3">
+ <span
+ className={`shrink-0 mt-0.5 text-[10px] font-medium uppercase tracking-wider px-1.5 py-px rounded ${
+ example.mode === t("settingsPage.agentConfig.instructionMode")
+ ? "bg-primary/10 text-primary dark:bg-primary/15"
+ : "bg-muted text-muted-foreground"
+ }`}
+ >
+ {example.mode}
+ </span>
+ <p className="text-[12px] text-muted-foreground leading-relaxed">
+ "{example.input}"
+ </p>
+ </div>
+ ))}
+ </div>
+ </SettingsPanelRow>
+ </SettingsPanel>
+ </div>
+ </div>
+ );
+
+ case "prompts":
+ return (
+ <div className="space-y-5">
+ <SectionHeader
+ title={t("settingsPage.prompts.title")}
+ description={t("settingsPage.prompts.description")}
+ />
+
+ <PromptStudio />
+ </div>
+ );
+
case "intelligence":
return (
<div className="space-y-6">
@@ -1849,24 +2243,7 @@ export default function SettingsPage({ activeSection = "general" }: SettingsPage
className="flex-1 text-center text-base font-mono"
/>
<Button
- onClick={() => {
- const trimmed = agentNameInput.trim();
- const oldName = agentName;
- setAgentName(trimmed);
- setAgentNameInput(trimmed);
- let dict = customDictionary.filter((w) => w !== oldName);
- if (trimmed && !dict.includes(trimmed)) dict = [trimmed, ...dict];
- setCustomDictionary(dict);
- showAlertDialog({
- title: t("settingsPage.agentConfig.dialogs.updatedTitle"),
- description: t(
- "settingsPage.agentConfig.dialogs.updatedDescription",
- {
- name: trimmed,
- }
- ),
- });
- }}
+ onClick={handleSaveAgentName}
disabled={!agentNameInput.trim()}
size="sm"
>
diff --git a/src/helpers/ipcHandlers.js b/src/helpers/ipcHandlers.js
index a5fb9896a..0701f03a3 100644
--- a/src/helpers/ipcHandlers.js
+++ b/src/helpers/ipcHandlers.js
@@ -12,6 +12,9 @@ const DeepgramStreaming = require("./deepgramStreaming");
const MISTRAL_TRANSCRIPTION_URL = "https://api.mistral.ai/v1/audio/transcriptions";
+// Debounce delay: wait for user to stop typing before processing corrections
+const AUTO_LEARN_DEBOUNCE_MS = 1500;
+
const AUDIO_MIME_TYPES = {
mp3: "audio/mpeg",
wav: "audio/wav",
@@ -93,11 +96,17 @@ class IPCHandlers {
this.windowManager = managers.windowManager;
this.updateManager = managers.updateManager;
this.windowsKeyManager = managers.windowsKeyManager;
+ this.textEditMonitor = managers.textEditMonitor;
this.getTrayManager = managers.getTrayManager;
this.whisperCudaManager = managers.whisperCudaManager;
this.sessionId = crypto.randomUUID();
this.assemblyAiStreaming = null;
this.deepgramStreaming = null;
+ this._autoLearnEnabled = true; // Default on, synced from renderer
+ this._autoLearnDebounceTimer = null;
+ this._autoLearnLatestData = null;
+ this._textEditHandler = null;
+ this._setupTextEditMonitor();
this.setupHandlers();
if (this.whisperManager?.serverManager) {
@@ -107,6 +116,102 @@ class IPCHandlers {
}
}
+ _getDictionarySafe() {
+ try {
+ return this.databaseManager.getDictionary();
+ } catch {
+ return [];
+ }
+ }
+
+ _cleanupTextEditMonitor() {
+ if (this._autoLearnDebounceTimer) {
+ clearTimeout(this._autoLearnDebounceTimer);
+ this._autoLearnDebounceTimer = null;
+ }
+ this._autoLearnLatestData = null;
+ if (this.textEditMonitor && this._textEditHandler) {
+ this.textEditMonitor.removeListener("text-edited", this._textEditHandler);
+ this._textEditHandler = null;
+ }
+ }
+
+ _setupTextEditMonitor() {
+ if (!this.textEditMonitor) return;
+
+ this._textEditHandler = (data) => {
+ if (
+ !data ||
+ typeof data.originalText !== "string" ||
+ typeof data.newFieldValue !== "string"
+ ) {
+ debugLogger.debug("[AutoLearn] Invalid event payload, skipping");
+ return;
+ }
+
+ const { originalText, newFieldValue } = data;
+
+ debugLogger.debug("[AutoLearn] text-edited event", {
+ originalPreview: originalText.substring(0, 80),
+ newValuePreview: newFieldValue.substring(0, 80),
+ });
+
+ this._autoLearnLatestData = { originalText, newFieldValue };
+
+ if (this._autoLearnDebounceTimer) {
+ clearTimeout(this._autoLearnDebounceTimer);
+ }
+
+ this._autoLearnDebounceTimer = setTimeout(() => {
+ this._processCorrections();
+ }, AUTO_LEARN_DEBOUNCE_MS);
+ };
+
+ this.textEditMonitor.on("text-edited", this._textEditHandler);
+ }
+
+ _processCorrections() {
+ this._autoLearnDebounceTimer = null;
+ if (!this._autoLearnLatestData) return;
+ if (!this._autoLearnEnabled) {
+ debugLogger.debug("[AutoLearn] Disabled, skipping correction processing");
+ this._autoLearnLatestData = null;
+ return;
+ }
+
+ const { originalText, newFieldValue } = this._autoLearnLatestData;
+ this._autoLearnLatestData = null;
+
+ try {
+ const { extractCorrections } = require("../utils/correctionLearner");
+ const currentDict = this._getDictionarySafe();
+ const corrections = extractCorrections(originalText, newFieldValue, currentDict);
+ debugLogger.debug("[AutoLearn] Corrections result", {
+ corrections,
+ dictSize: currentDict.length,
+ });
+
+ if (corrections.length > 0) {
+ const updatedDict = [...currentDict, ...corrections];
+ const saveResult = this.databaseManager.setDictionary(updatedDict);
+
+ if (saveResult?.success === false) {
+ debugLogger.debug("[AutoLearn] Failed to save dictionary", { error: saveResult.error });
+ return;
+ }
+
+ this.broadcastToWindows("dictionary-updated", updatedDict);
+
+ // Show the overlay so the toast is visible (it may have been hidden after dictation)
+ this.windowManager.showDictationPanel();
+ this.broadcastToWindows("corrections-learned", corrections);
+ debugLogger.debug("[AutoLearn] Saved corrections", { corrections });
+ }
+ } catch (error) {
+ debugLogger.debug("[AutoLearn] Error processing corrections", { error: error.message });
+ }
+ }
+
_syncStartupEnv(setVars, clearVars = []) {
let changed = false;
for (const [key, value] of Object.entries(setVars)) {
@@ -241,6 +346,19 @@ class IPCHandlers {
return result;
});
+ // Dictionary handlers
+ ipcMain.on("auto-learn-changed", (_event, enabled) => {
+ this._autoLearnEnabled = !!enabled;
+ if (!this._autoLearnEnabled) {
+ if (this._autoLearnDebounceTimer) {
+ clearTimeout(this._autoLearnDebounceTimer);
+ this._autoLearnDebounceTimer = null;
+ }
+ this._autoLearnLatestData = null;
+ }
+ debugLogger.debug("[AutoLearn] Setting changed", { enabled: this._autoLearnEnabled });
+ });
+
ipcMain.handle("db-get-dictionary", async () => {
return this.databaseManager.getDictionary();
});
@@ -252,6 +370,34 @@ class IPCHandlers {
return this.databaseManager.setDictionary(words);
});
+ ipcMain.handle("undo-learned-corrections", async (_event, words) => {
+ try {
+ if (!Array.isArray(words) || words.length === 0) {
+ return { success: false };
+ }
+ const validWords = words.filter((w) => typeof w === "string" && w.trim().length > 0);
+ if (validWords.length === 0) {
+ return { success: false };
+ }
+ const currentDict = this._getDictionarySafe();
+ const removeSet = new Set(validWords.map((w) => w.toLowerCase()));
+ const updatedDict = currentDict.filter((w) => !removeSet.has(w.toLowerCase()));
+ const saveResult = this.databaseManager.setDictionary(updatedDict);
+ if (saveResult?.success === false) {
+ debugLogger.debug("[AutoLearn] Undo failed to save dictionary", {
+ error: saveResult.error,
+ });
+ return { success: false };
+ }
+ this.broadcastToWindows("dictionary-updated", updatedDict);
+ debugLogger.debug("[AutoLearn] Undo: removed words", { words: validWords });
+ return { success: true };
+ } catch (err) {
+ debugLogger.debug("[AutoLearn] Undo failed", { error: err.message });
+ return { success: false };
+ }
+ });
+
ipcMain.handle(
"db-save-note",
async (event, title, content, noteType, sourceFile, audioDuration, folderId) => {
@@ -463,7 +609,29 @@ class IPCHandlers {
await new Promise((resolve) => setTimeout(resolve, 80));
}
}
- return this.clipboardManager.pasteText(text, { ...options, webContents: event.sender });
+ const result = await this.clipboardManager.pasteText(text, {
+ ...options,
+ webContents: event.sender,
+ });
+ const targetPid = this.textEditMonitor?.lastTargetPid || null;
+ debugLogger.debug("[AutoLearn] Paste completed", {
+ autoLearnEnabled: this._autoLearnEnabled,
+ hasMonitor: !!this.textEditMonitor,
+ targetPid,
+ });
+ if (this.textEditMonitor && this._autoLearnEnabled) {
+ setTimeout(() => {
+ try {
+ debugLogger.debug("[AutoLearn] Starting monitoring", {
+ textPreview: text.substring(0, 80),
+ });
+ this.textEditMonitor.startMonitoring(text, 30000, { targetPid });
+ } catch (err) {
+ debugLogger.debug("[AutoLearn] Failed to start monitoring", { error: err.message });
+ }
+ }, 500);
+ }
+ return result;
});
ipcMain.handle("check-accessibility-permission", async () => {
diff --git a/src/helpers/textEditMonitor.js b/src/helpers/textEditMonitor.js
new file mode 100644
index 000000000..7ec28a3b0
--- /dev/null
+++ b/src/helpers/textEditMonitor.js
@@ -0,0 +1,499 @@
+const { spawn, execFile } = require("child_process");
+const path = require("path");
+const EventEmitter = require("events");
+const fs = require("fs");
+const debugLogger = require("./debugLogger");
+
+const POLL_INTERVAL_MS = 500;
+const INITIAL_QUERY_DELAY_MS = 500; // Wait for paste to settle in target app
+const INITIAL_QUERY_RETRIES = 4; // Retry if AXValue is empty (paste not yet processed)
+const INITIAL_QUERY_RETRY_DELAY_MS = 300;
+
+// AppleScript to enable AXEnhancedUserInterface on the target app.
+// Chromium-based apps (Chrome, Electron, VS Code, Slack, etc.) don't build their
+// accessibility tree until an assistive technology announces itself via this attribute.
+// This is the same technique Grammarly uses on macOS.
+const MACOS_AX_ENABLE_SCRIPT = (pid) =>
+ `tell application "System Events"\n` +
+ `\tset targetProc to first application process whose unix id is ${pid}\n` +
+ `\ttry\n` +
+ `\t\tset value of attribute "AXEnhancedUserInterface" of targetProc to true\n` +
+ `\tend try\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
+// implement parameterized text attributes but not AXValue directly.
+const MACOS_AX_SCRIPT_BY_PID = (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` +
+ `\ttry\n` +
+ `\t\tset val to value of attribute "AXValue" of focAttr\n` +
+ `\t\tif val is not missing value and val is not "" then return val\n` +
+ `\tend try\n` +
+ `\ttry\n` +
+ `\t\tset charCount to value of attribute "AXNumberOfCharacters" of focAttr\n` +
+ `\t\tif charCount is greater than 0 then\n` +
+ `\t\t\treturn value of attribute "AXSelectedText" of focAttr\n` +
+ `\t\tend if\n` +
+ `\tend try\n` +
+ `\treturn ""\n` +
+ `end tell`;
+
+class TextEditMonitor extends EventEmitter {
+ constructor() {
+ super();
+ this.process = null;
+ this.currentOriginalText = null;
+ this.timeout = null;
+ this._pollInterval = null;
+ this._lastValue = null;
+ this._stdoutBuffer = "";
+ this.lastTargetPid = null;
+ }
+
+ /**
+ * macOS: capture the active app's PID via NSWorkspace before the overlay steals focus.
+ * 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.
+ */
+ captureTargetPid() {
+ if (process.platform !== "darwin") return;
+ const script =
+ 'ObjC.import("AppKit"); $.NSWorkspace.sharedWorkspace.frontmostApplication.processIdentifier';
+ execFile("osascript", ["-l", "JavaScript", "-e", script], { timeout: 2000 }, (err, stdout) => {
+ if (err) {
+ this.lastTargetPid = null;
+ } else {
+ const pid = parseInt(stdout.trim(), 10);
+ this.lastTargetPid = isNaN(pid) ? null : pid;
+ }
+ debugLogger.debug("[TextEditMonitor] Captured target PID", { pid: this.lastTargetPid });
+ });
+ }
+
+ /**
+ * Start monitoring the focused text field for edits after a paste.
+ * Kills any existing monitor before starting a new one.
+ * @param {string} originalText - The transcribed text that was pasted
+ * @param {number} timeoutMs - How long to monitor (default 30s)
+ */
+ startMonitoring(originalText, timeoutMs = 30000, options = {}) {
+ this.stopMonitoring();
+ this.currentOriginalText = originalText;
+
+ if (process.platform === "darwin") {
+ const resolved = this.resolveBinary();
+ if (resolved) {
+ this._startMacOSNative(originalText, timeoutMs, options.targetPid, resolved);
+ return;
+ }
+ this._startMacOSPolling(originalText, timeoutMs, options.targetPid);
+ return;
+ }
+
+ const resolved = this.resolveBinary();
+ if (!resolved) {
+ debugLogger.debug("[TextEditMonitor] No binary found for platform", {
+ platform: process.platform,
+ });
+ this.currentOriginalText = null;
+ return;
+ }
+
+ const { command, args } = resolved;
+ debugLogger.debug("[TextEditMonitor] Resolved binary", { command, args });
+
+ // For native binaries, verify executable permission
+ if (command !== "python3") {
+ try {
+ fs.accessSync(command, fs.constants.X_OK);
+ } catch {
+ debugLogger.debug("[TextEditMonitor] Binary not executable", { command });
+ this.currentOriginalText = null;
+ return;
+ }
+ }
+
+ debugLogger.debug("[TextEditMonitor] Spawning monitor", {
+ textPreview: originalText.substring(0, 80),
+ });
+
+ this.process = spawn(command, args, {
+ stdio: ["pipe", "pipe", "pipe"],
+ });
+
+ // Send original text via stdin
+ this.process.stdin.write(originalText + "\n");
+ this.process.stdin.end();
+
+ this._stdoutBuffer = "";
+ this.process.stdout.setEncoding("utf8");
+ this.process.stdout.on("data", (chunk) => {
+ debugLogger.debug("[TextEditMonitor] stdout", { data: chunk.trim() });
+ this._handleProcessStdoutChunk(chunk);
+ });
+
+ this.process.stderr.setEncoding("utf8");
+ this.process.stderr.on("data", (data) => {
+ debugLogger.debug("[TextEditMonitor] stderr", { data: data.trim() });
+ });
+
+ this.process.on("error", (err) => {
+ debugLogger.debug("[TextEditMonitor] Process error", { error: err.message });
+ this.process = null;
+ });
+
+ this.process.on("exit", (code, signal) => {
+ debugLogger.debug("[TextEditMonitor] Process exited", { code, signal });
+ this.process = null;
+ });
+
+ // Safety net timeout (binary also self-exits after its own timeout)
+ this.timeout = setTimeout(() => this.stopMonitoring(), timeoutMs);
+ }
+
+ stopMonitoring() {
+ if (this.timeout) {
+ clearTimeout(this.timeout);
+ this.timeout = null;
+ }
+ if (this._pollInterval) {
+ clearInterval(this._pollInterval);
+ this._pollInterval = null;
+ }
+ this._lastValue = null;
+ this._stdoutBuffer = "";
+ if (this.process) {
+ try {
+ this.process.kill();
+ } catch {
+ // ignore
+ }
+ this.process = null;
+ }
+ this.currentOriginalText = null;
+ }
+
+ _handleProcessStdoutChunk(chunk) {
+ this._stdoutBuffer += chunk;
+ const lines = this._stdoutBuffer.split(/\r?\n/);
+ this._stdoutBuffer = lines.pop() || "";
+
+ for (const rawLine of lines) {
+ if (!rawLine) continue;
+ this._handleProcessLine(rawLine);
+ }
+ }
+
+ _decodeBase64Payload(encoded) {
+ try {
+ return Buffer.from(encoded, "base64").toString("utf8");
+ } catch (error) {
+ debugLogger.debug("[TextEditMonitor] Failed to decode base64 payload", {
+ error: error.message,
+ });
+ return null;
+ }
+ }
+
+ _emitTextEdited(newFieldValue) {
+ if (typeof newFieldValue !== "string" || this.currentOriginalText === null) {
+ return;
+ }
+
+ debugLogger.debug("[TextEditMonitor] Text changed", {
+ newFieldValue: newFieldValue.substring(0, 80),
+ });
+ this.emit("text-edited", {
+ originalText: this.currentOriginalText,
+ newFieldValue,
+ });
+ }
+
+ _handleProcessLine(line) {
+ if (line.startsWith("CHANGED_B64:")) {
+ const decoded = this._decodeBase64Payload(line.slice("CHANGED_B64:".length));
+ if (decoded !== null) {
+ this._emitTextEdited(decoded);
+ }
+ return;
+ }
+
+ if (line.startsWith("CHANGED:")) {
+ this._emitTextEdited(line.slice("CHANGED:".length));
+ return;
+ }
+
+ if (line === "NO_ELEMENT" || line === "NO_VALUE") {
+ debugLogger.debug("[TextEditMonitor] No target element", { status: line });
+ this.stopMonitoring();
+ }
+ }
+
+ /**
+ * macOS: tell the target app that an assistive technology is present.
+ * This causes Chromium/Electron apps to build their accessibility tree.
+ */
+ _enableAccessibility(pid) {
+ return new Promise((resolve) => {
+ const script = MACOS_AX_ENABLE_SCRIPT(pid);
+ execFile("osascript", ["-e", script], { timeout: 3000 }, (err) => {
+ if (err) {
+ debugLogger.debug("[TextEditMonitor] macOS: AXEnhancedUserInterface failed", {
+ error: err.message,
+ });
+ } else {
+ debugLogger.debug("[TextEditMonitor] macOS: AXEnhancedUserInterface enabled", { pid });
+ }
+ resolve();
+ });
+ });
+ }
+
+ /**
+ * macOS: use the native Swift AXObserver binary for event-based text monitoring.
+ * Falls back to osascript polling if the binary fails to start.
+ */
+ async _startMacOSNative(originalText, timeoutMs, targetPid, resolved) {
+ if (!targetPid) {
+ debugLogger.debug("[TextEditMonitor] macOS native: no target PID");
+ this.stopMonitoring();
+ return;
+ }
+
+ debugLogger.debug("[TextEditMonitor] macOS native: starting", {
+ targetPid,
+ textPreview: originalText.substring(0, 80),
+ });
+
+ await this._enableAccessibility(targetPid);
+ if (this.currentOriginalText === null) return;
+
+ await new Promise((r) => setTimeout(r, INITIAL_QUERY_DELAY_MS));
+ if (this.currentOriginalText === null) return;
+
+ const { command, args } = resolved;
+
+ try {
+ fs.accessSync(command, fs.constants.X_OK);
+ } catch {
+ debugLogger.debug(
+ "[TextEditMonitor] macOS native: binary not executable, falling back to polling",
+ { command }
+ );
+ this._startMacOSPolling(originalText, timeoutMs, targetPid);
+ return;
+ }
+
+ this.process = spawn(command, [...args, String(targetPid)], {
+ stdio: ["pipe", "pipe", "pipe"],
+ });
+
+ this.process.stdin.write(originalText + "\n");
+ this.process.stdin.end();
+
+ this._stdoutBuffer = "";
+ this.process.stdout.setEncoding("utf8");
+ this.process.stdout.on("data", (chunk) => {
+ debugLogger.debug("[TextEditMonitor] stdout", { data: chunk.trim() });
+ this._handleProcessStdoutChunk(chunk);
+ });
+
+ this.process.stderr.setEncoding("utf8");
+ this.process.stderr.on("data", (data) => {
+ debugLogger.debug("[TextEditMonitor] stderr", { data: data.trim() });
+ });
+
+ this.process.on("error", (err) => {
+ debugLogger.debug("[TextEditMonitor] macOS native: process error, falling back to polling", {
+ error: err.message,
+ });
+ this.process = null;
+ if (this.currentOriginalText === null) return;
+ this._startMacOSPolling(originalText, timeoutMs, targetPid);
+ });
+
+ this.process.on("exit", (code, signal) => {
+ debugLogger.debug("[TextEditMonitor] Process exited", { code, signal });
+ this.process = null;
+ });
+
+ this.timeout = setTimeout(() => this.stopMonitoring(), timeoutMs);
+ }
+
+ /**
+ * macOS: query the focused text field value via osascript for a specific app PID.
+ * Returns the field value string, or null on error.
+ */
+ _queryMacOSValue(pid) {
+ return new Promise((resolve) => {
+ const script = MACOS_AX_SCRIPT_BY_PID(pid);
+ execFile("osascript", ["-e", script], { timeout: 3000 }, (err, stdout) => {
+ if (err) {
+ resolve(null);
+ } else {
+ resolve(stdout.replace(/\n$/, ""));
+ }
+ });
+ });
+ }
+
+ /**
+ * macOS: poll the focused text field for changes using osascript.
+ * Uses Apple-signed osascript binary which inherits accessibility trust.
+ * @param {string} originalText - The pasted text
+ * @param {number} timeoutMs - Monitoring timeout
+ * @param {number|null} targetPid - PID of the app that received the paste
+ */
+ _startMacOSPolling(originalText, timeoutMs, targetPid) {
+ if (!targetPid) {
+ debugLogger.debug("[TextEditMonitor] macOS: no target PID");
+ this.stopMonitoring();
+ return;
+ }
+
+ debugLogger.debug("[TextEditMonitor] macOS: starting osascript polling", {
+ targetPid,
+ textPreview: originalText.substring(0, 80),
+ });
+
+ // Enable accessibility on the target app first (needed for Chromium/Electron apps),
+ // then delay before querying to let the paste keystroke be processed.
+ this._enableAccessibility(targetPid).then(() => {
+ if (this.currentOriginalText === null) return; // guard against stopMonitoring()
+ setTimeout(
+ () => this._queryInitialValue(targetPid, originalText, timeoutMs),
+ INITIAL_QUERY_DELAY_MS
+ );
+ });
+ }
+
+ /**
+ * Query the initial AXValue with retries. The target app may not have processed
+ * the pasted text yet, so an empty value is retried a few times before giving up.
+ */
+ async _queryInitialValue(targetPid, originalText, timeoutMs, attempt = 1) {
+ // Guard against stopMonitoring() being called while we waited
+ if (this.currentOriginalText === null) return;
+
+ const initialValue = await this._queryMacOSValue(targetPid);
+ if (this.currentOriginalText === null) return;
+
+ if (initialValue === null) {
+ debugLogger.debug("[TextEditMonitor] macOS: no focused element");
+ this.stopMonitoring();
+ return;
+ }
+
+ if (!initialValue) {
+ if (attempt < INITIAL_QUERY_RETRIES) {
+ debugLogger.debug("[TextEditMonitor] macOS: AXValue empty, retrying", {
+ attempt,
+ maxRetries: INITIAL_QUERY_RETRIES,
+ });
+ setTimeout(
+ () => this._queryInitialValue(targetPid, originalText, timeoutMs, attempt + 1),
+ INITIAL_QUERY_RETRY_DELAY_MS
+ );
+ return;
+ }
+ debugLogger.debug("[TextEditMonitor] macOS: no text value after retries");
+ this.stopMonitoring();
+ return;
+ }
+
+ this._lastValue = initialValue;
+ debugLogger.debug("[TextEditMonitor] macOS: initial value", {
+ valuePreview: initialValue.substring(0, 80),
+ attempt,
+ });
+
+ this._pollInterval = setInterval(async () => {
+ const currentValue = await this._queryMacOSValue(targetPid);
+ // Guard against stopMonitoring() being called during the query
+ if (this.currentOriginalText === null) return;
+
+ if (currentValue === null) {
+ debugLogger.debug("[TextEditMonitor] macOS: lost focused element");
+ this.stopMonitoring();
+ return;
+ }
+
+ if (currentValue !== this._lastValue) {
+ this._lastValue = currentValue;
+ debugLogger.debug("[TextEditMonitor] macOS: text changed", {
+ newValuePreview: currentValue.substring(0, 80),
+ });
+ this.emit("text-edited", {
+ originalText: this.currentOriginalText,
+ newFieldValue: currentValue,
+ });
+ }
+ }, POLL_INTERVAL_MS);
+
+ this.timeout = setTimeout(() => this.stopMonitoring(), timeoutMs);
+ }
+
+ /**
+ * Resolve the platform-specific binary.
+ * Returns { command, args } or null if unavailable.
+ */
+ resolveBinary() {
+ const platform = process.platform;
+
+ if (platform === "linux") {
+ const nativePath = this._findFile("linux-text-monitor");
+ if (nativePath) return { command: nativePath, args: [] };
+ const scriptPath = this._findFile("linux-text-monitor.py");
+ return scriptPath ? { command: "python3", args: [scriptPath] } : null;
+ }
+
+ if (platform === "win32") {
+ const binaryPath = this._findFile("windows-text-monitor.exe");
+ return binaryPath ? { command: binaryPath, args: [] } : null;
+ }
+
+ if (platform === "darwin") {
+ const nativePath = this._findFile("macos-text-monitor");
+ if (nativePath) return { command: nativePath, args: [] }; // PID added at spawn time
+ return null;
+ }
+
+ return null;
+ }
+
+ _findFile(fileName) {
+ const candidates = new Set([
+ path.join(__dirname, "..", "..", "resources", "bin", fileName),
+ path.join(__dirname, "..", "..", "resources", fileName),
+ ]);
+
+ if (process.resourcesPath) {
+ [
+ path.join(process.resourcesPath, fileName),
+ path.join(process.resourcesPath, "bin", fileName),
+ path.join(process.resourcesPath, "resources", fileName),
+ path.join(process.resourcesPath, "resources", "bin", fileName),
+ path.join(process.resourcesPath, "app.asar.unpacked", "resources", fileName),
+ path.join(process.resourcesPath, "app.asar.unpacked", "resources", "bin", fileName),
+ ].forEach((c) => candidates.add(c));
+ }
+
+ for (const candidate of candidates) {
+ try {
+ if (fs.statSync(candidate).isFile()) return candidate;
+ } catch {
+ continue;
+ }
+ }
+
+ return null;
+ }
+}
+
+module.exports = TextEditMonitor;
diff --git a/src/helpers/windowManager.js b/src/helpers/windowManager.js
index ff67f3f21..8df7b87c5 100644
--- a/src/helpers/windowManager.js
+++ b/src/helpers/windowManager.js
@@ -182,6 +182,9 @@ class WindowManager {
}
lastToggleTime = now;
+ // Capture target app PID before the window might steal focus
+ if (this.textEditMonitor) this.textEditMonitor.captureTargetPid();
+
this.showDictationPanel();
this.mainWindow.webContents.send("toggle-dictation");
};
@@ -201,6 +204,7 @@ class WindowManager {
const MAX_PUSH_DURATION_MS = 300000; // 5 minutes max recording
const downTime = Date.now();
+ if (this.textEditMonitor) this.textEditMonitor.captureTargetPid();
this.showDictationPanel();
const safetyTimeoutId = setTimeout(() => {
diff --git a/src/hooks/useSettings.ts b/src/hooks/useSettings.ts
index f625b09f1..230576d8f 100644
--- a/src/hooks/useSettings.ts
+++ b/src/hooks/useSettings.ts
@@ -1,6 +1,7 @@
-import React, { createContext, useContext, useEffect, useRef } from "react";
+import React, { createContext, useCallback, useContext, useEffect, useRef } from "react";
import { useSettingsStore, initializeSettings } from "../stores/settingsStore";
import logger from "../utils/logger";
+import { useLocalStorage } from "./useLocalStorage";
import type { LocalTranscriptionProvider } from "../types/electron";
export interface TranscriptionSettings {
@@ -76,6 +77,41 @@ function useSettingsInternal() {
});
}, []);
+ // Listen for dictionary updates from main process (auto-learn corrections)
+ useEffect(() => {
+ if (typeof window === "undefined" || !window.electronAPI?.onDictionaryUpdated) return;
+ const unsubscribe = window.electronAPI.onDictionaryUpdated((words: string[]) => {
+ if (Array.isArray(words)) {
+ store.setCustomDictionary(words);
+ }
+ });
+ return unsubscribe;
+ }, [store.setCustomDictionary]);
+
+ // Auto-learn corrections from user edits in external apps
+ const [autoLearnCorrections, setAutoLearnCorrectionsRaw] = useLocalStorage(
+ "autoLearnCorrections",
+ true,
+ {
+ serialize: String,
+ deserialize: (value: string) => value !== "false",
+ }
+ );
+
+ const setAutoLearnCorrections = useCallback(
+ (enabled: boolean) => {
+ setAutoLearnCorrectionsRaw(enabled);
+ window.electronAPI?.setAutoLearnEnabled?.(enabled);
+ },
+ [setAutoLearnCorrectionsRaw]
+ );
+
+ // Sync auto-learn state to main process on mount
+ useEffect(() => {
+ window.electronAPI?.setAutoLearnEnabled?.(autoLearnCorrections);
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, []);
+
// Sync startup pre-warming preferences to main process
const {
useLocalWhisper,
@@ -183,6 +219,8 @@ function useSettingsInternal() {
selectedMicDeviceId: store.selectedMicDeviceId,
setPreferBuiltInMic: store.setPreferBuiltInMic,
setSelectedMicDeviceId: store.setSelectedMicDeviceId,
+ autoLearnCorrections,
+ setAutoLearnCorrections,
cloudBackupEnabled: store.cloudBackupEnabled,
setCloudBackupEnabled: store.setCloudBackupEnabled,
telemetryEnabled: store.telemetryEnabled,
diff --git a/src/locales/de/translation.json b/src/locales/de/translation.json
index 6662ff6c9..b0fc9b8a1 100644
--- a/src/locales/de/translation.json
+++ b/src/locales/de/translation.json
@@ -1024,6 +1024,28 @@
"resetAppData": "App-Daten zurücksetzen",
"resetAppDataDescription": "Alle Einstellungen, Transkriptionen und zwischengespeicherten Daten dauerhaft löschen"
},
+ "dictionary": {
+ "title": "Benutzerwörterbuch",
+ "description": "Bringen Sie der KI Ihren Wortschatz bei — Namen, Fachbegriffe und Ausdrücke, die sie sonst übersehen könnte",
+ "addWordOrPhrase": "Wort oder Ausdruck hinzufügen",
+ "placeholder": "Wort oder Ausdruck hinzufügen...",
+ "add": "Hinzufügen",
+ "pressEnterToAdd": "Enter drücken zum Hinzufügen",
+ "autoLearnTitle": "Automatisch aus Korrekturen lernen",
+ "autoLearnDescription": "Wenn Sie eine Transkription in der Ziel-App korrigieren, wird das korrigierte Wort automatisch Ihrem Wörterbuch hinzugefügt.",
+ "yourWords": "Ihre Wörter",
+ "clearDictionaryTitle": "Wörterbuch löschen?",
+ "clearDictionaryDescription": "Dadurch werden alle Wörter aus Ihrem benutzerdefinierten Wörterbuch entfernt. Diese Aktion kann nicht rückgängig gemacht werden.",
+ "clearAll": "Alles löschen",
+ "agentNameAutoManaged": "Automatisch verwaltet — synchronisiert mit dem Agentennamen",
+ "removeWord": "Wort entfernen",
+ "noWords": "Noch keine Wörter",
+ "wordsAppearHere": "Hinzugefügte Wörter erscheinen hier",
+ "howItWorksTitle": "So funktioniert es",
+ "howItWorksDescription": "Wörter werden als Kontexthinweise an das Sprachmodell übergeben, um ungewöhnliche Begriffe besser zu erkennen. Für schwierige Wörter versuchen Sie, Kontext hinzuzufügen wie \"The word is Synty\" neben dem Wort selbst.",
+ "tipLabel": "Tipp",
+ "tipDescription": "Trennen Sie mehrere Wörter mit Kommas. Fügen Sie Kontextphrasen wie \"The word is Synty\" für bessere Erkennung hinzu."
+ },
"general": {
"appearance": {
"auto": "Auto",
@@ -1533,7 +1555,9 @@
"hotkeyUnavailable": {
"title": "Tastenkombination nicht verfügbar",
"description": "Die ausgewählte Tastenkombination konnte nicht registriert werden. Bitte wähle eine andere in den Einstellungen."
- }
+ },
+ "addedToDict": "{{words}} zu deinem Wörterbuch hinzugefügt",
+ "undo": "Rückgängig"
},
"mic": {
"hotkeyToSpeak": "{{hotkey}} drücken zum Sprechen",
diff --git a/src/locales/en/translation.json b/src/locales/en/translation.json
index 8bb770af4..5de8bf651 100644
--- a/src/locales/en/translation.json
+++ b/src/locales/en/translation.json
@@ -1024,6 +1024,28 @@
"resetAppData": "Reset app data",
"resetAppDataDescription": "Permanently delete all settings, transcriptions, and cached data"
},
+ "dictionary": {
+ "title": "Custom Dictionary",
+ "description": "Teach the AI your vocabulary — names, jargon, and terms it might otherwise miss",
+ "addWordOrPhrase": "Add word or phrase",
+ "placeholder": "Add a word or phrase...",
+ "add": "Add",
+ "pressEnterToAdd": "Press Enter to add",
+ "autoLearnTitle": "Auto-learn from corrections",
+ "autoLearnDescription": "When you correct a transcription in the target app, the corrected word is automatically added to your dictionary.",
+ "yourWords": "Your words",
+ "clearDictionaryTitle": "Clear dictionary?",
+ "clearDictionaryDescription": "This will remove all words from your custom dictionary. This action cannot be undone.",
+ "clearAll": "Clear all",
+ "agentNameAutoManaged": "Auto-managed — synced from agent name",
+ "removeWord": "Remove word",
+ "noWords": "No words yet",
+ "wordsAppearHere": "Words you add will appear here",
+ "howItWorksTitle": "How it works",
+ "howItWorksDescription": "Words are fed as context hints to the speech model, helping it recognize uncommon terms. For difficult words, try adding context like \"The word is Synty\" alongside the word itself.",
+ "tipLabel": "Tip",
+ "tipDescription": "Separate multiple words with commas. Add context phrases like \"The word is Synty\" for better recognition."
+ },
"general": {
"appearance": {
"auto": "Auto",
@@ -1533,7 +1555,9 @@
"hotkeyUnavailable": {
"title": "Hotkey unavailable",
"description": "The selected hotkey could not be registered. Please choose a different one in settings."
- }
+ },
+ "addedToDict": "Added {{words}} to your dictionary",
+ "undo": "Undo"
},
"mic": {
"hotkeyToSpeak": "Press {{hotkey}} to speak",
diff --git a/src/locales/es/translation.json b/src/locales/es/translation.json
index 84d29ce48..e11c2bc54 100644
--- a/src/locales/es/translation.json
+++ b/src/locales/es/translation.json
@@ -1028,6 +1028,28 @@
"resetAppData": "Restablecer datos de la app",
"resetAppDataDescription": "Elimina permanentemente todos los ajustes, transcripciones y datos en caché"
},
+ "dictionary": {
+ "title": "Diccionario personalizado",
+ "description": "Enseña a la IA tu vocabulario: nombres, jerga y términos que podría pasar por alto",
+ "addWordOrPhrase": "Añadir palabra o frase",
+ "placeholder": "Añadir una palabra o frase...",
+ "add": "Añadir",
+ "pressEnterToAdd": "Pulsa Enter para añadir",
+ "autoLearnTitle": "Aprender automáticamente de las correcciones",
+ "autoLearnDescription": "Cuando corriges una transcripción en la aplicación de destino, la palabra corregida se añade automáticamente a tu diccionario.",
+ "yourWords": "Tus palabras",
+ "clearDictionaryTitle": "¿Borrar diccionario?",
+ "clearDictionaryDescription": "Esto eliminará todas las palabras de tu diccionario personalizado. Esta acción no se puede deshacer.",
+ "clearAll": "Borrar todo",
+ "agentNameAutoManaged": "Gestionado automáticamente — sincronizado con el nombre del agente",
+ "removeWord": "Eliminar palabra",
+ "noWords": "Aún no hay palabras",
+ "wordsAppearHere": "Las palabras que añadas aparecerán aquí",
+ "howItWorksTitle": "Cómo funciona",
+ "howItWorksDescription": "Las palabras se envían como pistas de contexto al modelo de voz, ayudándole a reconocer términos poco comunes. Para palabras difíciles, intenta añadir contexto como \"The word is Synty\" junto con la propia palabra.",
+ "tipLabel": "Consejo",
+ "tipDescription": "Separa varias palabras con comas. Añade frases de contexto como \"The word is Synty\" para un mejor reconocimiento."
+ },
"general": {
"appearance": {
"auto": "Auto",
@@ -1537,7 +1559,9 @@
"hotkeyUnavailable": {
"title": "Atajo no disponible",
"description": "No se pudo registrar el atajo seleccionado. Elige otro en la configuración."
- }
+ },
+ "addedToDict": "{{words}} añadido a tu diccionario",
+ "undo": "Deshacer"
},
"mic": {
"hotkeyToSpeak": "Pulsa {{hotkey}} para hablar",
diff --git a/src/locales/fr/translation.json b/src/locales/fr/translation.json
index c49bac4b2..fbc74e653 100644
--- a/src/locales/fr/translation.json
+++ b/src/locales/fr/translation.json
@@ -1028,6 +1028,28 @@
"resetAppData": "Réinitialiser les données de l'application",
"resetAppDataDescription": "Supprime définitivement tous les paramètres, transcriptions et données en cache"
},
+ "dictionary": {
+ "title": "Dictionnaire personnalisé",
+ "description": "Apprenez à l'IA votre vocabulaire — noms, jargon et termes qu'elle pourrait autrement manquer",
+ "addWordOrPhrase": "Ajouter un mot ou une expression",
+ "placeholder": "Ajouter un mot ou une expression...",
+ "add": "Ajouter",
+ "pressEnterToAdd": "Appuyez sur Entrée pour ajouter",
+ "autoLearnTitle": "Apprentissage automatique à partir des corrections",
+ "autoLearnDescription": "Lorsque vous corrigez une transcription dans l'application cible, le mot corrigé est automatiquement ajouté à votre dictionnaire.",
+ "yourWords": "Vos mots",
+ "clearDictionaryTitle": "Effacer le dictionnaire ?",
+ "clearDictionaryDescription": "Cela supprimera tous les mots de votre dictionnaire personnalisé. Cette action est irréversible.",
+ "clearAll": "Tout effacer",
+ "agentNameAutoManaged": "Géré automatiquement — synchronisé avec le nom de l'agent",
+ "removeWord": "Supprimer le mot",
+ "noWords": "Aucun mot pour l'instant",
+ "wordsAppearHere": "Les mots que vous ajoutez apparaîtront ici",
+ "howItWorksTitle": "Comment ça fonctionne",
+ "howItWorksDescription": "Les mots sont fournis comme indices de contexte au modèle vocal, l'aidant à reconnaître les termes peu courants. Pour les mots difficiles, essayez d'ajouter du contexte comme « The word is Synty » en plus du mot lui-même.",
+ "tipLabel": "Astuce",
+ "tipDescription": "Séparez plusieurs mots par des virgules. Ajoutez des phrases de contexte comme « The word is Synty » pour une meilleure reconnaissance."
+ },
"general": {
"appearance": {
"auto": "Auto",
@@ -1537,7 +1559,9 @@
"hotkeyUnavailable": {
"title": "Raccourci indisponible",
"description": "Le raccourci sélectionné n’a pas pu être enregistré. Veuillez en choisir un autre dans les paramètres."
- }
+ },
+ "addedToDict": "{{words}} ajouté à votre dictionnaire",
+ "undo": "Annuler"
},
"mic": {
"hotkeyToSpeak": "Appuyez sur {{hotkey}} pour parler",
diff --git a/src/locales/it/translation.json b/src/locales/it/translation.json
index fedc97805..c6b5b47d3 100644
--- a/src/locales/it/translation.json
+++ b/src/locales/it/translation.json
@@ -1028,6 +1028,28 @@
"resetAppData": "Reimposta dati app",
"resetAppDataDescription": "Elimina definitivamente tutte le impostazioni, le trascrizioni e i dati in cache"
},
+ "dictionary": {
+ "title": "Dizionario personalizzato",
+ "description": "Insegna all'IA il tuo vocabolario — nomi, gergo e termini che potrebbe altrimenti non riconoscere",
+ "addWordOrPhrase": "Aggiungi parola o frase",
+ "placeholder": "Aggiungi una parola o frase...",
+ "add": "Aggiungi",
+ "pressEnterToAdd": "Premi Invio per aggiungere",
+ "autoLearnTitle": "Apprendimento automatico dalle correzioni",
+ "autoLearnDescription": "Quando correggi una trascrizione nell'app di destinazione, la parola corretta viene aggiunta automaticamente al tuo dizionario.",
+ "yourWords": "Le tue parole",
+ "clearDictionaryTitle": "Svuotare il dizionario?",
+ "clearDictionaryDescription": "Verranno rimosse tutte le parole dal tuo dizionario personalizzato. Questa azione non può essere annullata.",
+ "clearAll": "Cancella tutto",
+ "agentNameAutoManaged": "Gestito automaticamente — sincronizzato con il nome dell'agente",
+ "removeWord": "Rimuovi parola",
+ "noWords": "Nessuna parola ancora",
+ "wordsAppearHere": "Le parole aggiunte appariranno qui",
+ "howItWorksTitle": "Come funziona",
+ "howItWorksDescription": "Le parole vengono fornite come suggerimenti di contesto al modello vocale, aiutandolo a riconoscere termini poco comuni. Per parole difficili, prova ad aggiungere contesto come \"The word is Synty\" insieme alla parola stessa.",
+ "tipLabel": "Suggerimento",
+ "tipDescription": "Separa più parole con le virgole. Aggiungi frasi di contesto come \"The word is Synty\" per un migliore riconoscimento."
+ },
"general": {
"appearance": {
"auto": "Automatico",
@@ -1537,7 +1559,9 @@
"hotkeyUnavailable": {
"title": "Scorciatoia non disponibile",
"description": "Non è stato possibile registrare la scorciatoia selezionata. Scegline un’altra nelle impostazioni."
- }
+ },
+ "addedToDict": "{{words}} aggiunto al tuo dizionario",
+ "undo": "Annulla"
},
"mic": {
"hotkeyToSpeak": "Premi {{hotkey}} per parlare",
diff --git a/src/locales/ja/translation.json b/src/locales/ja/translation.json
index 8a0529189..9500a38d4 100644
--- a/src/locales/ja/translation.json
+++ b/src/locales/ja/translation.json
@@ -1024,6 +1024,28 @@
"resetAppData": "アプリデータをリセット",
"resetAppDataDescription": "すべての設定、文字起こし履歴、キャッシュデータを完全に削除"
},
+ "dictionary": {
+ "title": "カスタム辞書",
+ "description": "AIにあなたの語彙を教えましょう — 名前、専門用語、見逃しがちな用語など",
+ "addWordOrPhrase": "単語またはフレーズを追加",
+ "placeholder": "単語またはフレーズを追加...",
+ "add": "追加",
+ "pressEnterToAdd": "Enterキーで追加",
+ "autoLearnTitle": "修正から自動学習",
+ "autoLearnDescription": "対象アプリで文字起こしを修正すると、修正された単語が自動的に辞書に追加されます。",
+ "yourWords": "あなたの単語",
+ "clearDictionaryTitle": "辞書をクリアしますか?",
+ "clearDictionaryDescription": "カスタム辞書からすべての単語が削除されます。この操作は元に戻せません。",
+ "clearAll": "すべてクリア",
+ "agentNameAutoManaged": "自動管理 — エージェント名と同期",
+ "removeWord": "単語を削除",
+ "noWords": "まだ単語がありません",
+ "wordsAppearHere": "追加した単語がここに表示されます",
+ "howItWorksTitle": "仕組み",
+ "howItWorksDescription": "単語は音声モデルへのコンテキストヒントとして提供され、一般的でない用語の認識を助けます。難しい単語には、単語自体に加えて \"The word is Synty\" のようなコンテキストを追加してみてください。",
+ "tipLabel": "ヒント",
+ "tipDescription": "複数の単語はカンマで区切ってください。より良い認識のために \"The word is Synty\" のようなコンテキストフレーズを追加してください。"
+ },
"general": {
"appearance": {
"auto": "自動",
@@ -1533,7 +1555,9 @@
"hotkeyUnavailable": {
"title": "ホットキーが使用できません",
"description": "選択したホットキーを登録できませんでした。設定から別のホットキーを選択してください。"
- }
+ },
+ "addedToDict": "{{words}} を辞書に追加しました",
+ "undo": "元に戻す"
},
"mic": {
"hotkeyToSpeak": "{{hotkey}} を押して話す",
diff --git a/src/locales/pt/translation.json b/src/locales/pt/translation.json
index 9ca65e2c6..776787e59 100644
--- a/src/locales/pt/translation.json
+++ b/src/locales/pt/translation.json
@@ -1000,6 +1000,28 @@
"resetAppData": "Redefinir dados do app",
"resetAppDataDescription": "Excluir permanentemente todas as configurações, transcrições e dados em cache"
},
+ "dictionary": {
+ "title": "Dicionário personalizado",
+ "description": "Ensine à IA o seu vocabulário — nomes, jargões e termos que ela poderia não reconhecer",
+ "addWordOrPhrase": "Adicionar palavra ou frase",
+ "placeholder": "Adicionar uma palavra ou frase...",
+ "add": "Adicionar",
+ "pressEnterToAdd": "Pressione Enter para adicionar",
+ "autoLearnTitle": "Aprender automaticamente com correções",
+ "autoLearnDescription": "Quando você corrige uma transcrição no aplicativo de destino, a palavra corrigida é adicionada automaticamente ao seu dicionário.",
+ "yourWords": "Suas palavras",
+ "clearDictionaryTitle": "Limpar dicionário?",
+ "clearDictionaryDescription": "Isso removerá todas as palavras do seu dicionário personalizado. Esta ação não pode ser desfeita.",
+ "clearAll": "Limpar tudo",
+ "agentNameAutoManaged": "Gerenciado automaticamente — sincronizado com o nome do agente",
+ "removeWord": "Remover palavra",
+ "noWords": "Nenhuma palavra ainda",
+ "wordsAppearHere": "Palavras que você adicionar aparecerão aqui",
+ "howItWorksTitle": "Como funciona",
+ "howItWorksDescription": "As palavras são fornecidas como dicas de contexto ao modelo de fala, ajudando-o a reconhecer termos incomuns. Para palavras difíceis, tente adicionar contexto como \"The word is Synty\" junto com a própria palavra.",
+ "tipLabel": "Dica",
+ "tipDescription": "Separe várias palavras com vírgulas. Adicione frases de contexto como \"The word is Synty\" para melhor reconhecimento."
+ },
"general": {
"appearance": {
"auto": "Auto",
@@ -1537,7 +1559,9 @@
"hotkeyUnavailable": {
"title": "Atalho indisponível",
"description": "Não foi possível registrar o atalho selecionado. Escolha outro nas configurações."
- }
+ },
+ "addedToDict": "{{words}} adicionado ao seu dicionário",
+ "undo": "Desfazer"
},
"mic": {
"hotkeyToSpeak": "Pressione {{hotkey}} para falar",
diff --git a/src/locales/ru/translation.json b/src/locales/ru/translation.json
index f6c2be5b0..1c29fe07e 100644
--- a/src/locales/ru/translation.json
+++ b/src/locales/ru/translation.json
@@ -1028,6 +1028,28 @@
"resetAppData": "Сбросить данные приложения",
"resetAppDataDescription": "Безвозвратно удалить все настройки, транскрипции и кешированные данные"
},
+ "dictionary": {
+ "title": "Пользовательский словарь",
+ "description": "Научите ИИ вашему словарю — именам, жаргону и терминам, которые он может не распознать",
+ "addWordOrPhrase": "Добавить слово или фразу",
+ "placeholder": "Добавить слово или фразу...",
+ "add": "Добавить",
+ "pressEnterToAdd": "Нажмите Enter для добавления",
+ "autoLearnTitle": "Автоматическое обучение на исправлениях",
+ "autoLearnDescription": "Когда вы исправляете транскрипцию в целевом приложении, исправленное слово автоматически добавляется в ваш словарь.",
+ "yourWords": "Ваши слова",
+ "clearDictionaryTitle": "Очистить словарь?",
+ "clearDictionaryDescription": "Все слова из вашего пользовательского словаря будут удалены. Это действие нельзя отменить.",
+ "clearAll": "Очистить всё",
+ "agentNameAutoManaged": "Управляется автоматически — синхронизировано с именем агента",
+ "removeWord": "Удалить слово",
+ "noWords": "Слов пока нет",
+ "wordsAppearHere": "Добавленные слова появятся здесь",
+ "howItWorksTitle": "Как это работает",
+ "howItWorksDescription": "Слова передаются как контекстные подсказки модели распознавания речи, помогая ей распознавать редкие термины. Для сложных слов попробуйте добавить контекст, например \"The word is Synty\", наряду с самим словом.",
+ "tipLabel": "Совет",
+ "tipDescription": "Разделяйте несколько слов запятыми. Добавляйте контекстные фразы, например \"The word is Synty\", для лучшего распознавания."
+ },
"general": {
"appearance": {
"auto": "Авто",
@@ -1537,7 +1559,9 @@
"hotkeyUnavailable": {
"title": "Горячая клавиша недоступна",
"description": "Не удалось зарегистрировать выбранную комбинацию. Выберите другую в настройках."
- }
+ },
+ "addedToDict": "{{words}} добавлено в ваш словарь",
+ "undo": "Отменить"
},
"mic": {
"hotkeyToSpeak": "Нажмите {{hotkey}} для записи",
diff --git a/src/locales/zh-CN/translation.json b/src/locales/zh-CN/translation.json
index 7c51e2a91..6c44408fe 100644
--- a/src/locales/zh-CN/translation.json
+++ b/src/locales/zh-CN/translation.json
@@ -1024,6 +1024,28 @@
"resetAppData": "重置应用数据",
"resetAppDataDescription": "永久删除所有设置、转录记录和缓存数据"
},
+ "dictionary": {
+ "title": "自定义词典",
+ "description": "教 AI 你的词汇 — 名字、术语和它可能遗漏的词语",
+ "addWordOrPhrase": "添加单词或短语",
+ "placeholder": "添加一个单词或短语...",
+ "add": "添加",
+ "pressEnterToAdd": "按 Enter 添加",
+ "autoLearnTitle": "从纠正中自动学习",
+ "autoLearnDescription": "当你在目标应用中纠正转录时,纠正后的词语会自动添加到你的词典中。",
+ "yourWords": "你的词语",
+ "clearDictionaryTitle": "清除词典?",
+ "clearDictionaryDescription": "这将删除自定义词典中的所有词语。此操作无法撤消。",
+ "clearAll": "全部清除",
+ "agentNameAutoManaged": "自动管理 — 与助手名称同步",
+ "removeWord": "移除词语",
+ "noWords": "暂无词语",
+ "wordsAppearHere": "你添加的词语将显示在这里",
+ "howItWorksTitle": "工作原理",
+ "howItWorksDescription": "词语作为上下文提示提供给语音模型,帮助它识别不常见的术语。对于难以识别的词语,可以尝试添加上下文,例如在词语旁添加 \"The word is Synty\"。",
+ "tipLabel": "提示",
+ "tipDescription": "用逗号分隔多个词语。添加上下文短语如 \"The word is Synty\" 以获得更好的识别效果。"
+ },
"general": {
"appearance": {
"auto": "自动",
@@ -1533,7 +1555,9 @@
"hotkeyUnavailable": {
"title": "快捷键不可用",
"description": "无法注册所选快捷键。请在设置中选择其他快捷键。"
- }
+ },
+ "addedToDict": "已将 {{words}} 添加到你的词典",
+ "undo": "撤消"
},
"mic": {
"hotkeyToSpeak": "按 {{hotkey}} 开始说话",
diff --git a/src/locales/zh-TW/translation.json b/src/locales/zh-TW/translation.json
index 4c3749b6a..8d169c1fe 100644
--- a/src/locales/zh-TW/translation.json
+++ b/src/locales/zh-TW/translation.json
@@ -1024,6 +1024,28 @@
"resetAppData": "重設應用程式資料",
"resetAppDataDescription": "永久刪除所有設定、轉錄記錄和快取資料"
},
+ "dictionary": {
+ "title": "自訂詞典",
+ "description": "教 AI 你的詞彙 — 名字、術語和它可能遺漏的詞語",
+ "addWordOrPhrase": "新增單字或片語",
+ "placeholder": "新增一個單字或片語...",
+ "add": "新增",
+ "pressEnterToAdd": "按 Enter 新增",
+ "autoLearnTitle": "從校正中自動學習",
+ "autoLearnDescription": "當你在目標應用程式中校正轉錄時,校正後的字詞會自動新增到你的詞典中。",
+ "yourWords": "你的字詞",
+ "clearDictionaryTitle": "清除詞典?",
+ "clearDictionaryDescription": "這將移除自訂詞典中的所有字詞。此操作無法復原。",
+ "clearAll": "全部清除",
+ "agentNameAutoManaged": "自動管理 — 與助理名稱同步",
+ "removeWord": "移除字詞",
+ "noWords": "尚無字詞",
+ "wordsAppearHere": "你新增的字詞將顯示在這裡",
+ "howItWorksTitle": "運作方式",
+ "howItWorksDescription": "字詞會作為上下文提示提供給語音模型,幫助它辨識不常見的術語。對於難以辨識的字詞,可以嘗試在字詞旁新增上下文,例如 \"The word is Synty\"。",
+ "tipLabel": "提示",
+ "tipDescription": "用逗號分隔多個字詞。新增上下文片語如 \"The word is Synty\" 以獲得更好的辨識效果。"
+ },
"general": {
"appearance": {
"auto": "自動",
@@ -1533,7 +1555,9 @@
"hotkeyUnavailable": {
"title": "快捷鍵無法使用",
"description": "無法註冊所選快捷鍵。請在設定中選擇其他快捷鍵。"
- }
+ },
+ "addedToDict": "已將 {{words}} 加入到你的詞典",
+ "undo": "復原"
},
"mic": {
"hotkeyToSpeak": "按 {{hotkey}} 開始說話",
diff --git a/src/types/electron.ts b/src/types/electron.ts
index 93719001c..f6e26ace8 100644
--- a/src/types/electron.ts
+++ b/src/types/electron.ts
@@ -287,6 +287,10 @@ declare global {
// Dictionary operations
getDictionary: () => Promise<string[]>;
setDictionary: (words: string[]) => Promise<{ success: boolean }>;
+ onDictionaryUpdated?: (callback: (words: string[]) => void) => () => void;
+ setAutoLearnEnabled?: (enabled: boolean) => void;
+ onCorrectionsLearned?: (callback: (words: string[]) => void) => () => void;
+ undoLearnedCorrections?: (words: string[]) => Promise<{ success: boolean }>;
// Note operations
saveNote: (
diff --git a/src/utils/correctionLearner.js b/src/utils/correctionLearner.js
new file mode 100644
index 000000000..0431a8000
--- /dev/null
+++ b/src/utils/correctionLearner.js
@@ -0,0 +1,179 @@
+/**
+ * Extracts transcription corrections by diffing original text against
+ * the edited field value. Returns corrected words to add to the custom dictionary.
+ */
+
+/** Levenshtein edit distance between two strings */
+function editDistance(a, b) {
+ const m = a.length;
+ const n = b.length;
+ const dp = Array.from({ length: m + 1 }, () => Array(n + 1).fill(0));
+
+ for (let i = 0; i <= m; i++) dp[i][0] = i;
+ for (let j = 0; j <= n; j++) dp[0][j] = j;
+
+ for (let i = 1; i <= m; i++) {
+ for (let j = 1; j <= n; j++) {
+ if (a[i - 1] === b[j - 1]) {
+ dp[i][j] = dp[i - 1][j - 1];
+ } else {
+ dp[i][j] = 1 + Math.min(dp[i - 1][j], dp[i][j - 1], dp[i - 1][j - 1]);
+ }
+ }
+ }
+ return dp[m][n];
+}
+
+/** Tokenize text into words, stripping punctuation from edges */
+function tokenize(text) {
+ return text
+ .split(/\s+/)
+ .map((w) => w.replace(/^[^\w]+|[^\w]+$/g, ""))
+ .filter((w) => w.length > 0);
+}
+
+/**
+ * Find the region in fieldValue that corresponds to the pasted originalText.
+ * If the field only contains the pasted text, returns fieldValue as-is.
+ */
+function findEditedRegion(originalText, fieldValue) {
+ if (fieldValue.length <= originalText.length * 1.5) {
+ return fieldValue;
+ }
+
+ const idx = fieldValue.indexOf(originalText);
+ if (idx !== -1) {
+ return originalText;
+ }
+
+ // Sliding window: find the region with highest word overlap
+ const origWords = tokenize(originalText);
+ const fieldWords = tokenize(fieldValue);
+ const windowSize = origWords.length;
+
+ if (fieldWords.length <= windowSize) {
+ return fieldValue;
+ }
+
+ let bestStart = 0;
+ let bestScore = -1;
+
+ for (let i = 0; i <= fieldWords.length - windowSize; i++) {
+ let matches = 0;
+ for (let j = 0; j < windowSize; j++) {
+ if (fieldWords[i + j].toLowerCase() === origWords[j].toLowerCase()) {
+ matches++;
+ }
+ }
+ if (matches > bestScore) {
+ bestScore = matches;
+ bestStart = i;
+ }
+ }
+
+ // Require at least 30% word overlap to consider it a match
+ if (bestScore < windowSize * 0.3) {
+ return fieldValue;
+ }
+
+ return fieldWords.slice(bestStart, bestStart + windowSize).join(" ");
+}
+
+/** Word-level LCS to find [originalWord, editedWord] substitution pairs. */
+function findSubstitutions(origWords, editedWords) {
+ const m = origWords.length;
+ const n = editedWords.length;
+
+ const dp = Array.from({ length: m + 1 }, () => Array(n + 1).fill(0));
+ for (let i = 1; i <= m; i++) {
+ for (let j = 1; j <= n; j++) {
+ if (origWords[i - 1].toLowerCase() === editedWords[j - 1].toLowerCase()) {
+ dp[i][j] = dp[i - 1][j - 1] + 1;
+ } else {
+ dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
+ }
+ }
+ }
+
+ const aligned = [];
+ let i = m,
+ j = n;
+ while (i > 0 || j > 0) {
+ if (i > 0 && j > 0 && origWords[i - 1].toLowerCase() === editedWords[j - 1].toLowerCase()) {
+ aligned.unshift([origWords[i - 1], editedWords[j - 1]]);
+ i--;
+ j--;
+ } else if (j > 0 && (i === 0 || dp[i][j - 1] >= dp[i - 1][j])) {
+ aligned.unshift([null, editedWords[j - 1]]);
+ j--;
+ } else {
+ aligned.unshift([origWords[i - 1], null]);
+ i--;
+ }
+ }
+
+ // Consecutive [origWord, null] + [null, editedWord] = substitution
+ const subs = [];
+ for (let k = 0; k < aligned.length - 1; k++) {
+ const [origW, editW] = aligned[k];
+ const [nextOrigW, nextEditW] = aligned[k + 1];
+
+ if (origW !== null && editW === null && nextOrigW === null && nextEditW !== null) {
+ subs.push([origW, nextEditW]);
+ }
+ }
+
+ return subs;
+}
+
+/**
+ * Extract corrected words from a user's edits to pasted transcription text.
+ *
+ * @param {string} originalText - The text that was originally pasted (from transcription)
+ * @param {string} fieldValue - The current value of the text field (after user edits)
+ * @param {string[]} existingDictionary - Words already in the custom dictionary
+ * @returns {string[]} Array of corrected words to add to the dictionary
+ */
+function extractCorrections(originalText, fieldValue, existingDictionary) {
+ if (!originalText || !fieldValue) return [];
+ if (originalText === fieldValue) return [];
+
+ const editedRegion = findEditedRegion(originalText, fieldValue);
+ if (editedRegion === originalText) return [];
+
+ const origWords = tokenize(originalText);
+ const editedWords = tokenize(editedRegion);
+
+ if (origWords.length === 0 || editedWords.length === 0) return [];
+
+ // If more than 50% of words changed, this is a rewrite, not corrections
+ const subs = findSubstitutions(origWords, editedWords);
+ if (subs.length > origWords.length * 0.5) return [];
+
+ const safeDict = Array.isArray(existingDictionary) ? existingDictionary : [];
+ const dictSet = new Set(safeDict.map((w) => w.toLowerCase()));
+ const seenCorrections = new Set();
+ const results = [];
+
+ for (const [origWord, correctedWord] of subs) {
+ const normalizedCorrected = correctedWord.toLowerCase();
+
+ if (dictSet.has(normalizedCorrected)) continue;
+ if (seenCorrections.has(normalizedCorrected)) continue;
+ if (origWord.toLowerCase() === normalizedCorrected) continue;
+ if (correctedWord.length < 3) continue;
+
+ // 0.65 threshold allows phonetic corrections like "Shunade" → "Sinead" (dist 4/7 = 0.57)
+ // while filtering out unrelated word replacements.
+ const dist = editDistance(origWord.toLowerCase(), correctedWord.toLowerCase());
+ const maxLen = Math.max(origWord.length, correctedWord.length);
+ if (dist / maxLen > 0.65) continue;
+
+ results.push(correctedWord);
+ seenCorrections.add(normalizedCorrected);
+ }
+
+ return results;
+}
+
+module.exports = { extractCorrections };