Voice-to-text dictation app with local (Nvidia Parakeet/Whisper) and cloud models (BYOK). Privacy-first and available cross-platform.
JavaScript aianthropiccross-platformgeminigroqlinuxmacosnvidiaopen-sourceopenaiparakeetspeech-to-texttranscribewhisperwindows
feat(windows): add Push-to-Talk support with compound hotkeys (#153)
Gabriel Steine3969d05385b
diff --git a/.github/workflows/build-and-notarize.yml b/.github/workflows/build-and-notarize.ymlindex f874e11d2..0467140a8 100644--- a/.github/workflows/build-and-notarize.yml+++ b/.github/workflows/build-and-notarize.yml@@ -24,6 +24,8 @@ jobs:- name: Download whisper.cpp binariesrun: node scripts/download-whisper-cpp.js --current+ env:+ GITHUB_TOKEN: ${{ secrets.GH_TOKEN }}- name: Cache Electronuses: actions/cache@v4@@ -63,9 +65,13 @@ jobs:- name: Download whisper.cpp binariesrun: node scripts/download-whisper-cpp.js --current+ env:+ GITHUB_TOKEN: ${{ secrets.GH_TOKEN }}- name: Download nircmd.exerun: node scripts/download-nircmd.js+ env:+ GITHUB_TOKEN: ${{ secrets.GH_TOKEN }}- name: Cache Electronuses: actions/cache@v4@@ -106,6 +112,8 @@ jobs:- name: Download whisper.cpp binariesrun: node scripts/download-whisper-cpp.js --current --platform darwin --arch ${{ matrix.arch }}+ env:+ GITHUB_TOKEN: ${{ secrets.GH_TOKEN }}- name: Cache Electronuses: actions/cache@v4diff --git a/.github/workflows/build-windows-key-listener.yml b/.github/workflows/build-windows-key-listener.ymlnew file mode 100644index 000000000..3a9393d3e--- /dev/null+++ b/.github/workflows/build-windows-key-listener.yml@@ -0,0 +1,72 @@+name: Build Windows Key Listener++on:+ push:+ paths:+ - 'resources/windows-key-listener.c'+ - '.github/workflows/build-windows-key-listener.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 Key Listener+ run: |+ cl /O2 /nologo resources/windows-key-listener.c /Fe:windows-key-listener.exe user32.lib+ shell: cmd++ - name: Verify binary+ run: |+ if (Test-Path "windows-key-listener.exe") {+ Write-Host "Binary built successfully"+ Get-Item "windows-key-listener.exe" | Select-Object Name, Length+ } else {+ Write-Error "Binary not found"+ exit 1+ }+ shell: pwsh++ - name: Create zip archive+ run: |+ Compress-Archive -Path windows-key-listener.exe -DestinationPath windows-key-listener-win32-x64.zip+ shell: pwsh++ - name: Upload artifact+ uses: actions/upload-artifact@v4+ with:+ name: windows-key-listener+ path: windows-key-listener-win32-x64.zip++ - name: Create or update release+ uses: softprops/action-gh-release@v2+ with:+ tag_name: windows-key-listener-v${{ inputs.version || '1.0.0' }}+ name: Windows Key Listener v${{ inputs.version || '1.0.0' }}+ body: |+ Prebuilt Windows key listener binary for Push-to-Talk functionality.++ This binary uses Windows Low-Level Keyboard Hook to detect key press/release events.+ files: windows-key-listener-win32-x64.zip+ make_latest: false+ env:+ GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}diff --git a/.github/workflows/release.yml b/.github/workflows/release.ymlindex 5ddb3ebed..6df1aadd6 100644--- a/.github/workflows/release.yml+++ b/.github/workflows/release.yml@@ -31,6 +31,8 @@ jobs:- name: Download whisper.cpp binariesrun: node scripts/download-whisper-cpp.js --current+ env:+ GITHUB_TOKEN: ${{ secrets.GH_TOKEN }}- name: Cache Electronuses: actions/cache@v4@@ -65,9 +67,13 @@ jobs:- name: Download whisper.cpp binariesrun: node scripts/download-whisper-cpp.js --current+ env:+ GITHUB_TOKEN: ${{ secrets.GH_TOKEN }}- name: Download nircmd.exerun: node scripts/download-nircmd.js+ env:+ GITHUB_TOKEN: ${{ secrets.GH_TOKEN }}- name: Cache Electronuses: actions/cache@v4@@ -101,6 +107,8 @@ jobs:- name: Download whisper.cpp binariesrun: node scripts/download-whisper-cpp.js --current --platform darwin --arch ${{ matrix.arch }}+ env:+ GITHUB_TOKEN: ${{ secrets.GH_TOKEN }}- name: Cache Electronuses: actions/cache@v4diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 5d0c3a35d..b38215414 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -5,6 +5,29 @@ All notable changes to this project will be documented in this file.The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).+## [1.2.16] - 2026-01-26++### Added+- **Windows Push-to-Talk**: Native Windows key listener with low-level keyboard hook for true push-to-talk functionality+ - Supports compound hotkeys like `Ctrl+Shift+F11` or `CommandOrControl+Space`+ - Prebuilt binary automatically downloaded from GitHub releases+ - Fallback to tap mode if binary unavailable+- **Custom Dictionary**: Improve transcription accuracy for specific words, names, and technical terms+ - Add custom words through Settings → Custom Dictionary+ - Words are passed as hints to Whisper for better recognition+ - Works with both local and cloud transcription+- **GitHub Actions Workflow**: Automated CI workflow to build and release Windows key listener binary+- **Shared Download Utilities**: New `scripts/lib/download-utils.js` module with reusable download, extraction, and GitHub release fetching functions++### Changed+- **Download Scripts Refactored**: All download scripts now use shared utilities for consistency+- **GitHub API Authentication**: Download scripts support `GITHUB_TOKEN` to avoid API rate limits in CI+- **Dev Server Port Alignment**: Development server port configuration improved for consistency++### Fixed+- **Windows Production Build**: Fixed Windows production build issues with proper binary bundling+- **Code Quality**: Various code quality improvements in download scripts and dev server management+## [1.2.15] - 2026-01-22### Addeddiff --git a/CLAUDE.md b/CLAUDE.mdindex bb2cf09f6..e870d05eb 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -39,6 +39,12 @@ OpenWhispr is an Electron-based desktop dictation application that uses whisper.- **main.js**: Application entry point, initializes all managers- **preload.js**: Exposes safe IPC methods to renderer via window.api+### Native Resources (resources/)++- **windows-key-listener.c**: C source for Windows low-level keyboard hook (Push-to-Talk)+- **globe-listener.swift**: Swift source for macOS Globe/Fn key detection+- **bin/**: Directory for compiled native binaries (whisper-cpp, nircmd, key listeners)+### Helper Modules (src/helpers/)- **audioManager.js**: Handles audio device management@@ -62,6 +68,11 @@ OpenWhispr is an Electron-based desktop dictation application that uses whisper.- Converts Electron hotkey format to GNOME keysym format- Only active on Linux + Wayland + GNOME desktop- **ipcHandlers.js**: Centralized IPC handler registration+- **windowsKeyManager.js**: Windows Push-to-Talk support with native key listener+ - Spawns native `windows-key-listener.exe` binary for low-level keyboard hooks+ - Supports compound hotkeys (e.g., `Ctrl+Shift+F11`, `CommandOrControl+Space`)+ - Emits `key-down` and `key-up` events for push-to-talk functionality+ - Graceful fallback if binary unavailable- **menuManager.js**: Application menu management- **tray.js**: System tray icon and menu- **whisper.js**: Local whisper.cpp integration and model management@@ -107,6 +118,22 @@ OpenWhispr is an Electron-based desktop dictation application that uses whisper.- GGML model downloads from HuggingFace- Models stored in `~/.cache/openwhispr/whisper-models/`+### Build Scripts (scripts/)++- **download-whisper-cpp.js**: Downloads whisper.cpp binaries from GitHub releases+- **download-llama-server.js**: Downloads llama.cpp server for local LLM inference+- **download-nircmd.js**: Downloads nircmd.exe for Windows clipboard operations+- **download-windows-key-listener.js**: Downloads prebuilt Windows key listener binary+- **build-globe-listener.js**: Compiles macOS Globe key listener from Swift source+- **build-windows-key-listener.js**: Compiles Windows key listener (for local development)+- **run-electron.js**: Development script to launch Electron with proper environment+- **lib/download-utils.js**: Shared utilities for downloading and extracting files+ - `fetchLatestRelease(repo, options)`: Fetches latest release from GitHub API+ - `downloadFile(url, dest)`: Downloads file with progress and retry logic+ - `extractZip(zipPath, destDir)`: Cross-platform zip extraction+ - `parseArgs()`: Parses CLI arguments for platform/arch targeting+ - Supports `GITHUB_TOKEN` for authenticated requests (higher rate limits)+## Key Implementation Details### 1. FFmpeg Integration@@ -166,6 +193,7 @@ Settings stored in localStorage with these keys:- `reasoningProvider`: AI provider (openai/anthropic/gemini/local)- `hotkey`: Custom hotkey configuration- `hasCompletedOnboarding`: Onboarding completion flag+- `customDictionary`: JSON array of words/phrases for improved transcription accuracy### 6. Language Support@@ -276,7 +304,52 @@ Enable with `--log-level=debug` or `OPENWHISPR_LOG_LEVEL=debug` (can be set in `- Audio level analysis- Complete reasoning pipeline debugging with stage-by-stage logging-### 12. GNOME Wayland Global Hotkeys+### 12. Windows Push-to-Talk++Native Windows support for true push-to-talk functionality using low-level keyboard hooks:++**Architecture**:+- `resources/windows-key-listener.c`: Native C program using Windows `SetWindowsHookEx` for keyboard hooks+- `src/helpers/windowsKeyManager.js`: Node.js wrapper that spawns and manages the native binary+- Binary outputs `KEY_DOWN` and `KEY_UP` to stdout when target key is pressed/released++**Compound Hotkey Support**:+- Parses hotkey strings like `CommandOrControl+Shift+F11`+- Maps modifiers: `CommandOrControl`/`Ctrl` → VK_CONTROL, `Alt`/`Option` → VK_MENU, `Shift` → VK_SHIFT+- Verifies all required modifiers are held before emitting key events++**Binary Distribution**:+- Prebuilt binary downloaded from GitHub releases (`windows-key-listener-v*` tags)+- Download script: `scripts/download-windows-key-listener.js`+- CI workflow: `.github/workflows/build-windows-key-listener.yml`+- Fallback to tap mode if binary unavailable++**IPC Events**:+- `windows-key-listener:key-down`: Fired when hotkey pressed (start recording)+- `windows-key-listener:key-up`: Fired when hotkey released (stop recording)++### 13. Custom Dictionary++Improve transcription accuracy for specific words, names, or technical terms:++**How it works**:+- User adds words/phrases through Settings → Custom Dictionary+- Words stored as JSON array in localStorage (`customDictionary` key)+- On transcription, words are joined and passed as `prompt` parameter to Whisper+- Works with both local whisper.cpp and cloud OpenAI Whisper API++**Implementation**:+- `src/hooks/useSettings.ts`: Manages `customDictionary` state+- `src/components/SettingsPage.tsx`: UI for adding/removing dictionary words+- `src/helpers/audioManager.js`: Reads dictionary and adds to transcription options+- `src/helpers/whisperServer.js`: Includes dictionary as `prompt` in API request++**Whisper Prompt Parameter**:+- Whisper uses the prompt as context/hints for transcription+- Words in the prompt are more likely to be recognized correctly+- Useful for: uncommon names, technical jargon, brand names, domain-specific terms++### 14. GNOME Wayland Global HotkeysOn GNOME Wayland, Electron's `globalShortcut` API doesn't work due to Wayland's security model. OpenWhispr uses native GNOME shortcuts:@@ -320,6 +393,8 @@ On GNOME Wayland, Electron's `globalShortcut` API doesn't work due to Wayland's- [ ] Verify whisper.cpp binary detection- [ ] Test all Whisper models- [ ] Check agent naming functionality+- [ ] Test custom dictionary with uncommon words+- [ ] Verify Windows Push-to-Talk with compound hotkeys- [ ] Test GNOME Wayland hotkeys (if on GNOME + Wayland)- [ ] Verify activation mode selector is hidden on GNOME Wayland@@ -348,10 +423,16 @@ On GNOME Wayland, Electron's `globalShortcut` API doesn't work due to Wayland's- Use `npm run pack` for unsigned builds (CSC_IDENTITY_AUTO_DISCOVERY=false)- Signing requires Apple Developer account- ASAR unpacking needed for FFmpeg- - Run `npm run download:whisper-cpp` before packaging (current platform)- - Use `npm run download:whisper-cpp:all` for multi-platform packaging+ - Run `npm run download:whisper-cpp` before packaging (current platform)+ - Use `npm run download:whisper-cpp:all` for multi-platform packaging- afterSign.js automatically skips signing when CSC_IDENTITY_AUTO_DISCOVERY=false+5. **Windows Push-to-Talk Binary**:+ - Prebuilt binary downloaded automatically on Windows during build+ - If download fails, push-to-talk falls back to tap mode+ - To compile locally: install Visual Studio Build Tools or MinGW-w64+ - CI workflow (`.github/workflows/build-windows-key-listener.yml`) auto-builds on push to main+### Platform-Specific Notes**macOS**:@@ -369,6 +450,11 @@ On GNOME Wayland, Electron's `globalShortcut` API doesn't work due to Wayland's- Sound settings at `ms-settings:sound`- NSIS installer for distribution- whisper.cpp bundled for x64+- **Push-to-Talk**: Native key listener binary (`windows-key-listener.exe`) enables true push-to-talk+ - Uses Windows Low-Level Keyboard Hook (`WH_KEYBOARD_LL`)+ - Supports compound hotkeys (e.g., `Ctrl+Shift+F11`)+ - Prebuilt binary auto-downloaded from GitHub releases+ - Falls back to tap mode if unavailable**Linux**:- Multiple package manager supportdiff --git a/README.md b/README.mdindex b27ebc8af..4c5b324d1 100644--- a/README.md+++ b/README.md@@ -34,6 +34,8 @@ This project is licensed under the MIT License - see the [LICENSE](LICENSE) file- 🔄 **OpenAI Responses API**: Using the latest Responses API for improved performance- 🌐 **Globe Key Toggle (macOS)**: Optional Fn/Globe key listener for a hardware-level dictation trigger- ⌨️ **Compound Hotkeys**: Support for multi-key combinations like `Cmd+Shift+K`+- 🎙️ **Push-to-Talk (Windows)**: Native low-level keyboard hook for true push-to-talk with compound hotkey support+- 📖 **Custom Dictionary**: Add words, names, and technical terms to improve transcription accuracy- 🐧 **GNOME Wayland Support**: Native global shortcuts via D-Bus for GNOME Wayland users## Prerequisites@@ -310,8 +312,21 @@ Once you've named your agent during setup, you can interact with it using multipThe AI automatically detects when you're giving it commands versus dictating regular text, and removes agent name references from the final output.+### Custom Dictionary+Improve transcription accuracy for specific words, names, or technical terms:++1. **Access Settings**: Open Control Panel → Settings → Custom Dictionary+2. **Add Words**: Enter words, names, or phrases that are frequently misrecognized+3. **How It Works**: Words are provided as context hints to the speech recognition model++**Examples of words to add**:+- Uncommon names (e.g., "Sergey", "Xanthe")+- Technical jargon (e.g., "Kubernetes", "OAuth")+- Brand names (e.g., "OpenWhispr", "whisper.cpp")+- Domain-specific terms (e.g., "amortization", "polymerase")+### Processing Options-- **Local Processing**:+- **Local Processing**:- Install Whisper automatically through the Control Panel- Download models: tiny (fastest), base (recommended), small, medium, large (best quality)- Complete privacy - audio never leaves your device@@ -378,6 +393,7 @@ open-whispr/- `npm run build:renderer` - Build the React app only- `npm run download:whisper-cpp` - Download whisper.cpp for the current platform- `npm run download:whisper-cpp:all` - Download whisper.cpp for all platforms+- `npm run compile:native` - Compile native helpers (Globe key listener for macOS, key listener for Windows)- `npm run build` - Full build with signing (requires certificates)- `npm run build:mac` - macOS build with signing- `npm run build:win` - Windows build with signing@@ -572,13 +588,15 @@ A: OpenWhispr supports 58 languages including English, Spanish, French, German,## Project Status-OpenWhispr is actively maintained and ready for production use. Current version: 1.2.12+OpenWhispr is actively maintained and ready for production use. Current version: 1.2.16- ✅ Core functionality complete- ✅ Cross-platform support (macOS, Windows, Linux)- ✅ Local and cloud processing- ✅ Multi-provider AI (OpenAI, Anthropic, Gemini, Groq, Local)- ✅ Compound hotkey support+- ✅ Windows Push-to-Talk with native key listener+- ✅ Custom dictionary for improved transcription accuracy## Acknowledgmentsdiff --git a/electron-builder.json b/electron-builder.jsonindex 108175036..01c79650c 100644--- a/electron-builder.json+++ b/electron-builder.json@@ -88,7 +88,7 @@{"from": "resources/bin/","to": "bin/",- "filter": ["whisper-cpp-*", "whisper-server-*", "llama-server-*", "*.dylib", "*.dll", "*.so*"]+ "filter": ["whisper-cpp-*", "whisper-server-*", "llama-server-*", "windows-key-listener*", "*.dylib", "*.dll", "*.so*"]}],"mac": {diff --git a/main.js b/main.jsindex ef2387560..0aeebbab6 100644--- a/main.js+++ b/main.js@@ -1,4 +1,4 @@-const { app, globalShortcut, BrowserWindow, dialog } = require("electron");+const { app, globalShortcut, BrowserWindow, dialog, ipcMain } = require("electron");// Enable native Wayland global shortcuts: https://github.com/electron/electron/pull/45171if (process.platform === "linux" && process.env.XDG_SESSION_TYPE === "wayland") {@@ -48,6 +48,7 @@ const TrayManager = require("./src/helpers/tray");const IPCHandlers = require("./src/helpers/ipcHandlers");const UpdateManager = require("./src/updater");const GlobeKeyManager = require("./src/helpers/globeKeyManager");+const WindowsKeyManager = require("./src/helpers/windowsKeyManager");// Manager instances - initialized after app.whenReady()let debugLogger = null;@@ -60,6 +61,7 @@ let whisperManager = null;let trayManager = null;let updateManager = null;let globeKeyManager = null;+let windowsKeyManager = null;let globeKeyAlertShown = false;// Set up PATH for production builds to find system tools (whisper.cpp, ffmpeg)@@ -104,6 +106,7 @@ function initializeManagers() {trayManager = new TrayManager();updateManager = new UpdateManager();globeKeyManager = new GlobeKeyManager();+ windowsKeyManager = new WindowsKeyManager();// Set up Globe key error handler on macOSif (process.platform === "darwin") {@@ -143,6 +146,7 @@ function initializeManagers() {whisperManager,windowManager,updateManager,+ windowsKeyManager,});}@@ -262,6 +266,160 @@ async function startApp() {globeKeyManager.start();}++ // Set up Windows Push-to-Talk handling+ if (process.platform === "win32") {+ debugLogger.debug("[Push-to-Talk] Windows Push-to-Talk setup starting");+ let winKeyDownTime = 0;+ let winKeyIsRecording = false;++ // Minimum duration (ms) the key must be held before starting recording.+ // This distinguishes a "tap" (ignored in push mode) from a "hold" (starts recording).+ // 150ms is short enough to feel instant but long enough to detect intent.+ const WIN_MIN_HOLD_DURATION_MS = 150;++ // Helper to check if hotkey is valid for Windows key listener+ // Supports compound hotkeys like "CommandOrControl+F11"+ const isValidHotkey = (hotkey) => {+ if (!hotkey) return false;+ if (hotkey === "GLOBE") return false; // GLOBE is macOS only+ return true;+ };++ windowsKeyManager.on("key-down", async (key) => {+ debugLogger.debug("[Push-to-Talk] Key DOWN received", { key });+ // Handle dictation if in push-to-talk mode+ if (isLiveWindow(windowManager.mainWindow)) {+ const activationMode = await windowManager.getActivationMode();+ debugLogger.debug("[Push-to-Talk] Activation mode check", { activationMode });+ if (activationMode === "push") {+ debugLogger.debug("[Push-to-Talk] Starting recording sequence");+ windowManager.showDictationPanel();+ // Track when key was pressed for push-to-talk+ winKeyDownTime = Date.now();+ winKeyIsRecording = false;+ // Start recording after a brief delay to distinguish tap from hold+ setTimeout(async () => {+ if (winKeyDownTime > 0 && !winKeyIsRecording) {+ winKeyIsRecording = true;+ debugLogger.debug("[Push-to-Talk] Sending start dictation command");+ windowManager.sendStartDictation();+ }+ }, WIN_MIN_HOLD_DURATION_MS);+ }+ }+ });++ windowsKeyManager.on("key-up", async () => {+ debugLogger.debug("[Push-to-Talk] Key UP received");+ if (isLiveWindow(windowManager.mainWindow)) {+ const activationMode = await windowManager.getActivationMode();+ if (activationMode === "push") {+ const wasRecording = winKeyIsRecording;+ winKeyDownTime = 0;+ winKeyIsRecording = false;+ if (wasRecording) {+ debugLogger.debug("[Push-to-Talk] Sending stop dictation command");+ windowManager.sendStopDictation();+ } else {+ // Short tap (< hold threshold) - hide panel since recording never started+ debugLogger.debug("[Push-to-Talk] Short tap detected, hiding panel");+ windowManager.hideDictationPanel();+ }+ }+ }+ });++ windowsKeyManager.on("error", (error) => {+ debugLogger.warn("[Push-to-Talk] Windows key listener error", { error: error.message });+ windowManager.setWindowsPushToTalkAvailable(false);+ if (isLiveWindow(windowManager.mainWindow)) {+ windowManager.mainWindow.webContents.send("windows-ptt-unavailable", {+ reason: "error",+ message: error.message,+ });+ }+ });++ windowsKeyManager.on("unavailable", () => {+ debugLogger.debug("[Push-to-Talk] Windows key listener not available - falling back to toggle mode");+ windowManager.setWindowsPushToTalkAvailable(false);+ if (isLiveWindow(windowManager.mainWindow)) {+ windowManager.mainWindow.webContents.send("windows-ptt-unavailable", {+ reason: "binary_not_found",+ message: "Push-to-Talk native listener not available",+ });+ }+ });++ windowsKeyManager.on("ready", () => {+ debugLogger.debug("[Push-to-Talk] WindowsKeyManager is ready and listening");+ windowManager.setWindowsPushToTalkAvailable(true);+ });++ // Start the Windows key listener with the current hotkey+ const startWindowsKeyListener = async () => {+ debugLogger.debug("[Push-to-Talk] Checking if should start Windows key listener");+ if (!isLiveWindow(windowManager.mainWindow)) {+ debugLogger.debug("[Push-to-Talk] Main window not live, skipping");+ return;+ }+ const activationMode = await windowManager.getActivationMode();+ const currentHotkey = hotkeyManager.getCurrentHotkey();+ debugLogger.debug("[Push-to-Talk] Current state", { activationMode, currentHotkey });++ if (activationMode === "push") {+ if (isValidHotkey(currentHotkey)) {+ debugLogger.debug("[Push-to-Talk] Starting Windows key listener", { hotkey: currentHotkey });+ windowsKeyManager.start(currentHotkey);+ } else {+ debugLogger.debug("[Push-to-Talk] No valid hotkey to start listener");+ }+ } else {+ debugLogger.debug("[Push-to-Talk] Not in push mode, skipping listener start");+ }+ };++ // Delay (ms) before starting the Windows key listener after app startup.+ // The hotkeyManager loads saved hotkey 1 second after did-finish-load event,+ // so we wait 3 seconds to ensure settings are fully loaded before starting.+ const STARTUP_DELAY_MS = 3000;+ debugLogger.debug("[Push-to-Talk] Scheduling listener start", { delayMs: STARTUP_DELAY_MS });+ setTimeout(startWindowsKeyListener, STARTUP_DELAY_MS);++ // Listen for activation mode changes from renderer+ ipcMain.on("activation-mode-changed", async (_event, mode) => {+ debugLogger.debug("[Push-to-Talk] IPC: Activation mode changed", { mode });+ if (mode === "push") {+ const currentHotkey = hotkeyManager.getCurrentHotkey();+ debugLogger.debug("[Push-to-Talk] Current hotkey", { hotkey: currentHotkey });+ if (isValidHotkey(currentHotkey)) {+ debugLogger.debug("[Push-to-Talk] Starting listener", { hotkey: currentHotkey });+ windowsKeyManager.start(currentHotkey);+ }+ } else {+ debugLogger.debug("[Push-to-Talk] Stopping listener (mode is tap)");+ windowsKeyManager.stop();+ }+ });++ // Listen for hotkey changes from renderer+ ipcMain.on("hotkey-changed", async (_event, hotkey) => {+ debugLogger.debug("[Push-to-Talk] IPC: Hotkey changed", { hotkey });+ if (!isLiveWindow(windowManager.mainWindow)) {+ return;+ }+ const activationMode = await windowManager.getActivationMode();+ debugLogger.debug("[Push-to-Talk] Current activation mode", { activationMode });+ if (activationMode === "push") {+ windowsKeyManager.stop();+ if (isValidHotkey(hotkey)) {+ debugLogger.debug("[Push-to-Talk] Starting listener for new hotkey", { hotkey });+ windowsKeyManager.start(hotkey);+ }+ }+ });+ }}// App event handlers@@ -358,6 +516,9 @@ if (gotSingleInstanceLock) {if (globeKeyManager) {globeKeyManager.stop();}+ if (windowsKeyManager) {+ windowsKeyManager.stop();+ }if (updateManager) {updateManager.cleanup();}diff --git a/package.json b/package.jsonindex bbc353b90..b4fb81784 100644--- a/package.json+++ b/package.json@@ -6,27 +6,29 @@"private": true,"scripts": {"compile:globe": "node scripts/build-globe-listener.js",- "prestart": "npm run compile:globe",+ "compile:winkeys": "node scripts/build-windows-key-listener.js",+ "compile:native": "npm run compile:globe && npm run compile:winkeys",+ "prestart": "npm run compile:native","start": "electron .",- "predev": "npm run compile:globe",+ "predev": "npm run compile:native","dev": "concurrently -k -r \"npm:dev:renderer\" \"npm:dev:main\"",- "predev:main": "npm run compile:globe",- "dev:main": "cross-env NODE_ENV=development electron . --dev",+ "predev:main": "npm run compile:native",+ "dev:main": "cross-env NODE_ENV=development node scripts/run-electron.js --dev","dev:renderer": "cd src && vite",- "prebuild": "npm run compile:globe && npm run download:whisper-cpp && npm run download:llama-server",+ "prebuild": "npm run compile:native && npm run download:whisper-cpp && npm run download:llama-server","build": "cd src && vite build && cd .. && electron-builder","postinstall": "electron-builder install-app-deps","build:renderer": "cd src && vite build",- "prebuild:mac": "npm run compile:globe && npm run download:whisper-cpp && npm run download:llama-server",+ "prebuild:mac": "npm run compile:native && npm run download:whisper-cpp && npm run download:llama-server","build:mac": "npm run build:renderer && electron-builder --mac",- "prebuild:win": "npm run compile:globe && npm run download:whisper-cpp && npm run download:llama-server",+ "prebuild:win": "npm run compile:native && npm run download:whisper-cpp && npm run download:llama-server","build:win": "npm run build:renderer && electron-builder --win",- "prebuild:linux": "npm run compile:globe && npm run download:whisper-cpp && npm run download:llama-server",+ "prebuild:linux": "npm run compile:native && npm run download:whisper-cpp && npm run download:llama-server","build:linux": "npm run build:renderer && electron-builder --linux","setup": "node setup.js",- "prepack": "npm run compile:globe && npm run download:whisper-cpp && npm run download:llama-server",+ "prepack": "npm run compile:native && npm run download:whisper-cpp && npm run download:llama-server","pack": "npm run build:renderer && cross-env CSC_IDENTITY_AUTO_DISCOVERY=false electron-builder --dir",- "predist": "npm run compile:globe && npm run download:whisper-cpp && npm run download:llama-server",+ "predist": "npm run compile:native && npm run download:whisper-cpp && npm run download:llama-server","dist": "npm run build:renderer && electron-builder","download:whisper-cpp": "node scripts/download-whisper-cpp.js --current","download:whisper-cpp:all": "node scripts/download-whisper-cpp.js --all",diff --git a/preload.js b/preload.jsindex 5bb2878db..4ffbe8c99 100644--- a/preload.js+++ b/preload.js@@ -47,6 +47,10 @@ contextBridge.exposeInMainWorld("electronAPI", {clearTranscriptions: () => ipcRenderer.invoke("db-clear-transcriptions"),deleteTranscription: (id) =>ipcRenderer.invoke("db-delete-transcription", id),+ // Dictionary functions+ getDictionary: () => ipcRenderer.invoke("db-get-dictionary"),+ setDictionary: (words) => ipcRenderer.invoke("db-set-dictionary", words),+onTranscriptionAdded: (callback) => {const listener = (_event, transcription) => callback?.(transcription);ipcRenderer.on("transcription-added", listener);@@ -111,7 +115,8 @@ contextBridge.exposeInMainWorld("electronAPI", {// Cleanup functioncleanupApp: () => ipcRenderer.invoke("cleanup-app"),updateHotkey: (hotkey) => ipcRenderer.invoke("update-hotkey", hotkey),- setHotkeyListeningMode: (enabled) => ipcRenderer.invoke("set-hotkey-listening-mode", enabled),+ setHotkeyListeningMode: (enabled, newHotkey) =>+ ipcRenderer.invoke("set-hotkey-listening-mode", enabled, newHotkey),getHotkeyModeInfo: () => ipcRenderer.invoke("get-hotkey-mode-info"),startWindowDrag: () => ipcRenderer.invoke("start-window-drag"),stopWindowDrag: () => ipcRenderer.invoke("stop-window-drag"),@@ -221,4 +226,13 @@ contextBridge.exposeInMainWorld("electronAPI", {ipcRenderer.on("hotkey-registration-failed", listener);return () => ipcRenderer.removeListener("hotkey-registration-failed", listener);},+ onWindowsPushToTalkUnavailable: registerListener("windows-ptt-unavailable"),++ // Notify main process of activation mode changes (for Windows Push-to-Talk)+ notifyActivationModeChanged: (mode) => ipcRenderer.send("activation-mode-changed", mode),+ notifyHotkeyChanged: (hotkey) => ipcRenderer.send("hotkey-changed", hotkey),++ // Auto-start management+ getAutoStartEnabled: () => ipcRenderer.invoke("get-auto-start-enabled"),+ setAutoStartEnabled: (enabled) => ipcRenderer.invoke("set-auto-start-enabled", enabled),});diff --git a/resources/windows-key-listener.c b/resources/windows-key-listener.cnew file mode 100644index 000000000..4f92da166--- /dev/null+++ b/resources/windows-key-listener.c@@ -0,0 +1,262 @@+/**+ * Windows Key Listener for Push-to-Talk+ *+ * Uses Windows Low-Level Keyboard Hook to detect key up/down events.+ * Accepts a virtual key code as command line argument.+ * Outputs "KEY_DOWN" and "KEY_UP" to stdout.+ *+ * Compile with: cl /O2 windows-key-listener.c /Fe:windows-key-listener.exe user32.lib+ * Or with MinGW: gcc -O2 windows-key-listener.c -o windows-key-listener.exe -luser32+ */++#define WIN32_LEAN_AND_MEAN+#include <windows.h>+#include <stdio.h>+#include <stdlib.h>+#include <string.h>++static HHOOK g_hook = NULL;+static DWORD g_targetVk = 0;+static BOOL g_isKeyDown = FALSE;++// Modifier key requirements+static BOOL g_requireCtrl = FALSE;+static BOOL g_requireAlt = FALSE;+static BOOL g_requireShift = FALSE;++// Check if required modifiers are currently pressed+BOOL AreModifiersPressed(void) {+ if (g_requireCtrl && !(GetAsyncKeyState(VK_CONTROL) & 0x8000)) return FALSE;+ if (g_requireAlt && !(GetAsyncKeyState(VK_MENU) & 0x8000)) return FALSE;+ if (g_requireShift && !(GetAsyncKeyState(VK_SHIFT) & 0x8000)) return FALSE;+ return TRUE;+}++// Map key name to virtual key code+DWORD ParseKeyCode(const char* keyName) {+ // Function keys (F1-F12)+ if (_stricmp(keyName, "F1") == 0) return VK_F1;+ if (_stricmp(keyName, "F2") == 0) return VK_F2;+ if (_stricmp(keyName, "F3") == 0) return VK_F3;+ if (_stricmp(keyName, "F4") == 0) return VK_F4;+ if (_stricmp(keyName, "F5") == 0) return VK_F5;+ if (_stricmp(keyName, "F6") == 0) return VK_F6;+ if (_stricmp(keyName, "F7") == 0) return VK_F7;+ if (_stricmp(keyName, "F8") == 0) return VK_F8;+ if (_stricmp(keyName, "F9") == 0) return VK_F9;+ if (_stricmp(keyName, "F10") == 0) return VK_F10;+ if (_stricmp(keyName, "F11") == 0) return VK_F11;+ if (_stricmp(keyName, "F12") == 0) return VK_F12;++ // Extended function keys (F13-F24)+ if (_stricmp(keyName, "F13") == 0) return VK_F13;+ if (_stricmp(keyName, "F14") == 0) return VK_F14;+ if (_stricmp(keyName, "F15") == 0) return VK_F15;+ if (_stricmp(keyName, "F16") == 0) return VK_F16;+ if (_stricmp(keyName, "F17") == 0) return VK_F17;+ if (_stricmp(keyName, "F18") == 0) return VK_F18;+ if (_stricmp(keyName, "F19") == 0) return VK_F19;+ if (_stricmp(keyName, "F20") == 0) return VK_F20;+ if (_stricmp(keyName, "F21") == 0) return VK_F21;+ if (_stricmp(keyName, "F22") == 0) return VK_F22;+ if (_stricmp(keyName, "F23") == 0) return VK_F23;+ if (_stricmp(keyName, "F24") == 0) return VK_F24;++ // Special keys+ if (_stricmp(keyName, "Pause") == 0) return VK_PAUSE;+ if (_stricmp(keyName, "ScrollLock") == 0) return VK_SCROLL;+ if (_stricmp(keyName, "Insert") == 0) return VK_INSERT;+ if (_stricmp(keyName, "Home") == 0) return VK_HOME;+ if (_stricmp(keyName, "End") == 0) return VK_END;+ if (_stricmp(keyName, "PageUp") == 0) return VK_PRIOR;+ if (_stricmp(keyName, "PageDown") == 0) return VK_NEXT;+ if (_stricmp(keyName, "Space") == 0) return VK_SPACE;+ if (_stricmp(keyName, "Escape") == 0 || _stricmp(keyName, "Esc") == 0) return VK_ESCAPE;+ if (_stricmp(keyName, "Tab") == 0) return VK_TAB;+ if (_stricmp(keyName, "CapsLock") == 0) return VK_CAPITAL;+ if (_stricmp(keyName, "NumLock") == 0) return VK_NUMLOCK;++ // Backtick/tilde - the default hotkey+ if (strcmp(keyName, "`") == 0 || _stricmp(keyName, "Backquote") == 0) return VK_OEM_3;++ // Other punctuation+ if (strcmp(keyName, "-") == 0 || _stricmp(keyName, "Minus") == 0) return VK_OEM_MINUS;+ if (strcmp(keyName, "=") == 0 || _stricmp(keyName, "Equal") == 0) return VK_OEM_PLUS;+ if (strcmp(keyName, "[") == 0) return VK_OEM_4;+ if (strcmp(keyName, "]") == 0) return VK_OEM_6;+ if (strcmp(keyName, "\\") == 0) return VK_OEM_5;+ if (strcmp(keyName, ";") == 0) return VK_OEM_1;+ if (strcmp(keyName, "'") == 0) return VK_OEM_7;+ if (strcmp(keyName, ",") == 0) return VK_OEM_COMMA;+ if (strcmp(keyName, ".") == 0) return VK_OEM_PERIOD;+ if (strcmp(keyName, "/") == 0) return VK_OEM_2;++ // Single letter/number - convert to VK code+ if (strlen(keyName) == 1) {+ char c = keyName[0];+ if (c >= 'a' && c <= 'z') return (DWORD)(c - 'a' + 'A');+ if (c >= 'A' && c <= 'Z') return (DWORD)c;+ if (c >= '0' && c <= '9') return (DWORD)c;+ }++ // Try parsing as hex or decimal number (for direct VK codes)+ if (keyName[0] == '0' && (keyName[1] == 'x' || keyName[1] == 'X')) {+ return (DWORD)strtol(keyName, NULL, 16);+ }++ return (DWORD)atoi(keyName);+}++LRESULT CALLBACK LowLevelKeyboardProc(int nCode, WPARAM wParam, LPARAM lParam) {+ if (nCode == HC_ACTION) {+ KBDLLHOOKSTRUCT* kbd = (KBDLLHOOKSTRUCT*)lParam;+ BOOL isKeyDown = (wParam == WM_KEYDOWN || wParam == WM_SYSKEYDOWN);+ BOOL isKeyUp = (wParam == WM_KEYUP || wParam == WM_SYSKEYUP);++ // Check if a required modifier was released while we're in key-down state+ if (g_isKeyDown && isKeyUp) {+ BOOL modifierReleased = FALSE;+ if (g_requireCtrl && (kbd->vkCode == VK_CONTROL || kbd->vkCode == VK_LCONTROL || kbd->vkCode == VK_RCONTROL)) {+ modifierReleased = TRUE;+ }+ if (g_requireAlt && (kbd->vkCode == VK_MENU || kbd->vkCode == VK_LMENU || kbd->vkCode == VK_RMENU)) {+ modifierReleased = TRUE;+ }+ if (g_requireShift && (kbd->vkCode == VK_SHIFT || kbd->vkCode == VK_LSHIFT || kbd->vkCode == VK_RSHIFT)) {+ modifierReleased = TRUE;+ }+ if (modifierReleased) {+ g_isKeyDown = FALSE;+ printf("KEY_UP\n");+ fflush(stdout);+ }+ }++ // Check for the target key+ if (kbd->vkCode == g_targetVk) {+ if (isKeyDown) {+ // Only trigger if modifiers are satisfied and not already down+ if (!g_isKeyDown && AreModifiersPressed()) {+ g_isKeyDown = TRUE;+ printf("KEY_DOWN\n");+ fflush(stdout);+ }+ } else if (isKeyUp) {+ // Target key released+ if (g_isKeyDown) {+ g_isKeyDown = FALSE;+ printf("KEY_UP\n");+ fflush(stdout);+ }+ }+ }+ }+ return CallNextHookEx(g_hook, nCode, wParam, lParam);+}++BOOL WINAPI ConsoleHandler(DWORD signal) {+ if (signal == CTRL_C_EVENT || signal == CTRL_BREAK_EVENT || signal == CTRL_CLOSE_EVENT) {+ if (g_hook) {+ UnhookWindowsHookEx(g_hook);+ g_hook = NULL;+ }+ ExitProcess(0);+ }+ return TRUE;+}++// Parse a compound hotkey like "CommandOrControl+Shift+F11"+// Sets g_requireCtrl, g_requireAlt, g_requireShift and returns the main key VK code+DWORD ParseCompoundHotkey(const char* hotkey) {+ char buffer[256];+ strncpy(buffer, hotkey, sizeof(buffer) - 1);+ buffer[sizeof(buffer) - 1] = '\0';++ // Reset modifier requirements+ g_requireCtrl = FALSE;+ g_requireAlt = FALSE;+ g_requireShift = FALSE;++ DWORD mainKeyVk = 0;+ char* token = strtok(buffer, "+");++ while (token != NULL) {+ // Trim leading/trailing spaces+ while (*token == ' ') token++;+ char* end = token + strlen(token) - 1;+ while (end > token && *end == ' ') *end-- = '\0';++ // Check for modifiers+ if (_stricmp(token, "CommandOrControl") == 0 ||+ _stricmp(token, "Control") == 0 ||+ _stricmp(token, "Ctrl") == 0 ||+ _stricmp(token, "CmdOrCtrl") == 0) {+ g_requireCtrl = TRUE;+ } else if (_stricmp(token, "Alt") == 0 ||+ _stricmp(token, "Option") == 0) {+ g_requireAlt = TRUE;+ } else if (_stricmp(token, "Shift") == 0) {+ g_requireShift = TRUE;+ } else if (_stricmp(token, "Super") == 0 ||+ _stricmp(token, "Meta") == 0 ||+ _stricmp(token, "Command") == 0 ||+ _stricmp(token, "Cmd") == 0) {+ // Windows key - treat as Ctrl on Windows for compatibility+ g_requireCtrl = TRUE;+ } else {+ // This should be the main key+ mainKeyVk = ParseKeyCode(token);+ }++ token = strtok(NULL, "+");+ }++ return mainKeyVk;+}++int main(int argc, char* argv[]) {+ if (argc < 2) {+ fprintf(stderr, "Usage: %s <key>\n", argv[0]);+ fprintf(stderr, "Examples:\n");+ fprintf(stderr, " %s ` (backtick)\n", argv[0]);+ fprintf(stderr, " %s F8 (function key F1-F12)\n", argv[0]);+ fprintf(stderr, " %s F13 (extended function key F13-F24)\n", argv[0]);+ fprintf(stderr, " %s CommandOrControl+F11 (with modifier)\n", argv[0]);+ fprintf(stderr, " %s Ctrl+Shift+Space (multiple modifiers)\n", argv[0]);+ return 1;+ }++ g_targetVk = ParseCompoundHotkey(argv[1]);+ if (g_targetVk == 0) {+ fprintf(stderr, "Error: Invalid key '%s'\n", argv[1]);+ return 1;+ }++ // Log what we're listening for+ fprintf(stderr, "Listening for: %s (VK=0x%02X, Ctrl=%d, Alt=%d, Shift=%d)\n",+ argv[1], g_targetVk, g_requireCtrl, g_requireAlt, g_requireShift);++ // Set up console handler for clean shutdown+ SetConsoleCtrlHandler(ConsoleHandler, TRUE);++ // Install the low-level keyboard hook+ g_hook = SetWindowsHookEx(WH_KEYBOARD_LL, LowLevelKeyboardProc, NULL, 0);+ if (!g_hook) {+ fprintf(stderr, "Error: Failed to install keyboard hook (error %lu)\n", GetLastError());+ return 1;+ }++ // Signal that we're ready+ printf("READY\n");+ fflush(stdout);++ // Message loop - required for low-level hooks to work+ MSG msg;+ while (GetMessage(&msg, NULL, 0, 0) > 0) {+ TranslateMessage(&msg);+ DispatchMessage(&msg);+ }++ UnhookWindowsHookEx(g_hook);+ return 0;+}diff --git a/scripts/build-windows-key-listener.js b/scripts/build-windows-key-listener.jsnew file mode 100644index 000000000..942da9e5c--- /dev/null+++ b/scripts/build-windows-key-listener.js@@ -0,0 +1,202 @@+#!/usr/bin/env node+/**+ * Ensures the Windows key listener 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) {+ // Only needed on Windows+ process.exit(0);+}++const projectRoot = path.resolve(__dirname, "..");+const cSource = path.join(projectRoot, "resources", "windows-key-listener.c");+const outputDir = path.join(projectRoot, "resources", "bin");+const outputBinary = path.join(outputDir, "windows-key-listener.exe");++function log(message) {+ console.log(`[windows-key-listener] ${message}`);+}++function ensureDir(dirPath) {+ if (!fs.existsSync(dirPath)) {+ fs.mkdirSync(dirPath, { recursive: true });+ }+}++// Check if binary exists and is up-to-date+function isBinaryUpToDate() {+ if (!fs.existsSync(outputBinary)) {+ return false;+ }++ // If source doesn't exist, can't check if rebuild needed - assume binary is good+ 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;+ }+}++// Try to download prebuilt binary+async function tryDownload() {+ log("Attempting to download prebuilt binary...");++ const downloadScript = path.join(__dirname, "download-windows-key-listener.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;+}++/**+ * Quote a path for use in shell commands on Windows.+ * @param {string} p - Path to quote+ * @returns {string} - Quoted path safe for shell use+ */+function quotePath(p) {+ // Use double quotes and escape any existing quotes+ return `"${p.replace(/"/g, '\\"')}"`;+}++// Try to compile locally+function tryCompile() {+ if (!fs.existsSync(cSource)) {+ log("C source not found, cannot compile locally");+ return false;+ }++ log("Attempting local compilation...");++ // For MSVC, we need to use a command string because /Fe: doesn't work well with spawn args+ // For GCC/Clang, we can use shell: false with proper args array+ const compilers = [+ // MSVC (Visual Studio) - uses command string due to /Fe: syntax+ {+ name: "MSVC",+ check: { command: "cl", args: [] },+ useShell: true,+ getCommand: () =>+ `cl /O2 /nologo ${quotePath(cSource)} /Fe:${quotePath(outputBinary)} user32.lib`,+ },+ // MinGW-w64 - can use shell: false+ {+ name: "MinGW-w64",+ check: { command: "gcc", args: ["--version"] },+ useShell: false,+ command: "gcc",+ args: ["-O2", "-mwindows", cSource, "-o", outputBinary, "-luser32"],+ },+ // Clang (LLVM) - can use shell: false+ {+ name: "Clang",+ check: { command: "clang", args: ["--version"] },+ useShell: false,+ command: "clang",+ args: ["-O2", cSource, "-o", outputBinary, "-luser32"],+ },+ ];++ for (const compiler of compilers) {+ log(`Trying ${compiler.name}...`);++ // Check if compiler is available+ 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);++ // Check if rebuild is needed+ if (isBinaryUpToDate()) {+ log("Binary is up to date, skipping build");+ return;+ }++ // Try download first, then compile+ const downloaded = await tryDownload();+ if (downloaded) {+ return;+ }++ const compiled = tryCompile();+ if (compiled) {+ return;+ }++ // 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.");+}++main().catch((error) => {+ console.error("[windows-key-listener] Unexpected error:", error);+ // Don't fail the build+});diff --git a/scripts/download-llama-server.js b/scripts/download-llama-server.jsindex 5dd232e5d..6c4e80101 100644--- a/scripts/download-llama-server.js+++ b/scripts/download-llama-server.js@@ -3,7 +3,8 @@ const fs = require("fs");const path = require("path");const {downloadFile,- extractZip,+ extractArchive,+ fetchLatestRelease,findBinaryInDir,parseArgs,setExecutable,@@ -11,29 +12,32 @@ const {} = require("./lib/download-utils");const LLAMA_CPP_REPO = "ggerganov/llama.cpp";-const LLAMA_CPP_VERSION = "b4621";+// Version can be pinned via environment variable for reproducible builds+const VERSION_OVERRIDE = process.env.LLAMA_CPP_VERSION || null;++// Asset name patterns to match in the release (version-independent)const BINARIES = {"darwin-arm64": {- zipName: `llama-${LLAMA_CPP_VERSION}-bin-macos-arm64.zip`,+ assetPattern: /^llama-.*-bin-macos-arm64\.tar\.gz$/,binaryPath: "build/bin/llama-server",outputName: "llama-server-darwin-arm64",libPattern: "*.dylib",},"darwin-x64": {- zipName: `llama-${LLAMA_CPP_VERSION}-bin-macos-x64.zip`,+ assetPattern: /^llama-.*-bin-macos-x64\.tar\.gz$/,binaryPath: "build/bin/llama-server",outputName: "llama-server-darwin-x64",libPattern: "*.dylib",},"win32-x64": {- zipName: `llama-${LLAMA_CPP_VERSION}-bin-win-avx2-x64.zip`,+ assetPattern: /^llama-.*-bin-win-cpu-x64\.zip$/,binaryPath: "build/bin/llama-server.exe",outputName: "llama-server-win32-x64.exe",libPattern: "*.dll",},"linux-x64": {- zipName: `llama-${LLAMA_CPP_VERSION}-bin-ubuntu-x64.zip`,+ assetPattern: /^llama-.*-bin-ubuntu-x64\.tar\.gz$/,binaryPath: "build/bin/llama-server",outputName: "llama-server-linux-x64",libPattern: "*.so*",@@ -42,8 +46,22 @@ const BINARIES = {const BIN_DIR = path.join(__dirname, "..", "resources", "bin");-function getDownloadUrl(zipName) {- return `https://github.com/${LLAMA_CPP_REPO}/releases/download/${LLAMA_CPP_VERSION}/${zipName}`;+// Cache the release info to avoid multiple API calls+let cachedRelease = null;++async function getRelease() {+ if (cachedRelease) return cachedRelease;++ if (VERSION_OVERRIDE) {+ cachedRelease = await fetchLatestRelease(LLAMA_CPP_REPO, { tagPrefix: VERSION_OVERRIDE });+ } else {+ cachedRelease = await fetchLatestRelease(LLAMA_CPP_REPO);+ }+ return cachedRelease;+}++function findAsset(release, pattern) {+ return release?.assets?.find((a) => pattern.test(a.name));}function findLibrariesInDir(dir, pattern, maxDepth = 5, currentDepth = 0) {@@ -78,7 +96,7 @@ function matchesPattern(filename, pattern) {return false;}-async function downloadBinary(platformArch, config) {+async function downloadBinary(platformArch, config, release, isForce = false) {if (!config) {console.log(` ${platformArch}: Not supported`);return false;@@ -86,22 +104,27 @@ async function downloadBinary(platformArch, config) {const outputPath = path.join(BIN_DIR, config.outputName);- if (fs.existsSync(outputPath)) {- console.log(` ${platformArch}: Already exists, skipping`);+ if (fs.existsSync(outputPath) && !isForce) {+ console.log(` ${platformArch}: Already exists (use --force to re-download)`);return true;}- const url = getDownloadUrl(config.zipName);- console.log(` ${platformArch}: Downloading from ${url}`);+ const asset = findAsset(release, config.assetPattern);+ if (!asset) {+ console.error(` ${platformArch}: No matching asset found for pattern ${config.assetPattern}`);+ return false;+ }++ console.log(` ${platformArch}: Downloading from ${asset.url}`);- const zipPath = path.join(BIN_DIR, config.zipName);+ const zipPath = path.join(BIN_DIR, asset.name);try {- await downloadFile(url, zipPath);+ await downloadFile(asset.url, zipPath);const extractDir = path.join(BIN_DIR, `temp-llama-${platformArch}`);fs.mkdirSync(extractDir, { recursive: true });- extractZip(zipPath, extractDir);+ extractArchive(zipPath, extractDir);const binaryName = path.basename(config.binaryPath);let binaryPath = path.join(extractDir, config.binaryPath);@@ -147,7 +170,21 @@ async function downloadBinary(platformArch, config) {}async function main() {- console.log(`\nDownloading llama-server binaries (${LLAMA_CPP_VERSION})...\n`);+ if (VERSION_OVERRIDE) {+ console.log(`\n[llama-server] Using pinned version: ${VERSION_OVERRIDE}`);+ } else {+ console.log("\n[llama-server] Fetching latest release...");+ }+ const release = await getRelease();++ if (!release) {+ console.error(`[llama-server] Could not fetch release from ${LLAMA_CPP_REPO}`);+ console.log(`\nMake sure release exists: https://github.com/${LLAMA_CPP_REPO}/releases`);+ process.exitCode = 1;+ return;+ }++ console.log(`\nDownloading llama-server binaries (${release.tag})...\n`);fs.mkdirSync(BIN_DIR, { recursive: true });@@ -161,7 +198,7 @@ async function main() {}console.log(`Downloading for target platform (${args.platformArch}):`);- const ok = await downloadBinary(args.platformArch, BINARIES[args.platformArch]);+ 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;@@ -174,7 +211,7 @@ async function main() {} else {console.log("Downloading binaries for all platforms:");for (const platformArch of Object.keys(BINARIES)) {- await downloadBinary(platformArch, BINARIES[platformArch]);+ await downloadBinary(platformArch, BINARIES[platformArch], release, args.isForce);}}@@ -189,7 +226,7 @@ async function main() {});} else {console.log("No binaries downloaded yet.");- console.log(`\nCheck: https://github.com/${LLAMA_CPP_REPO}/releases/tag/${LLAMA_CPP_VERSION}`);+ console.log(`\nMake sure release exists: https://github.com/${LLAMA_CPP_REPO}/releases`);}}diff --git a/scripts/download-nircmd.js b/scripts/download-nircmd.jsindex 509ee88f5..5af71e375 100644--- a/scripts/download-nircmd.js+++ b/scripts/download-nircmd.js@@ -9,124 +9,14 @@* License: Free for non-commercial use*/-const https = require("https");const fs = require("fs");const path = require("path");-const { execSync } = require("child_process");+const { downloadFile, extractZip } = require("./lib/download-utils");const NIRCMD_URL = "https://www.nirsoft.net/utils/nircmd-x64.zip";const BIN_DIR = path.join(__dirname, "..", "resources", "bin");const NIRCMD_PATH = path.join(BIN_DIR, "nircmd.exe");-const REQUEST_TIMEOUT = 30000; // 30 seconds-const MAX_RETRIES = 3;-const RETRY_DELAY = 2000;--function sleep(ms) {- return new Promise((resolve) => setTimeout(resolve, ms));-}--function downloadFile(url, dest, retryCount = 0) {- return new Promise((resolve, reject) => {- const file = fs.createWriteStream(dest);- let activeRequest = null;-- const cleanup = () => {- if (activeRequest) {- activeRequest.destroy();- activeRequest = null;- }- file.close();- };-- const request = (currentUrl, redirectCount = 0) => {- if (redirectCount > 5) {- cleanup();- reject(new Error("Too many redirects"));- return;- }-- activeRequest = https.get(currentUrl, (response) => {- if (response.statusCode === 302 || response.statusCode === 301) {- const redirectUrl = response.headers.location;- if (!redirectUrl) {- cleanup();- reject(new Error("Redirect without location header"));- return;- }- request(redirectUrl, redirectCount + 1);- return;- }-- if (response.statusCode !== 200) {- cleanup();- reject(new Error(`Failed to download: HTTP ${response.statusCode}`));- return;- }-- const total = parseInt(response.headers["content-length"], 10);- let downloaded = 0;-- response.on("data", (chunk) => {- downloaded += chunk.length;- const pct = total ? Math.round((downloaded / total) * 100) : 0;- process.stdout.write(`\r Downloading: ${pct}%`);- });-- response.on("error", (err) => {- cleanup();- reject(err);- });-- response.pipe(file);- file.on("finish", () => {- file.close();- console.log(" Done");- resolve();- });-- file.on("error", (err) => {- cleanup();- reject(err);- });- });-- activeRequest.on("error", (err) => {- cleanup();- reject(err);- });-- activeRequest.setTimeout(REQUEST_TIMEOUT, () => {- cleanup();- reject(new Error("Connection timed out"));- });- };-- request(url);- }).catch(async (error) => {- if (retryCount < MAX_RETRIES) {- console.log(`\n Retry ${retryCount + 1}/${MAX_RETRIES}: ${error.message}`);- await sleep(RETRY_DELAY);- if (fs.existsSync(dest)) {- fs.unlinkSync(dest);- }- return downloadFile(url, dest, retryCount + 1);- }- throw error;- });-}--function extractZip(zipPath, destDir) {- if (process.platform === "win32") {- execSync(- `powershell -command "Expand-Archive -Path '${zipPath}' -DestinationPath '${destDir}' -Force"`,- { stdio: "inherit" }- );- } else {- execSync(`unzip -o "${zipPath}" -d "${destDir}"`, { stdio: "inherit" });- }-}-async function main() {// Skip if not Windows and not building for all platformsif (process.platform !== "win32" && !process.argv.includes("--all")) {@@ -170,7 +60,6 @@ async function main() {// Cleanupfs.rmSync(extractDir, { recursive: true, force: true });fs.unlinkSync(zipPath);-} catch (error) {console.error(` ✗ Failed to download nircmd.exe: ${error.message}\n`);if (fs.existsSync(zipPath)) fs.unlinkSync(zipPath);diff --git a/scripts/download-whisper-cpp.js b/scripts/download-whisper-cpp.jsindex 8e83a96c3..68fb3a2d2 100644--- a/scripts/download-whisper-cpp.js+++ b/scripts/download-whisper-cpp.js@@ -4,13 +4,16 @@ const path = require("path");const {downloadFile,extractZip,+ fetchLatestRelease,parseArgs,setExecutable,cleanupFiles,} = require("./lib/download-utils");const WHISPER_CPP_REPO = "OpenWhispr/whisper.cpp";-const WHISPER_CPP_VERSION = "0.0.6";++// Version can be pinned via environment variable for reproducible builds+const VERSION_OVERRIDE = process.env.WHISPER_CPP_VERSION || null;const BINARIES = {"darwin-arm64": {@@ -37,11 +40,26 @@ const BINARIES = {const BIN_DIR = path.join(__dirname, "..", "resources", "bin");-function getDownloadUrl(zipName) {- return `https://github.com/${WHISPER_CPP_REPO}/releases/download/${WHISPER_CPP_VERSION}/${zipName}`;+// Cache the release info to avoid multiple API calls+let cachedRelease = null;++async function getRelease() {+ if (cachedRelease) return cachedRelease;++ if (VERSION_OVERRIDE) {+ cachedRelease = await fetchLatestRelease(WHISPER_CPP_REPO, { tagPrefix: VERSION_OVERRIDE });+ } else {+ cachedRelease = await fetchLatestRelease(WHISPER_CPP_REPO);+ }+ return cachedRelease;+}++function getDownloadUrl(release, zipName) {+ const asset = release?.assets?.find((a) => a.name === zipName);+ return asset?.url || null;}-async function downloadBinary(platformArch, config) {+async function downloadBinary(platformArch, config, release, isForce = false) {if (!config) {console.log(` [server] ${platformArch}: Not supported`);return false;@@ -49,12 +67,16 @@ async function downloadBinary(platformArch, config) {const outputPath = path.join(BIN_DIR, config.outputName);- if (fs.existsSync(outputPath)) {- console.log(` [server] ${platformArch}: Already exists, skipping`);+ if (fs.existsSync(outputPath) && !isForce) {+ console.log(` [server] ${platformArch}: Already exists (use --force to re-download)`);return true;}- const url = getDownloadUrl(config.zipName);+ const url = getDownloadUrl(release, config.zipName);+ if (!url) {+ console.error(` [server] ${platformArch}: Asset ${config.zipName} not found in release`);+ return false;+ }console.log(` [server] ${platformArch}: Downloading from ${url}`);const zipPath = path.join(BIN_DIR, config.zipName);@@ -87,7 +109,21 @@ async function downloadBinary(platformArch, config) {}async function main() {- console.log(`\nDownloading whisper-server binaries (${WHISPER_CPP_VERSION})...\n`);+ if (VERSION_OVERRIDE) {+ console.log(`\n[whisper-server] Using pinned version: ${VERSION_OVERRIDE}`);+ } else {+ console.log("\n[whisper-server] Fetching latest release...");+ }+ const release = await getRelease();++ if (!release) {+ console.error(`[whisper-server] Could not fetch release from ${WHISPER_CPP_REPO}`);+ console.log(`\nMake sure release exists: https://github.com/${WHISPER_CPP_REPO}/releases`);+ process.exitCode = 1;+ return;+ }++ console.log(`\nDownloading whisper-server binaries (${release.tag})...\n`);fs.mkdirSync(BIN_DIR, { recursive: true });@@ -101,7 +137,7 @@ async function main() {}console.log(`Downloading for target platform (${args.platformArch}):`);- const ok = await downloadBinary(args.platformArch, BINARIES[args.platformArch]);+ 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;@@ -114,7 +150,7 @@ async function main() {} else {console.log("Downloading binaries for all platforms:");for (const platformArch of Object.keys(BINARIES)) {- await downloadBinary(platformArch, BINARIES[platformArch]);+ await downloadBinary(platformArch, BINARIES[platformArch], release, args.isForce);}}diff --git a/scripts/download-windows-key-listener.js b/scripts/download-windows-key-listener.jsnew file mode 100644index 000000000..5e9e92b88--- /dev/null+++ b/scripts/download-windows-key-listener.js@@ -0,0 +1,120 @@+#!/usr/bin/env node+/**+ * Downloads prebuilt Windows key listener binary from GitHub releases.+ * Used for Push-to-Talk functionality on Windows.+ *+ * Usage:+ * node scripts/download-windows-key-listener.js [--force]+ *+ * Options:+ * --force Re-download even if binary already exists+ */++const fs = require("fs");+const path = require("path");+const { downloadFile, extractZip, fetchLatestRelease, setExecutable } = require("./lib/download-utils");++const REPO = "HeroTools/open-whispr";+const TAG_PREFIX = "windows-key-listener-v";+const ZIP_NAME = "windows-key-listener-win32-x64.zip";+const BINARY_NAME = "windows-key-listener.exe";++// Version can be pinned via environment variable for reproducible builds+const VERSION_OVERRIDE = process.env.WINDOWS_KEY_LISTENER_VERSION || null;++const BIN_DIR = path.join(__dirname, "..", "resources", "bin");++async function main() {+ // Only needed on Windows+ if (process.platform !== "win32") {+ console.log("[windows-key-listener] Skipping download (not Windows)");+ return;+ }++ const forceDownload = process.argv.includes("--force");+ const outputPath = path.join(BIN_DIR, BINARY_NAME);++ // Check if already exists+ if (fs.existsSync(outputPath) && !forceDownload) {+ console.log("[windows-key-listener] Already exists (use --force to re-download)");+ console.log(` ${outputPath}`);+ return;+ }++ // Fetch release (pinned version or latest)+ if (VERSION_OVERRIDE) {+ console.log(`\n[windows-key-listener] Using pinned version: ${VERSION_OVERRIDE}`);+ } else {+ console.log("\n[windows-key-listener] Fetching latest release...");+ }+ const tagToFind = VERSION_OVERRIDE || TAG_PREFIX;+ const release = await fetchLatestRelease(REPO, { tagPrefix: tagToFind });++ 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)");+ return;+ }++ // Find the zip asset+ 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(", "));+ return;+ }++ console.log(`\nDownloading Windows key listener (${release.tag})...\n`);++ // Ensure bin directory exists+ fs.mkdirSync(BIN_DIR, { recursive: true });++ const zipPath = path.join(BIN_DIR, ZIP_NAME);+ console.log(` Downloading from: ${zipAsset.url}`);++ try {+ await downloadFile(zipAsset.url, zipPath);++ // Extract zip+ const extractDir = path.join(BIN_DIR, "temp-windows-key-listener");+ fs.mkdirSync(extractDir, { recursive: true });++ console.log(" Extracting...");+ extractZip(zipPath, extractDir);++ // Find and copy the binary+ const binaryPath = path.join(extractDir, BINARY_NAME);+ if (fs.existsSync(binaryPath)) {+ fs.copyFileSync(binaryPath, outputPath);+ setExecutable(outputPath);+ console.log(` Extracted to: ${BINARY_NAME}`);+ } else {+ throw new Error(`Binary not found in archive: ${BINARY_NAME}`);+ }++ // Cleanup+ fs.rmSync(extractDir, { recursive: true, force: true });+ if (fs.existsSync(zipPath)) {+ fs.unlinkSync(zipPath);+ }++ const stats = fs.statSync(outputPath);+ 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}`);++ // Cleanup on failure+ if (fs.existsSync(zipPath)) {+ fs.unlinkSync(zipPath);+ }++ // 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");+ }+}++main().catch((error) => {+ console.error("[windows-key-listener] Unexpected error:", error);+ // Don't fail the build+});diff --git a/scripts/lib/download-utils.js b/scripts/lib/download-utils.jsindex 9eb3ad092..960c271d4 100644--- a/scripts/lib/download-utils.js+++ b/scripts/lib/download-utils.js@@ -8,6 +8,127 @@ const MAX_RETRIES = 3;const RETRY_DELAY = 2000;const MAX_REDIRECTS = 5;+/**+ * Fetch JSON from a URL with proper error handling.+ * @param {string} url - URL to fetch+ * @param {number} [redirectCount=0] - Current redirect count (internal use)+ * @returns {Promise<object>} - Parsed JSON response+ */+function fetchJson(url, redirectCount = 0) {+ return new Promise((resolve, reject) => {+ if (redirectCount > MAX_REDIRECTS) {+ reject(new Error("Too many redirects"));+ return;+ }++ const headers = {+ "User-Agent": "OpenWhispr-Downloader",+ Accept: "application/vnd.github+json",+ };++ // Use GitHub token if available (increases rate limit from 60 to 5000/hour)+ const token = process.env.GITHUB_TOKEN || process.env.GH_TOKEN;+ if (token) {+ headers.Authorization = `Bearer ${token}`;+ }++ const options = {+ headers,+ timeout: REQUEST_TIMEOUT,+ };++ https+ .get(url, options, (res) => {+ if (res.statusCode === 301 || res.statusCode === 302) {+ const redirectUrl = res.headers.location;+ if (!redirectUrl) {+ reject(new Error("Redirect without location header"));+ return;+ }+ fetchJson(redirectUrl, redirectCount + 1).then(resolve).catch(reject);+ return;+ }++ if (res.statusCode !== 200) {+ reject(new Error(`HTTP ${res.statusCode}`));+ return;+ }++ let data = "";+ res.on("data", (chunk) => (data += chunk));+ res.on("end", () => {+ try {+ resolve(JSON.parse(data));+ } catch (e) {+ reject(new Error(`Failed to parse JSON: ${e.message}`));+ }+ });+ res.on("error", reject);+ })+ .on("error", reject)+ .on("timeout", () => reject(new Error("Request timeout")));+ });+}++/**+ * Fetch the latest release from a GitHub repository.+ * @param {string} repo - Repository in "owner/repo" format+ * @param {object} options - Options+ * @param {string} [options.tagPrefix] - Only match releases with this tag prefix (e.g., "windows-key-listener-v")+ * @param {boolean} [options.includePrerelease=false] - Include prerelease versions+ * @returns {Promise<{tag: string, assets: Array<{name: string, url: string}>, url: string} | null>}+ */+async function fetchLatestRelease(repo, options = {}) {+ const { tagPrefix, includePrerelease = false } = options;++ try {+ // If no tag prefix, use the simple /latest endpoint+ if (!tagPrefix) {+ const url = `https://api.github.com/repos/${repo}/releases/latest`;+ const release = await fetchJson(url);+ return formatRelease(release);+ }++ // Otherwise, fetch all releases and filter by prefix+ const url = `https://api.github.com/repos/${repo}/releases?per_page=50`;+ const releases = await fetchJson(url);++ if (!Array.isArray(releases)) {+ return null;+ }++ // Find the latest release matching the prefix+ for (const release of releases) {+ if (release.draft) continue;+ if (!includePrerelease && release.prerelease) continue;+ if (release.tag_name && release.tag_name.startsWith(tagPrefix)) {+ return formatRelease(release);+ }+ }++ return null;+ } catch (error) {+ console.error(` Failed to fetch latest release for ${repo}: ${error.message}`);+ return null;+ }+}++/**+ * Format a GitHub release response into a simplified object.+ * @param {object} release - GitHub release API response+ * @returns {{tag: string, assets: Array<{name: string, url: string}>, url: string}}+ */+function formatRelease(release) {+ return {+ tag: release.tag_name,+ url: release.html_url,+ assets: (release.assets || []).map((asset) => ({+ name: asset.name,+ url: asset.browser_download_url,+ })),+ };+}+function sleep(ms) {return new Promise((resolve) => setTimeout(resolve, ms));}@@ -117,6 +238,18 @@ function extractZip(zipPath, destDir) {}}+function extractTarGz(tarPath, destDir) {+ execSync(`tar -xzf "${tarPath}" -C "${destDir}"`, { stdio: "inherit" });+}++function extractArchive(archivePath, destDir) {+ if (archivePath.endsWith(".tar.gz") || archivePath.endsWith(".tgz")) {+ extractTarGz(archivePath, destDir);+ } else {+ extractZip(archivePath, destDir);+ }+}+function findBinaryInDir(dir, binaryName, maxDepth = 5, currentDepth = 0) {if (currentDepth >= maxDepth) return null;@@ -157,6 +290,7 @@ function parseArgs() {platformArch: `${targetPlatform}-${targetArch}`,isCurrent: args.includes("--current"),isAll: args.includes("--all"),+ isForce: args.includes("--force"),shouldCleanup: args.includes("--clean") ||process.env.CI === "true" ||process.env.GITHUB_ACTIONS === "true",@@ -182,13 +316,11 @@ function cleanupFiles(binDir, prefix, keepPrefix) {module.exports = {downloadFile,+ extractArchive,extractZip,+ fetchLatestRelease,findBinaryInDir,parseArgs,setExecutable,cleanupFiles,- sleep,- REQUEST_TIMEOUT,- MAX_RETRIES,- RETRY_DELAY,};diff --git a/scripts/run-electron.js b/scripts/run-electron.jsnew file mode 100644index 000000000..5843cea3c--- /dev/null+++ b/scripts/run-electron.js@@ -0,0 +1,42 @@+#!/usr/bin/env node+/**+ * Wrapper script to run Electron with proper environment.+ * This unsets ELECTRON_RUN_AS_NODE which can be inherited from parent processes+ * (e.g., when running from Claude Code or other Node.js-based tools).+ */++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');++// Get the app directory (parent of scripts directory)+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);++// Spawn electron with the cleaned environment+const child = spawn(electronPath, [appDir, ...args], {+ stdio: 'inherit',+ env: process.env,+ cwd: appDir,+});++child.on('close', (code) => {+ process.exit(code || 0);+});++child.on('error', (err) => {+ console.error('[run-electron] Failed to start Electron:', err);+ process.exit(1);+});diff --git a/src/components/SettingsModal.tsx b/src/components/SettingsModal.tsxindex 0c522caed..ae5695d7f 100644--- a/src/components/SettingsModal.tsx+++ b/src/components/SettingsModal.tsx@@ -1,5 +1,5 @@import React from "react";-import { Settings, Mic, Brain, User, Sparkles, Wrench } from "lucide-react";+import { Settings, Mic, Brain, User, Sparkles, Wrench, BookOpen } from "lucide-react";import SidebarModal, { SidebarItem } from "./ui/SidebarModal";import SettingsPage, { SettingsSectionType } from "./SettingsPage";@@ -12,6 +12,7 @@ export default function SettingsModal({ open, onOpenChange }: SettingsModalPropsconst sidebarItems: SidebarItem<SettingsSectionType>[] = [{ id: "general", label: "General", icon: Settings },{ id: "transcription", label: "Transcription Mode", icon: Mic },+ { id: "dictionary", label: "Custom Dictionary", icon: BookOpen },{ id: "aiModels", label: "AI Text Cleanup", icon: Brain },{ id: "agentConfig", label: "Agent Configuration", icon: User },{ id: "prompts", label: "AI Prompts", icon: Sparkles },diff --git a/src/components/SettingsPage.tsx b/src/components/SettingsPage.tsxindex 3c3e739f0..bcd37c71b 100644--- a/src/components/SettingsPage.tsx+++ b/src/components/SettingsPage.tsx@@ -1,4 +1,4 @@-import React, { useState, useCallback, useEffect, useRef } from "react";+import React, { useState, useCallback, useEffect, useRef, useMemo } from "react";import { Button } from "./ui/button";import { Input } from "./ui/input";import { RefreshCw, Download, Command, Mic, Shield, FolderOpen } from "lucide-react";@@ -27,6 +27,7 @@ import DeveloperSection from "./DeveloperSection";export type SettingsSectionType =| "general"| "transcription"+ | "dictionary"| "aiModels"| "agentConfig"| "prompts"@@ -54,6 +55,7 @@ export default function SettingsPage({ activeSection = "general" }: SettingsPagecloudTranscriptionModel,cloudTranscriptionBaseUrl,cloudReasoningBaseUrl,+ customDictionary,useReasoningModel,reasoningModel,reasoningProvider,@@ -75,6 +77,7 @@ export default function SettingsPage({ activeSection = "general" }: SettingsPagesetCloudTranscriptionModel,setCloudTranscriptionBaseUrl,setCloudReasoningBaseUrl,+ setCustomDictionary,setUseReasoningModel,setReasoningModel,setReasoningProvider,@@ -137,6 +140,72 @@ export default function SettingsPage({ activeSection = "general" }: SettingsPage});const [isUsingGnomeHotkeys, setIsUsingGnomeHotkeys] = useState(false);+ // Platform detection for conditional features+ const platform = useMemo(() => {+ if (typeof window !== "undefined" && window.electronAPI?.getPlatform) {+ return window.electronAPI.getPlatform();+ }+ return "linux"; // Safe fallback+ }, []);++ // Custom dictionary state+ const [newDictionaryWord, setNewDictionaryWord] = useState("");++ const handleAddDictionaryWord = useCallback(() => {+ const word = newDictionaryWord.trim();+ if (word && !customDictionary.includes(word)) {+ setCustomDictionary([...customDictionary, word]);+ setNewDictionaryWord("");+ }+ }, [newDictionaryWord, customDictionary, setCustomDictionary]);++ const handleRemoveDictionaryWord = useCallback(+ (wordToRemove: string) => {+ setCustomDictionary(customDictionary.filter((word) => word !== wordToRemove));+ },+ [customDictionary, setCustomDictionary]+ );++ // Auto-start state+ const [autoStartEnabled, setAutoStartEnabled] = useState(false);+ const [autoStartLoading, setAutoStartLoading] = useState(true);++ // Load auto-start state on mount (not supported on Linux)+ useEffect(() => {+ if (platform === "linux") {+ setAutoStartLoading(false);+ return;+ }+ const loadAutoStart = async () => {+ if (window.electronAPI?.getAutoStartEnabled) {+ try {+ const enabled = await window.electronAPI.getAutoStartEnabled();+ setAutoStartEnabled(enabled);+ } catch (error) {+ console.error("Failed to get auto-start status:", error);+ }+ }+ setAutoStartLoading(false);+ };+ loadAutoStart();+ }, [platform]);++ const handleAutoStartChange = async (enabled: boolean) => {+ if (window.electronAPI?.setAutoStartEnabled) {+ try {+ setAutoStartLoading(true);+ const result = await window.electronAPI.setAutoStartEnabled(enabled);+ if (result.success) {+ setAutoStartEnabled(enabled);+ }+ } catch (error) {+ console.error("Failed to set auto-start:", error);+ } finally {+ setAutoStartLoading(false);+ }+ }+ };+useEffect(() => {let mounted = true;@@ -474,6 +543,39 @@ export default function SettingsPage({ activeSection = "general" }: SettingsPage)}</div>+ {/* Auto-start is only supported on macOS and Windows */}+ {platform !== "linux" && (+ <div className="border-t pt-8">+ <div>+ <h3 className="text-lg font-semibold text-gray-900 mb-2">Startup</h3>+ <p className="text-sm text-gray-600 mb-6">+ Control how OpenWhispr starts when you log in.+ </p>+ </div>+ <div className="flex items-center justify-between p-4 bg-gray-50 rounded-lg">+ <div>+ <p className="font-medium text-gray-900">Launch at Login</p>+ <p className="text-sm text-gray-600">+ Automatically start OpenWhispr when you log in to your computer+ </p>+ </div>+ <button+ onClick={() => handleAutoStartChange(!autoStartEnabled)}+ disabled={autoStartLoading}+ className={`relative inline-flex h-6 w-11 items-center rounded-full transition-colors focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2 ${+ autoStartEnabled ? "bg-indigo-600" : "bg-gray-200"+ } ${autoStartLoading ? "opacity-50 cursor-not-allowed" : ""}`}+ >+ <span+ className={`inline-block h-4 w-4 transform rounded-full bg-white transition-transform ${+ autoStartEnabled ? "translate-x-6" : "translate-x-1"+ }`}+ />+ </button>+ </div>+ </div>+ )}+<div className="border-t pt-8"><div><h3 className="text-lg font-semibold text-gray-900 mb-2">Permissions</h3>@@ -673,6 +775,81 @@ export default function SettingsPage({ activeSection = "general" }: SettingsPage</div>);+ case "dictionary":+ return (+ <div className="space-y-6">+ <div>+ <h3 className="text-lg font-semibold text-gray-900 mb-2">Custom Dictionary</h3>+ <p className="text-sm text-gray-600 mb-6">+ Add words, names, or technical terms that OpenWhispr should recognize during+ transcription. These words are used as hints to improve accuracy.+ </p>+ </div>++ <div className="space-y-4 p-4 bg-gray-50 border border-gray-200 rounded-xl">+ <h4 className="font-medium text-gray-900">Add Words</h4>+ <div className="flex gap-2">+ <Input+ placeholder="Enter a word or phrase..."+ value={newDictionaryWord}+ onChange={(e) => setNewDictionaryWord(e.target.value)}+ onKeyDown={(e) => {+ if (e.key === "Enter") {+ handleAddDictionaryWord();+ }+ }}+ className="flex-1"+ />+ <Button onClick={handleAddDictionaryWord} disabled={!newDictionaryWord.trim()}>+ Add+ </Button>+ </div>+ <p className="text-xs text-gray-500">+ Press Enter or click Add to add the word to your dictionary.+ </p>+ </div>++ {customDictionary.length > 0 && (+ <div className="space-y-3">+ <h4 className="font-medium text-gray-900">+ Your Dictionary ({customDictionary.length} words)+ </h4>+ <div className="flex flex-wrap gap-2">+ {customDictionary.map((word) => (+ <span+ key={word}+ className="inline-flex items-center gap-1 px-3 py-1 bg-indigo-100 text-indigo-800 rounded-full text-sm"+ >+ {word}+ <button+ onClick={() => handleRemoveDictionaryWord(word)}+ className="ml-1 text-indigo-600 hover:text-indigo-900 font-bold"+ title="Remove word"+ >+ ×+ </button>+ </span>+ ))}+ </div>+ </div>+ )}++ <div className="p-4 bg-blue-50 border border-blue-200 rounded-xl">+ <h4 className="font-medium text-blue-900 mb-2">How it works</h4>+ <p className="text-sm text-blue-800 mb-3">+ Words in your custom dictionary are provided as context to the speech recognition+ model. This helps improve accuracy for uncommon names, technical jargon, brand+ names, or any words that are frequently misrecognized.+ </p>+ <p className="text-sm text-blue-800">+ <strong>Tip:</strong> For difficult words, try adding context phrases like "The word+ is Synty" alongside the word itself. Adding related terms (e.g., "Synty" and+ "SyntyStudios") also helps the model understand the intended spelling.+ </p>+ </div>+ </div>+ );+case "aiModels":return (<div className="space-y-6">diff --git a/src/components/ui/HotkeyInput.tsx b/src/components/ui/HotkeyInput.tsxindex 4fdbcbbe2..cafc183a1 100644--- a/src/components/ui/HotkeyInput.tsx+++ b/src/components/ui/HotkeyInput.tsx@@ -71,6 +71,19 @@ const CODE_TO_KEY: Record<string, string> = {F10: "F10",F11: "F11",F12: "F12",+ // Extended function keys (F13-F24)+ F13: "F13",+ F14: "F14",+ F15: "F15",+ F16: "F16",+ F17: "F17",+ F18: "F18",+ F19: "F19",+ F20: "F20",+ F21: "F21",+ F22: "F22",+ F23: "F23",+ F24: "F24",// Arrow keysArrowUp: "Up",ArrowDown: "Down",@@ -167,6 +180,7 @@ export function HotkeyInput({const [isCapturing, setIsCapturing] = useState(false);const [activeModifiers, setActiveModifiers] = useState<Set<string>>(new Set());const containerRef = useRef<HTMLDivElement>(null);+ const lastCapturedHotkeyRef = useRef<string | null>(null);const isMac = typeof navigator !== "undefined" && /Mac|Darwin/.test(navigator.platform);const handleKeyDown = useCallback(@@ -183,6 +197,7 @@ export function HotkeyInput({const hotkey = mapKeyboardEventToHotkey(e.nativeEvent);if (hotkey) {+ lastCapturedHotkeyRef.current = hotkey;onChange(hotkey);setIsCapturing(false);setActiveModifiers(new Set());@@ -206,7 +221,8 @@ export function HotkeyInput({const handleBlur = useCallback(() => {setIsCapturing(false);setActiveModifiers(new Set());- window.electronAPI?.setHotkeyListeningMode?.(false);+ window.electronAPI?.setHotkeyListeningMode?.(false, lastCapturedHotkeyRef.current);+ lastCapturedHotkeyRef.current = null;onBlur?.();}, [onBlur]);@@ -218,7 +234,7 @@ export function HotkeyInput({useEffect(() => {return () => {- window.electronAPI?.setHotkeyListeningMode?.(false);+ window.electronAPI?.setHotkeyListeningMode?.(false, null);};}, []);@@ -226,6 +242,7 @@ export function HotkeyInput({if (!isCapturing || !isMac) return;const dispose = window.electronAPI?.onGlobeKeyPressed?.(() => {+ lastCapturedHotkeyRef.current = "GLOBE";onChange("GLOBE");setIsCapturing(false);setActiveModifiers(new Set());diff --git a/src/config/promptData.json b/src/config/promptData.jsonindex b48516e0c..b4afa6741 100644--- a/src/config/promptData.json+++ b/src/config/promptData.json@@ -1,5 +1,6 @@{"UNIFIED_SYSTEM_PROMPT": "You are an AI assistant named \"{{agentName}}\", integrated into a speech-to-text dictation application. Your primary function is to process transcribed speech and output clean, polished, well-formatted text.\n\nCORE RESPONSIBILITY:\nYour job is ALWAYS to clean up transcribed speech. This is your default behavior for every input. Cleanup means:\n- Removing filler words (um, uh, er, like, you know, I mean, so, basically) unless they add genuine meaning\n- Fixing grammar, spelling, and punctuation errors\n- Breaking up run-on sentences with appropriate punctuation\n- Removing false starts, stutters, and accidental word repetitions\n- Correcting obvious speech-to-text transcription errors\n- Maintaining the speaker's natural voice, tone, vocabulary, and intent\n- Preserving technical terms, proper nouns, names, and specialized jargon exactly as spoken\n- Keeping the same level of formality (casual speech stays casual, formal stays formal)\n\nSMART FORMATTING:\nApply intelligent formatting based on content context. Use your judgment to make the output readable and well-structured:\n\nBullet points - Use when the user is listing items:\n- Shopping or grocery lists (\"I need to get eggs, milk, bread...\")\n- To-do items (\"I need to remember to call John, send the report, book the flight...\")\n- Multiple points or ideas (\"There are a few things... first... also... and finally...\")\n- Features, benefits, or options being enumerated\n\nNumbered lists - Use when order or sequence matters:\n- Step-by-step instructions (\"First do this, then do that, finally...\")\n- Ranked items or priorities\n- Processes or procedures\n\nParagraph breaks - Add line breaks between:\n- Distinct topics or ideas\n- Natural transitions in thought\n- Different sections of longer content\n\nEmail formatting - When dictating an email:\n- Greeting on its own line\n- Body paragraphs separated by line breaks\n- Closing and signature on separate lines\n\nSocial media / posts - When dictating content for LinkedIn, Twitter, etc:\n- Break into digestible paragraphs\n- Separate the hook/opening from the main content\n- Use line breaks for emphasis and readability\n\nDo NOT over-format. If someone is dictating a simple sentence or two, just output clean text. Only apply formatting when it genuinely improves readability and matches the content type.\n\nWHEN YOU ARE DIRECTLY ADDRESSED:\nSince your name is \"{{agentName}}\", the user may speak to you directly to give instructions. When you detect that the user is addressing YOU with a command or request, you should:\n1. STILL perform cleanup on the relevant content\n2. ALSO execute the instruction they gave you\n3. Remove your name and the instruction itself from the final output\n4. Output only the resulting processed text\n\nExamples of being directly addressed:\n- \"Hey {{agentName}}, make this sound more professional\"\n- \"{{agentName}}, put this in bullet points\"\n- \"Can you rewrite that more formally, {{agentName}}\"\n- \"{{agentName}} summarize what I just said\"\n\nCRITICAL: NOT EVERY MENTION OF YOUR NAME IS AN INSTRUCTION\nIf your name appears but the user is NOT giving you a command, treat it as normal content to clean up:\n- \"I was telling {{agentName}} about the project yesterday\" → Clean this up, keep your name in output\n- \"{{agentName}} is really helpful for dictation\" → Clean this up normally\n- \"My assistant {{agentName}} suggested we try this\" → Clean this up normally\n\nHOW TO TELL THE DIFFERENCE:\n- Direct address typically starts with or includes your name + a verb/action: \"{{agentName}}, make...\", \"Hey {{agentName}}, change...\", \"{{agentName}} please rewrite...\"\n- Talking ABOUT you uses your name as a subject/object in a sentence: \"I told {{agentName}}...\", \"{{agentName}} said...\", \"using {{agentName}} to...\"\n- When genuinely uncertain, default to cleanup-only mode\n\nOUTPUT RULES - THESE ARE ABSOLUTE:\n1. Output ONLY the processed text\n2. NEVER include explanations, commentary, or meta-text\n3. NEVER say things like \"Here's the cleaned up version:\" or \"I've made it more formal:\"\n4. NEVER offer alternatives or ask clarifying questions\n5. NEVER add content that wasn't in the original speech\n6. NEVER use labels, headers, or formatting unless specifically instructed\n7. If the input is empty or just filler words, output nothing\n\nYou are processing transcribed speech, so expect imperfect input. Your goal is to output exactly what the user intended to say, cleaned up and polished, as if they had typed it perfectly themselves.",+ "DICTIONARY_SUFFIX": "\n\nCustom Dictionary (use these exact spellings when they appear in the text): ","LEGACY_PROMPTS": {"agent": "You are {{agentName}}, a helpful AI assistant. Clean up the following dictated text by fixing grammar, punctuation, and formatting. If I give you an instruction, execute it and remove the instruction from the output. Output ONLY the cleaned text:\n\n{{text}}","regular": "Clean up the following dictated text by fixing grammar, punctuation, and formatting. Output ONLY the cleaned text without any explanations, options, or commentary:\n\n{{text}}"diff --git a/src/config/prompts.ts b/src/config/prompts.tsindex f36392c39..9449a7123 100644--- a/src/config/prompts.ts+++ b/src/config/prompts.ts@@ -2,13 +2,14 @@ import promptData from "./promptData.json";export const UNIFIED_SYSTEM_PROMPT = promptData.UNIFIED_SYSTEM_PROMPT;export const LEGACY_PROMPTS = promptData.LEGACY_PROMPTS;+const DICTIONARY_SUFFIX = promptData.DICTIONARY_SUFFIX;export function buildPrompt(text: string, agentName: string | null): string {const name = agentName?.trim() || "Assistant";return UNIFIED_SYSTEM_PROMPT.replace(/\{\{agentName\}\}/g, name).replace(/\{\{text\}\}/g, text);}-export function getSystemPrompt(agentName: string | null): string {+export function getSystemPrompt(agentName: string | null, customDictionary?: string[]): string {const name = agentName?.trim() || "Assistant";let promptTemplate = UNIFIED_SYSTEM_PROMPT;@@ -23,7 +24,13 @@ export function getSystemPrompt(agentName: string | null): string {}}- return promptTemplate.replace(/\{\{agentName\}\}/g, name);+ let prompt = promptTemplate.replace(/\{\{agentName\}\}/g, name);++ if (customDictionary && customDictionary.length > 0) {+ prompt += DICTIONARY_SUFFIX + customDictionary.join(", ");+ }++ return prompt;}export function getUserPrompt(text: string): string {diff --git a/src/helpers/audioManager.js b/src/helpers/audioManager.jsindex 11f28527b..5790857e9 100644--- a/src/helpers/audioManager.js+++ b/src/helpers/audioManager.js@@ -37,6 +37,18 @@ class AudioManager {this.cachedReasoningPreference = null;}+ getCustomDictionaryPrompt() {+ try {+ const raw = localStorage.getItem("customDictionary");+ if (!raw) return null;+ const parsed = JSON.parse(raw);+ if (Array.isArray(parsed) && parsed.length > 0) return parsed.join(", ");+ } catch {+ // ignore parse errors+ }+ return null;+ }+setCallbacks({ onStateChange, onError, onTranscriptionComplete }) {this.onStateChange = onStateChange;this.onError = onError;@@ -90,6 +102,22 @@ class AudioManager {const constraints = await this.getAudioConstraints();const stream = await navigator.mediaDevices.getUserMedia(constraints);+ // Log which microphone is actually being used+ const audioTrack = stream.getAudioTracks()[0];+ if (audioTrack) {+ const settings = audioTrack.getSettings();+ logger.info(+ "Recording started with microphone",+ {+ label: audioTrack.label,+ deviceId: settings.deviceId?.slice(0, 20) + "...",+ sampleRate: settings.sampleRate,+ channelCount: settings.channelCount,+ },+ "audio"+ );+ }+this.mediaRecorder = new MediaRecorder(stream);this.audioChunks = [];this.recordingStartTime = Date.now();@@ -106,6 +134,17 @@ class AudioManager {const audioBlob = new Blob(this.audioChunks, { type: this.recordingMimeType });+ // Debug: Log audio blob info+ logger.info(+ "Recording stopped",+ {+ blobSize: audioBlob.size,+ blobType: audioBlob.type,+ chunksCount: this.audioChunks.length,+ },+ "audio"+ );+const durationSeconds = this.recordingStartTime? (Date.now() - this.recordingStartTime) / 1000: null;@@ -252,6 +291,12 @@ class AudioManager {options.language = language;}+ // Add custom dictionary as initial prompt to help Whisper recognize specific words+ const dictionaryPrompt = this.getCustomDictionaryPrompt();+ if (dictionaryPrompt) {+ options.initialPrompt = dictionaryPrompt;+ }+logger.debug("Local transcription starting",{@@ -872,6 +917,12 @@ class AudioManager {formData.append("language", language);}+ // Add custom dictionary as prompt hint for cloud transcription+ const dictionaryPrompt = this.getCustomDictionaryPrompt();+ if (dictionaryPrompt) {+ formData.append("prompt", dictionaryPrompt);+ }+const shouldStream = this.shouldStreamTranscription(model, provider);if (shouldStream) {formData.append("stream", "true");diff --git a/src/helpers/database.js b/src/helpers/database.jsindex 1f5f3bb98..9d9e8e6dc 100644--- a/src/helpers/database.js+++ b/src/helpers/database.js@@ -28,6 +28,14 @@ class DatabaseManager {)`);+ this.db.exec(`+ CREATE TABLE IF NOT EXISTS custom_dictionary (+ id INTEGER PRIMARY KEY AUTOINCREMENT,+ word TEXT NOT NULL UNIQUE,+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP+ )+ `);+return true;} catch (error) {console.error("Database initialization failed:", error.message);@@ -96,6 +104,43 @@ class DatabaseManager {}}+ getDictionary() {+ try {+ if (!this.db) {+ throw new Error("Database not initialized");+ }+ const stmt = this.db.prepare("SELECT word FROM custom_dictionary ORDER BY id ASC");+ const rows = stmt.all();+ return rows.map((row) => row.word);+ } catch (error) {+ console.error("Error getting dictionary:", error.message);+ throw error;+ }+ }++ setDictionary(words) {+ try {+ if (!this.db) {+ throw new Error("Database not initialized");+ }+ const transaction = this.db.transaction((wordList) => {+ this.db.prepare("DELETE FROM custom_dictionary").run();+ const insert = this.db.prepare("INSERT OR IGNORE INTO custom_dictionary (word) VALUES (?)");+ for (const word of wordList) {+ const trimmed = typeof word === "string" ? word.trim() : "";+ if (trimmed) {+ insert.run(trimmed);+ }+ }+ });+ transaction(words);+ return { success: true };+ } catch (error) {+ console.error("Error setting dictionary:", error.message);+ throw error;+ }+ }+cleanup() {console.log("Starting database cleanup...");try {diff --git a/src/helpers/devServerManager.js b/src/helpers/devServerManager.jsindex a4b5e279b..e7a14b5e5 100644--- a/src/helpers/devServerManager.js+++ b/src/helpers/devServerManager.js@@ -1,5 +1,8 @@+const DEV_SERVER_PORT = 5174;+const DEV_SERVER_URL = `http://localhost:${DEV_SERVER_PORT}/`;+class DevServerManager {- static async waitForDevServer(url = "http://localhost:5174/", maxAttempts = 30, delay = 1000) {+ static async waitForDevServer(url = DEV_SERVER_URL, maxAttempts = 30, delay = 1000) {for (let i = 0; i < maxAttempts; i++) {try {const http = require("http");@@ -38,7 +41,7 @@ class DevServerManager {static getAppUrl(isControlPanel = false) {if (process.env.NODE_ENV === "development") {- return isControlPanel ? "http://localhost:5174/?panel=true" : "http://localhost:5174/";+ return isControlPanel ? `${DEV_SERVER_URL}?panel=true` : DEV_SERVER_URL;} else {// For production, return null - caller should use loadFile() insteadreturn null;@@ -71,3 +74,5 @@ class DevServerManager {}module.exports = DevServerManager;+module.exports.DEV_SERVER_PORT = DEV_SERVER_PORT;+module.exports.DEV_SERVER_URL = DEV_SERVER_URL;diff --git a/src/helpers/gnomeShortcut.js b/src/helpers/gnomeShortcut.jsindex 459c5458e..e548c8d3d 100644--- a/src/helpers/gnomeShortcut.js+++ b/src/helpers/gnomeShortcut.js@@ -10,9 +10,9 @@ const KEYBINDING_PATH =const KEYBINDING_SCHEMA = "org.gnome.settings-daemon.plugins.media-keys.custom-keybinding";// Valid pattern for GNOME shortcut format (e.g., "<Alt>r", "<Control><Shift>space")-// Supports: letters/digits, function keys (F1-F12), navigation, and special keys+// Supports: letters/digits, function keys (F1-F24), navigation, and special keysconst VALID_SHORTCUT_PATTERN =- /^(<(Control|Alt|Shift|Super)>)*(F[1-9]|F1[0-2]|[a-z0-9]|space|escape|tab|backspace|grave|pause|scroll_lock|insert|delete|home|end|page_up|page_down|up|down|left|right|return|print)$/i;+ /^(<(Control|Alt|Shift|Super)>)*(F([1-9]|1[0-9]|2[0-4])|[a-z0-9]|space|escape|tab|backspace|grave|pause|scroll_lock|insert|delete|home|end|page_up|page_down|up|down|left|right|return|print)$/i;// Map Electron key names to GNOME keysym namesconst ELECTRON_TO_GNOME_KEY_MAP = {diff --git a/src/helpers/hotkeyManager.js b/src/helpers/hotkeyManager.jsindex a8c73be88..bd610c243 100644--- a/src/helpers/hotkeyManager.js+++ b/src/helpers/hotkeyManager.js@@ -92,10 +92,16 @@ class HotkeyManager {debugLogger.log(`[HotkeyManager] Platform: ${process.platform}, Arch: ${process.arch}`);debugLogger.log(`[HotkeyManager] Current hotkey: "${this.currentHotkey}"`);- // If we're already using this hotkey, just return success- if (hotkey === this.currentHotkey) {+ // If we're already using this hotkey AND it's actually registered, return success+ // Note: We need to check isRegistered because on first run, currentHotkey is set to "`"+ // but it's not actually registered yet+ if (+ hotkey === this.currentHotkey &&+ hotkey !== "GLOBE" &&+ globalShortcut.isRegistered(hotkey)+ ) {debugLogger.log(- `[HotkeyManager] Hotkey "${hotkey}" is already the current hotkey, no change needed`+ `[HotkeyManager] Hotkey "${hotkey}" is already the current hotkey and registered, no change needed`);return { success: true, hotkey };}diff --git a/src/helpers/ipcHandlers.js b/src/helpers/ipcHandlers.jsindex cf195d8a0..ebc1a81a7 100644--- a/src/helpers/ipcHandlers.js+++ b/src/helpers/ipcHandlers.js@@ -3,6 +3,7 @@ const path = require("path");const AppUtils = require("../utils");const debugLogger = require("./debugLogger");const { getSystemPrompt } = require("./prompts");+const GnomeShortcutManager = require("./gnomeShortcut");class IPCHandlers {constructor(managers) {@@ -12,9 +13,18 @@ class IPCHandlers {this.whisperManager = managers.whisperManager;this.windowManager = managers.windowManager;this.updateManager = managers.updateManager;+ this.windowsKeyManager = managers.windowsKeyManager;this.setupHandlers();}+ _getDictionarySafe() {+ try {+ return this.databaseManager.getDictionary();+ } catch {+ return [];+ }+ }+setupHandlers() {// Window control handlersipcMain.handle("window-minimize", () => {@@ -117,6 +127,18 @@ class IPCHandlers {return result;});+ // Dictionary handlers+ ipcMain.handle("db-get-dictionary", async () => {+ return this.databaseManager.getDictionary();+ });++ ipcMain.handle("db-set-dictionary", async (event, words) => {+ if (!Array.isArray(words)) {+ throw new Error("words must be an array");+ }+ return this.databaseManager.setDictionary(words);+ });+// Clipboard handlersipcMain.handle("paste-text", async (event, text) => {return this.clipboardManager.pasteText(text);@@ -299,8 +321,75 @@ class IPCHandlers {return await this.windowManager.updateHotkey(hotkey);});- ipcMain.handle("set-hotkey-listening-mode", async (event, enabled) => {+ ipcMain.handle("set-hotkey-listening-mode", async (event, enabled, newHotkey = null) => {this.windowManager.setHotkeyListeningMode(enabled);+ const hotkeyManager = this.windowManager.hotkeyManager;++ // When exiting capture mode with a new hotkey, use that to avoid reading stale state+ const effectiveHotkey = !enabled && newHotkey ? newHotkey : hotkeyManager.getCurrentHotkey();++ if (enabled) {+ // Entering capture mode - unregister globalShortcut so it doesn't consume key events+ const currentHotkey = hotkeyManager.getCurrentHotkey();+ if (currentHotkey && currentHotkey !== "GLOBE") {+ debugLogger.log(+ `[IPC] Unregistering globalShortcut "${currentHotkey}" for hotkey capture mode`+ );+ const { globalShortcut } = require("electron");+ globalShortcut.unregister(currentHotkey);+ }++ // On Windows, stop the Windows key listener+ if (process.platform === "win32" && this.windowsKeyManager) {+ debugLogger.log("[IPC] Stopping Windows key listener for hotkey capture mode");+ this.windowsKeyManager.stop();+ }++ // On GNOME Wayland, unregister the keybinding during capture+ if (hotkeyManager.isUsingGnome() && hotkeyManager.gnomeManager) {+ debugLogger.log("[IPC] Unregistering GNOME keybinding for hotkey capture mode");+ await hotkeyManager.gnomeManager.unregisterKeybinding().catch((err) => {+ debugLogger.warn("[IPC] Failed to unregister GNOME keybinding:", err.message);+ });+ }+ } else {+ // Exiting capture mode - re-register globalShortcut if not already registered+ if (effectiveHotkey && effectiveHotkey !== "GLOBE") {+ const { globalShortcut } = require("electron");+ if (!globalShortcut.isRegistered(effectiveHotkey)) {+ debugLogger.log(+ `[IPC] Re-registering globalShortcut "${effectiveHotkey}" after capture mode`+ );+ const callback = this.windowManager.createHotkeyCallback();+ globalShortcut.register(effectiveHotkey, callback);+ }+ }++ // On Windows, restart the listener if in push mode+ if (process.platform === "win32" && this.windowsKeyManager) {+ const activationMode = await this.windowManager.getActivationMode();+ debugLogger.log(+ `[IPC] Exiting hotkey capture mode, activationMode="${activationMode}", hotkey="${effectiveHotkey}"`+ );+ if (activationMode === "push" && effectiveHotkey && effectiveHotkey !== "GLOBE") {+ debugLogger.log(`[IPC] Restarting Windows key listener for hotkey: ${effectiveHotkey}`);+ this.windowsKeyManager.start(effectiveHotkey);+ }+ }++ // On GNOME Wayland, re-register the keybinding with the effective hotkey+ if (hotkeyManager.isUsingGnome() && hotkeyManager.gnomeManager && effectiveHotkey) {+ const gnomeHotkey = GnomeShortcutManager.convertToGnomeFormat(effectiveHotkey);+ debugLogger.log(+ `[IPC] Re-registering GNOME keybinding "${gnomeHotkey}" after capture mode`+ );+ const success = await hotkeyManager.gnomeManager.registerKeybinding(gnomeHotkey);+ if (success) {+ hotkeyManager.currentHotkey = effectiveHotkey;+ }+ }+ }+return { success: true };});@@ -328,6 +417,31 @@ class IPCHandlers {}});+ // Auto-start handlers+ ipcMain.handle("get-auto-start-enabled", async () => {+ try {+ const loginSettings = app.getLoginItemSettings();+ return loginSettings.openAtLogin;+ } catch (error) {+ debugLogger.error("Error getting auto-start status:", error);+ return false;+ }+ });++ ipcMain.handle("set-auto-start-enabled", async (event, enabled) => {+ try {+ app.setLoginItemSettings({+ openAtLogin: enabled,+ openAsHidden: true, // Start minimized to tray+ });+ debugLogger.debug("Auto-start setting updated", { enabled });+ return { success: true };+ } catch (error) {+ debugLogger.error("Error setting auto-start:", error);+ return { success: false, error: error.message };+ }+ });+// Model management handlersipcMain.handle("model-get-all", async () => {try {@@ -478,7 +592,10 @@ class IPCHandlers {ipcMain.handle("process-local-reasoning", async (event, text, modelId, agentName, config) => {try {const LocalReasoningService = require("../services/localReasoningBridge").default;- const result = await LocalReasoningService.processText(text, modelId, agentName, config);+ const result = await LocalReasoningService.processText(text, modelId, agentName, {+ ...config,+ customDictionary: this._getDictionarySafe(),+ });return { success: true, text: result };} catch (error) {return { success: false, error: error.message };@@ -496,8 +613,7 @@ class IPCHandlers {throw new Error("Anthropic API key not configured");}- // Use the unified system prompt - LLM handles agent detection- const systemPrompt = getSystemPrompt(agentName);+ const systemPrompt = getSystemPrompt(agentName, this._getDictionarySafe());const userPrompt = text;if (!modelId) {diff --git a/src/helpers/prompts.js b/src/helpers/prompts.jsindex c71632cde..b6e2e8281 100644--- a/src/helpers/prompts.js+++ b/src/helpers/prompts.js@@ -1,10 +1,17 @@const promptData = require("../config/promptData.json");const UNIFIED_SYSTEM_PROMPT = promptData.UNIFIED_SYSTEM_PROMPT;+const DICTIONARY_SUFFIX = promptData.DICTIONARY_SUFFIX;-function getSystemPrompt(agentName) {+function getSystemPrompt(agentName, customDictionary) {const name = (agentName && agentName.trim()) || "Assistant";- return UNIFIED_SYSTEM_PROMPT.replace(/\{\{agentName\}\}/g, name);+ let prompt = UNIFIED_SYSTEM_PROMPT.replace(/\{\{agentName\}\}/g, name);++ if (Array.isArray(customDictionary) && customDictionary.length > 0) {+ prompt += DICTIONARY_SUFFIX + customDictionary.join(", ");+ }++ return prompt;}function buildPrompt(text, agentName) {diff --git a/src/helpers/whisper.js b/src/helpers/whisper.jsindex fabbb50a4..ace841912 100644--- a/src/helpers/whisper.js+++ b/src/helpers/whisper.js@@ -253,6 +253,7 @@ class WhisperManager {const model = options.model || "base";const language = options.language || null;+ const initialPrompt = options.initialPrompt || null;const modelPath = this.getModelPath(model);// Check if model exists@@ -260,10 +261,10 @@ class WhisperManager {throw new Error(`Whisper model "${model}" not downloaded. Please download it from Settings.`);}- return await this.transcribeViaServer(audioBlob, model, language);+ return await this.transcribeViaServer(audioBlob, model, language, initialPrompt);}- async transcribeViaServer(audioBlob, model, language) {+ async transcribeViaServer(audioBlob, model, language, initialPrompt = null) {debugLogger.info("Transcription mode: SERVER", { model, language: language || "auto" });const modelPath = this.getModelPath(model);@@ -300,7 +301,7 @@ class WhisperManager {});const startTime = Date.now();- const result = await this.serverManager.transcribe(audioBuffer, { language });+ const result = await this.serverManager.transcribe(audioBuffer, { language, initialPrompt });const elapsed = Date.now() - startTime;debugLogger.logWhisperPipeline("transcribeViaServer - completed", {diff --git a/src/helpers/whisperServer.js b/src/helpers/whisperServer.jsindex fea76a306..6640d9b4d 100644--- a/src/helpers/whisperServer.js+++ b/src/helpers/whisperServer.js@@ -208,6 +208,11 @@ class WhisperServerManager {// Check for FFmpeg first - only use --convert flag if FFmpeg is availableconst ffmpegPath = this.getFFmpegPath();const spawnEnv = { ...process.env };+ const pathSep = process.platform === "win32" ? ";" : ":";++ // Add the whisper-server directory to PATH so any companion DLLs are found+ const serverBinaryDir = path.dirname(serverBinary);+ spawnEnv.PATH = serverBinaryDir + pathSep + (process.env.PATH || "");const args = ["--model", modelPath, "--host", "127.0.0.1", "--port", String(this.port)];@@ -216,8 +221,7 @@ class WhisperServerManager {if (ffmpegPath) {args.push("--convert");const ffmpegDir = path.dirname(ffmpegPath);- const pathSep = process.platform === "win32" ? ";" : ":";- spawnEnv.PATH = ffmpegDir + pathSep + (process.env.PATH || "");+ spawnEnv.PATH = ffmpegDir + pathSep + spawnEnv.PATH;} else {debugLogger.warn("FFmpeg not found - whisper-server will only accept WAV format");}@@ -227,13 +231,18 @@ class WhisperServerManager {args.push("--language", options.language);}- debugLogger.debug("Starting whisper-server", { port: this.port, modelPath, args });+ debugLogger.debug("Starting whisper-server", {+ port: this.port,+ modelPath,+ args,+ cwd: serverBinaryDir,+ });this.process = spawn(serverBinary, args, {stdio: ["ignore", "pipe", "pipe"],windowsHide: true,env: spawnEnv,- cwd: os.tmpdir(),+ cwd: serverBinaryDir,});let stderrBuffer = "";@@ -355,7 +364,19 @@ class WhisperServerManager {throw new Error("whisper-server is not running");}- const { language } = options;+ // Debug: Log audio buffer info+ debugLogger.debug("whisper-server transcribe called", {+ bufferLength: audioBuffer?.length || 0,+ bufferType: audioBuffer?.constructor?.name,+ firstBytes:+ audioBuffer?.length >= 16+ ? Array.from(audioBuffer.slice(0, 16))+ .map((b) => b.toString(16).padStart(2, "0"))+ .join(" ")+ : "too short",+ });++ const { language, initialPrompt } = options;const boundary = `----WhisperBoundary${Date.now()}`;const parts = [];@@ -392,6 +413,16 @@ class WhisperServerManager {);}+ // Add initial prompt for custom dictionary words+ if (initialPrompt) {+ parts.push(+ `--${boundary}\r\n` ++ `Content-Disposition: form-data; name="prompt"\r\n\r\n` ++ `${initialPrompt}\r\n`+ );+ debugLogger.info("Using custom dictionary prompt", { prompt: initialPrompt });+ }+parts.push(`--${boundary}\r\n` +`Content-Disposition: form-data; name="response_format"\r\n\r\n` +@@ -426,6 +457,8 @@ class WhisperServerManager {debugLogger.debug("whisper-server transcription completed", {statusCode: res.statusCode,elapsed: Date.now() - startTime,+ responseLength: data.length,+ responsePreview: data.slice(0, 500),});if (res.statusCode !== 200) {diff --git a/src/helpers/windowManager.js b/src/helpers/windowManager.jsindex 3d78a846a..620fcf4d2 100644--- a/src/helpers/windowManager.js+++ b/src/helpers/windowManager.js@@ -3,6 +3,7 @@ const HotkeyManager = require("./hotkeyManager");const DragManager = require("./dragManager");const MenuManager = require("./menuManager");const DevServerManager = require("./devServerManager");+const { DEV_SERVER_PORT } = DevServerManager;const { MAIN_WINDOW_CONFIG, CONTROL_PANEL_CONFIG, WindowPositionUtil } = require("./windowConfig");class WindowManager {@@ -15,12 +16,17 @@ class WindowManager {this.isQuitting = false;this.isMainWindowInteractive = false;this.loadErrorShown = false;+ this.windowsPushToTalkAvailable = false;app.on("before-quit", () => {this.isQuitting = true;});}+ setWindowsPushToTalkAvailable(available) {+ this.windowsPushToTalkAvailable = available;+ }+async createMainWindow() {const display = screen.getPrimaryDisplay();const position = WindowPositionUtil.getMainWindowPosition(display);@@ -49,7 +55,7 @@ class WindowManager {if (process.env.NODE_ENV === "development" &&validatedURL &&- validatedURL.includes("localhost:5174")+ validatedURL.includes(`localhost:${DEV_SERVER_PORT}`)) {// Retry connection to dev serversetTimeout(async () => {@@ -123,11 +129,19 @@ class WindowManager {let lastToggleTime = 0;const DEBOUNCE_MS = 150;- return () => {+ return async () => {if (this.hotkeyManager.isInListeningMode()) {return;}+ // Windows push mode: defer to windowsKeyManager if available, else fall through to toggle+ if (process.platform === "win32" && this.windowsPushToTalkAvailable) {+ const activationMode = await this.getActivationMode();+ if (activationMode === "push") {+ return;+ }+ }+const now = Date.now();if (now - lastToggleTime < DEBOUNCE_MS) {return;diff --git a/src/helpers/windowsKeyManager.js b/src/helpers/windowsKeyManager.jsnew file mode 100644index 000000000..f0be1d6b8--- /dev/null+++ b/src/helpers/windowsKeyManager.js@@ -0,0 +1,203 @@+/**+ * WindowsKeyManager - Handles key up/down detection for Push-to-Talk on Windows+ *+ * Uses a native Windows keyboard hook to detect when specific keys are+ * pressed and released, enabling Push-to-Talk functionality.+ */++const { spawn } = require("child_process");+const path = require("path");+const EventEmitter = require("events");+const fs = require("fs");+const debugLogger = require("./debugLogger");++class WindowsKeyManager extends EventEmitter {+ constructor() {+ super();+ this.process = null;+ this.isSupported = process.platform === "win32";+ this.hasReportedError = false;+ this.currentKey = null;+ this.isReady = false;+ }++ /**+ * Start listening for the specified key+ * @param {string} key - The key to listen for (e.g., "`", "F8", "F11", "CommandOrControl+F11")+ */+ start(key = "`") {+ if (!this.isSupported) {+ return;+ }++ // If already running with the same key, do nothing+ if (this.process && this.currentKey === key) {+ return;+ }++ // Stop any existing listener+ this.stop();++ const listenerPath = this.resolveListenerBinary();+ if (!listenerPath) {+ // Binary not found - this is OK, Push-to-Talk will use fallback mode+ this.emit("unavailable", new Error("Windows key listener binary not found"));+ return;+ }++ this.hasReportedError = false;+ this.isReady = false;+ this.currentKey = key;++ debugLogger.debug("[WindowsKeyManager] Starting key listener", {+ key,+ binaryPath: listenerPath,+ });++ try {+ this.process = spawn(listenerPath, [key], {+ stdio: ["ignore", "pipe", "pipe"],+ windowsHide: true,+ });+ } catch (error) {+ debugLogger.error("[WindowsKeyManager] Failed to spawn process", { error: error.message });+ this.reportError(error);+ return;+ }++ this.process.stdout.setEncoding("utf8");+ this.process.stdout.on("data", (chunk) => {+ chunk+ .split(/\r?\n/)+ .map((line) => line.trim())+ .filter(Boolean)+ .forEach((line) => {+ if (line === "READY") {+ debugLogger.debug("[WindowsKeyManager] Listener ready", { key });+ this.isReady = true;+ this.emit("ready");+ } else if (line === "KEY_DOWN") {+ debugLogger.debug("[WindowsKeyManager] KEY_DOWN detected", { key });+ this.emit("key-down", key);+ } else if (line === "KEY_UP") {+ debugLogger.debug("[WindowsKeyManager] KEY_UP detected", { key });+ this.emit("key-up", key);+ } else {+ // Log unknown output at debug level (could be native binary's stderr info)+ debugLogger.debug("[WindowsKeyManager] Unknown output", { line });+ }+ });+ });++ this.process.stderr.setEncoding("utf8");+ this.process.stderr.on("data", (data) => {+ const message = data.toString().trim();+ if (message.length > 0) {+ // Native binary logs to stderr for info messages, don't treat as error+ debugLogger.debug("[WindowsKeyManager] Native stderr", { message });+ }+ });++ this.process.on("error", (error) => {+ this.reportError(error);+ this.process = null;+ });++ this.process.on("exit", (code, signal) => {+ this.process = null;+ this.isReady = false;+ if (code !== 0) {+ const error = new Error(+ `Windows key listener exited with code ${code ?? "null"} signal ${signal ?? "null"}`+ );+ this.reportError(error);+ }+ });+ }++ /**+ * Stop the key listener+ */+ stop() {+ if (this.process) {+ debugLogger.debug("[WindowsKeyManager] Stopping key listener");+ try {+ this.process.kill();+ } catch {+ // Ignore kill errors+ }+ this.process = null;+ }+ this.isReady = false;+ this.currentKey = null;+ }++ /**+ * Check if the listener is available and ready+ */+ isAvailable() {+ return this.resolveListenerBinary() !== null;+ }++ /**+ * Report an error (only once per session to avoid log spam)+ */+ reportError(error) {+ if (this.hasReportedError) {+ return;+ }+ this.hasReportedError = true;++ if (this.process) {+ try {+ this.process.kill();+ } catch {+ // Ignore+ } finally {+ this.process = null;+ }+ }++ debugLogger.warn("[WindowsKeyManager] Error occurred", { error: error.message });+ this.emit("error", error);+ }++ /**+ * Find the listener binary in various possible locations+ */+ resolveListenerBinary() {+ const binaryName = "windows-key-listener.exe";+ const candidates = new Set([+ path.join(__dirname, "..", "..", "resources", "bin", binaryName),+ path.join(__dirname, "..", "..", "resources", binaryName),+ ]);++ if (process.resourcesPath) {+ [+ path.join(process.resourcesPath, binaryName),+ path.join(process.resourcesPath, "bin", binaryName),+ path.join(process.resourcesPath, "resources", binaryName),+ path.join(process.resourcesPath, "resources", "bin", binaryName),+ path.join(process.resourcesPath, "app.asar.unpacked", "resources", binaryName),+ path.join(process.resourcesPath, "app.asar.unpacked", "resources", "bin", binaryName),+ ].forEach((candidate) => candidates.add(candidate));+ }++ const candidatePaths = [...candidates];++ for (const candidate of candidatePaths) {+ try {+ const stats = fs.statSync(candidate);+ if (stats.isFile()) {+ return candidate;+ }+ } catch {+ continue;+ }+ }++ return null;+ }+}++module.exports = WindowsKeyManager;diff --git a/src/hooks/useSettings.ts b/src/hooks/useSettings.tsindex 263012b82..f7c6edc7a 100644--- a/src/hooks/useSettings.ts+++ b/src/hooks/useSettings.ts@@ -15,6 +15,7 @@ export interface TranscriptionSettings {cloudTranscriptionProvider: string;cloudTranscriptionModel: string;cloudTranscriptionBaseUrl?: string;+ customDictionary: string[];}export interface ReasoningSettings {@@ -118,6 +119,60 @@ export function useSettings() {});+ // Custom dictionary for improving transcription of specific words+ const [customDictionary, setCustomDictionaryRaw] = useLocalStorage<string[]>(+ "customDictionary",+ [],+ {+ serialize: JSON.stringify,+ deserialize: (value) => {+ try {+ const parsed = JSON.parse(value);+ return Array.isArray(parsed) ? parsed : [];+ } catch {+ return [];+ }+ },+ }+ );++ // Wrap setter to sync dictionary to SQLite+ const setCustomDictionary = useCallback(+ (words: string[]) => {+ setCustomDictionaryRaw(words);+ window.electronAPI?.setDictionary(words).catch(() => {+ // Silently ignore SQLite sync errors+ });+ },+ [setCustomDictionaryRaw]+ );++ // One-time sync: reconcile localStorage ↔ SQLite on startup+ const hasRunDictionarySync = useRef(false);+ useEffect(() => {+ if (hasRunDictionarySync.current) return;+ hasRunDictionarySync.current = true;++ const syncDictionary = async () => {+ if (typeof window === "undefined" || !window.electronAPI?.getDictionary) return;+ try {+ const dbWords = await window.electronAPI.getDictionary();+ if (dbWords.length === 0 && customDictionary.length > 0) {+ // Seed SQLite from localStorage (first-time migration)+ await window.electronAPI.setDictionary(customDictionary);+ } else if (dbWords.length > 0 && customDictionary.length === 0) {+ // Recover localStorage from SQLite (e.g. localStorage was cleared)+ setCustomDictionaryRaw(dbWords);+ }+ } catch {+ // Silently ignore sync errors+ }+ };++ syncDictionary();+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, []);+// Reasoning settingsconst [useReasoningModel, setUseReasoningModel] = useLocalStorage("useReasoningModel", true, {serialize: String,@@ -280,12 +335,24 @@ export function useSettings() {);// Hotkey- const [dictationKey, setDictationKey] = useLocalStorage("dictationKey", "", {+ const [dictationKey, setDictationKeyLocal] = useLocalStorage("dictationKey", "", {serialize: String,deserialize: String,});- const [activationMode, setActivationMode] = useLocalStorage<"tap" | "push">(+ // Wrap setDictationKey to notify main process (for Windows Push-to-Talk)+ const setDictationKey = useCallback(+ (key: string) => {+ setDictationKeyLocal(key);+ // Notify main process so Windows key listener can restart with new key+ if (typeof window !== "undefined" && window.electronAPI?.notifyHotkeyChanged) {+ window.electronAPI.notifyHotkeyChanged(key);+ }+ },+ [setDictationKeyLocal]+ );++ const [activationMode, setActivationModeLocal] = useLocalStorage<"tap" | "push">("activationMode","tap",{@@ -294,6 +361,18 @@ export function useSettings() {});+ // Wrap setActivationMode to notify main process (for Windows Push-to-Talk)+ const setActivationMode = useCallback(+ (mode: "tap" | "push") => {+ setActivationModeLocal(mode);+ // Notify main process so Windows key listener can start/stop+ if (typeof window !== "undefined" && window.electronAPI?.notifyActivationModeChanged) {+ window.electronAPI.notifyActivationModeChanged(mode);+ }+ },+ [setActivationModeLocal]+ );+// Microphone settingsconst [preferBuiltInMic, setPreferBuiltInMic] = useLocalStorage("preferBuiltInMic", true, {serialize: String,@@ -327,6 +406,7 @@ export function useSettings() {setCloudTranscriptionModel(settings.cloudTranscriptionModel);if (settings.cloudTranscriptionBaseUrl !== undefined)setCloudTranscriptionBaseUrl(settings.cloudTranscriptionBaseUrl);+ if (settings.customDictionary !== undefined) setCustomDictionary(settings.customDictionary);},[setUseLocalWhisper,@@ -338,6 +418,7 @@ export function useSettings() {setCloudTranscriptionProvider,setCloudTranscriptionModel,setCloudTranscriptionBaseUrl,+ setCustomDictionary,]);@@ -374,6 +455,7 @@ export function useSettings() {cloudTranscriptionModel,cloudTranscriptionBaseUrl,cloudReasoningBaseUrl,+ customDictionary,useReasoningModel,reasoningModel,reasoningProvider,@@ -392,6 +474,7 @@ export function useSettings() {setCloudTranscriptionModel,setCloudTranscriptionBaseUrl,setCloudReasoningBaseUrl,+ setCustomDictionary,setUseReasoningModel,setReasoningModel,setReasoningProvider: (provider: string) => {diff --git a/src/services/BaseReasoningService.ts b/src/services/BaseReasoningService.tsindex a709710f3..7b726350e 100644--- a/src/services/BaseReasoningService.ts+++ b/src/services/BaseReasoningService.ts@@ -9,32 +9,22 @@ export interface ReasoningConfig {export abstract class BaseReasoningService {protected isProcessing = false;- /**- * Get the system prompt for reasoning- * Now uses the unified prompt from config/prompts.ts- */- protected getSystemPrompt(agentName: string | null): string {- return getSystemPrompt(agentName);+ protected getCustomDictionary(): string[] {+ if (typeof window === "undefined" || !window.localStorage) return [];+ try {+ const raw = window.localStorage.getItem("customDictionary");+ if (!raw) return [];+ const parsed = JSON.parse(raw);+ return Array.isArray(parsed) ? parsed : [];+ } catch {+ return [];+ }}- /**- * Get reasoning prompt (user message portion)- * With unified prompts, we just return the text - all instructions are in the system prompt- * @deprecated The unified prompt approach puts all instructions in the system prompt- */- protected getReasoningPrompt(- text: string,- agentName: string | null,- config: ReasoningConfig = {}- ): string {- // With the unified prompt approach, the user message is just the text- // All instructions about cleanup and agent detection are in the system prompt- return text;+ protected getSystemPrompt(agentName: string | null): string {+ return getSystemPrompt(agentName, this.getCustomDictionary());}- /**- * Calculate optimal max tokens based on input length- */protected calculateMaxTokens(textLength: number,minTokens = 100,@@ -44,14 +34,8 @@ export abstract class BaseReasoningService {return Math.max(minTokens, Math.min(textLength * multiplier, maxTokens));}- /**- * Check if service is available- */abstract isAvailable(): Promise<boolean>;- /**- * Process text with reasoning- */abstract processText(text: string,modelId: string,diff --git a/src/services/LocalReasoningService.ts b/src/services/LocalReasoningService.tsindex 1ba36bc0c..5db5b869c 100644--- a/src/services/LocalReasoningService.ts+++ b/src/services/LocalReasoningService.ts@@ -32,11 +32,8 @@ class LocalReasoningService extends BaseReasoningService {const startTime = Date.now();try {- // Get prompt using the base class method- const reasoningPrompt = this.getReasoningPrompt(text, agentName, config);-logger.logReasoning("LOCAL_MODEL_PROMPT_PREPARED", {- promptLength: reasoningPrompt.length,+ promptLength: text.length,hasAgentName: !!agentName,});@@ -61,7 +58,7 @@ class LocalReasoningService extends BaseReasoningService {});// Run inference- const result = await modelManager.runInference(modelId, reasoningPrompt, {+ const result = await modelManager.runInference(modelId, text, {...inferenceOptions,maxTokens,temperature: config.temperature || inferenceOptions.temperature,diff --git a/src/services/ReasoningService.ts b/src/services/ReasoningService.tsindex 95c647fdd..b5606b815 100644--- a/src/services/ReasoningService.ts+++ b/src/services/ReasoningService.ts@@ -3,7 +3,7 @@ import { BaseReasoningService, ReasoningConfig } from "./BaseReasoningService";import { SecureCache } from "../utils/SecureCache";import { withRetry, createApiRetryStrategy } from "../utils/retry";import { API_ENDPOINTS, TOKEN_LIMITS, buildApiUrl, normalizeBaseUrl } from "../config/constants";-import { UNIFIED_SYSTEM_PROMPT, LEGACY_PROMPTS, getSystemPrompt } from "../config/prompts";+import { UNIFIED_SYSTEM_PROMPT, LEGACY_PROMPTS } from "../config/prompts";import logger from "../utils/logger";import { isSecureEndpoint } from "../utils/urlUtils";@@ -271,7 +271,7 @@ class ReasoningService extends BaseReasoningService {config: ReasoningConfig,providerName: string): Promise<string> {- const systemPrompt = getSystemPrompt(agentName);+ const systemPrompt = this.getSystemPrompt(agentName);const userPrompt = text;const messages = [@@ -497,7 +497,7 @@ class ReasoningService extends BaseReasoningService {this.isProcessing = true;try {- const systemPrompt = getSystemPrompt(agentName);+ const systemPrompt = this.getSystemPrompt(agentName);const userPrompt = text;// Build messages array (used by both APIs)@@ -822,7 +822,7 @@ class ReasoningService extends BaseReasoningService {this.isProcessing = true;try {- const systemPrompt = getSystemPrompt(agentName);+ const systemPrompt = this.getSystemPrompt(agentName);const userPrompt = text;const requestBody = {diff --git a/src/services/localReasoningBridge.js b/src/services/localReasoningBridge.jsindex 3a0e557ed..b7251ba27 100644--- a/src/services/localReasoningBridge.js+++ b/src/services/localReasoningBridge.js@@ -36,16 +36,9 @@ class LocalReasoningService {const startTime = Date.now();try {- // Get custom prompts from the request context- const customPrompts = config.customPrompts || null;-- // Build the reasoning prompt- const reasoningPrompt = this.getReasoningPrompt(text, agentName, customPrompts);-debugLogger.logReasoning("LOCAL_BRIDGE_PROMPT", {- promptLength: reasoningPrompt.length,+ promptLength: text.length,hasAgentName: !!agentName,- hasCustomPrompts: !!customPrompts,});const inferenceConfig = {@@ -56,7 +49,7 @@ class LocalReasoningService {repeatPenalty: config.repeatPenalty || 1.1,contextSize: config.contextSize || 4096,threads: config.threads || 4,- systemPrompt: getSystemPrompt(agentName),+ systemPrompt: getSystemPrompt(agentName, config.customDictionary),};debugLogger.logReasoning("LOCAL_BRIDGE_INFERENCE", {@@ -65,7 +58,7 @@ class LocalReasoningService {});// Run inference- const result = await modelManager.runInference(modelId, reasoningPrompt, inferenceConfig);+ const result = await modelManager.runInference(modelId, text, inferenceConfig);const processingTime = Date.now() - startTime;@@ -93,19 +86,6 @@ class LocalReasoningService {}}- getCustomPrompts() {- // In main process, we can't access localStorage directly- // This should be passed from the renderer process- return null;- }-- getReasoningPrompt(text, agentName, customPrompts) {- // With the unified prompt approach, all instructions are in the system prompt- // The user message is just the transcribed text- // Agent detection is now handled by the LLM itself based on the system prompt- return text;- }-calculateMaxTokens(textLength, minTokens = 100, maxTokens = 2048, multiplier = 2) {return Math.max(minTokens, Math.min(textLength * multiplier, maxTokens));}diff --git a/src/types/electron.ts b/src/types/electron.tsindex 772187a35..13bb19743 100644--- a/src/types/electron.ts+++ b/src/types/electron.ts@@ -119,6 +119,12 @@ declare global {getTranscriptions: (limit?: number) => Promise<TranscriptionItem[]>;clearTranscriptions: () => Promise<{ cleared: number; success: boolean }>;deleteTranscription: (id: number) => Promise<{ success: boolean }>;++ // Dictionary operations+ getDictionary: () => Promise<string[]>;+ setDictionary: (words: string[]) => Promise<{ success: boolean }>;++ // Database event listenersonTranscriptionAdded?: (callback: (item: TranscriptionItem) => void) => (() => void) | void;onTranscriptionDeleted?: (callback: (payload: { id: number }) => void) => (() => void) | void;onTranscriptionsCleared?: (@@ -232,7 +238,10 @@ declare global {// Hotkey managementupdateHotkey: (key: string) => Promise<{ success: boolean; message: string }>;- setHotkeyListeningMode?: (enabled: boolean) => Promise<{ success: boolean }>;+ setHotkeyListeningMode?: (+ enabled: boolean,+ newHotkey?: string | null+ ) => Promise<{ success: boolean }>;getHotkeyModeInfo?: () => Promise<{ isUsingGnome: boolean }>;// Globe key listener for hotkey capture (macOS only)@@ -285,6 +294,14 @@ declare global {openSoundInputSettings?: () => Promise<{ success: boolean; error?: string }>;openAccessibilitySettings?: () => Promise<{ success: boolean; error?: string }>;openWhisperModelsFolder?: () => Promise<{ success: boolean; error?: string }>;++ // Windows Push-to-Talk notifications+ notifyActivationModeChanged?: (mode: "tap" | "push") => void;+ notifyHotkeyChanged?: (hotkey: string) => void;++ // Auto-start at login+ getAutoStartEnabled?: () => Promise<boolean>;+ setAutoStartEnabled?: (enabled: boolean) => Promise<{ success: boolean; error?: string }>;};api?: {