Skip to content

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

fix(resources): Release unused search and meeting detection resources (#2299)

Chad Piha5e74e7c9bfb2
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 8144e8c05..7b4c89c11 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,6 +9,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Fixed
+- **Idle OpenWhispr no longer keeps a vector database and an inference process running.** The Qdrant sidecar and the embedding model started on every launch and stayed up for the whole session, and the meeting detectors ran from boot even with meeting notifications turned off. Semantic search now starts on the first assistant search, serves keyword results while it warms up, and releases Qdrant and the embedding session after five minutes without a search. Note edits made while it is asleep are journaled in the notes database and indexed on the next activation, so search results stay complete. The microphone and meeting-app detectors start only once your saved notification preferences are loaded, stop when meeting notifications are off, and a detector stopped mid-scan can no longer come back reporting a meeting app. (#2143)
- **Assistant selection capture handles dormant macOS accessibility trees.** When accessibility exposes only a browser or Electron window, selection capture now tries a synthetic copy instead of assuming nothing is selected. The caret probe also waits long enough for its native retries to finish. Automatic answer delivery still requires a verified writable field at capture and delivery time: an unknown target keeps the answer in the panel and, with Auto-Paste enabled, copies it for manual paste. Dormant inputs still require manual paste because an empty copy cannot distinguish them from an integrated terminal, a page without an input, or some live selections. (#1952)
## [1.10.2] - 2026-09-15
diff --git a/CLAUDE.md b/CLAUDE.md
index 7823a3441..d4a2bbdb8 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -33,7 +33,7 @@ OpenWhispr is an Electron-based desktop dictation application that uses whisper.
- Main Process: Electron main, IPC handlers, database operations
- Renderer Process: React app with context isolation
- Preload Script: Secure bridge between processes
- - ONNX Utility Process: hosts all `onnxruntime-node` inference (text embeddings, speaker embeddings, fbank). Lazy-spawned on first use via `src/helpers/onnxWorkerClient.js` → `src/workers/onnxWorker.js`. Native crashes (e.g., ORT `bad_alloc`) confine to the worker; main process rejects in-flight requests and respawns with backoff. Stopped in `will-quit`.
+ - ONNX Utility Process: hosts all `onnxruntime-node` inference (text embeddings, speaker embeddings, fbank). Lazy-spawned on first use via `src/helpers/onnxWorkerClient.js` → `src/workers/onnxWorker.js`. Native crashes (e.g., ORT `bad_alloc`) confine to the worker; main process rejects in-flight requests and respawns with backoff. A request that times out kills the worker so it respawns the same way; the embedding clients reload their sessions on the new worker. Exits once idle with no session loaded (`releaseIfIdle`, after semantic search releases its model). Stopped in `will-quit`.
3. **Audio Pipeline**:
- MediaRecorder API → Blob → ArrayBuffer → IPC → File → whisper.cpp
@@ -127,9 +127,11 @@ OpenWhispr is an Electron-based desktop dictation application that uses whisper.
- Gates notifications during recording (tap-to-talk and push-to-talk)
- Post-recording cooldown (2.5s) before showing queued notifications
- Priority-based coalescing (process > audio) — one notification, not three
+ - Both detectors start off and only run once the renderer has synced its saved notification preferences (`sync-notification-preferences`); they stop when meeting prompts are disabled and restart when re-enabled. The derivation lives in `meetingDetectionPreferencePolicy.js` (pure, unit-tested in `test/helpers/meetingDetectionPreferencePolicy.test.js`); `ipcHandlers.js` is a thin adapter over it
- **meetingProcessDetector.js**: Detects running meeting apps
- macOS: Event-driven via `systemPreferences.subscribeWorkspaceNotification` (zero CPU)
- Windows/Linux: Shared `processListCache` polling (30s interval)
+ - Scans are start-generation guarded: a process-list read that completes after `stop()` or a newer `start()` is discarded, since the detector is now stopped and started at runtime (notification toggles, auto-end sessions)
- **audioActivityDetector.js**: Detects microphone usage for unscheduled meetings
- macOS: Event-driven via `macos-mic-listener` binary (CoreAudio process objects; aggregate device activity prompts only while a known meeting app is running)
- Windows: Event-driven via `windows-mic-listener.exe` (WASAPI sessions, self-PID exclusion)
@@ -158,8 +160,9 @@ OpenWhispr is an Electron-based desktop dictation application that uses whisper.
- **parakeet.js**: NVIDIA Parakeet model management via sherpa-onnx
- **parakeetServer.js**: sherpa-onnx CLI wrapper for transcription
- **qdrantManager.js**: Qdrant vector DB sidecar process lifecycle (spawn, health check, shutdown)
+- **semanticSearchLifecycle.js**: Single owner of the semantic search resources — starts Qdrant and the embedding model on demand, drains the SQLite change journal, and releases both after 5 minutes idle
- **localEmbeddings.js**: Local text embedding via ONNX Runtime + all-MiniLM-L6-v2 (384-dim vectors)
-- **vectorIndex.js**: Qdrant collection management — upsert, delete, search, batch reindex
+- **vectorIndex.js**: Qdrant collection management — upsert, delete, search
- **windowConfig.js**: Centralized window configuration
- **windowManager.js**: Window creation and lifecycle management
- **cliBridge.js**: Loopback HTTP server on ports 8200–8219, bearer-token auth (token at `~/.openwhispr/cli-bridge.json`), 127.0.0.1-only. Used by the unified CLI to talk to a running desktop app. `POST /v1/transcribe` takes a file **path** (never audio) and runs the user's downloaded local model through `IPCHandlers.transcribeLocalFile`, approving the path with `approveAudioPath` first; `GET /v1/transcribe/models` lists local models with download state and the app's default (`localTranscriptionModels.js`, read from the `.env` pre-warm values).
@@ -238,20 +241,22 @@ OpenWhispr is an Electron-based desktop dictation application that uses whisper.
### Local Semantic Search (Qdrant + MiniLM)
-Always-on offline semantic search that finds notes by meaning, not just keywords. Used by the AI agent's `search_notes` tool. Qdrant starts automatically on app launch; embedding model auto-downloads on first run if missing.
+Offline semantic search that finds notes by meaning, not just keywords. Used by the AI agent's `search_notes` tool. Its resources are lazy (#2143): Qdrant and the embedding model start on the first semantic search (or the first vector write while the index is active), the embedding model downloads on that first activation if missing, and everything is released after 5 minutes idle. While asleep, keyword FTS5 serves searches and note changes are journaled in SQLite.
**Architecture**:
- **Qdrant sidecar**: Rust binary spawned as child process (`qdrantManager.js`), port 6333–6350
- **Embedding model**: `all-MiniLM-L6-v2` via ONNX Runtime (`localEmbeddings.js`), 384-dim vectors
- **Vector index**: Qdrant collection management (`vectorIndex.js`), cosine distance
+- **Lifecycle owner**: `semanticSearchLifecycle.js` — the only caller that starts or stops Qdrant, the embedding model and the collection
- **Hybrid search**: FTS5 + Qdrant in parallel → Reciprocal Rank Fusion (K=60) with 0.3 cosine score threshold
**Pipeline**:
-1. App launches → Qdrant binary starts → collection created. Embedding model auto-downloads if missing (~22MB)
-2. Note create/update/delete → SQLite write → background vector upsert/delete via `_asyncVectorUpsert()`/`_asyncVectorDelete()`
+1. App launches → nothing starts. The first `db-semantic-search-notes` call activates the lifecycle: embedding model downloaded if missing (~22MB) → Qdrant binary starts → collection ensured → the journal is drained. A cold search does not wait: it answers with FTS5 results while activation runs in the background. An existing collection serves searches while the journal drains; a newly created one waits until that activation's drain finishes. A journal row whose upsert keeps failing is parked after three failed attempts, so one bad note never blocks the rest of the index
+2. Note create/update/delete → SQLite write → triggers journal the note id in `pending_vector_changes` → `IPCHandlers.notifyVectorChanges()` wakes an already-active index to drain the journal; an idle index drains it on its next activation
3. Agent searches → `db-semantic-search-notes` IPC → parallel FTS5 + vector search → RRF merge → ranked results
+4. 5 minutes without a search or write → Qdrant is stopped and the embedding session released; FTS5 keeps serving
**Search fallback chain** (in `searchNotesTool.ts`): cloud search → local semantic → FTS5 keyword
@@ -259,11 +264,12 @@ Always-on offline semantic search that finds notes by meaning, not just keywords
- Qdrant data: `~/.cache/openwhispr/qdrant-data/` (`qdrant-data-dev/` in development)
- Qdrant binary: `resources/bin/qdrant-{platform}-{arch}` (bundled — downloaded during `prebuild` / `predev:main`)
-- Embedding model: `~/.cache/openwhispr/embedding-models/all-MiniLM-L6-v2/` (auto-downloaded on first launch)
+- Embedding model: `~/.cache/openwhispr/embedding-models/all-MiniLM-L6-v2/` (downloaded on the first semantic search)
+- Change journal: `pending_vector_changes` table in the notes SQLite database, maintained by triggers
**Dependencies**: `@qdrant/js-client-rest`, `onnxruntime-node`
-**Dev setup**: The Qdrant binary downloads automatically via `predev`/`prestart`. The embedding model auto-downloads on first app launch. To manually download: `npm run download:qdrant` and `npm run download:embedding-model`.
+**Dev setup**: The Qdrant binary downloads automatically via `predev`/`prestart`. The embedding model downloads on the first semantic search. To manually download: `npm run download:qdrant` and `npm run download:embedding-model`.
### Build Scripts (scripts/)
@@ -652,7 +658,7 @@ Detects meetings via three independent sources, orchestrated by `MeetingDetectio
- All prompts render in one always-on-top overlay window (`MeetingNotificationCard`), content-protected so it never appears in screen shares
- Prompt copy is derived in the renderer from `{ variant, event, joinUrl }` (`meetingNotification.*` i18n keys); variants: `detected` (mic evidence), `starting` (calendar event not yet started), `underway` (event in progress)
-- Per-source notification prefs: `notifyCalendarReminders` gates calendar prompts, `notifyMeetingDetection` gates mic/process prompts
+- Per-source notification prefs: `notifyCalendarReminders` gates calendar prompts, `notifyMeetingDetection` gates mic/process prompts and, with `notificationsEnabled`, whether the mic and process detectors run at all (`meetingProcessDetection` additionally gates the process detector); nothing runs until the renderer has synced the saved snapshot
- During recording (tap-to-talk or push-to-talk): ALL notifications suppressed
- After recording: 2.5s cooldown before showing queued notifications
- Multiple signals coalesced: one overlay at a time; a newer prompt replaces the current one
@@ -803,7 +809,7 @@ UI icons come from `src/components/icons/` (vendored Nucleo core outline compone
- [ ] Test meeting notification suppression during recording
- [ ] Test post-recording cooldown (notifications shouldn't flash immediately)
- [ ] Create a note about "quarterly revenue projections", search via agent for "financial forecast" — should match semantically
-- [ ] Verify Qdrant starts on app launch (check debug logs for "qdrant started successfully")
+- [ ] Verify Qdrant stays down at launch and starts on the first agent search (check debug logs for "qdrant started successfully"), then stops after 5 idle minutes
- [ ] Kill Qdrant process manually — verify FTS5 keyword search still works as fallback
### Common Issues and Solutions
@@ -853,7 +859,7 @@ UI icons come from `src/components/icons/` (vendored Nucleo core outline compone
7. **Local Semantic Search Not Working**:
- Qdrant binary should be in `resources/bin/qdrant-{platform}-{arch}` (auto-downloaded during `predev`/`prebuild`)
- - Embedding model should be in `~/.cache/openwhispr/embedding-models/all-MiniLM-L6-v2/model.onnx` (auto-downloaded on first app launch)
+ - Embedding model should be in `~/.cache/openwhispr/embedding-models/all-MiniLM-L6-v2/model.onnx` (downloaded on the first semantic search)
- Run `npm run download:qdrant` and `npm run download:embedding-model` manually if missing
- Check debug logs for "qdrant" entries (port, health check, errors)
- If Qdrant fails to start, search still works via FTS5 keyword fallback
diff --git a/main.js b/main.js
index 991125da3..c843205e3 100644
--- a/main.js
+++ b/main.js
@@ -336,7 +336,7 @@ let audioTapManager = null;
let linuxPortalAudioManager = null;
let windowsLoopbackAudioManager = null;
let meetingAecManager = null;
-let qdrantManager = null;
+let semanticSearch = null;
let ipcHandlers = null;
let cliBridge = null;
let globeKeyAlertShown = false;
@@ -559,7 +559,7 @@ function initializeCoreManagers() {
linuxPortalAudioManager,
windowsLoopbackAudioManager,
meetingAecManager,
- getQdrantManager: () => qdrantManager,
+ getSemanticSearch: () => semanticSearch,
getTrayManager: () => trayManager,
oauthProtocolRegistered: protocolRegistered,
oauthProtocol: OAUTH_PROTOCOL,
@@ -1292,43 +1292,18 @@ async function startApp() {
}
const QdrantManager = require("./src/helpers/qdrantManager");
- qdrantManager = new QdrantManager();
- // Must not throw: this also runs inside the unhealthy-restart path, whose
- // catch would stop the replacement sidecar.
- const wireVectorIndex = (port) => {
- try {
- const vectorIndex = require("./src/helpers/vectorIndex");
- vectorIndex.init(port);
- vectorIndex
- .ensureCollection()
- .then(() => ipcHandlers?.drainPendingVectorPurges())
- .catch((err) => {
- debugLogger.debug("Qdrant collection setup error (non-fatal)", { error: err.message });
- });
- } catch (err) {
- debugLogger.debug("Qdrant rewire error (non-fatal)", { error: err.message });
- }
- };
- // A successful unhealthy-restart can bring the sidecar back on a new port.
- qdrantManager.on("restarted", wireVectorIndex);
- sidecarRegistry.register("qdrant", () => qdrantManager.stop());
- if (qdrantManager.isAvailable()) {
- qdrantManager
- .start()
- .then(() => {
- if (qdrantManager.isReady()) wireVectorIndex(qdrantManager.getPort());
- })
- .catch((err) => {
- debugLogger.debug("Qdrant startup error (non-fatal)", { error: err.message });
- });
- }
-
+ const SemanticSearchLifecycle = require("./src/helpers/semanticSearchLifecycle");
const localEmbeddings = require("./src/helpers/localEmbeddings");
- if (!localEmbeddings.isAvailable()) {
- localEmbeddings.downloadModel().catch((err) => {
- debugLogger.debug("Embedding model download error (non-fatal)", { error: err.message });
- });
- }
+ const qdrantManager = new QdrantManager();
+ semanticSearch = new SemanticSearchLifecycle({
+ qdrant: qdrantManager,
+ vectorIndex: require("./src/helpers/vectorIndex"),
+ embeddings: localEmbeddings,
+ noteEmbedText: localEmbeddings.LocalEmbeddings.noteEmbedText,
+ database: databaseManager,
+ logger: debugLogger,
+ });
+ sidecarRegistry.register("qdrant", () => semanticSearch.stop());
if (process.platform === "win32") {
const nircmdStatus = clipboardManager.getNircmdStatus();
diff --git a/preload.js b/preload.js
index 79d43900e..ebe0d9746 100644
--- a/preload.js
+++ b/preload.js
@@ -224,12 +224,6 @@ contextBridge.exposeInMainWorld("electronAPI", {
ipcRenderer.invoke("db-search-notes", query, limit, spaceId, folderId),
semanticSearchNotes: (query, limit, spaceId, folderId) =>
ipcRenderer.invoke("db-semantic-search-notes", query, limit, spaceId, folderId),
- semanticReindexAll: () => ipcRenderer.invoke("db-semantic-reindex-all"),
- onSemanticReindexProgress: (callback) => {
- const listener = (_event, data) => callback?.(data);
- ipcRenderer.on("semantic-reindex-progress", listener);
- return () => ipcRenderer.removeListener("semantic-reindex-progress", listener);
- },
updateNoteCloudId: (id, cloudId) => ipcRenderer.invoke("db-update-note-cloud-id", id, cloudId),
updateNoteShareState: (id, state) => ipcRenderer.invoke("db-update-note-share-state", id, state),
@@ -1320,9 +1314,6 @@ contextBridge.exposeInMainWorld("electronAPI", {
),
// Meeting detection
- meetingDetectionGetPreferences: () => ipcRenderer.invoke("meeting-detection-get-preferences"),
- meetingDetectionSetPreferences: (prefs) =>
- ipcRenderer.invoke("meeting-detection-set-preferences", prefs),
syncNotificationPreferences: (prefs) =>
ipcRenderer.invoke("sync-notification-preferences", prefs),
setSpeakerDiarizationEnabled: (enabled) =>
diff --git a/src/components/ControlPanel.tsx b/src/components/ControlPanel.tsx
index fd4768b11..106c8f4ed 100644
--- a/src/components/ControlPanel.tsx
+++ b/src/components/ControlPanel.tsx
@@ -93,10 +93,6 @@ const platform = getCachedPlatform();
const SIDEBAR_WIDTH_PX = 192;
-// Bump to force a one-time full semantic reindex on next launch (see the
-// reindex effect for the per-version history).
-const SEMANTIC_REINDEX_VERSION = 2;
-
const SettingsModal = React.lazy(() => import("./SettingsModal"));
const ReferralModal = React.lazy(() => import("./ReferralModal"));
const InviteTeammateDialog = React.lazy(() => import("./InviteTeammateDialog"));
@@ -283,26 +279,6 @@ export default function ControlPanel({ initialSettingsSection }: ControlPanelPro
});
}, []);
- // One-time background reindex, versioned: v1 backfilled space_id payloads
- // after the spaces migration; v2 backfills cloud-pulled notes, which were
- // never incrementally indexed before the upsert-from-cloud handler gained a
- // vector upsert. Delayed so the Qdrant sidecar has time to come up; if it
- // isn't ready yet the flag stays unset and the next launch retries.
- useEffect(() => {
- if (Number(localStorage.getItem("semanticReindexVersion")) >= SEMANTIC_REINDEX_VERSION) return;
- const timer = setTimeout(() => {
- window.electronAPI
- ?.semanticReindexAll?.()
- .then((result) => {
- if (result?.success) {
- localStorage.setItem("semanticReindexVersion", String(SEMANTIC_REINDEX_VERSION));
- }
- })
- .catch(() => {});
- }, 15_000);
- return () => clearTimeout(timer);
- }, []);
-
useEffect(() => {
if (platform !== "darwin") return;
window.electronAPI?.getPostMigrationState?.().then((state) => {
diff --git a/src/components/SettingsPage.tsx b/src/components/SettingsPage.tsx
index f6231174f..95270764d 100644
--- a/src/components/SettingsPage.tsx
+++ b/src/components/SettingsPage.tsx
@@ -1290,6 +1290,7 @@ export default function SettingsPage({
setWhisperVadSamplesOverlap,
} = useSettings();
+ const meetingProcessDetection = useSettingsStore((state) => state.meetingProcessDetection);
const voiceAgentKey = useSettingsStore((s) => s.voiceAgentKey);
const setVoiceAgentKey = useSettingsStore((s) => s.setVoiceAgentKey);
const translationKey = useSettingsStore((s) => s.translationKey);
@@ -1612,8 +1613,14 @@ export default function SettingsPage({
notificationsEnabled,
notifyMeetingDetection,
notifyCalendarReminders,
+ meetingProcessDetection,
});
- }, [notificationsEnabled, notifyMeetingDetection, notifyCalendarReminders]);
+ }, [
+ notificationsEnabled,
+ notifyMeetingDetection,
+ notifyCalendarReminders,
+ meetingProcessDetection,
+ ]);
const handleAutoStartChange = async (enabled: boolean) => {
if (!window.electronAPI?.setAutoStartEnabled) return;
diff --git a/src/helpers/cliBridge.js b/src/helpers/cliBridge.js
index b9f098f7e..b550a4879 100644
--- a/src/helpers/cliBridge.js
+++ b/src/helpers/cliBridge.js
@@ -424,7 +424,7 @@ class CliBridge {
);
const note = unwrapMutationResult(result, "note");
setImmediate(() => broadcastToWindows("note-added", note));
- ipc._asyncVectorUpsert(note);
+ ipc.notifyVectorChanges();
ipc._asyncMirrorWrite(note);
return { data: note };
},
@@ -435,7 +435,7 @@ class CliBridge {
const result = db.updateNote(id, body || {});
const note = unwrapMutationResult(result, "note");
setImmediate(() => broadcastToWindows("note-updated", note));
- ipc._asyncVectorUpsert(note);
+ ipc.notifyVectorChanges();
ipc._asyncMirrorWrite(note);
return { data: note };
}),
diff --git a/src/helpers/database.js b/src/helpers/database.js
index b517e36b7..ad1b42655 100644
--- a/src/helpers/database.js
+++ b/src/helpers/database.js
@@ -1274,13 +1274,14 @@ class DatabaseManager {
}
// Space vector purges owed to Qdrant while the sidecar was down/booting;
- // drained once the vector index is ready.
+ // drained on the next semantic search activation.
this.db.exec(`
CREATE TABLE IF NOT EXISTS pending_vector_purges (
space_id INTEGER PRIMARY KEY,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
)
`);
+ this._initVectorChangeJournal();
return true;
} catch (error) {
@@ -3949,6 +3950,76 @@ class DatabaseManager {
}
}
+ _initVectorChangeJournal() {
+ this.db.transaction(() => {
+ const journalExists = this.db
+ .prepare(
+ "SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'pending_vector_changes'"
+ )
+ .get();
+ // AUTOINCREMENT keeps acknowledgements unique even after the queue is
+ // emptied or a deleted note id is reused while indexing is in flight.
+ this.db.exec(`
+ CREATE TABLE IF NOT EXISTS pending_vector_changes (
+ revision INTEGER PRIMARY KEY AUTOINCREMENT,
+ note_id INTEGER NOT NULL UNIQUE
+ );
+ CREATE TRIGGER IF NOT EXISTS notes_vector_insert AFTER INSERT ON notes BEGIN
+ INSERT INTO pending_vector_changes (note_id) VALUES (NEW.id)
+ ON CONFLICT(note_id) DO UPDATE SET revision = excluded.revision;
+ END;
+ CREATE TRIGGER IF NOT EXISTS notes_vector_update
+ AFTER UPDATE OF title, content, enhanced_content, space_id, folder_id, deleted_at ON notes
+ WHEN OLD.title IS NOT NEW.title OR OLD.content IS NOT NEW.content
+ OR OLD.enhanced_content IS NOT NEW.enhanced_content
+ OR OLD.space_id IS NOT NEW.space_id OR OLD.folder_id IS NOT NEW.folder_id
+ OR OLD.deleted_at IS NOT NEW.deleted_at
+ BEGIN
+ INSERT INTO pending_vector_changes (note_id) VALUES (NEW.id)
+ ON CONFLICT(note_id) DO UPDATE SET revision = excluded.revision;
+ END;
+ CREATE TRIGGER IF NOT EXISTS notes_vector_delete AFTER DELETE ON notes BEGIN
+ INSERT INTO pending_vector_changes (note_id) VALUES (OLD.id)
+ ON CONFLICT(note_id) DO UPDATE SET revision = excluded.revision;
+ END;
+ `);
+ if (!journalExists) this.enqueueAllVectorChanges();
+ })();
+ }
+
+ getPendingVectorChanges(limit = 50, afterRevision = 0) {
+ if (!this.db) throw new Error("Database not initialized");
+ return this.db
+ .prepare(
+ "SELECT note_id, revision FROM pending_vector_changes WHERE revision > ? ORDER BY revision LIMIT ?"
+ )
+ .all(afterRevision, limit);
+ }
+
+ clearPendingVectorChange(noteId, revision) {
+ if (!this.db) throw new Error("Database not initialized");
+ const result = this.db
+ .prepare("DELETE FROM pending_vector_changes WHERE note_id = ? AND revision = ?")
+ .run(noteId, revision);
+ return { success: true, changes: result.changes };
+ }
+
+ enqueueAllVectorChanges() {
+ if (!this.db) throw new Error("Database not initialized");
+ this.db.exec(`
+ INSERT INTO pending_vector_changes (note_id) SELECT id FROM notes WHERE TRUE
+ ON CONFLICT(note_id) DO UPDATE SET revision = excluded.revision
+ `);
+ return { success: true };
+ }
+
+ getNoteForVectorIndex(noteId) {
+ if (!this.db) throw new Error("Database not initialized");
+ // The durable index spans accounts; renderer/search reads still use the
+ // scoped getNote API before exposing any indexed result.
+ return this.db.prepare("SELECT * FROM notes WHERE id = ?").get(noteId) || null;
+ }
+
addPendingVectorPurge(spaceId) {
try {
if (!this.db) throw new Error("Database not initialized");
diff --git a/src/helpers/ipcHandlers.js b/src/helpers/ipcHandlers.js
index 6514afba0..cdd6cf64c 100644
--- a/src/helpers/ipcHandlers.js
+++ b/src/helpers/ipcHandlers.js
@@ -119,6 +119,7 @@ const {
MEETING_MIC_SILENCE_RMS,
MEETING_MIC_SILENCE_PEAK,
} = require("./meetingMicGate");
+const { deriveDetectorPreferences } = require("./meetingDetectionPreferencePolicy");
const { resolveDiarizationInput } = require("./meetingDiarizationInput");
const { applySmartSpacing } = require("./smartSpacing");
const { applyAutoLearnSetting } = require("./autoLearnSetting");
@@ -615,7 +616,7 @@ class IPCHandlers {
this.linuxPortalAudioManager = managers.linuxPortalAudioManager;
this.windowsLoopbackAudioManager = managers.windowsLoopbackAudioManager;
this.meetingAecManager = managers.meetingAecManager;
- this.getQdrantManager = managers.getQdrantManager;
+ this.getSemanticSearch = managers.getSemanticSearch;
this.oauthProtocolRegistered = managers.oauthProtocolRegistered === true;
this.oauthProtocol = managers.oauthProtocol || "openwhispr";
this.sessionId = crypto.randomUUID();
@@ -655,6 +656,9 @@ class IPCHandlers {
this._granolaImportPending = null;
this._analyticsHistoryBackfillPromise = null;
this.speakerDiarizationEnabled = true;
+ // Default for the saved process-detection toggle. The engine keeps both detectors
+ // off until the renderer syncs (see meetingDetectionPreferencePolicy.js).
+ this.meetingProcessDetection = true;
this.activeMeetingSpeakerConfig = null;
this.whisperVadSettings = {
dictationSileroEnabled: false,
@@ -902,46 +906,10 @@ class IPCHandlers {
};
}
- _asyncVectorUpsert(note) {
- setImmediate(() => {
- const vectorIndex = require("./vectorIndex");
- if (!vectorIndex.isReady()) return;
- const { LocalEmbeddings } = require("./localEmbeddings");
- const text = LocalEmbeddings.noteEmbedText(note.title, note.content, note.enhanced_content);
- vectorIndex
- .upsertNote(note.id, text, { space_id: note.space_id, folder_id: note.folder_id ?? null })
- .catch(() => {});
- });
- }
-
- _asyncVectorDelete(noteId) {
- setImmediate(() => {
- const vectorIndex = require("./vectorIndex");
- if (!vectorIndex.isReady()) return;
- vectorIndex.deleteNote(noteId).catch(() => {});
- });
- }
-
- // Space vector purges are persisted (pending_vector_purges) so a purge that
- // lands while Qdrant is booting or down is retried once the index is ready.
- drainPendingVectorPurges() {
- setImmediate(() => {
- void (async () => {
- const vectorIndex = require("./vectorIndex");
- if (!vectorIndex.isReady()) return;
- for (const { space_id } of this.databaseManager.getPendingVectorPurges()) {
- if (await vectorIndex.deleteBySpace(space_id)) {
- this.databaseManager.clearPendingVectorPurge(space_id);
- }
- }
- })().catch((error) => {
- debugLogger.error(
- "Pending vector purge drain failed",
- { error: error?.message || String(error) },
- "semantic-search"
- );
- });
- });
+ // Note writes are journaled by SQLite triggers (pending_vector_changes); this
+ // only wakes an active semantic index to drain them.
+ notifyVectorChanges() {
+ this.getSemanticSearch?.()?.notifyChanges();
}
_mirrorDeleteFolderIfUnshared(folderName) {
@@ -2027,7 +1995,7 @@ class IPCHandlers {
);
if (result?.success && result?.note) {
setImmediate(() => broadcastToWindows("note-added", result.note));
- this._asyncVectorUpsert(result.note);
+ this.notifyVectorChanges();
this._asyncMirrorWrite(result.note);
}
return result;
@@ -2050,7 +2018,7 @@ class IPCHandlers {
const result = this.databaseManager.updateNote(id, updates);
if (result?.success && result?.note) {
setImmediate(() => broadcastToWindows("note-updated", result.note));
- this._asyncVectorUpsert(result.note);
+ this.notifyVectorChanges();
this._asyncMirrorWrite(result.note);
if (updates.participants) {
this._tryAutoLabelOneOnOne(id);
@@ -2071,11 +2039,6 @@ class IPCHandlers {
ipcMain.handle(
"db-semantic-search-notes",
async (event, query, limit = 5, spaceId, folderId) => {
- const vectorIndex = require("./vectorIndex");
- if (!vectorIndex.isReady()) {
- return this.databaseManager.searchNotes(query, limit, spaceId, folderId);
- }
-
try {
// Qdrant payload updates are best-effort. Use its space filter to
// reduce the candidate set, then validate every scoped vector hit
@@ -2087,8 +2050,9 @@ class IPCHandlers {
: undefined;
const [ftsResults, vectorResults] = await Promise.all([
this.databaseManager.searchNotes(query, overFetch, spaceId, folderId),
- vectorIndex.search(query, overFetch, vectorFilter),
+ this.getSemanticSearch?.()?.search(query, overFetch, vectorFilter),
]);
+ if (vectorResults == null) return ftsResults.slice(0, limit);
const scopedIds = new Set(
this.databaseManager.getNoteIdsInScope(
spaceId,
@@ -2135,20 +2099,6 @@ class IPCHandlers {
}
);
- ipcMain.handle("db-semantic-reindex-all", async () => {
- const vectorIndex = require("./vectorIndex");
- if (!vectorIndex.isReady()) return { success: false, error: "Vector index not ready" };
-
- const notes = this.databaseManager.getNotes(null, 100000);
- let done = 0;
- const { failed } = await vectorIndex.reindexAll(notes, (completed, total) => {
- done = completed;
- broadcastToWindows("semantic-reindex-progress", { done: completed, total });
- });
- // Report failed batches so callers only latch their done-flag on a clean pass.
- return { success: failed === 0, indexed: done - failed };
- });
-
ipcMain.handle("db-update-note-cloud-id", async (event, id, cloudId) => {
return this.databaseManager.updateNoteCloudId(id, cloudId);
});
@@ -2183,9 +2133,7 @@ class IPCHandlers {
const folderName = this._noteFilesEnabled ? this._getFolderName(id) : null;
const result = this.databaseManager.deleteFolder(id);
if (result?.success) {
- for (const noteId of result.noteIds ?? []) {
- this._asyncVectorDelete(noteId);
- }
+ this.notifyVectorChanges();
// Other accounts' notes were released to the space root; their mirror
// files leave with the folder directory, so rewrite the live ones.
for (const note of result.relocatedNotes ?? []) {
@@ -2217,10 +2165,8 @@ class IPCHandlers {
ipcMain.handle("db-move-folder-to-space", async (event, id, spaceId) => {
const result = this.databaseManager.moveFolderToSpace(id, spaceId);
if (result?.success) {
- // Qdrant payloads carry space_id — refresh the moved notes' vectors.
- for (const note of result.notes ?? []) {
- this._asyncVectorUpsert(note);
- }
+ // Qdrant payloads carry space_id — the triggers journaled the moved notes.
+ this.notifyVectorChanges();
if (result.folder) {
setImmediate(() => broadcastToWindows("folder-synced", result.folder));
}
@@ -2287,8 +2233,8 @@ class IPCHandlers {
}
try {
const result = this.databaseManager.deleteAccountData(accountId);
+ this.notifyVectorChanges();
for (const noteId of result.deletedNoteIds) {
- this._asyncVectorDelete(noteId);
this._asyncMirrorDelete(noteId);
}
return { success: true, ...result };
@@ -2319,10 +2265,10 @@ class IPCHandlers {
const result = this.databaseManager.purgeSpace(id, options);
if (result?.success) {
if (!result.preservedForOtherAccounts) {
+ // The purge row and the relocated notes' trigger rows drain together.
this.databaseManager.addPendingVectorPurge(result.spaceId);
- this.drainPendingVectorPurges();
+ this.notifyVectorChanges();
for (const note of result.relocatedNotes ?? []) {
- this._asyncVectorUpsert(note);
this._asyncMirrorWrite(note);
}
for (const noteId of result.noteIds ?? []) {
@@ -2505,7 +2451,7 @@ class IPCHandlers {
const note = this.databaseManager.upsertNoteFromCloud(cloudNote, localFolderId, localSpaceId);
if (note) {
setImmediate(() => broadcastToWindows("note-synced", note));
- this._asyncVectorUpsert(note);
+ this.notifyVectorChanges();
}
return note;
});
@@ -2550,7 +2496,7 @@ class IPCHandlers {
ipcMain.handle("db-hard-delete-note", (_, id) => {
const result = this.databaseManager.hardDeleteNote(id);
if (result?.success) {
- this._asyncVectorDelete(id);
+ this.notifyVectorChanges();
this._asyncMirrorDelete(id);
setImmediate(() => broadcastToWindows("note-deleted", { id }));
}
@@ -2591,8 +2537,8 @@ class IPCHandlers {
ipcMain.handle("db-restore-folder-after-denied-delete", (_, id) => {
const result = this.databaseManager.restoreFolderAfterDeniedDelete(id);
if (result?.success) {
+ this.notifyVectorChanges();
for (const note of result.notes ?? []) {
- this._asyncVectorUpsert(note);
this._asyncMirrorWrite(note);
}
setImmediate(() => {
@@ -2607,9 +2553,7 @@ class IPCHandlers {
ipcMain.handle("db-hard-delete-folder", (_, id) => {
const result = this.databaseManager.hardDeleteFolder(id);
if (result?.success) {
- for (const noteId of result.noteIds ?? []) {
- this._asyncVectorDelete(noteId);
- }
+ this.notifyVectorChanges();
// Other accounts' notes were released to the space root; their mirror
// files leave with the folder directory, so rewrite the live ones.
for (const note of result.relocatedNotes ?? []) {
@@ -2625,14 +2569,13 @@ class IPCHandlers {
ipcMain.handle("db-relocate-revoked-folder", (_, id, privateSpaceId, preserveFolder) => {
const result = this.databaseManager.relocateRevokedFolder(id, privateSpaceId, preserveFolder);
if (result?.success) {
- // Qdrant payloads carry space_id and the markdown mirror files by
- // folder — refresh relocated notes, drop the server-owned ones.
+ // The triggers journaled the relocated and deleted notes. Mirror files live by
+ // folder, so rewrite the relocated notes and drop the server-owned ones.
+ this.notifyVectorChanges();
for (const note of result.relocatedNotes ?? []) {
- this._asyncVectorUpsert(note);
this._asyncMirrorWrite(note);
}
for (const noteId of result.deletedNoteIds ?? []) {
- this._asyncVectorDelete(noteId);
this._asyncMirrorDelete(noteId);
}
setImmediate(() => {
@@ -3961,7 +3904,7 @@ class IPCHandlers {
errors.push(`Diarization stop: ${e.message}`);
}
try {
- await this.getQdrantManager?.()?.stop();
+ await this.getSemanticSearch?.()?.stop();
} catch (e) {
errors.push(`Vector index stop: ${e.message}`);
}
@@ -11587,23 +11530,6 @@ class IPCHandlers {
return crypto.createHash("md5").update(text.toLowerCase().trim()).digest("hex");
});
- ipcMain.handle("meeting-detection-get-preferences", async () => {
- try {
- return { success: true, preferences: this.meetingDetectionEngine.getPreferences() };
- } catch (error) {
- return { success: false, error: error.message };
- }
- });
-
- ipcMain.handle("meeting-detection-set-preferences", async (_event, prefs) => {
- try {
- this.meetingDetectionEngine.setPreferences(prefs);
- return { success: true };
- } catch (error) {
- return { success: false, error: error.message };
- }
- });
-
const NOTIFICATION_PREF_KEYS = new Set([
"notificationsEnabled",
"notifyMeetingDetection",
@@ -11615,17 +11541,23 @@ class IPCHandlers {
if (!prefs || typeof prefs !== "object") {
return { success: false, error: "Invalid preferences" };
}
- for (const [k, v] of Object.entries(prefs)) {
- if (NOTIFICATION_PREF_KEYS.has(k)) {
- this.windowManager.notificationPrefs[k] = !!v;
+ for (const [key, value] of Object.entries(prefs)) {
+ if (NOTIFICATION_PREF_KEYS.has(key)) {
+ this.windowManager.notificationPrefs[key] = !!value;
}
}
- // Detection only serves the notification, so the toggle also gates the detector.
+ if (typeof prefs.meetingProcessDetection === "boolean") {
+ this.meetingProcessDetection = prefs.meetingProcessDetection;
+ }
const { notificationsEnabled, notifyMeetingDetection } =
this.windowManager.notificationPrefs;
- this.meetingDetectionEngine?.setPreferences({
- audioDetection: notificationsEnabled && notifyMeetingDetection,
- });
+ this.meetingDetectionEngine?.setPreferences(
+ deriveDetectorPreferences({
+ notificationsEnabled,
+ notifyMeetingDetection,
+ meetingProcessDetection: this.meetingProcessDetection,
+ })
+ );
return { success: true };
} catch (error) {
return { success: false, error: error.message };
@@ -11897,23 +11829,12 @@ class IPCHandlers {
try {
const result = this.databaseManager.importNotes(pending.notes);
if (result.imported > 0) {
- const importedIds = result.noteIds;
- // One-shot side effects: batched vector upsert of just the new notes
- // and a single mirror rebuild — never per-note work (sync storm /
- // O(notes × files) mirror scans).
+ // One-shot side effects: a single index wake-up (the SQLite triggers
+ // already journaled every imported note) and a single mirror rebuild —
+ // never per-note work (sync storm / O(notes × files) mirror scans).
setImmediate(() => {
try {
- const vectorIndex = require("./vectorIndex");
- if (vectorIndex.isReady()) {
- const importedNotes = importedIds
- .map((id) => this.databaseManager.getNote(id))
- .filter(Boolean);
- vectorIndex
- .reindexAll(importedNotes, (done, total) => {
- broadcastToWindows("semantic-reindex-progress", { done, total });
- })
- .catch(() => {});
- }
+ this.notifyVectorChanges();
if (this._noteFilesEnabled) this._rebuildMirror();
} catch (sideEffectError) {
debugLogger.error(
@@ -12524,7 +12445,7 @@ class IPCHandlers {
const result = this.databaseManager.deleteNote(id);
if (result?.success) {
setImmediate(() => broadcastToWindows("note-deleted", { id }));
- this._asyncVectorDelete(id);
+ this.notifyVectorChanges();
this._asyncMirrorDelete(id);
}
return result;
diff --git a/src/helpers/localEmbeddings.js b/src/helpers/localEmbeddings.js
index 25d7e71ee..fd8857354 100644
--- a/src/helpers/localEmbeddings.js
+++ b/src/helpers/localEmbeddings.js
@@ -9,6 +9,8 @@ const MODEL_SUBDIR = "all-MiniLM-L6-v2";
class LocalEmbeddings {
constructor() {
this.loadPromise = null;
+ this.loadedGeneration = null;
+ this.operationQueue = Promise.resolve();
this.modelDir = this._resolveModelDir();
}
@@ -50,13 +52,16 @@ class LocalEmbeddings {
}
_ensureLoaded() {
- if (this.loadPromise) return this.loadPromise;
+ if (this.loadPromise && this.loadedGeneration === onnxWorkerClient.generation) {
+ return this.loadPromise;
+ }
if (!this.isAvailable()) {
return Promise.reject(
new Error("Embedding model not found. Run: node scripts/download-minilm.js")
);
}
debugLogger.debug("local-embeddings loading model", { modelDir: this.modelDir });
+ this.loadedGeneration = onnxWorkerClient.generation;
this.loadPromise = onnxWorkerClient
.request("text.load", { modelDir: this.modelDir })
.then(() => debugLogger.debug("local-embeddings model loaded"))
@@ -67,18 +72,42 @@ class LocalEmbeddings {
return this.loadPromise;
}
- async embedText(text) {
+ _enqueue(operation) {
+ const result = this.operationQueue.then(operation);
+ this.operationQueue = result.catch(() => {});
+ return result;
+ }
+
+ async _embedText(text) {
await this._ensureLoaded();
const { embeddingBuffer } = await onnxWorkerClient.request("text.embed", { text });
return new Float32Array(embeddingBuffer);
}
- async embedTexts(texts) {
- const results = [];
- for (const text of texts) {
- results.push(await this.embedText(text));
- }
- return results;
+ embedText(text) {
+ return this._enqueue(() => this._embedText(text));
+ }
+
+ embedTexts(texts) {
+ return this._enqueue(async () => {
+ const results = [];
+ for (const text of texts) {
+ results.push(await this._embedText(text));
+ }
+ return results;
+ });
+ }
+
+ unload() {
+ return this._enqueue(async () => {
+ try {
+ await onnxWorkerClient.request("text.unload", {});
+ } finally {
+ this.loadPromise = null;
+ this.loadedGeneration = null;
+ }
+ await onnxWorkerClient.releaseIfIdle();
+ });
}
static noteEmbedText(title, content, enhancedContent) {
diff --git a/src/helpers/meetingDetectionEngine.js b/src/helpers/meetingDetectionEngine.js
index 02e173383..efd130eee 100644
--- a/src/helpers/meetingDetectionEngine.js
+++ b/src/helpers/meetingDetectionEngine.js
@@ -48,7 +48,8 @@ class MeetingDetectionEngine {
this.windowManager = windowManager;
this.databaseManager = databaseManager;
this.activeDetections = new Map();
- this.preferences = { processDetection: true, audioDetection: true };
+ // Saved renderer preferences arrive after engine startup.
+ this.preferences = { processDetection: false, audioDetection: false };
this._userRecording = false;
this._meetingModeActive = false;
this._notificationQueue = [];
@@ -738,10 +739,6 @@ class MeetingDetectionEngine {
this._syncAudioActivityDetector();
}
- getPreferences() {
- return { ...this.preferences };
- }
-
start() {
debugLogger.info("Meeting detection engine started", this.preferences, "meeting");
this._syncMeetingProcessDetector();
diff --git a/src/helpers/meetingDetectionPreferencePolicy.js b/src/helpers/meetingDetectionPreferencePolicy.js
new file mode 100644
index 000000000..de2734cfe
--- /dev/null
+++ b/src/helpers/meetingDetectionPreferencePolicy.js
@@ -0,0 +1,19 @@
+// Meeting detector gating, kept free of Electron so it can be unit-tested.
+//
+// The detectors exist only to serve meeting prompts, so they follow the saved
+// notification toggles: both detectors stop when meeting prompts are off, and
+// process detection additionally honours its own toggle.
+
+function deriveDetectorPreferences({
+ notificationsEnabled,
+ notifyMeetingDetection,
+ meetingProcessDetection,
+}) {
+ const audioDetection = notificationsEnabled === true && notifyMeetingDetection === true;
+ return {
+ audioDetection,
+ processDetection: audioDetection && meetingProcessDetection === true,
+ };
+}
+
+module.exports = { deriveDetectorPreferences };
diff --git a/src/helpers/meetingProcessDetector.js b/src/helpers/meetingProcessDetector.js
index 2bc77b75a..2fc33f4c9 100644
--- a/src/helpers/meetingProcessDetector.js
+++ b/src/helpers/meetingProcessDetector.js
@@ -39,13 +39,17 @@ class MeetingProcessDetector extends EventEmitter {
this.dismissedProcesses = new Set();
this._polling = false;
this._subscriptionIds = [];
+ this._running = false;
+ this._startGeneration = 0;
}
start() {
- if (this.pollInterval || this._subscriptionIds.length > 0) return;
+ if (this._running) return;
+ this._running = true;
+ const generation = ++this._startGeneration;
if (process.platform === "darwin") {
- this._startDarwin();
+ this._startDarwin(generation);
} else {
const apps = MEETING_APPS[process.platform] || [];
debugLogger.info(
@@ -57,18 +61,17 @@ class MeetingProcessDetector extends EventEmitter {
},
"meeting"
);
- this._poll();
- this.pollInterval = setInterval(() => this._poll(), POLL_INTERVAL_MS);
+ this._startPolling(generation);
}
}
- _startDarwin() {
+ _startDarwin(generation) {
let systemPreferences;
try {
systemPreferences = require("electron").systemPreferences;
} catch {
debugLogger.warn("systemPreferences unavailable, falling back to polling", {}, "meeting");
- this._startPollingFallback();
+ this._startPollingFallback(generation);
return;
}
@@ -78,7 +81,7 @@ class MeetingProcessDetector extends EventEmitter {
{},
"meeting"
);
- this._startPollingFallback();
+ this._startPollingFallback(generation);
return;
}
@@ -120,12 +123,18 @@ class MeetingProcessDetector extends EventEmitter {
"meeting"
);
- this._initialScanDarwin();
+ this._initialScanDarwin(generation);
}
- async _initialScanDarwin() {
+ // True once stop() or a newer start() has superseded the run that owns `generation`.
+ _isStale(generation) {
+ return !this._running || generation !== this._startGeneration;
+ }
+
+ async _initialScanDarwin(generation) {
try {
const processList = await processListCache.getProcessList();
+ if (this._isStale(generation)) return;
const darwinProcessNames = [
{ match: "zoom.us", processKey: "zoom" },
{ match: "microsoft teams", processKey: "teams" },
@@ -144,7 +153,7 @@ class MeetingProcessDetector extends EventEmitter {
}
}
- _startPollingFallback() {
+ _startPollingFallback(generation) {
const apps = MEETING_APPS.linux || [];
debugLogger.info(
"Process detector started (polling fallback)",
@@ -155,11 +164,18 @@ class MeetingProcessDetector extends EventEmitter {
},
"meeting"
);
- this._poll();
- this.pollInterval = setInterval(() => this._poll(), POLL_INTERVAL_MS);
+ this._startPolling(generation);
+ }
+
+ _startPolling(generation) {
+ this._poll(generation);
+ this.pollInterval = setInterval(() => this._poll(generation), POLL_INTERVAL_MS);
}
stop() {
+ if (!this._running) return;
+ this._running = false;
+
if (this.pollInterval) {
clearInterval(this.pollInterval);
this.pollInterval = null;
@@ -204,12 +220,13 @@ class MeetingProcessDetector extends EventEmitter {
return entry ? entry.appName : processKey;
}
- async _poll() {
+ async _poll(generation) {
if (this._polling) return;
this._polling = true;
try {
const apps = MEETING_APPS[process.platform] || MEETING_APPS.linux || [];
const processList = await processListCache.getProcessList();
+ if (this._isStale(generation)) return;
for (const { processKey, appName, imageName } of apps) {
const isRunning = processList.includes(imageName);
diff --git a/src/helpers/onnxWorkerClient.js b/src/helpers/onnxWorkerClient.js
index deee39127..a68e59491 100644
--- a/src/helpers/onnxWorkerClient.js
+++ b/src/helpers/onnxWorkerClient.js
@@ -37,6 +37,8 @@ class OnnxWorkerClient {
this.gaveUp = false;
this.spawnPromise = null;
this.respawnTimer = null;
+ this.generation = 0;
+ this.killedForTimeout = false;
}
_logPath() {
@@ -91,7 +93,7 @@ class OnnxWorkerClient {
child.postMessage("init", [port2]);
- child.on("exit", (code) => this._onExit(code));
+ child.on("exit", (code) => this._onExit(child, code));
this.child = child;
this.port = port1;
@@ -118,7 +120,23 @@ class OnnxWorkerClient {
}
}
- _onExit(code) {
+ _closePort() {
+ if (!this.port) return;
+ try {
+ this.port.close();
+ } catch {
+ // already closed
+ }
+ this.port = null;
+ }
+
+ _onExit(child, code) {
+ // A worker released by releaseIfIdle() was already detached; its exit is expected.
+ if (child !== this.child) {
+ debugLogger.info("onnx worker released", { code, pid: child.pid });
+ return;
+ }
+ this.generation += 1;
debugLogger.warn("onnx worker exited", {
code,
pending: this.pending.size,
@@ -126,14 +144,7 @@ class OnnxWorkerClient {
});
this.child = null;
- if (this.port) {
- try {
- this.port.close();
- } catch {
- // already closed
- }
- this.port = null;
- }
+ this._closePort();
const err = new WorkerCrashedError();
for (const entry of this.pending.values()) {
@@ -144,7 +155,10 @@ class OnnxWorkerClient {
if (this.shuttingDown) return;
- if (code !== 0) {
+ // A kill after a hung request must respawn even if the process reports a clean exit.
+ const crashed = code !== 0 || this.killedForTimeout;
+ this.killedForTimeout = false;
+ if (crashed) {
this.crashCount += 1;
if (this.crashCount > MAX_RESPAWN_ATTEMPTS) {
this.gaveUp = true;
@@ -166,7 +180,34 @@ class OnnxWorkerClient {
}
}
+ // Exits the worker once no session is loaded, so an idle text unload also frees
+ // the onnxruntime arena. Detaches before the kill so a racing request spawns fresh.
+ async releaseIfIdle() {
+ if (!this.child || this.shuttingDown || this.pending.size) return false;
+ let sessions;
+ try {
+ ({ sessions } = await this.request("ping", {}));
+ } catch (err) {
+ debugLogger.debug("onnx worker release probe failed", { error: err?.message });
+ return false;
+ }
+ if (!this.child || sessions.speaker || sessions.text || this.pending.size) return false;
+ const child = this.child;
+ this.child = null;
+ this._closePort();
+ this.generation += 1;
+ try {
+ child.kill();
+ } catch {
+ // already dead
+ }
+ return true;
+ }
+
async request(method, payload, transferList) {
+ // Releasing text must never start a worker just to free an absent session; a
+ // worker that is shutting down takes its session with it.
+ if (method === "text.unload" && (!this.child || this.shuttingDown)) return { ok: true };
if (this.shuttingDown) {
throw new WorkerCrashedError("worker shutting down");
}
@@ -194,8 +235,15 @@ class OnnxWorkerClient {
const id = this.nextRequestId++;
return new Promise((resolve, reject) => {
const timeout = setTimeout(() => {
- if (this.pending.delete(id)) {
- reject(new Error(`onnx worker request timeout: ${method}`));
+ if (!this.pending.delete(id)) return;
+ reject(new Error(`onnx worker request timeout: ${method}`));
+ // The worker serializes text work, so one hung request wedges every later one.
+ debugLogger.warn("onnx worker request timeout; killing worker", { method });
+ this.killedForTimeout = true;
+ try {
+ this.child?.kill();
+ } catch {
+ // already dead
}
}, REQUEST_TIMEOUT_MS);
this.pending.set(id, { resolve, reject, timeout });
diff --git a/src/helpers/qdrantManager.js b/src/helpers/qdrantManager.js
index b10857707..526690fc0 100644
--- a/src/helpers/qdrantManager.js
+++ b/src/helpers/qdrantManager.js
@@ -49,6 +49,7 @@ class QdrantManager extends EventEmitter {
this.cachedBinaryPath = null;
this.consecutiveHealthFailures = 0;
this.restartCount = 0;
+ this.restartBlocked = false;
this.restarting = false;
this.stopRequested = false;
}
@@ -237,12 +238,15 @@ class QdrantManager extends EventEmitter {
this._stopHealthCheck();
this.consecutiveHealthFailures = 0;
this.healthCheckInterval = setInterval(async () => {
- if (!this.process) {
+ const child = this.process;
+ if (!child) {
this._stopHealthCheck();
return;
}
if (await this._checkHealth()) {
this.consecutiveHealthFailures = 0;
+ // A check that resolves after a stop or restart must not revive the old process.
+ if (this.process === child) this.ready = true;
return;
}
this.consecutiveHealthFailures++;
@@ -269,6 +273,7 @@ class QdrantManager extends EventEmitter {
this.restarting = true;
try {
if (this.restartCount >= MAX_RESTARTS_PER_SESSION) {
+ this.restartBlocked = true;
await this._stopProcess();
debugLogger.warn(
"qdrant still unhealthy after max restarts, leaving it stopped (note search falls back to FTS5 keywords)",
@@ -285,6 +290,7 @@ class QdrantManager extends EventEmitter {
await this._stopProcess();
if (pid && !(await waitForExit(pid, RESTART_EXIT_WAIT_MS))) {
// Mirror the reaper's policy: keep the pid entry so the next launch retries.
+ this.restartBlocked = true;
sidecarPidFile.write("qdrant", pid);
debugLogger.error("qdrant survived SIGKILL, not restarting", { pid });
return;
@@ -296,6 +302,7 @@ class QdrantManager extends EventEmitter {
// _doStart can reject after spawning (e.g. startup timeout); make sure
// the replacement really is stopped, not left running unsupervised.
await this._stopProcess();
+ this.restartBlocked = this.restartCount >= MAX_RESTARTS_PER_SESSION;
debugLogger.warn("qdrant restart failed, leaving it stopped", { error: error.message });
} finally {
this.restarting = false;
diff --git a/src/helpers/semanticSearchLifecycle.js b/src/helpers/semanticSearchLifecycle.js
new file mode 100644
index 000000000..ca250f2fa
--- /dev/null
+++ b/src/helpers/semanticSearchLifecycle.js
@@ -0,0 +1,322 @@
+const IDLE_TIMEOUT_MS = 5 * 60 * 1000;
+const RETRY_DELAY_MS = 30 * 1000;
+const DRAIN_PAGE_SIZE = 50;
+// A row that fails this many passes is parked until the next activation, so one
+// poison note never disables semantic search for the rest.
+const MAX_ROW_FAILURES = 3;
+
+// Owns all note-vector work so idle teardown cannot race a query or an index write.
+class SemanticSearchLifecycle {
+ constructor({
+ qdrant,
+ vectorIndex,
+ embeddings,
+ noteEmbedText,
+ database,
+ logger,
+ now = Date.now,
+ setTimeout = global.setTimeout,
+ clearTimeout = global.clearTimeout,
+ }) {
+ this.qdrant = qdrant;
+ this.vectorIndex = vectorIndex;
+ this.embeddings = embeddings;
+ this.noteEmbedText = noteEmbedText;
+ this.database = database;
+ this.logger = logger;
+ this.now = now;
+ this.setTimeout = setTimeout;
+ this.clearTimeout = clearTimeout;
+ this.ready = false;
+ this.closed = false;
+ this.activationPromise = null;
+ this.stoppingPromise = null;
+ this.searches = new Set();
+ this.idleTimer = null;
+ this.retryTimer = null;
+ this.retryAfter = 0;
+ this.indexPort = null;
+ this.drainedThroughRevision = 0;
+ this.retryDue = false;
+ this.rowFailures = new Map();
+ this.lastActivity = now();
+ this.onRestart = () => {
+ this.ready = false;
+ // Qdrant emits before leaving its restart critical section. Also wait
+ // for any old-port indexing attempt before preparing the replacement.
+ Promise.resolve(this.activationPromise)
+ .then(() => (this.closed ? false : this.warmUp({ recovery: true })))
+ .catch((error) =>
+ this.logger.warn("Semantic search recovery failed", { error: error.message })
+ );
+ };
+ qdrant.on("restarted", this.onRestart);
+ }
+
+ // An initialized index on a live Qdrant; it may lag journal rows still draining.
+ _canSearch() {
+ return (
+ this.ready &&
+ !this.closed &&
+ !this.stoppingPromise &&
+ this.qdrant.isReady() &&
+ this.indexPort === this.qdrant.getPort()
+ );
+ }
+
+ isReady() {
+ return (
+ this._canSearch() &&
+ !this.activationPromise &&
+ !this.retryDue &&
+ this.database.getPendingVectorChanges(1, this.drainedThroughRevision).length === 0
+ );
+ }
+
+ _clearIdleTimer() {
+ if (this.idleTimer !== null) this.clearTimeout(this.idleTimer);
+ this.idleTimer = null;
+ }
+
+ _clearRetryTimer() {
+ if (this.retryTimer !== null) this.clearTimeout(this.retryTimer);
+ this.retryTimer = null;
+ this.retryDue = false;
+ }
+
+ // One timer per pass. Indexed rows leave the journal, so a retry pass re-walks
+ // it from the start and only revisits the rows that failed.
+ _scheduleRetry() {
+ if (this.retryTimer !== null) return;
+ this.retryTimer = this.setTimeout(() => {
+ this.retryTimer = null;
+ // Wait for an in-flight pass so it cannot overwrite the rewound cursor.
+ return Promise.resolve(this.activationPromise)
+ .then(() => {
+ this.retryDue = true;
+ this.drainedThroughRevision = 0;
+ return this.closed ? false : this.warmUp({ recovery: true });
+ })
+ .catch((error) =>
+ this.logger.warn("Semantic search retry failed", { error: error.message })
+ );
+ }, RETRY_DELAY_MS);
+ this.retryTimer?.unref?.();
+ }
+
+ _scheduleIdle() {
+ this._clearIdleTimer();
+ if (!this.ready || this.closed || this.activationPromise || this.searches.size) return;
+ const remaining = Math.max(0, IDLE_TIMEOUT_MS - (this.now() - this.lastActivity));
+ this.idleTimer = this.setTimeout(() => this._stopIdle(), remaining);
+ this.idleTimer?.unref?.();
+ }
+
+ // Forget the index so the next activation re-walks the whole journal.
+ _resetIndexState() {
+ this.ready = false;
+ this.vectorIndex.reset();
+ this.indexPort = null;
+ this.drainedThroughRevision = 0;
+ this.rowFailures.clear();
+ this._clearRetryTimer();
+ }
+
+ async _releaseResources() {
+ this._resetIndexState();
+ try {
+ await this.qdrant.stop();
+ } finally {
+ await this.embeddings.unload();
+ }
+ }
+
+ _stopIdle() {
+ this._clearIdleTimer();
+ if (this.closed || this.activationPromise || this.searches.size) return Promise.resolve();
+ if (this.qdrant.restarting) {
+ // Stopping inside _restartUnhealthy would burn a restart attempt; look again later.
+ this.idleTimer = this.setTimeout(() => this._stopIdle(), RETRY_DELAY_MS);
+ this.idleTimer?.unref?.();
+ return Promise.resolve();
+ }
+ this.stoppingPromise = this._releaseResources()
+ .catch((error) =>
+ this.logger.warn("Semantic search idle cleanup failed", { error: error.message })
+ )
+ .finally(() => {
+ this.stoppingPromise = null;
+ });
+ return this.stoppingPromise;
+ }
+
+ // Database triggers retain changes while asleep; notifications only wake an already-used index.
+ notifyChanges() {
+ if (!this.ready && !this.activationPromise) return;
+ this.warmUp().catch((error) =>
+ this.logger.warn("Semantic search wake failed", { error: error.message })
+ );
+ }
+
+ async warmUp({ recovery = false } = {}) {
+ if (this.closed) return false;
+ if (this.activationPromise) return this.activationPromise;
+ if (this.isReady()) return true;
+ if (this.now() < this.retryAfter) return false;
+ // Let the existing health supervisor own unhealthy restarts and their retry budget.
+ if (
+ !this.stoppingPromise &&
+ (this.qdrant.restarting || (this.qdrant.process && !this.qdrant.isReady()))
+ ) {
+ return false;
+ }
+ if (this.qdrant.restartBlocked) return false;
+
+ if (!recovery) this.lastActivity = this.now();
+ this._clearIdleTimer();
+ this.activationPromise = this._activate()
+ .catch(async (error) => {
+ this.retryAfter = this.now() + RETRY_DELAY_MS;
+ this.logger.debug("Semantic search unavailable; using keyword search", {
+ error: error.message,
+ });
+ await this._releaseResources().catch((cleanupError) => {
+ this.logger.warn("Semantic search cleanup failed", { error: cleanupError.message });
+ });
+ return false;
+ })
+ .finally(() => {
+ this.activationPromise = null;
+ this._scheduleIdle();
+ });
+ return this.activationPromise;
+ }
+
+ async _activate() {
+ if (this.stoppingPromise) await this.stoppingPromise;
+ await Promise.allSettled([...this.searches]);
+ if (this.closed) return false;
+ if (!this.qdrant.isAvailable()) throw new Error("Qdrant binary is unavailable");
+ if (!this.embeddings.isAvailable()) await this.embeddings.downloadModel();
+ if (this.closed) return false;
+ await this.qdrant.start();
+ if (this.closed || !this.qdrant.isReady()) return false;
+ this.vectorIndex.init(this.qdrant.getPort());
+ this.indexPort = this.qdrant.getPort();
+ const collection = await this.vectorIndex.ensureCollection();
+ // An existing collection answers while the journal catches it up; a new one is empty.
+ if (collection.created) this.database.enqueueAllVectorChanges();
+ else this.ready = true;
+ await this._drainPending();
+ if (this.closed) return false;
+ this.ready = true;
+ this.retryAfter = 0;
+ return true;
+ }
+
+ // Returns whether the row is still worth retrying after this failure.
+ _recordRowFailure(key, meta) {
+ const failures = (this.rowFailures.get(key) ?? 0) + 1;
+ this.rowFailures.set(key, failures);
+ this.logger.debug("Vector update failed; skipping row for this pass", { ...meta, failures });
+ return failures < MAX_ROW_FAILURES;
+ }
+
+ _isParked(key) {
+ return (this.rowFailures.get(key) ?? 0) >= MAX_ROW_FAILURES;
+ }
+
+ async _applyChange(noteId) {
+ const note = this.database.getNoteForVectorIndex(noteId);
+ if (!note || note.deleted_at) return this.vectorIndex.deleteNote(noteId);
+ return this.vectorIndex.upsertNote(
+ noteId,
+ this.noteEmbedText(note.title, note.content, note.enhanced_content),
+ { space_id: note.space_id, folder_id: note.folder_id ?? null }
+ );
+ }
+
+ // Purged notes are also journaled by the delete triggers and filtered by scope
+ // on read, so a failed purge is retried without blocking readiness.
+ async _drainPurges() {
+ let retry = false;
+ for (const { space_id } of this.database.getPendingVectorPurges()) {
+ if (this.closed) return retry;
+ const key = `space:${space_id}`;
+ if (this._isParked(key)) continue;
+ if (await this.vectorIndex.deleteBySpace(space_id)) {
+ this.database.clearPendingVectorPurge(space_id);
+ } else if (this._recordRowFailure(key, { spaceId: space_id })) {
+ retry = true;
+ }
+ this.lastActivity = this.now();
+ }
+ return retry;
+ }
+
+ async _drainPending() {
+ this.retryDue = false;
+ let retry = await this._drainPurges();
+ let cursor = this.drainedThroughRevision;
+ while (!this.closed) {
+ const changes = this.database.getPendingVectorChanges(DRAIN_PAGE_SIZE, cursor);
+ if (changes.length === 0) break;
+ for (const { note_id, revision } of changes) {
+ if (this.closed) return;
+ cursor = revision;
+ const key = `${note_id}:${revision}`;
+ if (this._isParked(key)) continue;
+ if (await this._applyChange(note_id)) {
+ this.database.clearPendingVectorChange(note_id, revision);
+ } else if (this._recordRowFailure(key, { noteId: note_id, revision })) {
+ retry = true;
+ }
+ this.lastActivity = this.now();
+ }
+ }
+ if (this.closed) return;
+ this.drainedThroughRevision = cursor;
+ if (retry) this._scheduleRetry();
+ }
+
+ // Never waits: a cold index answers with keywords, and a warm one searches while
+ // pending changes drain in the background.
+ async search(query, limit, filter) {
+ this.lastActivity = this.now();
+ if (!this.isReady()) {
+ this.warmUp().catch((error) =>
+ this.logger.warn("Semantic search warm-up failed", { error: error.message })
+ );
+ if (!this._canSearch()) return null;
+ }
+ this._clearIdleTimer();
+ const search = this.vectorIndex.search(query, limit, filter);
+ this.searches.add(search);
+ try {
+ return await search;
+ } finally {
+ this.searches.delete(search);
+ this.lastActivity = this.now();
+ this._scheduleIdle();
+ }
+ }
+
+ async stop() {
+ this.closed = true;
+ this.ready = false;
+ this._clearIdleTimer();
+ this._clearRetryTimer();
+ this.qdrant.removeListener("restarted", this.onRestart);
+ try {
+ // Cancel a port scan immediately; _activate checks closed after each preparation step.
+ await this.qdrant.stop();
+ await Promise.allSettled([this.activationPromise, this.stoppingPromise, ...this.searches]);
+ this._resetIndexState();
+ await this.embeddings.unload();
+ } catch (error) {
+ this.logger.warn("Semantic search shutdown cleanup failed", { error: error.message });
+ }
+ }
+}
+
+module.exports = SemanticSearchLifecycle;
diff --git a/src/helpers/speakerEmbeddings.js b/src/helpers/speakerEmbeddings.js
index b236c5741..e402b066f 100644
--- a/src/helpers/speakerEmbeddings.js
+++ b/src/helpers/speakerEmbeddings.js
@@ -15,6 +15,7 @@ const MODEL_FILE = "3dspeaker_speech_campplus_sv_en_voxceleb_16k.onnx";
class SpeakerEmbeddings {
constructor() {
this.loadPromise = null;
+ this.loadedGeneration = null;
}
getModelPath() {
@@ -33,7 +34,9 @@ class SpeakerEmbeddings {
}
_ensureLoaded() {
- if (this.loadPromise) return this.loadPromise;
+ if (this.loadPromise && this.loadedGeneration === onnxWorkerClient.generation) {
+ return this.loadPromise;
+ }
if (!this.isAvailable()) {
return Promise.reject(
new Error(`Speaker embedding model not found at ${this.getModelPath()}`)
@@ -41,6 +44,7 @@ class SpeakerEmbeddings {
}
const modelPath = this.getModelPath();
debugLogger.debug("speaker-embeddings loading model", { modelPath });
+ this.loadedGeneration = onnxWorkerClient.generation;
this.loadPromise = onnxWorkerClient
.request("speaker.load", { modelPath })
.then(() => debugLogger.debug("speaker-embeddings model loaded"))
diff --git a/src/helpers/vectorIndex.js b/src/helpers/vectorIndex.js
index 4c0f0419f..3af57c084 100644
--- a/src/helpers/vectorIndex.js
+++ b/src/helpers/vectorIndex.js
@@ -1,6 +1,5 @@
const { QdrantClient } = require("@qdrant/js-client-rest");
const localEmbeddings = require("./localEmbeddings");
-const { LocalEmbeddings } = localEmbeddings;
const debugLogger = require("./debugLogger");
const { chunkConversation } = require("./conversationChunker");
@@ -15,39 +14,47 @@ class VectorIndex {
this.client = new QdrantClient({ host: "127.0.0.1", port });
}
+ reset() {
+ this.client = null;
+ }
+
async ensureCollection() {
- if (!this.client) return;
+ if (!this.client) throw new Error("Vector index is not initialized");
try {
await this.client.getCollection(this.collectionName);
- } catch {
- try {
- await this.client.createCollection(this.collectionName, {
- vectors: { size: 384, distance: "Cosine" },
- });
- } catch (err) {
- debugLogger.error("Failed to create Qdrant collection", { error: err.message });
- }
+ return { created: false };
+ } catch (error) {
+ if (error.status !== 404) throw error;
+ await this.client.createCollection(this.collectionName, {
+ vectors: { size: 384, distance: "Cosine" },
+ });
+ return { created: true };
}
}
async upsertNote(noteId, text, payload = {}) {
- if (!this.client) return;
+ if (!this.client) return false;
try {
const vector = await localEmbeddings.embedText(text);
await this.client.upsert(this.collectionName, {
+ wait: true,
points: [{ id: noteId, vector: Array.from(vector), payload }],
});
+ return true;
} catch (err) {
debugLogger.debug("Vector index upsert failed", { noteId, error: err.message });
+ return false;
}
}
async deleteNote(noteId) {
- if (!this.client) return;
+ if (!this.client) return false;
try {
- await this.client.delete(this.collectionName, { points: [noteId] });
+ await this.client.delete(this.collectionName, { wait: true, points: [noteId] });
+ return true;
} catch (err) {
debugLogger.debug("Vector index delete failed", { noteId, error: err.message });
+ return false;
}
}
@@ -55,6 +62,7 @@ class VectorIndex {
if (!this.client) return false;
try {
await this.client.delete(this.collectionName, {
+ wait: true,
filter: { must: [{ key: "space_id", match: { value: spaceId } }] },
});
return true;
@@ -80,32 +88,6 @@ class VectorIndex {
}
}
- async reindexAll(notes, onProgress) {
- if (!this.client) return { failed: notes.length };
- const BATCH_SIZE = 50;
- let failed = 0;
- for (let i = 0; i < notes.length; i += BATCH_SIZE) {
- const batch = notes.slice(i, i + BATCH_SIZE);
- const texts = batch.map((n) =>
- LocalEmbeddings.noteEmbedText(n.title, n.content, n.enhanced_content)
- );
- try {
- const vectors = await localEmbeddings.embedTexts(texts);
- const points = batch.map((n, j) => ({
- id: n.id,
- vector: Array.from(vectors[j]),
- payload: { space_id: n.space_id, folder_id: n.folder_id ?? null },
- }));
- await this.client.upsert(this.collectionName, { points });
- } catch (err) {
- failed += batch.length;
- debugLogger.debug("Vector reindex batch failed", { offset: i, error: err.message });
- }
- if (onProgress) onProgress(Math.min(i + BATCH_SIZE, notes.length), notes.length);
- }
- return { failed };
- }
-
async ensureConversationChunksCollection() {
if (!this.client) return;
try {
@@ -217,10 +199,6 @@ class VectorIndex {
onProgress(Math.min(i + BATCH_SIZE, conversations.length), conversations.length);
}
}
-
- isReady() {
- return this.client !== null;
- }
}
module.exports = new VectorIndex();
diff --git a/src/stores/settingsStore.ts b/src/stores/settingsStore.ts
index 72c73fa88..f4dab3dd8 100644
--- a/src/stores/settingsStore.ts
+++ b/src/stores/settingsStore.ts
@@ -3275,6 +3275,22 @@ export async function initializeSettings(): Promise<void> {
const state = useSettingsStore.getState();
if (window.electronAPI) {
+ // Preferences are already in localStorage; do not wait for secret or provider hydration.
+ try {
+ await window.electronAPI.syncNotificationPreferences?.({
+ notificationsEnabled: state.notificationsEnabled,
+ notifyMeetingDetection: state.notifyMeetingDetection,
+ notifyCalendarReminders: state.notifyCalendarReminders,
+ meetingProcessDetection: state.meetingProcessDetection,
+ });
+ } catch (err) {
+ logger.warn(
+ "Failed to sync notification preferences on startup",
+ { error: (err as Error).message },
+ "settings"
+ );
+ }
+
try {
const [
openai,
@@ -3393,6 +3409,8 @@ export async function initializeSettings(): Promise<void> {
for (const key of STALE_SECRET_LOCALSTORAGE_KEYS) {
localStorage.removeItem(key);
}
+ // Latch for the one-time semantic reindex that no longer exists (#2143).
+ localStorage.removeItem("semanticReindexVersion");
// Users who configured OpenRouter through the Custom tab keep their key
// in the shared custom slot — seed the dedicated slot from it once.
@@ -3564,36 +3582,6 @@ export async function initializeSettings(): Promise<void> {
);
}
- // Audio detection is derived from the meeting-notification toggle in
- // sync-notification-preferences, so it is not sent here.
- try {
- const currentState = useSettingsStore.getState();
- await window.electronAPI.meetingDetectionSetPreferences?.({
- processDetection: currentState.meetingProcessDetection,
- });
- } catch (err) {
- logger.warn(
- "Failed to sync meeting detection preferences on startup",
- { error: (err as Error).message },
- "settings"
- );
- }
-
- try {
- const currentState = useSettingsStore.getState();
- await window.electronAPI.syncNotificationPreferences?.({
- notificationsEnabled: currentState.notificationsEnabled,
- notifyMeetingDetection: currentState.notifyMeetingDetection,
- notifyCalendarReminders: currentState.notifyCalendarReminders,
- });
- } catch (err) {
- logger.warn(
- "Failed to sync notification preferences on startup",
- { error: (err as Error).message },
- "settings"
- );
- }
-
try {
await window.electronAPI.setAutoUpdatesEnabled?.(
useSettingsStore.getState().autoUpdatesEnabled
diff --git a/src/types/calendar.ts b/src/types/calendar.ts
index eec07a18e..6db5ee800 100644
--- a/src/types/calendar.ts
+++ b/src/types/calendar.ts
@@ -68,11 +68,6 @@ export interface CalendarConnectionStatus {
email: string | null;
}
-export interface MeetingDetectionPreferences {
- processDetection: boolean;
- audioDetection: boolean;
-}
-
export interface CalendarAttendee {
email: string;
displayName: string | null;
diff --git a/src/types/electron.ts b/src/types/electron.ts
index 545d43fa6..7006963b3 100644
--- a/src/types/electron.ts
+++ b/src/types/electron.ts
@@ -1489,10 +1489,6 @@ declare global {
spaceId?: number | null,
folderId?: number | null
) => Promise<NoteItem[]>;
- semanticReindexAll: () => Promise<{ success: boolean; indexed?: number; error?: string }>;
- onSemanticReindexProgress: (
- callback: (data: { done: number; total: number }) => void
- ) => () => void;
updateNoteCloudId: (id: number, cloudId: string) => Promise<NoteItem>;
updateNoteShareState: (
id: number,
@@ -3146,13 +3142,12 @@ declare global {
) => () => void;
onAcalEventsSynced?: (callback: (data: any) => void) => () => void;
- meetingDetectionGetPreferences?: () => Promise<{ success: boolean; preferences?: any }>;
- meetingDetectionSetPreferences?: (
- prefs: Record<string, boolean>
- ) => Promise<{ success: boolean }>;
- syncNotificationPreferences?: (
- prefs: Record<string, boolean>
- ) => Promise<{ success: boolean }>;
+ syncNotificationPreferences?: (prefs: {
+ notificationsEnabled: boolean;
+ notifyMeetingDetection: boolean;
+ notifyCalendarReminders: boolean;
+ meetingProcessDetection: boolean;
+ }) => Promise<{ success: boolean }>;
setSpeakerDiarizationEnabled?: (
enabled: boolean
) => Promise<{ success: boolean; error?: string }>;
diff --git a/src/workers/onnxWorker.js b/src/workers/onnxWorker.js
index 46b29d7ac..832e1b174 100644
--- a/src/workers/onnxWorker.js
+++ b/src/workers/onnxWorker.js
@@ -38,6 +38,7 @@ let speakerSession = null;
let speakerInputName = null;
let textSession = null;
let textTokenizer = null;
+let textQueue = Promise.resolve();
function log(level, message, extra) {
if (!logStream) return;
@@ -313,12 +314,13 @@ async function textLoad({ modelDir }) {
loadOrt();
const tokenizerData = JSON.parse(fs.readFileSync(path.join(modelDir, "tokenizer.json"), "utf-8"));
- textTokenizer = buildTextTokenizer(tokenizerData);
+ const tokenizer = buildTextTokenizer(tokenizerData);
textSession = await ort.InferenceSession.create(
path.join(modelDir, "model.onnx"),
SESSION_OPTIONS
);
+ textTokenizer = tokenizer;
log("info", "text session loaded", { modelDir });
return { ok: true };
}
@@ -338,12 +340,21 @@ async function textEmbed({ text }) {
return { embeddingBuffer: embedding.buffer };
}
+async function textUnload() {
+ if (textSession) await textSession.release();
+ textSession = null;
+ textTokenizer = null;
+ log("info", "text session unloaded");
+ return { ok: true };
+}
+
const handlers = {
ping: () => ({ ok: true, sessions: { speaker: !!speakerSession, text: !!textSession } }),
"speaker.load": speakerLoad,
"speaker.extract": speakerExtract,
"text.load": textLoad,
"text.embed": textEmbed,
+ "text.unload": textUnload,
shutdown: () => {
log("info", "shutdown requested");
setImmediate(() => process.exit(0));
@@ -357,7 +368,15 @@ async function dispatch({ id, method, payload }) {
return { reply: { id, error: { message: `unknown method: ${method}` } }, transferList: [] };
}
try {
- const result = await handler(payload || {});
+ let result;
+ if (method.startsWith("text.")) {
+ // Message callbacks overlap; never release a session during native inference.
+ const operation = textQueue.then(() => handler(payload || {}));
+ textQueue = operation.catch(() => {});
+ result = await operation;
+ } else {
+ result = await handler(payload || {});
+ }
// MessagePortMain transfers only ports, not ArrayBuffers — clone the result buffers instead.
return { reply: { id, result }, transferList: [] };
} catch (err) {
diff --git a/test/helpers/cliBridgeRequestBody.test.js b/test/helpers/cliBridgeRequestBody.test.js
index a09bd454e..98e276b8b 100644
--- a/test/helpers/cliBridgeRequestBody.test.js
+++ b/test/helpers/cliBridgeRequestBody.test.js
@@ -67,7 +67,7 @@ test("CLI request body limit counts UTF-8 bytes, not JavaScript characters", asy
return { success: true, note: { id: 1 } };
},
},
- _asyncVectorUpsert() {},
+ notifyVectorChanges() {},
_asyncMirrorWrite() {},
});
bridge.token = "test-token";
@@ -98,7 +98,7 @@ test("multibyte content split across request chunks is preserved", async () => {
return { success: true, note: { id: 1 } };
},
},
- _asyncVectorUpsert() {},
+ notifyVectorChanges() {},
_asyncMirrorWrite() {},
});
bridge.token = "test-token";
@@ -126,7 +126,7 @@ test("a JSON body exactly at the byte limit is accepted", async () => {
return { success: true, note: { id: 1 } };
},
},
- _asyncVectorUpsert() {},
+ notifyVectorChanges() {},
_asyncMirrorWrite() {},
});
bridge.token = "test-token";
diff --git a/test/helpers/localEmbeddingsLifecycle.test.js b/test/helpers/localEmbeddingsLifecycle.test.js
new file mode 100644
index 000000000..4cbe6b2c1
--- /dev/null
+++ b/test/helpers/localEmbeddingsLifecycle.test.js
@@ -0,0 +1,370 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+const { EventEmitter } = require("node:events");
+const fs = require("node:fs");
+const path = require("node:path");
+const vm = require("node:vm");
+
+const WORKER_SOURCE = fs.readFileSync(path.resolve("src/workers/onnxWorker.js"), "utf8");
+const CLIENT_SOURCE = fs.readFileSync(path.resolve("src/helpers/onnxWorkerClient.js"), "utf8");
+const EMBEDDINGS_SOURCE = fs.readFileSync(path.resolve("src/helpers/localEmbeddings.js"), "utf8");
+
+function fakeOrt(events, nativeSession) {
+ return {
+ InferenceSession: {
+ create: async (file) => {
+ events.push(`${file === "speaker" ? "speaker" : "text"}.create`);
+ return nativeSession(file === "speaker" ? "speaker" : "text");
+ },
+ },
+ Tensor: class {},
+ };
+}
+
+function loadEmbeddings(client) {
+ const localContext = vm.createContext({
+ module: { exports: {} },
+ __dirname: path.resolve("src/helpers"),
+ process: {},
+ require(name) {
+ if (name === "fs") return { existsSync: () => true };
+ if (name === "./debugLogger") return { debug() {} };
+ if (name === "./onnxWorkerClient") return client;
+ return require(name);
+ },
+ });
+ vm.runInContext(EMBEDDINGS_SOURCE, localContext);
+ return localContext.module.exports;
+}
+
+function createHarness() {
+ const events = [];
+ let releaseInference;
+ let gateInference = false;
+ const nativeSession = (name) => ({
+ inputNames: ["input"],
+ async run() {
+ events.push(`${name}.run`);
+ if (name === "text" && gateInference) {
+ await new Promise((resolve) => {
+ releaseInference = resolve;
+ });
+ }
+ events.push(`${name}.done`);
+ return { last_hidden_state: { data: new Float32Array(768).fill(1) } };
+ },
+ async release() {
+ events.push(`${name}.release`);
+ },
+ });
+ const workerContext = vm.createContext({
+ require(name) {
+ if (name === "fs") return { readFileSync: () => JSON.stringify({ model: { vocab: {} } }) };
+ if (name === "onnxruntime-node")
+ return {
+ InferenceSession: {
+ create: async (file) => nativeSession(file === "speaker" ? "speaker" : "text"),
+ },
+ Tensor: class {},
+ };
+ return require(name);
+ },
+ process: { env: {}, on() {}, parentPort: { once() {} } },
+ setImmediate,
+ });
+ vm.runInContext(WORKER_SOURCE, workerContext);
+ const dispatch = vm.runInContext("dispatch", workerContext);
+ const client = {
+ generation: 0,
+ async request(method, payload) {
+ events.push(method);
+ const { reply } = await dispatch({ id: 1, method, payload });
+ if (reply.error) throw new Error(reply.error.message);
+ return reply.result;
+ },
+ async releaseIfIdle() {
+ events.push("releaseIfIdle");
+ return false;
+ },
+ };
+ return {
+ embeddings: loadEmbeddings(client),
+ client,
+ events,
+ gateInference() {
+ gateInference = true;
+ },
+ releaseInference() {
+ gateInference = false;
+ releaseInference();
+ },
+ };
+}
+
+async function nextTurn() {
+ await new Promise((resolve) => setImmediate(resolve));
+}
+
+test("unloads the text session, preserves speaker inference, and reloads on next embedding", async () => {
+ const { embeddings, client, events } = createHarness();
+ await client.request("speaker.load", { modelPath: "speaker" });
+ await embeddings.embedText("");
+ await embeddings.unload();
+ const { sessions } = await client.request("ping", {});
+ assert.equal(sessions.text, false);
+ assert.equal(sessions.speaker, true);
+ await client.request("speaker.extract", { samplesBuffer: new Float32Array(400).buffer });
+ assert.ok(events.includes("speaker.run"));
+ assert.ok(!events.includes("speaker.release"));
+ await embeddings.embedText("");
+ assert.equal(events.filter((event) => event === "text.load").length, 2);
+});
+
+test("unload waits for inference and a racing embedding reloads after release", async () => {
+ const harness = createHarness();
+ harness.gateInference();
+ const first = harness.embeddings.embedText("");
+ await nextTurn();
+ const unloading = harness.embeddings.unload();
+ const second = harness.embeddings.embedText("");
+ await nextTurn();
+ assert.ok(!harness.events.includes("text.release"));
+ harness.releaseInference();
+ await Promise.all([first, unloading, second]);
+ assert.deepEqual(
+ harness.events.filter((event) => event.startsWith("text")),
+ [
+ "text.load",
+ "text.embed",
+ "text.run",
+ "text.done",
+ "text.unload",
+ "text.release",
+ "text.load",
+ "text.embed",
+ "text.run",
+ "text.done",
+ ]
+ );
+});
+
+test("worker serializes text unload behind in-flight native inference", async () => {
+ const harness = createHarness();
+ await harness.client.request("text.load", { modelDir: "text" });
+ harness.gateInference();
+ const first = harness.client.request("text.embed", { text: "" });
+ await nextTurn();
+ const unload = harness.client.request("text.unload", {});
+ await nextTurn();
+ assert.ok(!harness.events.includes("text.release"));
+ harness.releaseInference();
+ await Promise.all([first, unload]);
+ assert.ok(harness.events.indexOf("text.done") < harness.events.indexOf("text.release"));
+});
+
+test("reloads after the shared worker restarts", async () => {
+ const { embeddings, client, events } = createHarness();
+ await embeddings.embedText("");
+ await client.request("text.unload", {});
+ client.generation += 1;
+ await embeddings.embedText("");
+ assert.equal(events.filter((event) => event === "text.load").length, 2);
+});
+
+test("speaker embeddings reload after the shared worker restarts", async () => {
+ const methods = [];
+ const client = {
+ generation: 0,
+ async request(method) {
+ methods.push(method);
+ return method === "speaker.extract" ? { embeddingBuffer: new ArrayBuffer(4) } : { ok: true };
+ },
+ };
+ const context = vm.createContext({
+ module: { exports: {} },
+ process: {},
+ require(name) {
+ if (name === "fs") return { existsSync: () => true };
+ if (name === "./debugLogger") return { debug() {} };
+ if (name === "./modelDirUtils") return { getModelsDirForService: () => "/models" };
+ if (name === "./onnxWorkerClient") return client;
+ return require(name);
+ },
+ });
+ vm.runInContext(
+ fs.readFileSync(path.resolve("src/helpers/speakerEmbeddings.js"), "utf8"),
+ context
+ );
+ const speakerEmbeddings = context.module.exports;
+ const samples = new Float32Array(16000 * 2);
+ await speakerEmbeddings.extractEmbeddingFromSamples(samples);
+ client.generation += 1;
+ await speakerEmbeddings.extractEmbeddingFromSamples(samples);
+ assert.equal(methods.filter((method) => method === "speaker.load").length, 2);
+});
+
+test("a failed load does not block unloading or the next load attempt", async () => {
+ const { embeddings, client, events } = createHarness();
+ const request = client.request.bind(client);
+ let failLoad = true;
+ client.request = async (method, payload) => {
+ if (method === "text.load" && failLoad) {
+ failLoad = false;
+ throw new Error("model unavailable");
+ }
+ return request(method, payload);
+ };
+ await assert.rejects(embeddings.embedText(""), /model unavailable/);
+ await embeddings.unload();
+ const result = await embeddings.embedText("");
+ assert.equal(result.length, 384);
+ assert.equal(events.filter((event) => event === "text.run").length, 1);
+});
+
+test("unload waits for the complete embedding batch", async () => {
+ const harness = createHarness();
+ harness.gateInference();
+ const batch = harness.embeddings.embedTexts(["", ""]);
+ await nextTurn();
+ const unload = harness.embeddings.unload();
+ harness.releaseInference();
+ assert.equal((await batch).length, 2);
+ await unload;
+ const finished = harness.events.lastIndexOf("text.done");
+ assert.ok(finished < harness.events.indexOf("text.release"));
+});
+
+test("unload asks the worker client to release itself once the text session is gone", async () => {
+ const { embeddings, events } = createHarness();
+ await embeddings.embedText("");
+ await embeddings.unload();
+ assert.ok(events.indexOf("text.unload") < events.indexOf("releaseIfIdle"));
+});
+
+class FakePort extends EventEmitter {
+ constructor() {
+ super();
+ this.peer = null;
+ this.closed = false;
+ }
+
+ start() {}
+
+ postMessage(data) {
+ const { peer } = this;
+ setImmediate(() => {
+ if (!peer.closed) peer.emit("message", { data });
+ });
+ }
+
+ close() {
+ this.closed = true;
+ this.peer.emit("close");
+ }
+}
+
+// The real client driving the real worker source: each fork boots a fresh worker context.
+function createIntegratedHarness() {
+ const events = [];
+ const workers = [];
+ const nativeSession = (name) => ({
+ inputNames: ["input"],
+ async run() {
+ return { last_hidden_state: { data: new Float32Array(768).fill(1) } };
+ },
+ async release() {
+ events.push(`${name}.release`);
+ },
+ });
+ const fork = () => {
+ let onInit = null;
+ const worker = { exited: null };
+ const workerContext = vm.createContext({
+ require(name) {
+ if (name === "fs") return { readFileSync: () => JSON.stringify({ model: { vocab: {} } }) };
+ if (name === "onnxruntime-node") return fakeOrt(events, nativeSession);
+ return require(name);
+ },
+ process: {
+ env: {},
+ pid: 500 + workers.length,
+ on() {},
+ exit(code) {
+ worker.exited = code;
+ },
+ parentPort: {
+ once(_, callback) {
+ onInit = callback;
+ },
+ },
+ },
+ setImmediate,
+ });
+ vm.runInContext(WORKER_SOURCE, workerContext);
+ const child = new EventEmitter();
+ child.pid = workerContext.process.pid;
+ child.killed = false;
+ child.kill = () => {
+ child.killed = true;
+ setImmediate(() => child.emit("exit", 0));
+ };
+ child.postMessage = (data, ports) => onInit({ data, ports });
+ workers.push({ child, worker });
+ setImmediate(() => child.emit("spawn"));
+ return child;
+ };
+ const clientContext = vm.createContext({
+ module: { exports: {} },
+ __dirname: path.resolve("src/helpers"),
+ process,
+ setTimeout,
+ clearTimeout,
+ require(name) {
+ if (name === "electron")
+ return {
+ app: { getPath: () => "/tmp" },
+ MessageChannelMain: class {
+ constructor() {
+ this.port1 = new FakePort();
+ this.port2 = new FakePort();
+ this.port1.peer = this.port2;
+ this.port2.peer = this.port1;
+ }
+ },
+ utilityProcess: { fork },
+ };
+ if (name === "./debugLogger") return { debug() {}, info() {}, warn() {}, error() {} };
+ return require(name);
+ },
+ });
+ vm.runInContext(CLIENT_SOURCE, clientContext);
+ const client = clientContext.module.exports;
+ return { client, embeddings: loadEmbeddings(client), events, workers };
+}
+
+test("unloading the last session exits the worker and a later embedding respawns and reloads it", async () => {
+ const h = createIntegratedHarness();
+ await h.embeddings.embedText("");
+ await h.embeddings.unload();
+ assert.deepEqual(h.events, ["text.create", "text.release"]);
+ assert.equal(h.workers.length, 1);
+ assert.equal(h.workers[0].child.killed, true);
+ assert.equal(h.client.child, null);
+ assert.equal(h.workers[0].worker.exited, 0);
+ assert.equal((await h.embeddings.embedText("")).length, 384);
+ assert.equal(h.workers.length, 2);
+ assert.deepEqual(h.events, ["text.create", "text.release", "text.create"]);
+});
+
+test("unloading text keeps the worker alive while diarization holds a speaker session", async () => {
+ const h = createIntegratedHarness();
+ await h.client.request("speaker.load", { modelPath: "speaker" });
+ await h.embeddings.embedText("");
+ await h.embeddings.unload();
+ assert.equal(h.workers.length, 1);
+ assert.equal(h.workers[0].child.killed, false);
+ assert.ok(h.client.child);
+ const { sessions } = await h.client.request("ping", {});
+ assert.equal(sessions.speaker, true);
+ assert.equal(sessions.text, false);
+});
diff --git a/test/helpers/meetingDetectionEngine.test.js b/test/helpers/meetingDetectionEngine.test.js
index 51114d6cd..5e7a743ca 100644
--- a/test/helpers/meetingDetectionEngine.test.js
+++ b/test/helpers/meetingDetectionEngine.test.js
@@ -40,19 +40,30 @@ function createEngine() {
getActiveMeetingState: () => ({ activeMeeting: null, activeEvents: [], upcomingEvents: [] }),
};
const processDetector = new EventEmitter();
- processDetector.start = () => {};
- processDetector.stop = () => {};
+ processDetector.running = false;
+ processDetector.start = () => {
+ processDetector.running = true;
+ };
+ processDetector.stop = () => {
+ processDetector.running = false;
+ };
const audioDetector = new EventEmitter();
audioDetector.dismissals = 0;
audioDetector.dismiss = () => audioDetector.dismissals++;
audioDetector.resetPrompt = () => {};
+ audioDetector.getExternalMicState = () => ({ reliable: true, externalMicActive: true });
audioDetector.setUserRecording = () => {};
audioDetector.setMicWarmHold = () => {};
audioDetector.meetingAppNotifications = 0;
audioDetector.notifyMeetingAppsChanged = () => audioDetector.meetingAppNotifications++;
- audioDetector.start = () => {};
- audioDetector.stop = () => {};
+ audioDetector.running = false;
+ audioDetector.start = () => {
+ audioDetector.running = true;
+ };
+ audioDetector.stop = () => {
+ audioDetector.running = false;
+ };
const shown = [];
const meetingNavigations = [];
@@ -73,12 +84,21 @@ function createEngine() {
{}
);
- return { engine, audioDetector, processDetector, shown, meetingNavigations, noteNavigations };
+ return {
+ engine,
+ audioDetector,
+ processDetector,
+ windowManager,
+ shown,
+ meetingNavigations,
+ noteNavigations,
+ };
}
test("an unanswered audio prompt expires without cooling down the mic detector", () => {
const { engine, audioDetector, shown } = createEngine();
+ engine.setPreferences({ audioDetection: true, processDetection: true });
audioDetector.emit("sustained-audio-detected", { durationMs: 2000, detectedAt: 0 });
assert.equal(shown.length, 1, "the detection must reach the overlay");
@@ -91,6 +111,7 @@ test("an unanswered audio prompt expires without cooling down the mic detector",
test("explicitly dismissing an audio prompt still starts the mic cooldown", async () => {
const { engine, audioDetector, shown } = createEngine();
+ engine.setPreferences({ audioDetection: true, processDetection: true });
audioDetector.emit("sustained-audio-detected", { durationMs: 2000, detectedAt: 0 });
await engine.handleNotificationResponse(shown[0].detectionId, "dismiss");
@@ -100,6 +121,7 @@ test("explicitly dismissing an audio prompt still starts the mic cooldown", asyn
test("a detection card closed without a response allows the next prompt", () => {
const { engine, audioDetector, shown } = createEngine();
+ engine.setPreferences({ audioDetection: true, processDetection: true });
audioDetector.emit("sustained-audio-detected", { durationMs: 2000, detectedAt: 0 });
engine.handleDetectionNotificationClosed(shown[0].detectionId);
audioDetector.emit("sustained-audio-detected", { durationMs: 4000, detectedAt: 1 });
@@ -139,3 +161,76 @@ test("a live recording with no note id still blocks a second manual meeting", as
assert.deepEqual(noteNavigations, []);
});
+
+// The IPC adapter derives detector preferences through this policy; the engine
+// only has to honour whatever it is handed (adapter coverage lives in
+// meetingDetectionPreferencesIpc.test.js).
+const { deriveDetectorPreferences } = require("../../src/helpers/meetingDetectionPreferencePolicy");
+
+const ENABLED_SNAPSHOT = {
+ notificationsEnabled: true,
+ notifyMeetingDetection: true,
+ meetingProcessDetection: true,
+};
+
+function applySnapshot(engine, snapshot) {
+ engine.setPreferences(deriveDetectorPreferences(snapshot));
+}
+
+test("startup waits for saved notification preferences before starting prompt detectors", () => {
+ const { engine, audioDetector, processDetector } = createEngine();
+ engine.start();
+ assert.equal(audioDetector.running, false);
+ assert.equal(processDetector.running, false);
+});
+
+test("a snapshot with meeting prompts disabled never starts prompt detectors", () => {
+ const { engine, audioDetector, processDetector } = createEngine();
+ engine.start();
+ applySnapshot(engine, { ...ENABLED_SNAPSHOT, notifyMeetingDetection: false });
+ assert.equal(audioDetector.running, false);
+ assert.equal(processDetector.running, false);
+});
+
+test("notification toggles gate both detectors and retain the process preference", () => {
+ const { engine, audioDetector, processDetector } = createEngine();
+ applySnapshot(engine, ENABLED_SNAPSHOT);
+ assert.equal(audioDetector.running, true);
+ assert.equal(processDetector.running, true);
+ applySnapshot(engine, { ...ENABLED_SNAPSHOT, notificationsEnabled: false });
+ assert.equal(audioDetector.running, false);
+ assert.equal(processDetector.running, false);
+ applySnapshot(engine, { ...ENABLED_SNAPSHOT, meetingProcessDetection: false });
+ assert.equal(audioDetector.running, true);
+ assert.equal(processDetector.running, false);
+ applySnapshot(engine, { ...ENABLED_SNAPSHOT, notifyMeetingDetection: false });
+ assert.equal(audioDetector.running, false);
+ assert.equal(processDetector.running, false);
+ applySnapshot(engine, ENABLED_SNAPSHOT);
+ assert.equal(audioDetector.running, true);
+ assert.equal(processDetector.running, true);
+});
+
+test("repeated preference snapshots preserve the detector listener registrations", () => {
+ const { engine, audioDetector, processDetector } = createEngine();
+ for (let index = 0; index < 3; index += 1) applySnapshot(engine, ENABLED_SNAPSHOT);
+ assert.equal(audioDetector.listenerCount("sustained-audio-detected"), 1);
+ assert.equal(processDetector.listenerCount("meeting-process-detected"), 1);
+});
+
+test("disabling notifications preserves active auto-end and releases both detectors at session end", async (t) => {
+ const { engine, audioDetector, processDetector } = createEngine();
+ t.after(() => engine.stop());
+ applySnapshot(engine, ENABLED_SNAPSHOT);
+ await engine.beginRecordingSession({
+ sessionId: "active-meeting",
+ autoEndEligible: true,
+ systemAudioAvailable: true,
+ });
+ applySnapshot(engine, { ...ENABLED_SNAPSHOT, notificationsEnabled: false });
+ assert.equal(audioDetector.running, true);
+ assert.equal(processDetector.running, true);
+ assert.equal(engine.endRecordingSession("active-meeting"), true);
+ assert.equal(audioDetector.running, false);
+ assert.equal(processDetector.running, false);
+});
diff --git a/test/helpers/meetingDetectionEngineAutoEnd.test.js b/test/helpers/meetingDetectionEngineAutoEnd.test.js
index 2c437196a..a33794236 100644
--- a/test/helpers/meetingDetectionEngineAutoEnd.test.js
+++ b/test/helpers/meetingDetectionEngineAutoEnd.test.js
@@ -355,7 +355,7 @@ test("a legacy autoEnd preference cannot disable eligible meeting auto-end", asy
const harness = createEngine();
const messages = [];
harness.engine.setPreferences({ audioDetection: false, processDetection: false, autoEnd: false });
- assert.deepEqual(harness.engine.getPreferences(), {
+ assert.deepEqual(harness.engine.preferences, {
processDetection: false,
audioDetection: false,
});
@@ -465,6 +465,7 @@ test("a post-dictation queue flush holds detections while the meeting session is
test("a detection-started recording re-enables prompts once its session ends", async (t) => {
t.mock.timers.enable({ apis: ["setTimeout"] });
const { audioActivityDetector, clock, engine, owner, shownNotifications } = createEngine();
+ engine.setPreferences({ audioDetection: true, processDetection: true });
engine.setMeetingModeActive(true);
engine.setUserRecording(true);
await engine.beginRecordingSession({
@@ -490,6 +491,7 @@ test("a detection-started recording re-enables prompts once its session ends", a
test("the next reminder prompts after a detection-started recording ends", async (t) => {
t.mock.timers.enable({ apis: ["setTimeout"] });
const { clock, engine, owner, shownNotifications } = createEngine();
+ engine.setPreferences({ audioDetection: true, processDetection: true });
engine.setMeetingModeActive(true);
engine.setUserRecording(true);
await engine.beginRecordingSession({
@@ -512,6 +514,7 @@ test("the next reminder prompts after a detection-started recording ends", async
test("meeting mode still suppresses prompts while a detection-started recording is live", async (t) => {
t.mock.timers.enable({ apis: ["setTimeout"] });
const { audioActivityDetector, clock, engine, owner, shownNotifications } = createEngine();
+ engine.setPreferences({ audioDetection: true, processDetection: true });
engine.setMeetingModeActive(true);
engine.setUserRecording(true);
await engine.beginRecordingSession({
diff --git a/test/helpers/meetingDetectionPreferencePolicy.test.js b/test/helpers/meetingDetectionPreferencePolicy.test.js
new file mode 100644
index 000000000..371de3c0e
--- /dev/null
+++ b/test/helpers/meetingDetectionPreferencePolicy.test.js
@@ -0,0 +1,34 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+
+const {
+ deriveDetectorPreferences,
+} = require("../../src/helpers/meetingDetectionPreferencePolicy.js");
+
+// Full truth table: audio = notifications && meeting prompts; process detection
+// additionally needs its own toggle.
+test("detector preferences derive from the notification toggles", () => {
+ for (const notificationsEnabled of [false, true]) {
+ for (const notifyMeetingDetection of [false, true]) {
+ for (const meetingProcessDetection of [false, true]) {
+ const audioDetection = notificationsEnabled && notifyMeetingDetection;
+ assert.deepEqual(
+ deriveDetectorPreferences({
+ notificationsEnabled,
+ notifyMeetingDetection,
+ meetingProcessDetection,
+ }),
+ { audioDetection, processDetection: audioDetection && meetingProcessDetection },
+ JSON.stringify({ notificationsEnabled, notifyMeetingDetection, meetingProcessDetection })
+ );
+ }
+ }
+ }
+});
+
+test("the derived values are plain booleans even for missing inputs", () => {
+ assert.deepEqual(deriveDetectorPreferences({}), {
+ audioDetection: false,
+ processDetection: false,
+ });
+});
diff --git a/test/helpers/meetingDetectionPreferencesIpc.test.js b/test/helpers/meetingDetectionPreferencesIpc.test.js
new file mode 100644
index 000000000..18e179c67
--- /dev/null
+++ b/test/helpers/meetingDetectionPreferencesIpc.test.js
@@ -0,0 +1,127 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+const Module = require("node:module");
+
+// Registers the real handler closures against a fake `this` (the scaffolding
+// from granolaImportIpc.test.js) so the sync-notification-preferences adapter
+// runs its real code path into a recording meeting detection engine.
+const handlersModulePath = require.resolve("../../src/helpers/ipcHandlers");
+const originalLoad = Module._load;
+const handlers = new Map();
+
+const electronStub = {
+ app: {
+ getPath: () => "/tmp",
+ getName: () => "test",
+ getVersion: () => "0.0.0",
+ isPackaged: false,
+ on: () => {},
+ requestSingleInstanceLock: () => true,
+ },
+ ipcMain: {
+ handle: (channel, handler) => handlers.set(channel, handler),
+ on: () => {},
+ removeHandler: () => {},
+ },
+ net: { fetch: async () => ({ ok: true, status: 200, json: async () => ({}) }) },
+ BrowserWindow: class BrowserWindow {
+ static getAllWindows() {
+ return [];
+ }
+
+ static fromWebContents() {
+ return null;
+ }
+ },
+ shell: {},
+ dialog: {},
+ screen: { getPrimaryDisplay: () => ({ workAreaSize: { width: 0, height: 0 } }) },
+ systemPreferences: { getMediaAccessStatus: () => "granted" },
+ session: { fromPartition: () => ({}) },
+ clipboard: {},
+ nativeImage: {},
+ globalShortcut: {},
+ utilityProcess: {},
+ MessageChannelMain: class {},
+};
+
+Module._load = function loadWithElectronStub(request, parent, isMain) {
+ if (request === "electron") return electronStub;
+ if (parent?.filename === handlersModulePath && request === "./debugLogger") {
+ return new Proxy({}, { get: () => () => {} });
+ }
+ return originalLoad.call(this, request, parent, isMain);
+};
+
+function anything() {
+ return new Proxy(function () {}, {
+ get: (_target, property) => {
+ if (property === Symbol.toPrimitive || property === "toString") return () => "";
+ if (property === "then") return undefined;
+ return anything();
+ },
+ apply: () => anything(),
+ });
+}
+
+const applied = [];
+let target;
+
+test.before(() => {
+ delete require.cache[handlersModulePath];
+ const IPCHandlers = require(handlersModulePath);
+ const Ctor = IPCHandlers.default || IPCHandlers;
+ // Mirrors the constructor's initial detector-gating state.
+ target = {
+ meetingProcessDetection: true,
+ windowManager: { notificationPrefs: {} },
+ meetingDetectionEngine: { setPreferences: (prefs) => applied.push(prefs) },
+ };
+ Ctor.prototype.setupHandlers.call(
+ new Proxy(target, {
+ get: (value, property) => (property in value ? value[property] : anything()),
+ })
+ );
+});
+
+test.after(() => {
+ Module._load = originalLoad;
+});
+
+const sync = (prefs) => handlers.get("sync-notification-preferences")({}, prefs);
+
+const ENABLED_SNAPSHOT = {
+ notificationsEnabled: true,
+ notifyMeetingDetection: true,
+ notifyCalendarReminders: true,
+ meetingProcessDetection: true,
+};
+
+test("the saved snapshot drives both detectors", async () => {
+ applied.length = 0;
+ await sync({ ...ENABLED_SNAPSHOT, meetingProcessDetection: false });
+ assert.equal(target.meetingProcessDetection, false);
+ assert.deepEqual(applied, [{ audioDetection: true, processDetection: false }]);
+
+ applied.length = 0;
+ await sync(ENABLED_SNAPSHOT);
+ assert.deepEqual(applied, [{ audioDetection: true, processDetection: true }]);
+
+ applied.length = 0;
+ await sync({ ...ENABLED_SNAPSHOT, notifyMeetingDetection: false });
+ assert.deepEqual(applied, [{ audioDetection: false, processDetection: false }]);
+});
+
+test("a partial update re-derives from the retained state", async () => {
+ await sync(ENABLED_SNAPSHOT);
+ applied.length = 0;
+ await sync({ notificationsEnabled: false });
+ assert.deepEqual(applied, [{ audioDetection: false, processDetection: false }]);
+ assert.equal(target.windowManager.notificationPrefs.notifyMeetingDetection, true);
+});
+
+test("a non-object payload is rejected without touching the detectors", async () => {
+ applied.length = 0;
+ assert.deepEqual(await sync(null), { success: false, error: "Invalid preferences" });
+ assert.deepEqual(applied, []);
+});
diff --git a/test/helpers/meetingProcessDetector.test.js b/test/helpers/meetingProcessDetector.test.js
new file mode 100644
index 000000000..f512be698
--- /dev/null
+++ b/test/helpers/meetingProcessDetector.test.js
@@ -0,0 +1,142 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+const Module = require("node:module");
+
+const detectorPath = require.resolve("../../src/helpers/meetingProcessDetector");
+const originalLoad = Module._load;
+const originalPlatform = process.platform;
+
+function setPlatform(platform) {
+ Object.defineProperty(process, "platform", { value: platform, configurable: true });
+}
+
+// Every scan awaits a process list the test releases by hand, so a stop() or a
+// second start() can be interleaved while a scan is still in flight. The
+// detector requires electron lazily, so the stubs stay installed for the file.
+let current = null;
+Module._load = function loadWithMocks(request, parent, isMain) {
+ if (parent?.filename === detectorPath) {
+ if (request === "electron") {
+ return {
+ systemPreferences: {
+ subscribeWorkspaceNotification: () => 1,
+ unsubscribeWorkspaceNotification: () => {},
+ },
+ };
+ }
+ if (request === "./debugLogger") {
+ return {
+ info: (message) => current.infoLogs.push(message),
+ warn() {},
+ debug() {},
+ error() {},
+ };
+ }
+ if (request === "./processListCache") {
+ return {
+ getProcessList: () =>
+ new Promise((resolve) => {
+ current.pendingScans.push(resolve);
+ }),
+ };
+ }
+ }
+ return originalLoad.call(this, request, parent, isMain);
+};
+
+function loadDetector(platform) {
+ setPlatform(platform);
+ current = { infoLogs: [], pendingScans: [] };
+ delete require.cache[detectorPath];
+ const MeetingProcessDetector = require(detectorPath);
+ const { infoLogs, pendingScans } = current;
+ return {
+ detector: new MeetingProcessDetector(),
+ infoLogs,
+ pendingScans,
+ releaseScan: (processes) => pendingScans.shift()(processes),
+ };
+}
+
+test.after(() => {
+ Module._load = originalLoad;
+});
+
+test.afterEach(() => {
+ setPlatform(originalPlatform);
+});
+
+const settle = () => new Promise((resolve) => setImmediate(resolve));
+
+test("stop() on a never-started detector is a silent no-op", () => {
+ const { detector, infoLogs } = loadDetector("darwin");
+ detector.stop();
+ assert.deepEqual(infoLogs, []);
+});
+
+test("stop() after start() still reports the shutdown", () => {
+ const { detector, infoLogs } = loadDetector("darwin");
+ detector.start();
+ detector.stop();
+ assert.ok(infoLogs.includes("Stopped meeting process detector"));
+});
+
+test("a macOS initial scan that completes after stop() cannot revive a stopped detector", async () => {
+ const { detector, releaseScan } = loadDetector("darwin");
+ const detected = [];
+ detector.on("meeting-process-detected", (event) => detected.push(event.processKey));
+
+ detector.start();
+ detector.stop();
+ releaseScan(["zoom.us"]);
+ await settle();
+
+ assert.deepEqual(detector.getDetectedProcesses(), []);
+ assert.deepEqual(detected, []);
+});
+
+test("a macOS initial scan superseded by a newer start() is discarded", async () => {
+ const { detector, releaseScan, pendingScans } = loadDetector("darwin");
+ const detected = [];
+ detector.on("meeting-process-detected", (event) => detected.push(event.processKey));
+
+ detector.start();
+ detector.stop();
+ detector.start();
+ assert.equal(pendingScans.length, 2);
+ // The stale scan reports Zoom; the live one reports nothing running.
+ releaseScan(["zoom.us"]);
+ releaseScan([]);
+ await settle();
+
+ assert.deepEqual(detector.getDetectedProcesses(), []);
+ assert.deepEqual(detected, []);
+});
+
+test("a live macOS initial scan still reports already-running meeting apps", async () => {
+ const { detector, releaseScan } = loadDetector("darwin");
+ detector.start();
+ releaseScan(["zoom.us"]);
+ await settle();
+
+ assert.deepEqual(
+ detector.getDetectedProcesses().map((entry) => entry.processKey),
+ ["zoom"]
+ );
+ detector.stop();
+});
+
+test("a polling scan that completes after stop() cannot revive a stopped detector", async (t) => {
+ const { detector, releaseScan } = loadDetector("linux");
+ t.after(() => detector.stop());
+ const detected = [];
+ detector.on("meeting-process-detected", (event) => detected.push(event.processKey));
+
+ detector.start();
+ detector.stop();
+ releaseScan(["zoom"]);
+ await settle();
+
+ assert.deepEqual(detector.getDetectedProcesses(), []);
+ assert.deepEqual(detected, []);
+});
diff --git a/test/helpers/onnxWorkerClientLifecycle.test.js b/test/helpers/onnxWorkerClientLifecycle.test.js
new file mode 100644
index 000000000..0705ca975
--- /dev/null
+++ b/test/helpers/onnxWorkerClientLifecycle.test.js
@@ -0,0 +1,241 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+const { EventEmitter } = require("node:events");
+const fs = require("node:fs");
+const path = require("node:path");
+const vm = require("node:vm");
+
+const REQUEST_TIMEOUT_MS = 30000;
+
+// Timers are recorded, never fired: request timeouts and respawn backoff are driven explicitly.
+function createTimers() {
+ const timers = new Map();
+ let nextId = 0;
+ return {
+ timers,
+ setTimeout(callback, delay) {
+ timers.set(++nextId, { callback, delay });
+ return nextId;
+ },
+ clearTimeout(id) {
+ timers.delete(id);
+ },
+ fire(delay) {
+ const [id, timer] = [...timers].find(([, entry]) => entry.delay === delay);
+ timers.delete(id);
+ return timer.callback();
+ },
+ };
+}
+
+class FakePort extends EventEmitter {
+ constructor() {
+ super();
+ this.peer = null;
+ this.closed = false;
+ }
+
+ start() {}
+
+ postMessage(data) {
+ const { peer } = this;
+ setImmediate(() => {
+ if (!peer.closed) peer.emit("message", { data });
+ });
+ }
+
+ close() {
+ this.closed = true;
+ this.peer.emit("close");
+ }
+}
+
+class FakeMessageChannelMain {
+ constructor() {
+ this.port1 = new FakePort();
+ this.port2 = new FakePort();
+ this.port1.peer = this.port2;
+ this.port2.peer = this.port1;
+ }
+}
+
+function nextTurn() {
+ return new Promise((resolve) => setImmediate(resolve));
+}
+
+// Runs the real client against a fake utility process whose worker side is `respond`.
+function createHarness({ killExitCode = 0 } = {}) {
+ const forks = [];
+ const logs = [];
+ const timers = createTimers();
+ const sessions = { speaker: false, text: false };
+ const hanging = new Set();
+ const respond = (method) => {
+ if (hanging.has(method)) return new Promise(() => {});
+ if (method === "ping") return { ok: true, sessions: { ...sessions } };
+ return { ok: true };
+ };
+ const fork = () => {
+ const child = new EventEmitter();
+ child.pid = 100 + forks.length;
+ child.killed = false;
+ child.kill = () => {
+ child.killed = true;
+ setImmediate(() => child.emit("exit", killExitCode));
+ };
+ child.postMessage = (data, ports) => {
+ const [port] = ports;
+ port.on("message", async ({ data: { id, method } }) => {
+ port.postMessage({ id, result: await respond(method) });
+ });
+ port.start();
+ };
+ forks.push(child);
+ setImmediate(() => child.emit("spawn"));
+ return child;
+ };
+ const context = vm.createContext({
+ module: { exports: {} },
+ __dirname: path.resolve("src/helpers"),
+ process,
+ setTimeout: timers.setTimeout,
+ clearTimeout: timers.clearTimeout,
+ require(name) {
+ if (name === "electron")
+ return {
+ app: { getPath: () => "/tmp" },
+ MessageChannelMain: FakeMessageChannelMain,
+ utilityProcess: { fork },
+ };
+ if (name === "./debugLogger")
+ return Object.fromEntries(
+ ["debug", "info", "warn", "error"].map((level) => [
+ level,
+ (message, meta) => logs.push({ level, message, meta }),
+ ])
+ );
+ return require(name);
+ },
+ });
+ vm.runInContext(
+ fs.readFileSync(path.resolve("src/helpers/onnxWorkerClient.js"), "utf8"),
+ context
+ );
+ return {
+ client: context.module.exports,
+ forks,
+ logs,
+ timers,
+ sessions,
+ hang(method) {
+ hanging.add(method);
+ },
+ };
+}
+
+test("unloading unused text does not spawn a worker", async () => {
+ const h = createHarness();
+ await h.client.request("text.unload", {});
+ assert.equal(h.client.child, null);
+ assert.equal(h.forks.length, 0);
+});
+
+test("unloading after worker exit succeeds without restarting it", async () => {
+ const h = createHarness();
+ await h.client.request("ping", {});
+ const generation = h.client.generation;
+ h.forks[0].emit("exit", 0);
+ assert.equal(h.client.generation, generation + 1);
+ await h.client.request("text.unload", {});
+ assert.equal(h.client.child, null);
+ assert.equal(h.forks.length, 1);
+});
+
+test("releasing an idle worker kills it without counting a crash, and the next request respawns it", async () => {
+ const h = createHarness({ killExitCode: 15 });
+ await h.client.request("text.unload", {});
+ await h.client.request("ping", {});
+ const generation = h.client.generation;
+ assert.equal(await h.client.releaseIfIdle(), true);
+ assert.equal(h.forks[0].killed, true);
+ await nextTurn();
+ assert.equal(h.client.child, null);
+ assert.equal(h.client.generation, generation + 1);
+ assert.equal(h.client.crashCount, 0);
+ assert.equal(h.client.respawnTimer, null);
+ assert.equal(h.client.gaveUp, false);
+ assert.equal(h.client.shuttingDown, false);
+ assert.ok(h.logs.some((entry) => entry.level === "info" && /released/.test(entry.message)));
+ assert.equal(
+ h.logs.some((entry) => entry.level === "warn" && /exited/.test(entry.message)),
+ false
+ );
+ await h.client.request("ping", {});
+ assert.equal(h.forks.length, 2);
+});
+
+test("a worker with a loaded speaker session is left alone", async () => {
+ const h = createHarness();
+ h.sessions.speaker = true;
+ await h.client.request("speaker.load", {});
+ assert.equal(await h.client.releaseIfIdle(), false);
+ await nextTurn();
+ assert.equal(h.forks[0].killed, false);
+ assert.ok(h.client.child);
+});
+
+test("a worker with an in-flight request is left alone", async () => {
+ const h = createHarness();
+ h.hang("speaker.extract");
+ await h.client.request("ping", {});
+ const extract = h.client.request("speaker.extract", {});
+ await nextTurn();
+ assert.equal(h.client.pending.size, 1);
+ assert.equal(await h.client.releaseIfIdle(), false);
+ await nextTurn();
+ assert.equal(h.forks[0].killed, false);
+ assert.ok(h.client.child);
+ assert.equal(h.client.pending.size, 1);
+ h.forks[0].emit("exit", 0);
+ await assert.rejects(extract, /crashed/);
+});
+
+test("releasing does nothing without a worker", async () => {
+ const h = createHarness();
+ assert.equal(await h.client.releaseIfIdle(), false);
+ assert.equal(h.forks.length, 0);
+});
+
+test("text unload resolves while the worker is shutting down", async () => {
+ const h = createHarness();
+ await h.client.request("ping", {});
+ const stopping = h.client.stop();
+ assert.equal((await h.client.request("text.unload", {})).ok, true);
+ h.forks[0].emit("exit", 0);
+ await stopping;
+});
+
+test("text unload resolves while a crash respawn is pending", async () => {
+ const h = createHarness();
+ await h.client.request("ping", {});
+ h.forks[0].emit("exit", 1);
+ assert.ok(h.client.respawnTimer);
+ assert.equal((await h.client.request("text.unload", {})).ok, true);
+ assert.equal(h.forks.length, 1);
+});
+
+test("a request timeout kills the worker so the crash path respawns it", async () => {
+ const h = createHarness({ killExitCode: 0 });
+ h.hang("text.embed");
+ await h.client.request("ping", {});
+ const embed = h.client.request("text.embed", {});
+ await nextTurn();
+ await h.timers.fire(REQUEST_TIMEOUT_MS);
+ await assert.rejects(embed, /timeout/);
+ assert.equal(h.forks[0].killed, true);
+ assert.ok(h.logs.some((entry) => entry.level === "warn" && /timeout/i.test(entry.message)));
+ await nextTurn();
+ assert.equal(h.client.child, null);
+ assert.equal(h.client.crashCount, 1);
+ assert.ok(h.client.respawnTimer);
+});
diff --git a/test/helpers/qdrantManager.test.js b/test/helpers/qdrantManager.test.js
index 1ec53243b..829c52047 100644
--- a/test/helpers/qdrantManager.test.js
+++ b/test/helpers/qdrantManager.test.js
@@ -195,6 +195,20 @@ test("a healthy check resets the consecutive-failure count", async (t) => {
assert.equal(state.spawnCalls.length, 1, "should never have restarted");
});
+test("a healthy check after a failed one marks qdrant ready again", async (t) => {
+ t.mock.timers.enable({ apis: ["setInterval"] });
+ const { manager, state } = loadManager();
+ await manager.start();
+
+ state.healthy = false;
+ await tickHealthCheck(t, 1);
+ assert.equal(manager.isReady(), false);
+ state.healthy = true;
+ await tickHealthCheck(t, 1);
+
+ assert.equal(manager.isReady(), true);
+});
+
test("stays stopped with one warning once the restart budget is spent", async (t) => {
t.mock.timers.enable({ apis: ["setInterval"] });
const { QdrantManager, manager, state } = loadManager();
@@ -311,6 +325,7 @@ test("does not respawn over a process that survived SIGKILL", async (t) => {
await tickHealthCheck(t, QdrantManager.HEALTH_FAILURES_BEFORE_RESTART);
assert.equal(state.spawnCalls.length, 1);
+ assert.equal(manager.restartBlocked, true);
assert.equal(manager.getStatus().running, false);
// The pid entry is restored so the next launch's reaper retries the kill.
assert.deepEqual(state.pidFileOps[state.pidFileOps.length - 1], ["write", "qdrant", 1001]);
@@ -369,3 +384,16 @@ test("a late close from the replaced child does not clobber the new process", as
assert.notEqual(manager.healthCheckInterval, null);
assert.equal(state.pidFileOps.length, opsBeforeLateClose, "pid entry must not be cleared");
});
+
+test("restart exhaustion distinguishes an unhealthy cap from a healthy idle stop", async (t) => {
+ t.mock.timers.enable({ apis: ["setInterval"] });
+ const { QdrantManager, manager } = loadManager();
+ await manager.start();
+ manager.restartCount = QdrantManager.MAX_RESTARTS_PER_SESSION;
+ await manager.stop();
+ assert.equal(manager.restartBlocked, false);
+ await manager.start();
+ await manager._restartUnhealthy();
+ assert.equal(manager.restartBlocked, true);
+ assert.equal(manager.isReady(), false);
+});
diff --git a/test/helpers/semanticSearchIpc.test.js b/test/helpers/semanticSearchIpc.test.js
new file mode 100644
index 000000000..7f622689b
--- /dev/null
+++ b/test/helpers/semanticSearchIpc.test.js
@@ -0,0 +1,138 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+const Module = require("node:module");
+
+// Registers the real handler closures against a fake `this` (the scaffolding
+// from granolaImportIpc.test.js) so the semantic-search handlers run their real
+// code paths against a scripted lifecycle owner and database.
+const handlersModulePath = require.resolve("../../src/helpers/ipcHandlers");
+const originalLoad = Module._load;
+const handlers = new Map();
+
+const electronStub = {
+ app: {
+ getPath: () => "/tmp",
+ getName: () => "test",
+ getVersion: () => "0.0.0",
+ isPackaged: false,
+ on: () => {},
+ requestSingleInstanceLock: () => true,
+ },
+ ipcMain: {
+ handle: (channel, handler) => handlers.set(channel, handler),
+ on: () => {},
+ removeHandler: () => {},
+ },
+ net: { fetch: async () => ({ ok: true, status: 200, json: async () => ({}) }) },
+ BrowserWindow: class BrowserWindow {
+ static getAllWindows() {
+ return [];
+ }
+
+ static fromWebContents() {
+ return null;
+ }
+ },
+ shell: {},
+ dialog: {},
+ screen: { getPrimaryDisplay: () => ({ workAreaSize: { width: 0, height: 0 } }) },
+ systemPreferences: { getMediaAccessStatus: () => "granted" },
+ session: { fromPartition: () => ({}) },
+ clipboard: {},
+ nativeImage: {},
+ globalShortcut: {},
+ utilityProcess: {},
+ MessageChannelMain: class {},
+};
+
+Module._load = function loadWithElectronStub(request, parent, isMain) {
+ if (request === "electron") return electronStub;
+ if (parent?.filename === handlersModulePath && request === "./debugLogger") {
+ return new Proxy({}, { get: () => () => {} });
+ }
+ return originalLoad.call(this, request, parent, isMain);
+};
+
+function anything() {
+ return new Proxy(function () {}, {
+ get: (_target, property) => {
+ if (property === Symbol.toPrimitive || property === "toString") return () => "";
+ if (property === "then") return undefined;
+ return anything();
+ },
+ apply: () => anything(),
+ });
+}
+
+const KEYWORD_NOTE = { id: 1, title: "Keyword" };
+let lifecycle = null;
+let target;
+
+test.before(() => {
+ delete require.cache[handlersModulePath];
+ const IPCHandlers = require(handlersModulePath);
+ const Ctor = IPCHandlers.default || IPCHandlers;
+ target = {
+ getSemanticSearch: () => lifecycle,
+ notifyVectorChanges: Ctor.prototype.notifyVectorChanges,
+ databaseManager: {
+ searchNotes: () => [KEYWORD_NOTE],
+ getNoteIdsInScope: () => [1, 2],
+ getNote: (id) => ({ id, title: "Semantic" }),
+ saveNote: () => ({ success: true, note: { id: 7, title: "Saved" } }),
+ },
+ };
+ Ctor.prototype.setupHandlers.call(
+ new Proxy(target, {
+ get: (value, property) => (property in value ? value[property] : anything()),
+ })
+ );
+});
+
+test.after(() => {
+ Module._load = originalLoad;
+});
+
+const search = () => handlers.get("db-semantic-search-notes")(null, "query", 5, 4);
+
+test("keyword results serve while no semantic search owner is composed", async () => {
+ lifecycle = null;
+ assert.deepEqual(await search(), [KEYWORD_NOTE]);
+});
+
+test("a cold index answers with keyword results after delegating warmup", async () => {
+ let requests = 0;
+ lifecycle = {
+ search: async () => {
+ requests++;
+ return null;
+ },
+ };
+ assert.deepEqual(await search(), [KEYWORD_NOTE]);
+ assert.equal(requests, 1);
+});
+
+test("a warm index fuses vector hits and drops vectors outside the SQLite scope", async () => {
+ lifecycle = {
+ search: async () => [
+ { noteId: 9, score: 0.99 },
+ { noteId: 2, score: 0.9 },
+ ],
+ };
+ const results = await search();
+ assert.deepEqual(results.map((note) => note.id).sort(), [1, 2]);
+});
+
+test("a note save wakes the semantic index through the single poke", async () => {
+ let pokes = 0;
+ lifecycle = { notifyChanges: () => pokes++ };
+ const result = await handlers.get("db-save-note")(null, "Saved", "body");
+ assert.equal(result.success, true);
+ assert.equal(pokes, 1);
+});
+
+test("a note save with no semantic search owner composed is harmless", async () => {
+ lifecycle = null;
+ const result = await handlers.get("db-save-note")(null, "Saved", "body");
+ assert.equal(result.success, true);
+});
diff --git a/test/helpers/semanticSearchLifecycle.test.js b/test/helpers/semanticSearchLifecycle.test.js
new file mode 100644
index 000000000..9f04f423e
--- /dev/null
+++ b/test/helpers/semanticSearchLifecycle.test.js
@@ -0,0 +1,548 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+const { EventEmitter } = require("node:events");
+const SemanticSearchLifecycle = require("../../src/helpers/semanticSearchLifecycle");
+
+const IDLE_TIMEOUT_MS = 5 * 60 * 1000;
+
+function deferred() {
+ let resolve;
+ const promise = new Promise((done) => {
+ resolve = done;
+ });
+ return { promise, resolve };
+}
+
+function harness() {
+ const calls = [];
+ const logs = [];
+ const pending = new Map();
+ const notes = new Map();
+ const purges = new Set();
+ const timers = new Map();
+ let nextTimer = 0;
+ let now = 0;
+ const qdrant = new EventEmitter();
+ Object.assign(qdrant, {
+ ready: false,
+ available: true,
+ port: 6333,
+ isAvailable() {
+ return this.available;
+ },
+ isReady() {
+ return this.ready;
+ },
+ getPort() {
+ return this.port;
+ },
+ async start() {
+ calls.push("start");
+ this.ready = true;
+ },
+ async stop() {
+ calls.push("stop");
+ this.ready = false;
+ },
+ });
+ const index = {
+ init(port) {
+ calls.push(["init", port]);
+ },
+ reset() {
+ calls.push("reset");
+ },
+ async ensureCollection() {
+ return { created: false };
+ },
+ async upsertNote(id, text, payload) {
+ calls.push(["upsert", id, text, payload]);
+ return true;
+ },
+ async deleteNote(id) {
+ calls.push(["delete", id]);
+ return true;
+ },
+ async deleteBySpace(id) {
+ calls.push(["purge", id]);
+ return true;
+ },
+ async search() {
+ calls.push("search");
+ return [{ noteId: 1, score: 0.9 }];
+ },
+ };
+ const embeddings = {
+ isAvailable() {
+ return true;
+ },
+ async downloadModel() {
+ calls.push("download");
+ },
+ async unload() {
+ calls.push("unload");
+ },
+ };
+ const database = {
+ getPendingVectorChanges(limit = 50, afterRevision = 0) {
+ return [...pending]
+ .filter(([, revision]) => revision > afterRevision)
+ .sort(([, a], [, b]) => a - b)
+ .slice(0, limit)
+ .map(([note_id, revision]) => ({ note_id, revision }));
+ },
+ clearPendingVectorChange(id, revision) {
+ if (pending.get(id) === revision) pending.delete(id);
+ },
+ getNoteForVectorIndex(id) {
+ return notes.get(id);
+ },
+ getPendingVectorPurges() {
+ return [...purges].map((space_id) => ({ space_id }));
+ },
+ clearPendingVectorPurge(id) {
+ purges.delete(id);
+ },
+ enqueueAllVectorChanges() {
+ for (const id of notes.keys()) pending.set(id, (pending.get(id) || 0) + 1);
+ return { success: true };
+ },
+ };
+ const lifecycle = new SemanticSearchLifecycle({
+ qdrant,
+ vectorIndex: index,
+ embeddings,
+ database,
+ noteEmbedText: (title, content, enhanced) => `${title}\n${enhanced || content}`.slice(0, 1500),
+ logger: {
+ debug(message, meta) {
+ logs.push(["debug", message, meta]);
+ },
+ warn(message, meta) {
+ logs.push(["warn", message, meta]);
+ },
+ },
+ now: () => now,
+ setTimeout(callback, delay) {
+ timers.set(++nextTimer, { callback, delay });
+ return nextTimer;
+ },
+ clearTimeout(id) {
+ timers.delete(id);
+ },
+ });
+ return {
+ lifecycle,
+ qdrant,
+ index,
+ embeddings,
+ database,
+ pending,
+ notes,
+ purges,
+ calls,
+ logs,
+ timers,
+ fireTimer(delay) {
+ const [id, timer] = [...timers].find(([, entry]) => entry.delay === delay);
+ timers.delete(id);
+ return timer.callback();
+ },
+ setNow(value) {
+ now = value;
+ },
+ };
+}
+
+test("construction and background note changes do not start resources", () => {
+ const h = harness();
+ h.lifecycle.notifyChanges();
+ assert.deepEqual(h.calls, []);
+ assert.equal(h.lifecycle.isReady(), false);
+});
+
+function gateStart(h) {
+ const gate = deferred();
+ h.qdrant.start = async () => {
+ h.calls.push("start");
+ await gate.promise;
+ h.qdrant.ready = true;
+ };
+ return gate;
+}
+
+test("cold searches answer with keywords at once and share one background activation", async () => {
+ const h = harness();
+ const gate = gateStart(h);
+ assert.equal(await h.lifecycle.search("first"), null);
+ assert.equal(await h.lifecycle.search("second"), null);
+ gate.resolve();
+ assert.equal(await h.lifecycle.warmUp(), true);
+ assert.equal(h.calls.filter((call) => call === "start").length, 1);
+ assert.deepEqual(await h.lifecycle.search("warm"), [{ noteId: 1, score: 0.9 }]);
+});
+
+test("a warm index keeps answering while an edit drains in the background", async () => {
+ const h = harness();
+ await h.lifecycle.warmUp();
+ const gate = deferred();
+ h.index.upsertNote = () => gate.promise;
+ h.pending.set(1, 1);
+ h.notes.set(1, { title: "Live note", content: "" });
+ h.lifecycle.notifyChanges();
+ assert.deepEqual(await h.lifecycle.search("query"), [{ noteId: 1, score: 0.9 }]);
+ gate.resolve(true);
+ assert.equal(await h.lifecycle.warmUp(), true);
+ assert.equal(h.pending.size, 0);
+});
+
+test("an existing collection answers while activation drains; a new one waits for the drain", async () => {
+ for (const created of [false, true]) {
+ const h = harness();
+ h.index.ensureCollection = async () => ({ created });
+ const started = deferred();
+ const gate = deferred();
+ h.index.upsertNote = () => {
+ started.resolve();
+ return gate.promise;
+ };
+ h.notes.set(1, { title: "Queued", content: "" });
+ h.pending.set(1, 1);
+ const activation = h.lifecycle.warmUp();
+ await started.promise;
+ assert.deepEqual(
+ await h.lifecycle.search("query"),
+ created ? null : [{ noteId: 1, score: 0.9 }]
+ );
+ gate.resolve(true);
+ assert.equal(await activation, true);
+ }
+});
+
+test("activation drains purges, live updates and deletions before readiness", async () => {
+ const h = harness();
+ h.pending.set(1, 1);
+ h.pending.set(2, 2);
+ h.pending.set(3, 3);
+ h.notes.set(1, {
+ title: "Title",
+ content: "old",
+ enhanced_content: "latest",
+ space_id: 4,
+ folder_id: 5,
+ });
+ h.notes.set(3, { deleted_at: "today" });
+ h.purges.add(8);
+ assert.equal(await h.lifecycle.warmUp(), true);
+ assert.deepEqual(h.calls.filter(Array.isArray), [
+ ["init", 6333],
+ ["purge", 8],
+ ["upsert", 1, "Title\nlatest", { space_id: 4, folder_id: 5 }],
+ ["delete", 2],
+ ["delete", 3],
+ ]);
+ assert.equal(h.pending.size, 0);
+ assert.equal(h.purges.size, 0);
+});
+
+test("an update arriving during indexing cannot be acknowledged by an older revision", async () => {
+ const h = harness();
+ h.pending.set(1, 1);
+ h.notes.set(1, { title: "Before", content: "" });
+ const original = h.index.upsertNote;
+ let count = 0;
+ h.index.upsertNote = async (...args) => {
+ await original(...args);
+ if (++count === 1) {
+ h.pending.set(1, 2);
+ h.notes.set(1, { title: "After", content: "" });
+ }
+ return true;
+ };
+ await h.lifecycle.warmUp();
+ assert.deepEqual(
+ h.calls.filter((call) => Array.isArray(call) && call[0] === "upsert").map((call) => call[2]),
+ ["Before\n", "After\n"]
+ );
+ assert.equal(h.pending.size, 0);
+});
+
+function failUpsertFor(h, noteId) {
+ const original = h.index.upsertNote;
+ h.index.upsertNote = async (id, ...rest) => {
+ await original(id, ...rest);
+ return id !== noteId;
+ };
+}
+
+function upsertsFor(h, noteId) {
+ return h.calls.filter((call) => Array.isArray(call) && call[0] === "upsert" && call[1] === noteId)
+ .length;
+}
+
+test("a row that keeps failing is skipped: later rows index, search works and Qdrant stays up", async () => {
+ const h = harness();
+ h.pending.set(1, 1);
+ h.pending.set(2, 2);
+ h.notes.set(1, { title: "Poison", content: "" });
+ h.notes.set(2, { title: "Healthy", content: "" });
+ failUpsertFor(h, 1);
+ assert.equal(await h.lifecycle.warmUp(), true);
+ assert.equal(upsertsFor(h, 2), 1);
+ assert.equal(h.pending.has(1), true);
+ assert.equal(h.pending.has(2), false);
+ assert.equal(h.lifecycle.isReady(), true);
+ assert.deepEqual(await h.lifecycle.search("query"), [{ noteId: 1, score: 0.9 }]);
+ assert.equal(h.calls.includes("stop"), false);
+ assert.equal(h.calls.includes("unload"), false);
+ assert.ok(h.logs.some(([level, message]) => level === "debug" && /failed/i.test(message)));
+});
+
+test("a failing row is retried after the delay, parked after three failures, and re-walked after release", async () => {
+ const h = harness();
+ h.pending.set(1, 1);
+ h.notes.set(1, { title: "Poison", content: "" });
+ failUpsertFor(h, 1);
+ assert.equal(await h.lifecycle.warmUp(), true);
+ assert.equal(upsertsFor(h, 1), 1);
+ await h.fireTimer(30000);
+ assert.equal(upsertsFor(h, 1), 2);
+ await h.fireTimer(30000);
+ assert.equal(upsertsFor(h, 1), 3);
+ assert.equal(
+ [...h.timers.values()].some((timer) => timer.delay === 30000),
+ false
+ );
+ assert.equal(h.lifecycle.isReady(), true);
+ assert.equal(h.pending.has(1), true);
+ await h.fireTimer(300000);
+ assert.equal(await h.lifecycle.warmUp(), true);
+ assert.equal(upsertsFor(h, 1), 4);
+});
+
+test("a new revision for a parked note is processed", async () => {
+ const h = harness();
+ h.pending.set(1, 1);
+ h.notes.set(1, { title: "Poison", content: "" });
+ failUpsertFor(h, 1);
+ await h.lifecycle.warmUp();
+ await h.fireTimer(30000);
+ await h.fireTimer(30000);
+ assert.equal(upsertsFor(h, 1), 3);
+ h.pending.set(1, 2);
+ h.notes.set(1, { title: "Fixed", content: "" });
+ h.index.upsertNote = async (...args) => {
+ h.calls.push(["upsert", ...args]);
+ return true;
+ };
+ assert.equal(h.lifecycle.isReady(), false);
+ assert.equal(await h.lifecycle.warmUp(), true);
+ assert.equal(upsertsFor(h, 1), 4);
+ assert.equal(h.pending.size, 0);
+});
+
+test("five minutes of idle releases resources and later search can wake them", async () => {
+ const h = harness();
+ await h.lifecycle.warmUp();
+ const timer = [...h.timers.values()][0];
+ assert.equal(timer.delay, 300000);
+ await timer.callback();
+ assert.equal(h.lifecycle.isReady(), false);
+ assert.ok(h.calls.includes("unload"));
+ assert.equal(await h.lifecycle.search("wake"), null);
+ assert.equal(await h.lifecycle.warmUp(), true);
+ assert.deepEqual(await h.lifecycle.search("wake"), [{ noteId: 1, score: 0.9 }]);
+});
+
+test("an in-flight search prevents idle teardown", async () => {
+ const h = harness();
+ await h.lifecycle.warmUp();
+ const gate = deferred();
+ h.index.search = () => gate.promise;
+ const search = h.lifecycle.search("slow");
+ assert.equal(h.timers.size, 0);
+ gate.resolve([]);
+ await search;
+ assert.equal(h.timers.size, 1);
+});
+
+test("a search during idle shutdown waits for teardown before warming", async () => {
+ const h = harness();
+ await h.lifecycle.warmUp();
+ const gate = deferred();
+ h.qdrant.stop = async () => {
+ h.calls.push("stop");
+ await gate.promise;
+ h.qdrant.ready = false;
+ };
+ const stopping = [...h.timers.values()][0].callback();
+ assert.equal(await h.lifecycle.search("wake"), null);
+ gate.resolve();
+ await stopping;
+ assert.equal(await h.lifecycle.warmUp(), true);
+ assert.equal(h.lifecycle.isReady(), true);
+});
+
+test("quit during model preparation prevents a late child spawn", async () => {
+ const h = harness();
+ const gate = deferred();
+ h.embeddings.isAvailable = () => false;
+ h.embeddings.downloadModel = () => gate.promise;
+ const warming = h.lifecycle.warmUp();
+ await Promise.resolve();
+ const stopping = h.lifecycle.stop();
+ gate.resolve();
+ await Promise.all([warming, stopping]);
+ assert.equal(h.calls.includes("start"), false);
+ assert.equal(await h.lifecycle.warmUp(), false);
+});
+
+test("missing binary remains dormant and retries once the retry window passes", async () => {
+ const h = harness();
+ h.qdrant.available = false;
+ assert.equal(await h.lifecycle.warmUp(), false);
+ assert.equal(h.calls.includes("start"), false);
+ h.qdrant.available = true;
+ assert.equal(await h.lifecycle.warmUp(), false);
+ h.setNow(30000);
+ assert.equal(await h.lifecycle.warmUp(), true);
+});
+
+test("Qdrant recovery rewires the new port and drains updates", async () => {
+ const h = harness();
+ await h.lifecycle.warmUp();
+ h.qdrant.port = 6335;
+ h.qdrant.emit("restarted", 6335);
+ await h.lifecycle.warmUp();
+ assert.ok(h.calls.some((call) => Array.isArray(call) && call[0] === "init" && call[1] === 6335));
+});
+
+test("successful final health restart does not prevent wake after a deliberate idle stop", async () => {
+ const h = harness();
+ h.qdrant.restartCount = 3;
+ h.qdrant.ready = true;
+ await h.lifecycle.warmUp();
+ await [...h.timers.values()][0].callback();
+ assert.equal(await h.lifecycle.warmUp(), true);
+});
+
+test("an exhausted unhealthy restart budget is not bypassed by queries", async () => {
+ const h = harness();
+ h.qdrant.restartBlocked = true;
+ assert.equal(await h.lifecycle.warmUp(), false);
+ assert.equal(h.calls.includes("start"), false);
+});
+
+test("restart event recovers after the manager finishes its restarting critical section", async () => {
+ const h = harness();
+ await h.lifecycle.warmUp();
+ h.qdrant.restarting = true;
+ h.qdrant.port = 6335;
+ h.qdrant.emit("restarted", 6335);
+ h.qdrant.restarting = false;
+ await new Promise((resolve) => setImmediate(resolve));
+ assert.equal(h.lifecycle.isReady(), true);
+ assert.ok(h.calls.some((call) => Array.isArray(call) && call[0] === "init" && call[1] === 6335));
+});
+
+test("failed model preparation releases resources and is retried without losing queued notes", async () => {
+ const h = harness();
+ h.pending.set(1, 1);
+ h.notes.set(1, { title: "Queued", content: "" });
+ h.embeddings.isAvailable = () => false;
+ h.embeddings.downloadModel = async () => {
+ throw new Error("download failed");
+ };
+ assert.equal(await h.lifecycle.warmUp(), false);
+ assert.equal(h.pending.size, 1);
+ assert.ok(h.calls.includes("unload"));
+ h.embeddings.isAvailable = () => true;
+ h.setNow(30000);
+ assert.equal(await h.lifecycle.warmUp(), true);
+ assert.equal(h.pending.size, 0);
+});
+
+test("a failed space purge is retried after the delay without blocking semantic search", async () => {
+ const h = harness();
+ h.purges.add(4);
+ let purgeAttempts = 0;
+ h.index.deleteBySpace = async () => {
+ purgeAttempts++;
+ return purgeAttempts > 1;
+ };
+ assert.equal(await h.lifecycle.warmUp(), true);
+ assert.equal(h.purges.has(4), true);
+ assert.equal(h.lifecycle.isReady(), true);
+ assert.deepEqual(await h.lifecycle.search("query"), [{ noteId: 1, score: 0.9 }]);
+ await h.fireTimer(30000);
+ assert.equal(purgeAttempts, 2);
+ assert.equal(h.purges.has(4), false);
+});
+
+test("collection recreation queues unchanged notes for embedding again", async () => {
+ const h = harness();
+ h.notes.set(1, { title: "Existing", content: "" });
+ h.index.ensureCollection = async () => ({ created: true });
+ assert.equal(await h.lifecycle.warmUp(), true);
+ assert.ok(h.calls.some((call) => Array.isArray(call) && call[0] === "upsert" && call[1] === 1));
+});
+
+test("health recovery preserves the deadline when no search or indexing occurs", async () => {
+ const h = harness();
+ await h.lifecycle.warmUp();
+ h.setNow(290000);
+ h.qdrant.restarting = true;
+ h.qdrant.emit("restarted", 6333);
+ h.qdrant.restarting = false;
+ await new Promise((resolve) => setImmediate(resolve));
+ assert.equal([...h.timers.values()][0].delay, 10000);
+});
+
+test("indexing during recovery starts a new idle window", async () => {
+ const h = harness();
+ await h.lifecycle.warmUp();
+ h.setNow(290000);
+ h.pending.set(1, 1);
+ h.notes.set(1, { title: "Changed", content: "" });
+ h.qdrant.emit("restarted", 6333);
+ await new Promise((resolve) => setImmediate(resolve));
+ assert.equal([...h.timers.values()][0].delay, 300000);
+});
+
+test("stop releases without a second Qdrant stop and swallows cleanup errors", async () => {
+ const h = harness();
+ await h.lifecycle.warmUp();
+ h.embeddings.unload = async () => {
+ throw new Error("worker gone");
+ };
+ await h.lifecycle.stop();
+ assert.equal(h.calls.filter((call) => call === "stop").length, 1);
+ assert.ok(h.calls.includes("reset"));
+ assert.ok(h.logs.some(([level]) => level === "warn"));
+});
+
+test("idle stop defers while Qdrant is restarting and lands after the restart settles", async () => {
+ const h = harness();
+ await h.lifecycle.warmUp();
+ h.qdrant.restarting = true;
+ await h.fireTimer(IDLE_TIMEOUT_MS);
+ assert.equal(h.calls.includes("stop"), false);
+ assert.equal(h.calls.includes("unload"), false);
+ h.qdrant.restarting = false;
+ await h.fireTimer(30000);
+ assert.ok(h.calls.includes("stop"));
+ assert.ok(h.calls.includes("unload"));
+});
+
+test("a change notification with a closed database logs instead of throwing", async () => {
+ const h = harness();
+ await h.lifecycle.warmUp();
+ h.database.getPendingVectorChanges = () => {
+ throw new Error("database closed");
+ };
+ assert.doesNotThrow(() => h.lifecycle.notifyChanges());
+ await new Promise((resolve) => setImmediate(resolve));
+ assert.ok(
+ h.logs.some(([level, , meta]) => level === "warn" && meta?.error === "database closed")
+ );
+});
diff --git a/test/helpers/settingsStoreNotificationPreferences.test.js b/test/helpers/settingsStoreNotificationPreferences.test.js
new file mode 100644
index 000000000..04e77310b
--- /dev/null
+++ b/test/helpers/settingsStoreNotificationPreferences.test.js
@@ -0,0 +1,43 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+const { createRendererServer, installBrowserGlobals } = require("../lib/rendererTestHarness");
+
+test("startup syncs the full saved notification snapshot once", async (t) => {
+ const snapshots = [];
+ installBrowserGlobals(t, {
+ initialStorage: {
+ notificationsEnabled: "false",
+ notifyMeetingDetection: "true",
+ notifyCalendarReminders: "false",
+ meetingProcessDetection: "false",
+ customDictionary: '["OpenWhispr"]',
+ },
+ window: {
+ electronAPI: {
+ getOpenAIKey: async () => "",
+ setDictionary: async () => {},
+ syncNotificationPreferences: async (prefs) => {
+ snapshots.push(prefs);
+ },
+ },
+ },
+ });
+ const vite = await createRendererServer(t, {
+ cachePrefix: "openwhispr-notification-preferences-test-",
+ });
+ const { initializeSettings } = await vite.ssrLoadModule("/stores/settingsStore.ts");
+ try {
+ await initializeSettings();
+ } finally {
+ const { default: i18n } = await vite.ssrLoadModule("/i18n.ts");
+ await i18n.changeLanguage("en");
+ }
+ assert.deepEqual(snapshots, [
+ {
+ notificationsEnabled: false,
+ notifyMeetingDetection: true,
+ notifyCalendarReminders: false,
+ meetingProcessDetection: false,
+ },
+ ]);
+});
diff --git a/test/helpers/vectorChangesDatabase.test.js b/test/helpers/vectorChangesDatabase.test.js
new file mode 100644
index 000000000..b9efa6ed6
--- /dev/null
+++ b/test/helpers/vectorChangesDatabase.test.js
@@ -0,0 +1,194 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+const { DatabaseSync } = require("node:sqlite");
+const Module = require("node:module");
+const fs = require("node:fs");
+const os = require("node:os");
+const path = require("node:path");
+
+const originalLoad = Module._load;
+Module._load = function patchedLoad(request, parent, isMain) {
+ if (request === "electron") return { app: {} };
+ return originalLoad.call(this, request, parent, isMain);
+};
+const DatabaseManager = require("../../src/helpers/database.js");
+Module._load = originalLoad;
+
+function createDatabase(t, { migrate = true, filename = ":memory:" } = {}) {
+ const sqlite = new DatabaseSync(filename);
+ t.after(() => {
+ if (sqlite.isOpen) sqlite.close();
+ });
+ sqlite.exec(`
+ CREATE TABLE IF NOT EXISTS notes (
+ id INTEGER PRIMARY KEY, title TEXT, content TEXT, enhanced_content TEXT,
+ space_id INTEGER, folder_id INTEGER, deleted_at TEXT, account_id TEXT,
+ updated_at TEXT
+ );
+ `);
+ sqlite.transaction = (callback) => () => {
+ sqlite.exec("BEGIN");
+ try {
+ const result = callback();
+ sqlite.exec("COMMIT");
+ return result;
+ } catch (error) {
+ sqlite.exec("ROLLBACK");
+ throw error;
+ }
+ };
+ const manager = Object.create(DatabaseManager.prototype);
+ manager.db = sqlite;
+ if (migrate) manager._initVectorChangeJournal();
+ return manager;
+}
+
+function acknowledgeAll(manager) {
+ for (const change of manager.getPendingVectorChanges()) {
+ manager.clearPendingVectorChange(change.note_id, change.revision);
+ }
+}
+
+test("vector journal seeds existing notes once without reviving acknowledged work", (t) => {
+ const manager = createDatabase(t, { migrate: false });
+ manager.db.exec("INSERT INTO notes (id, title) VALUES (1, 'Existing')");
+ assert.equal(typeof manager._initVectorChangeJournal, "function");
+ manager._initVectorChangeJournal();
+ assert.deepEqual(
+ manager.getPendingVectorChanges().map((row) => row.note_id),
+ [1]
+ );
+ acknowledgeAll(manager);
+ manager._initVectorChangeJournal();
+ assert.deepEqual(manager.getPendingVectorChanges(), []);
+});
+
+test("vector journal tracks raw insert, indexed field changes, and physical deletion", (t) => {
+ const manager = createDatabase(t);
+ manager.db.exec("INSERT INTO notes (id, title) VALUES (1, 'Imported')");
+ assert.equal(manager.getPendingVectorChanges()[0].note_id, 1);
+ acknowledgeAll(manager);
+ for (const [field, value] of [
+ ["title", "Renamed"],
+ ["content", "Cloud edit"],
+ ["enhanced_content", "Enhanced"],
+ ["space_id", 2],
+ ["folder_id", 3],
+ ["deleted_at", "2026-09-21"],
+ ["deleted_at", null],
+ ]) {
+ manager.db.prepare(`UPDATE notes SET ${field} = ? WHERE id = 1`).run(value);
+ assert.equal(manager.getPendingVectorChanges()[0]?.note_id, 1, field);
+ acknowledgeAll(manager);
+ }
+ manager.db.exec("DELETE FROM notes WHERE id = 1");
+ assert.equal(manager.getPendingVectorChanges()[0].note_id, 1);
+ assert.equal(manager.getNoteForVectorIndex(1), null);
+});
+
+test("vector journal skips irrelevant or unchanged field updates", (t) => {
+ const manager = createDatabase(t);
+ manager.db.exec("INSERT INTO notes (id, title) VALUES (1, 'Title')");
+ acknowledgeAll(manager);
+ manager.db.exec("UPDATE notes SET title = 'Title', updated_at = '2026-09-21' WHERE id = 1");
+ assert.deepEqual(manager.getPendingVectorChanges(), []);
+});
+
+test("vector journal acknowledgements cannot erase newer edits or reused note ids", (t) => {
+ const manager = createDatabase(t);
+ manager.db.exec("INSERT INTO notes (id, title) VALUES (1, 'Original')");
+ const initial = manager.getPendingVectorChanges()[0];
+ manager.db.exec("UPDATE notes SET content = 'Concurrent edit' WHERE id = 1");
+ assert.equal(manager.clearPendingVectorChange(1, initial.revision).changes, 0);
+ const edited = manager.getPendingVectorChanges()[0];
+ assert.ok(edited.revision > initial.revision);
+ acknowledgeAll(manager);
+ manager.db.exec("DELETE FROM notes WHERE id = 1");
+ acknowledgeAll(manager);
+ manager.db.exec("INSERT INTO notes (id, title) VALUES (1, 'Reinserted')");
+ assert.equal(manager.clearPendingVectorChange(1, edited.revision).changes, 0);
+ assert.ok(manager.getPendingVectorChanges()[0].revision > edited.revision);
+});
+
+test("vector journal changes roll back with note writes", (t) => {
+ const manager = createDatabase(t);
+ assert.throws(
+ () =>
+ manager.db.transaction(() => {
+ manager.db.exec("INSERT INTO notes (id, title) VALUES (1, 'Aborted')");
+ throw new Error("aborted");
+ })(),
+ /aborted/
+ );
+ assert.deepEqual(manager.getPendingVectorChanges(), []);
+ assert.equal(manager.getNoteForVectorIndex(1), null);
+});
+
+test("full reindex refreshes revisions and preserves deletion tombstones", (t) => {
+ const manager = createDatabase(t);
+ manager.db.exec("INSERT INTO notes (id, title) VALUES (1, 'First'), (2, 'Second')");
+ const previous = manager.getPendingVectorChanges()[0];
+ manager.db.exec("DELETE FROM notes WHERE id = 2");
+ manager.enqueueAllVectorChanges();
+ assert.deepEqual(
+ manager
+ .getPendingVectorChanges()
+ .map((row) => row.note_id)
+ .sort(),
+ [1, 2]
+ );
+ assert.equal(manager.getPendingVectorChanges(1).length, 1);
+ assert.equal(manager.clearPendingVectorChange(1, previous.revision).changes, 0);
+ assert.equal(
+ manager.clearPendingVectorChange(
+ 1,
+ manager.getPendingVectorChanges().find((row) => row.note_id === 1).revision
+ ).changes,
+ 1
+ );
+});
+
+test("indexing reads current notes across accounts including soft deletion", (t) => {
+ const manager = createDatabase(t);
+ manager.activeAccountId = "first-account";
+ manager.db.exec(
+ "INSERT INTO notes (id, title, account_id, deleted_at) VALUES (1, 'Other', 'other-account', '2026-09-21')"
+ );
+ const note = manager.getNoteForVectorIndex(1);
+ assert.equal(note.title, "Other");
+ assert.equal(note.deleted_at, "2026-09-21");
+});
+
+test("pending deletions and acknowledged revisions survive database restart", (t) => {
+ const directory = fs.mkdtempSync(path.join(os.tmpdir(), "openwhispr-vector-journal-"));
+ t.after(() => fs.rmSync(directory, { recursive: true, force: true }));
+ const filename = path.join(directory, "notes.db");
+ const manager = createDatabase(t, { filename });
+ manager.db.exec("INSERT INTO notes (id, title) VALUES (1, 'Keep'), (2, 'Remove')");
+ const originalRevision = manager.getPendingVectorChanges()[0].revision;
+ acknowledgeAll(manager);
+ manager.db.exec("DELETE FROM notes WHERE id = 2");
+ const pendingDeletion = manager.getPendingVectorChanges()[0];
+ manager.db.close();
+
+ const reopened = createDatabase(t, { filename });
+ assert.deepEqual(reopened.getPendingVectorChanges(), [pendingDeletion]);
+ acknowledgeAll(reopened);
+ reopened.db.exec("UPDATE notes SET title = 'Edited after restart' WHERE id = 1");
+ assert.ok(reopened.getPendingVectorChanges()[0].revision > pendingDeletion.revision);
+ assert.equal(reopened.clearPendingVectorChange(1, originalRevision).changes, 0);
+ reopened.db.close();
+});
+
+test("pending changes can be paged by revision cursor so parked rows are skipped", (t) => {
+ const manager = createDatabase(t);
+ manager.db.exec("INSERT INTO notes (id, title) VALUES (1, 'A'), (2, 'B'), (3, 'C')");
+ const [first, second, third] = manager.getPendingVectorChanges();
+ assert.deepEqual(manager.getPendingVectorChanges(50, first.revision), [second, third]);
+ assert.deepEqual(manager.getPendingVectorChanges(1, first.revision), [second]);
+ assert.deepEqual(manager.getPendingVectorChanges(50, third.revision), []);
+ manager.db.exec("UPDATE notes SET title = 'A2' WHERE id = 1");
+ const [edited] = manager.getPendingVectorChanges(50, third.revision);
+ assert.equal(edited.note_id, 1);
+ assert.ok(edited.revision > third.revision);
+});
diff --git a/test/helpers/vectorIndexLifecycle.test.js b/test/helpers/vectorIndexLifecycle.test.js
new file mode 100644
index 000000000..9b4364414
--- /dev/null
+++ b/test/helpers/vectorIndexLifecycle.test.js
@@ -0,0 +1,86 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+const Module = require("node:module");
+
+function loadIndex() {
+ const originalLoad = Module._load;
+ let collectionError;
+ let writeError;
+ const calls = [];
+ const client = {
+ async getCollection() {
+ if (collectionError) throw collectionError;
+ },
+ async createCollection() {
+ calls.push("create");
+ },
+ async upsert(name, request) {
+ calls.push(["upsert", request]);
+ if (writeError) throw writeError;
+ },
+ async delete(name, request) {
+ calls.push(["delete", request]);
+ if (writeError) throw writeError;
+ },
+ };
+ Module._load = function (request, parent, isMain) {
+ if (request === "@qdrant/js-client-rest")
+ return {
+ QdrantClient: function () {
+ return client;
+ },
+ };
+ if (request === "./debugLogger") return { debug() {}, error() {} };
+ if (request === "./localEmbeddings")
+ return { embedText: async () => new Float32Array([1]), LocalEmbeddings: {} };
+ if (request === "./conversationChunker") return {};
+ return originalLoad.call(this, request, parent, isMain);
+ };
+ const modulePath = require.resolve("../../src/helpers/vectorIndex");
+ delete require.cache[modulePath];
+ try {
+ return {
+ index: require(modulePath),
+ calls,
+ failCollection(error) {
+ collectionError = error;
+ },
+ failWrite(error) {
+ writeError = error;
+ },
+ };
+ } finally {
+ Module._load = originalLoad;
+ }
+}
+
+test("note writes acknowledge only completed successful Qdrant mutations", async () => {
+ const h = loadIndex();
+ h.index.init(6333);
+ assert.equal(await h.index.upsertNote(1, "test"), true);
+ assert.equal(await h.index.deleteNote(1), true);
+ assert.equal(await h.index.deleteBySpace(5), true);
+ for (const [, request] of h.calls) assert.equal(request.wait, true);
+ h.failWrite(new Error("offline"));
+ assert.equal(await h.index.upsertNote(1, "test"), false);
+ assert.equal(await h.index.deleteNote(1), false);
+});
+
+test("collection startup distinguishes creation from availability failures", async () => {
+ const h = loadIndex();
+ h.index.init(6333);
+ assert.deepEqual(await h.index.ensureCollection(), { created: false });
+ h.failCollection({ status: 404 });
+ assert.deepEqual(await h.index.ensureCollection(), { created: true });
+ h.failCollection(new Error("offline"));
+ await assert.rejects(h.index.ensureCollection(), /offline/);
+ assert.equal(h.calls.filter((call) => call === "create").length, 1);
+});
+
+test("reset invalidates readiness and prevents acknowledging writes", async () => {
+ const h = loadIndex();
+ h.index.init(6333);
+ h.index.reset();
+ assert.equal(await h.index.upsertNote(1, "test"), false);
+ assert.equal(await h.index.deleteNote(1), false);
+});