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(cli): local HTTP bridge for unified CLI (#676)
Gabriel Steinf6119b18fa64
diff --git a/agent-skills/openwhispr-cli/SKILL.md b/agent-skills/openwhispr-cli/SKILL.mdnew file mode 100644index 000000000..099e64893--- /dev/null+++ b/agent-skills/openwhispr-cli/SKILL.md@@ -0,0 +1,214 @@+---+name: openwhispr-cli+description: Use this skill whenever the user wants to operate on OpenWhispr notes, folders, transcriptions, or audio from a terminal or shell. The OpenWhispr CLI (`openwhispr` binary, npm package `@openwhispr/cli`) talks to either the local desktop app or the cloud API and exposes every operation needed for managing notes, folders, transcriptions, audio, plus auth and config. Trigger this skill when the user mentions "openwhispr cli", running shell commands against OpenWhispr, automating note workflows, cleaning up a transcription, building agent integrations against OpenWhispr, or scripting any OpenWhispr operation — even if they don't say "CLI" explicitly.+---++# OpenWhispr CLI++Use this reference when running the `openwhispr` command-line tool. The CLI is a single binary that operates against either the local desktop app (via a loopback HTTP bridge) or the cloud REST API. The same command works against both backends.++## Install++```bash+npm install -g @openwhispr/cli+```++Requires Node.js 20 or later. Verify with `openwhispr --version`. If the user reports `command not found`, ensure their npm global bin is on `$PATH`.++## Backends++Every command runs against one of two backends. The behavior is identical from the user's perspective — only the data source differs.++| Backend | What it talks to | Use when |+|---------|------------------|----------|+| **local** | Desktop app's loopback HTTP bridge on `127.0.0.1` | The desktop app is running. Authoritative during/right after a recording. |+| **remote** | `https://api.openwhispr.com/api/v1` | Desktop is closed, or running on a different machine, or the user wants cloud-side semantics. |++### How the CLI picks a backend++Resolution order (first match wins):++1. The `--local` or `--remote` flag on the command+2. The `OPENWHISPR_BACKEND` environment variable (`local`, `remote`, or `auto`)+3. The `backend` key in `~/.openwhispr/cli-config.json`+4. Auto-detect: local if the desktop bridge is reachable, otherwise remote if an API key is configured, otherwise error with guidance++### Local backend (no setup needed)++When the desktop app starts, it writes `{version, port, token}` to `~/.openwhispr/cli-bridge.json` with mode `0600`. The CLI reads it automatically. If the file is missing or stale, local is treated as unavailable.++### Remote backend (needs an API key)++Generate a key in the desktop app under **Integrations > API Keys**, then run:++```bash+openwhispr auth login # prompts for the key, stores it 0600 in ~/.openwhispr/cli-config.json+openwhispr auth status # confirm it works+openwhispr auth logout # clear it+```++API keys are scoped server-side. Match scopes to the commands the user needs to run:++| Scope | Commands |+|-------|----------|+| `notes:read` | `notes list/get/search`, `folders list` |+| `notes:write` | `notes create/update/delete`, `folders create` |+| `transcriptions:read` | `transcriptions list/get` |+| `transcriptions:delete` | `transcriptions delete` |+| `usage:read` | (used internally by `doctor` and the remote backend's reachability ping) |++Scopes are enforced server-side; the CLI does not validate them locally. If a scope is missing, the API returns a 401/403 and the CLI exits with code 3.++## Output++The CLI auto-detects whether stdout is a TTY:++- TTY → human-readable (table for lists, markdown or text for single resources)+- Pipe/redirect → JSON++Override with `--format <fmt>`. Supported values vary by command:++- Lists (`notes list`, `notes search`, `folders list`, `transcriptions list`): `json|table`+- `notes get`: `json|markdown`+- `transcriptions get`: `json|text`+- `notes create`, `notes update`, `folders create`: no `--format` flag — always emit the full JSON of the created/updated resource on stdout+- Delete-style mutations (`notes delete`, `transcriptions delete`, `audio delete`) and status commands (`auth status`, `config get`, `doctor`, `version`): `--format json` for machine output; otherwise human-readable text++Always pass `--format json` when parsing CLI output programmatically.++## Exit codes++Honor these exit codes when scripting or recovering from errors:++| Code | Meaning | Recovery |+|------|---------|----------|+| 0 | Success | Continue |+| 1 | User error (bad args, missing required flag) | Fix the command and rerun |+| 2 | Backend unreachable | Start the desktop app, or run `auth login` for cloud, or try `--remote`/`--local` explicitly |+| 3 | Auth failure (missing/invalid key, insufficient scope) | Do not retry — surface to the user |+| 4 | Not found (no such note/transcription/folder) | Check the ID and rerun |++## Commands++Noun-verb syntax: `openwhispr <noun> <verb>`. Same convention as `gh`, `kubectl`, `aws`, `stripe`.++### Notes++```bash+openwhispr notes list [--folder <id>] [--limit N] [--format json|table]+openwhispr notes get <id> [--format json|markdown]+openwhispr notes create --content <text> | --content-file <path>+ [--title <t>] [--folder <id>]+openwhispr notes update <id> [--content <t>] [--folder <id>] [--title <t>]+openwhispr notes delete <id> [--dry-run] [--format json]+openwhispr notes search <query> [--limit N] [--format json|table]+```++### Folders++```bash+openwhispr folders list [--format json|table]+openwhispr folders create --name <name> [--sort-order <n>]+```++Folder names must be unique per user. Create returns 409-equivalent on duplicates (exit code 1 with a clear message).++### Transcriptions++```bash+openwhispr transcriptions list [--limit N] [--format json|table]+openwhispr transcriptions get <id> [--format json|text]+openwhispr transcriptions delete <id> [--dry-run] [--format json]+```++`--format text` returns the plain transcript text body. SRT/VTT export is not currently exposed by the CLI; use `--format json` and post-process if you need timestamped subtitle formats.++### Audio++```bash+openwhispr audio delete <transcription-id> [--format json]+```++Local-only. The cloud API does not store audio. Running this with `--remote` returns a clear "not supported" error (exit 1).++### Auth++```bash+openwhispr auth login [--api-key <key>] # prompts on stdin if --api-key omitted+openwhispr auth status [--format json]+openwhispr auth logout+```++`auth status` reads the stored config and reports whether a key is configured — it does **not** make a network call. To verify the key actually works, use `openwhispr doctor`.++### Config++```bash+openwhispr config get [--format json]+openwhispr config set backend auto|local|remote+openwhispr config set api-base https://api.openwhispr.com+```++Only `backend` and `api-base` are settable via `config set`. The API key is managed through `auth login`/`auth logout`. `api-base` is overridable for self-hosted or staging deployments (default: production cloud). The `OPENWHISPR_API_BASE` env var also overrides it for a single invocation.++### Doctor++```bash+openwhispr doctor [--format json]+```++Probes both backends and reports each independently. Exit 0 if at least one is reachable; exit 2 if neither. Run this first when the user reports "the CLI isn't working" — it isolates whether the problem is the desktop bridge, the API key, or something else.++### Version++```bash+openwhispr --version # or: openwhispr version+```++## Workflows++### Bulk note operations++Pipe `notes list --format json` through `jq` for filtering, then iterate:++```bash+openwhispr notes list --limit 100 --format json | \+ jq -r '.[] | select(.title | contains("draft")) | .id' | \+ while read id; do+ openwhispr notes delete "$id"+ done+```++### Searching for context before writing a note++```bash+openwhispr notes search "quarterly budget" --format json | jq '.[].id'+```++Use the IDs returned to read related notes with `notes get` before composing the new note's content.++## Configuration files++The CLI reads/writes these files. Both should always be `0600`.++| File | Written by | Contains |+|------|-----------|----------|+| `~/.openwhispr/cli-bridge.json` | The desktop app at startup | `{version, port, token}` for the loopback bridge |+| `~/.openwhispr/cli-config.json` | The CLI's `auth login` and `config set` | `{backend, apiBase, apiKey}` |++The CLI writes both files with `0600`. If you see them with looser permissions (e.g., after manual editing), tighten with `chmod 0600 <file>`.++## Troubleshooting++| Symptom | Likely cause | Fix |+|---------|--------------|-----|+| `Backend unreachable` (exit 2) on every command | Desktop closed and no API key | Start desktop, or `openwhispr auth login` |+| `Auth failed` (exit 3) on remote commands only | API key revoked, expired, or missing scope | Regenerate key with the right scopes |+| `Not found` (exit 4) on a known-existing note | Wrong backend — the note is on the other side, not yet synced | Try the opposite backend (`--local` or `--remote`) |+| Config file readable by other users | File created or edited outside the CLI | `chmod 0600 ~/.openwhispr/cli-config.json` |++## Programmatic invocation++When invoking from another program, always pass `--format json` and parse stdout. Inspect the exit code first — non-zero codes (1–4) follow the table above. On error, the CLI writes a plain-text message to **stderr** (not JSON) and exits with the relevant code; capture stderr separately to surface it to users.++Successful list/search responses print a bare JSON array (the CLI strips the API's `{data: [...]}` envelope before printing), so `jq '.[]'` is correct, not `jq '.data[]'`. Single-resource gets print the bare object.diff --git a/main.js b/main.jsindex eeeed4445..0c2b23ee2 100644--- a/main.js+++ b/main.js@@ -244,6 +244,7 @@ const ParakeetManager = require("./src/helpers/parakeet");const DiarizationManager = require("./src/helpers/diarization");const TrayManager = require("./src/helpers/tray");const IPCHandlers = require("./src/helpers/ipcHandlers");+const CliBridge = require("./src/helpers/cliBridge");const UpdateManager = require("./src/updater");const GlobeKeyManager = require("./src/helpers/globeKeyManager");const DevServerManager = require("./src/helpers/devServerManager");@@ -285,6 +286,7 @@ let linuxPortalAudioManager = null;let meetingAecManager = null;let qdrantManager = null;let ipcHandlers = null;+let cliBridge = null;let globeKeyAlertShown = false;let authBridgeServer = null;@@ -597,6 +599,12 @@ async function startApp() {initializeCoreManagers();startAuthBridgeServer();+ cliBridge = new CliBridge(ipcHandlers);+ cliBridge.start().catch((err) => {+ debugLogger.error("CLI bridge failed to start", { error: err.message });+ cliBridge = null;+ });+// Electron's file:// sends no Origin header, which Neon Auth rejects.session.defaultSession.webRequest.onBeforeSendHeaders({ urls: ["https://*.neon.tech/*"] },@@ -1321,6 +1329,10 @@ if (gotSingleInstanceLock) {authBridgeServer.close();authBridgeServer = null;}+ if (cliBridge) {+ cliBridge.stop().catch(() => {});+ cliBridge = null;+ }if (windowManager && isLiveWindow(windowManager.agentWindow)) {windowManager.agentWindow.destroy();}diff --git a/src/helpers/cliBridge.js b/src/helpers/cliBridge.jsnew file mode 100644index 000000000..dbc265052--- /dev/null+++ b/src/helpers/cliBridge.js@@ -0,0 +1,407 @@+const http = require("http");+const net = require("net");+const fs = require("fs");+const os = require("os");+const path = require("path");+const crypto = require("crypto");+const debugLogger = require("./debugLogger");++const PORT_RANGE_START = 8200;+const PORT_RANGE_END = 8219;+const HOST = "127.0.0.1";+const BRIDGE_FILE_VERSION = 1;+const MAX_REQUEST_BODY_BYTES = 1 * 1024 * 1024;+const LOOPBACK_ADDRESSES = new Set(["127.0.0.1", "::1", "::ffff:127.0.0.1"]);++const NO_CONTENT = Symbol("CliBridge.NoContent");++function getBridgeFilePath() {+ return path.join(os.homedir(), ".openwhispr", "cli-bridge.json");+}++function isPortAvailable(port) {+ return new Promise((resolve) => {+ const server = net.createServer();+ server.once("error", () => resolve(false));+ server.once("listening", () => {+ server.close();+ resolve(true);+ });+ server.listen(port, HOST);+ });+}++async function findAvailablePort() {+ for (let port = PORT_RANGE_START; port <= PORT_RANGE_END; port++) {+ if (await isPortAvailable(port)) return port;+ }+ throw new Error(`No available ports in range ${PORT_RANGE_START}-${PORT_RANGE_END}`);+}++function readJsonBody(req) {+ return new Promise((resolve, reject) => {+ let raw = "";+ req.on("data", (chunk) => {+ raw += chunk;+ if (raw.length > MAX_REQUEST_BODY_BYTES) {+ reject(new Error("Request body too large"));+ req.destroy();+ }+ });+ req.on("end", () => {+ if (!raw) return resolve({});+ try {+ resolve(JSON.parse(raw));+ } catch {+ reject(new Error("Invalid JSON payload"));+ }+ });+ req.on("error", reject);+ });+}++function sendJson(res, statusCode, payload) {+ const body = JSON.stringify(payload);+ res.writeHead(statusCode, {+ "Content-Type": "application/json; charset=utf-8",+ "Content-Length": Buffer.byteLength(body),+ });+ res.end(body);+}++function sendNoContent(res) {+ res.writeHead(204);+ res.end();+}++function sendV1Error(res, statusCode, code, message) {+ sendJson(res, statusCode, { error: { code, message } });+}++function parseIdParam(value) {+ const id = Number(value);+ if (!Number.isInteger(id) || id <= 0) return null;+ return id;+}++function unwrapMutationResult(result, label) {+ if (!result?.success || !result[label]) {+ throw new Error(result?.error || `Failed to write ${label}`);+ }+ return result[label];+}++class CliBridge {+ constructor(ipcHandlers) {+ this.ipcHandlers = ipcHandlers;+ this.server = null;+ this.port = null;+ this.token = null;+ this.bridgeFilePath = getBridgeFilePath();+ this.routes = this._buildRouteTable();+ }++ async start() {+ if (this.server) return;++ this.token = crypto.randomBytes(32).toString("hex");+ this.port = await findAvailablePort();+ this.server = http.createServer((req, res) => {+ this._handleRequest(req, res).catch((err) => {+ debugLogger.error("CLI bridge handler error", { error: err.message }, "cli-bridge");+ if (!res.headersSent) {+ sendV1Error(res, 500, "internal_error", "Internal server error");+ }+ });+ });++ await new Promise((resolve, reject) => {+ const onError = (err) => {+ this.server = null;+ reject(err);+ };+ this.server.once("error", onError);+ this.server.listen(this.port, HOST, () => {+ this.server.removeListener("error", onError);+ resolve();+ });+ });++ this._writeBridgeFile();+ debugLogger.info("CLI bridge started", { port: this.port }, "cli-bridge");+ }++ async stop() {+ if (!this.server) return;+ await new Promise((resolve) => {+ this.server.close(() => resolve());+ });+ this.server = null;+ this.port = null;+ this.token = null;+ this._removeBridgeFile();+ debugLogger.info("CLI bridge stopped", {}, "cli-bridge");+ }++ _writeBridgeFile() {+ const dir = path.dirname(this.bridgeFilePath);+ fs.mkdirSync(dir, { recursive: true });+ const payload = JSON.stringify({+ version: BRIDGE_FILE_VERSION,+ port: this.port,+ token: this.token,+ });+ fs.writeFileSync(this.bridgeFilePath, payload, { mode: 0o600 });+ // Re-apply mode in case the filesystem ignored the mode arg on create.+ // No-op on Windows ACLs but harmless; swallow errors from exotic filesystems.+ try {+ fs.chmodSync(this.bridgeFilePath, 0o600);+ } catch (err) {+ debugLogger.debug("CLI bridge chmod failed", { error: err.message }, "cli-bridge");+ }+ }++ _removeBridgeFile() {+ try {+ fs.unlinkSync(this.bridgeFilePath);+ } catch (err) {+ if (err.code !== "ENOENT") {+ debugLogger.debug("CLI bridge file removal failed", { error: err.message }, "cli-bridge");+ }+ }+ }++ async _handleRequest(req, res) {+ const remote = req.socket?.remoteAddress;+ if (!remote || !LOOPBACK_ADDRESSES.has(remote)) {+ sendV1Error(res, 403, "forbidden", "Forbidden");+ return;+ }++ const auth = req.headers["authorization"] || "";+ const expected = `Bearer ${this.token}`;+ if (+ auth.length !== expected.length ||+ !crypto.timingSafeEqual(Buffer.from(auth), Buffer.from(expected))+ ) {+ sendV1Error(res, 401, "unauthorized", "Unauthorized");+ return;+ }++ const url = new URL(req.url || "/", `http://${HOST}:${this.port}`);+ const route = this._matchRoute(req.method, url.pathname);+ if (!route) {+ sendV1Error(res, 404, "not_found", "Not found");+ return;+ }++ let body = {};+ if (req.method !== "GET" && req.method !== "DELETE") {+ try {+ body = await readJsonBody(req);+ } catch (err) {+ sendV1Error(res, 400, "validation_error", err.message);+ return;+ }+ }++ try {+ const result = await route.handler({ params: route.params, query: url.searchParams, body });+ if (result === NO_CONTENT) {+ sendNoContent(res);+ return;+ }+ const status = route.status || 200;+ sendJson(res, status, result);+ } catch (err) {+ this._sendError(res, err);+ }+ }++ _sendError(res, err) {+ if (err.code === "NOT_FOUND") {+ sendV1Error(res, 404, "not_found", err.message);+ return;+ }+ debugLogger.error("CLI bridge route error", { error: err.message }, "cli-bridge");+ sendV1Error(res, 500, "internal_error", err.message || "Internal server error");+ }++ _matchRoute(method, pathname) {+ for (const route of this.routes) {+ if (route.method !== method) continue;+ const params = route.match(pathname);+ if (params) return { ...route, params };+ }+ return null;+ }++ _buildRouteTable() {+ const exact = (method, path, handler, status) => ({+ method,+ match: (p) => (p === path ? {} : null),+ handler,+ status,+ });+ const param = (method, prefix, suffix, paramName, handler, status) => ({+ method,+ match: (p) => {+ if (!p.startsWith(prefix)) return null;+ const rest = p.slice(prefix.length);+ if (suffix) {+ if (!rest.endsWith(suffix)) return null;+ const value = rest.slice(0, rest.length - suffix.length);+ if (!value || value.includes("/")) return null;+ return { [paramName]: value };+ }+ if (rest.includes("/")) return null;+ return { [paramName]: rest };+ },+ handler,+ status,+ });++ const db = this.ipcHandlers.databaseManager;+ const ipc = this.ipcHandlers;++ const requireId = (params, label) => {+ const id = parseIdParam(params.id);+ if (id == null) {+ const err = new Error(`Invalid ${label} id`);+ err.code = "NOT_FOUND";+ throw err;+ }+ return id;+ };++ const requireSuccess = (result, message) => {+ if (!result?.success) {+ const err = new Error(result?.error || message);+ err.code = "NOT_FOUND";+ throw err;+ }+ };++ return [+ exact("GET", "/v1/health", () => ({ data: { ok: true, version: 1 } })),+ exact("GET", "/v1/notes/list", ({ query }) => {+ const noteType = query.get("note_type") || null;+ const limit = query.get("limit") ? Number(query.get("limit")) : 100;+ const folderId = query.get("folder_id") ? Number(query.get("folder_id")) : null;+ const notes = db.getNotes(noteType, limit, folderId);+ return { data: notes, has_more: false, next_cursor: null };+ }),+ exact("GET", "/v1/notes/search", ({ query }) => {+ const q = query.get("q") || "";+ if (!q.trim()) {+ const err = new Error("Search query is required");+ err.code = "VALIDATION";+ throw err;+ }+ const limit = query.get("limit") ? Number(query.get("limit")) : 20;+ const notes = db.searchNotes(q, limit);+ return { data: notes, has_more: false, next_cursor: null };+ }),+ param("GET", "/v1/notes/", "", "id", ({ params }) => {+ const id = requireId(params, "note");+ const note = db.getNote(id);+ if (!note || note.deleted_at) {+ const err = new Error(`Note ${id} not found`);+ err.code = "NOT_FOUND";+ throw err;+ }+ return { data: note };+ }),+ exact(+ "POST",+ "/v1/notes/create",+ ({ body }) => {+ const result = db.saveNote(+ body.title ?? "Untitled Note",+ body.content ?? "",+ body.note_type ?? "personal",+ body.source_file ?? null,+ body.audio_duration_seconds ?? null,+ body.folder_id ?? null+ );+ const note = unwrapMutationResult(result, "note");+ setImmediate(() => ipc.broadcastToWindows("note-added", note));+ ipc._asyncVectorUpsert(note);+ ipc._asyncMirrorWrite(note);+ return { data: note };+ },+ 201+ ),+ param("PATCH", "/v1/notes/", "", "id", ({ params, body }) => {+ const id = requireId(params, "note");+ const result = db.updateNote(id, body || {});+ const note = unwrapMutationResult(result, "note");+ setImmediate(() => ipc.broadcastToWindows("note-updated", note));+ ipc._asyncVectorUpsert(note);+ ipc._asyncMirrorWrite(note);+ return { data: note };+ }),+ param("DELETE", "/v1/notes/", "", "id", ({ params }) => {+ const id = requireId(params, "note");+ const result = ipc.deleteNoteInternal(id);+ requireSuccess(result, `Note ${id} not found`);+ return NO_CONTENT;+ }),+ exact("GET", "/v1/folders/list", () => {+ return { data: db.getFolders(), has_more: false, next_cursor: null };+ }),+ exact(+ "POST",+ "/v1/folders/create",+ ({ body }) => {+ const result = db.createFolder(body?.name);+ const folder = unwrapMutationResult(result, "folder");+ setImmediate(() => ipc.broadcastToWindows("folder-created", folder));+ return { data: folder };+ },+ 201+ ),+ exact("GET", "/v1/transcriptions/list", ({ query }) => {+ const limit = query.get("limit") ? Number(query.get("limit")) : 50;+ return {+ data: db.getTranscriptions(limit),+ has_more: false,+ next_cursor: null,+ };+ }),+ param("GET", "/v1/transcriptions/", "", "id", ({ params }) => {+ const id = requireId(params, "transcription");+ const transcription = db.getTranscriptionById(id);+ if (!transcription || transcription.deleted_at) {+ const err = new Error(`Transcription ${id} not found`);+ err.code = "NOT_FOUND";+ throw err;+ }+ return { data: transcription };+ }),+ param("DELETE", "/v1/transcriptions/", "", "id", ({ params }) => {+ const id = requireId(params, "transcription");+ const result = ipc.deleteTranscriptionInternal(id);+ requireSuccess(result, `Transcription ${id} not found`);+ return NO_CONTENT;+ }),+ param("DELETE", "/v1/transcriptions/", "/audio", "id", ({ params }) => {+ const id = requireId(params, "transcription");+ const result = ipc.audioStorageManager.deleteAudio(id);+ if (!result?.success) {+ throw new Error(`Failed to delete audio for transcription ${id}`);+ }+ db.updateTranscriptionAudio(id, {+ hasAudio: 0,+ audioDurationMs: null,+ provider: null,+ model: null,+ });+ return NO_CONTENT;+ }),+ ];+ }+}++module.exports = CliBridge;+module.exports.getBridgeFilePath = getBridgeFilePath;diff --git a/src/helpers/database.js b/src/helpers/database.jsindex d0399e1ff..5b7e2535e 100644--- a/src/helpers/database.js+++ b/src/helpers/database.js@@ -610,11 +610,13 @@ class DatabaseManager {if (!this.db) {throw new Error("Database not initialized");}- const row = this.db.prepare("SELECT cloud_id FROM transcriptions WHERE id = ?").get(id);- if (!row) return { success: false, id };+ const row = this.db+ .prepare("SELECT cloud_id, deleted_at FROM transcriptions WHERE id = ?")+ .get(id);+ if (!row || row.deleted_at) return { success: false, id };const stmt = row.cloud_id? this.db.prepare(- "UPDATE transcriptions SET deleted_at = datetime('now'), sync_status = 'pending' WHERE id = ?"+ "UPDATE transcriptions SET deleted_at = datetime('now'), sync_status = 'pending' WHERE id = ? AND deleted_at IS NULL"): this.db.prepare("DELETE FROM transcriptions WHERE id = ?");const result = stmt.run(id);@@ -1045,7 +1047,7 @@ class DatabaseManager {throw new Error("Database not initialized");}const stmt = this.db.prepare(- "UPDATE notes SET deleted_at = datetime('now'), sync_status = 'pending', updated_at = datetime('now') WHERE id = ?"+ "UPDATE notes SET deleted_at = datetime('now'), sync_status = 'pending', updated_at = datetime('now') WHERE id = ? AND deleted_at IS NULL");const result = stmt.run(id);return { success: result.changes > 0, id };diff --git a/src/helpers/ipcHandlers.js b/src/helpers/ipcHandlers.jsindex 16068c5cb..e6bac55fd 100644--- a/src/helpers/ipcHandlers.js+++ b/src/helpers/ipcHandlers.js@@ -737,14 +737,7 @@ class IPCHandlers {});ipcMain.handle("db-delete-transcription", async (event, id) => {- this.audioStorageManager.deleteAudio(id);- const result = this.databaseManager.deleteTranscription(id);- if (result?.success) {- setImmediate(() => {- this.broadcastToWindows("transcription-deleted", { id });- });- }- return result;+ return this.deleteTranscriptionInternal(id);});// Audio storage handlers@@ -913,13 +906,7 @@ class IPCHandlers {});ipcMain.handle("db-delete-note", async (event, id) => {- const result = this.databaseManager.deleteNote(id);- if (result?.success) {- setImmediate(() => this.broadcastToWindows("note-deleted", { id }));- this._asyncVectorDelete(id);- this._asyncMirrorDelete(id);- }- return result;+ return this.deleteNoteInternal(id);});ipcMain.handle("db-search-notes", async (event, query, limit) => {@@ -7720,6 +7707,27 @@ class IPCHandlers {})();}+ deleteTranscriptionInternal(id) {+ this.audioStorageManager.deleteAudio(id);+ const result = this.databaseManager.deleteTranscription(id);+ if (result?.success) {+ setImmediate(() => {+ this.broadcastToWindows("transcription-deleted", { id });+ });+ }+ return result;+ }++ deleteNoteInternal(id) {+ const result = this.databaseManager.deleteNote(id);+ if (result?.success) {+ setImmediate(() => this.broadcastToWindows("note-deleted", { id }));+ this._asyncVectorDelete(id);+ this._asyncMirrorDelete(id);+ }+ return result;+ }+broadcastToWindows(channel, payload) {const windows = BrowserWindow.getAllWindows();windows.forEach((win) => {