Voice-to-text dictation app with local (Nvidia Parakeet/Whisper) and cloud models (BYOK). Privacy-first and available cross-platform.
JavaScript aianthropiccross-platformgeminigroqlinuxmacosnvidiaopen-sourceopenaiparakeetspeech-to-texttranscribewhisperwindows
fix: agent calendar tool, tests and outdated claude.md
Chadpiha21a63ad26e0b
diff --git a/CLAUDE.md b/CLAUDE.mdindex 88c550f89..645496374 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -114,10 +114,17 @@ OpenWhispr is an Electron-based desktop dictation application that uses whisper.- Linux: Event-driven via `pactl subscribe` (PulseAudio source-output events)- All platforms: Graceful fallback to polling if native approach fails- **processListCache.js**: Shared singleton process list cache (5s TTL, `ps-list` npm)-- **googleCalendarManager.js**: Google Calendar sync with exponential backoff+- **googleCalendarManager.js**: Google Calendar sync (REST, OAuth via `googleCalendarOAuth.js`)- 10s socket timeout on API requests- - Backoff: 2min → 4min → 8min → cap 30min on consecutive failures- - Reset to normal interval on success+ - Incremental sync via `syncToken`; full re-sync on 410 prunes stale events (note-linked rows retained)+- **microsoftCalendarManager.js**: Microsoft Calendar sync via Graph API (OAuth via `microsoftCalendarOAuth.js`)+ - `calendarView/delta` incremental sync over a 14-day window; delta token discarded after 7 days (Graph delta links never roll their window forward)+ - Full re-sync (410 or expired token) prunes stale events like Google+- **appleCalendarManager.js**: Apple Calendar (EventKit) via the `macos-calendar-listener` Swift helper — macOS only, snapshot-push over stdout, no tokens ("connected" = `apple_calendars` has rows)+- **calendarReminderScheduler.js**: Provider-agnostic meeting reminder scheduling over the shared `calendar_events` table (provider-scoped reset keys, so one provider's disconnect doesn't re-fire another's reminders)+- **calendarSyncInterval.js**: Shared interval runner for the REST providers — exponential backoff (2min → 4min → 8min → cap 30min on consecutive failures, reset on success) and 30s focus-sync throttle+- **oauthLoopbackFlow.js**: Shared PKCE auth-code flow over an ephemeral 127.0.0.1 server, used by both calendar OAuth helpers+- Events from all providers land in the shared `calendar_events` table with a `provider` column; queries suppress the Apple copy of a meeting when a REST row occupies the same time slot + title (Calendar.app mirrors the same accounts)- **menuManager.js**: Application menu management- **tray.js**: System tray icon and menu- **whisper.js**: Local whisper.cpp integration and model management@@ -559,7 +566,7 @@ Detects meetings via three independent sources, orchestrated by `MeetingDetectio**Architecture**:- `MeetingDetectionEngine` listens to events from `MeetingProcessDetector` and `AudioActivityDetector`-- `GoogleCalendarManager` provides calendar context (imminent events, active meetings)+- `CalendarReminderScheduler` provides calendar context (imminent events, active meetings) from the shared `calendar_events` table, fed by the Google/Microsoft/Apple calendar managers- All three sources feed into a unified notification pipeline**Process Detection** (known meeting apps — Zoom, Teams, Webex, FaceTime):@@ -576,7 +583,7 @@ Detects meetings via three independent sources, orchestrated by `MeetingDetectio**Calendar Reminders** (scheduled meetings):-- `GoogleCalendarManager` fires `meetingDetectionEngine.handleCalendarReminder(event)` 1 minute before the scheduled start (`MEETING_REMINDER_LEAD_MS`) — no native OS notifications; all meeting prompts use the in-app overlay so they survive Focus/DND and screen-share notification muting+- `CalendarReminderScheduler` fires `meetingDetectionEngine.handleCalendarReminder(event)` 1 minute before the scheduled start (`MEETING_REMINDER_LEAD_MS`) — no native OS notifications; all meeting prompts use the in-app overlay so they survive Focus/DND and screen-share notification muting- Calendar-sourced prompts show a Join primary action when the event has a meeting link (`getMeetingJoinUrl` in `src/helpers/meetingJoinUrl.js`, shared with the renderer's Upcoming Meetings join button) — Join opens the link and starts the note**UX Rules**:@@ -801,7 +808,7 @@ const { t } = useTranslation();- Process timeout protection (5 minutes)- Meeting detection uses event-driven OS APIs (near-zero CPU) with polling fallback- Process list cache shared between detectors to avoid duplicate `tasklist`/`pgrep` calls-- Google Calendar sync uses exponential backoff to avoid hammering API on network failures+- Calendar sync (Google/Microsoft) uses exponential backoff to avoid hammering APIs on network failures## Security Considerationsdiff --git a/src/components/chat/useChatStreaming.ts b/src/components/chat/useChatStreaming.tsindex 896e8b029..eb9e3e1be 100644--- a/src/components/chat/useChatStreaming.ts+++ b/src/components/chat/useChatStreaming.ts@@ -131,13 +131,17 @@ export function useChatStreaming({let registry: ToolRegistry | null = null;if (supportsTools) {const scopeKey = scope ? `${scope.spaceId}:${scope.folderId ?? ""}` : "";- const cacheKey = `${settings.isSignedIn}-${settings.gcalConnected}-${settings.cloudBackupEnabled}-${scopeKey}`;+ // The calendar tool reads the shared provider-deduped events table,+ // so any connected provider enables it.+ const calendarConnected =+ settings.gcalConnected || settings.mcalConnected || settings.appleCalendarConnected;+ const cacheKey = `${settings.isSignedIn}-${calendarConnected}-${settings.cloudBackupEnabled}-${scopeKey}`;if (toolRegistryRef.current?.key === cacheKey) {registry = toolRegistryRef.current.registry;} else {registry = createToolRegistry({isSignedIn: settings.isSignedIn,- gcalConnected: settings.gcalConnected,+ calendarConnected,cloudBackupEnabled: settings.cloudBackupEnabled,searchScope: scope,});diff --git a/src/helpers/appleCalendarManager.js b/src/helpers/appleCalendarManager.jsindex 93a804b65..889e3ed22 100644--- a/src/helpers/appleCalendarManager.js+++ b/src/helpers/appleCalendarManager.js@@ -4,9 +4,9 @@ const debugLogger = require("./debugLogger");const { resolveBundledBinary } = require("./binaryResolver");const { extractMeetingUrl } = require("./meetingJoinUrl");const { broadcastToWindows } = require("./windowBroadcast");+const { FOCUS_SYNC_THROTTLE_MS } = require("./calendarSyncInterval");const BINARY_NAME = "macos-calendar-listener";-const FOCUS_SYNC_THROTTLE_MS = 30 * 1000;const HELPER_RESTART_BASE_MS = 1000;const HELPER_RESTART_MAX_MS = 30 * 1000;diff --git a/src/helpers/calendarSyncInterval.js b/src/helpers/calendarSyncInterval.jsindex 1cb286b60..4ac7f0eec 100644--- a/src/helpers/calendarSyncInterval.js+++ b/src/helpers/calendarSyncInterval.js@@ -84,3 +84,4 @@ class CalendarSyncInterval {}module.exports = CalendarSyncInterval;+module.exports.FOCUS_SYNC_THROTTLE_MS = FOCUS_SYNC_THROTTLE_MS;diff --git a/src/helpers/database.js b/src/helpers/database.jsindex fab51dcd4..14a52242e 100644--- a/src/helpers/database.js+++ b/src/helpers/database.js@@ -3516,6 +3516,38 @@ class DatabaseManager {}}+ // A full (non-incremental) REST sync is authoritative for its calendar's+ // window: rows the provider no longer returns were deleted while no valid+ // sync token existed (e.g. the app was offline past the token TTL), so they+ // would otherwise linger and fire reminders for cancelled meetings. Rows+ // referenced by meeting notes are kept so notes retain calendar metadata.+ removeStaleCalendarEvents(provider, calendarId, freshEventIds) {+ try {+ if (!this.db) throw new Error("Database not initialized");+ const placeholders = freshEventIds.map(() => "?").join(", ");+ const freshFilter = freshEventIds.length > 0 ? `AND id NOT IN (${placeholders})` : "";+ this.db+ .prepare(+ `DELETE FROM calendar_events+ WHERE provider = ? AND calendar_id = ? ${freshFilter}+ AND id NOT IN (+ SELECT calendar_event_id+ FROM notes+ WHERE calendar_event_id IS NOT NULL AND deleted_at IS NULL+ )`+ )+ .run(provider, calendarId, ...freshEventIds);+ return { success: true };+ } catch (error) {+ debugLogger.error(+ "Error removing stale calendar events",+ { error: error.message },+ provider === "microsoft" ? "mcal" : "gcal"+ );+ throw error;+ }+ }+removeEventsFromDeselectedCalendars(provider) {try {if (!this.db) throw new Error("Database not initialized");diff --git a/src/helpers/googleCalendarManager.js b/src/helpers/googleCalendarManager.jsindex 29834a836..493ce8c42 100644--- a/src/helpers/googleCalendarManager.js+++ b/src/helpers/googleCalendarManager.js@@ -170,6 +170,7 @@ class GoogleCalendarManager {params.set("syncToken", calendar.sync_token);}+ let isFullSync = !calendar.sync_token;let data;try {data = await this._apiGet(@@ -179,6 +180,7 @@ class GoogleCalendarManager {} catch (err) {// 410 Gone means syncToken is invalid; fall back to full syncif (err.statusCode === 410) {+ isFullSync = true;const fullParams = new URLSearchParams({singleEvents: "true",orderBy: "startTime",@@ -230,6 +232,16 @@ class GoogleCalendarManager {});}+ // A full sync has no incremental baseline, so deletions that happened+ // while the sync token was invalid never arrive as cancelled items —+ // prune what the fresh snapshot no longer contains.+ if (isFullSync) {+ this.databaseManager.removeStaleCalendarEvents(+ "google",+ calendar.id,+ toUpsert.map((event) => event.id)+ );+ }if (toUpsert.length > 0) this.databaseManager.upsertCalendarEvents(toUpsert);if (toRemove.length > 0) this.databaseManager.removeCalendarEvents(toRemove);if (data.nextSyncToken)diff --git a/src/helpers/googleCalendarOAuth.js b/src/helpers/googleCalendarOAuth.jsindex e1b1b98a9..7918ab973 100644--- a/src/helpers/googleCalendarOAuth.js+++ b/src/helpers/googleCalendarOAuth.js@@ -143,6 +143,7 @@ class GoogleCalendarOAuth {method: "POST",headers: { "Content-Type": "application/x-www-form-urlencoded" },body,+ signal: AbortSignal.timeout(10000),useSessionCookies: false,});const text = await response.text();diff --git a/src/helpers/ipcHandlers.js b/src/helpers/ipcHandlers.jsindex 39a031278..a3293f16b 100644--- a/src/helpers/ipcHandlers.js+++ b/src/helpers/ipcHandlers.js@@ -2924,6 +2924,11 @@ class IPCHandlers {} catch (e) {errors.push(`MCal stop: ${e.message}`);}+ try {+ this.appleCalendarManager?.stop();+ } catch (e) {+ errors.push(`ACal stop: ${e.message}`);+ }// Revoke Google OAuth tokens before DB is closedtry {diff --git a/src/helpers/microsoftCalendarManager.js b/src/helpers/microsoftCalendarManager.jsindex 709a1c575..8418e8f53 100644--- a/src/helpers/microsoftCalendarManager.js+++ b/src/helpers/microsoftCalendarManager.js@@ -175,6 +175,7 @@ class MicrosoftCalendarManager {let deltaLink = null;const hasFreshToken = calendar.sync_token && calendar.sync_token_expires_at > Date.now();+ let isFullSync = !hasFreshToken;let url = hasFreshToken ? calendar.sync_token : this._deltaUrl(calendar.id);let tokenExpiresAt = hasFreshToken? calendar.sync_token_expires_at@@ -187,6 +188,7 @@ class MicrosoftCalendarManager {} catch (err) {// 410 Gone means the delta token expired; fall back to a full syncif (err.statusCode === 410 && url === calendar.sync_token) {+ isFullSync = true;url = this._deltaUrl(calendar.id);tokenExpiresAt = Date.now() + DELTA_TOKEN_TTL_MS;continue;@@ -214,6 +216,16 @@ class MicrosoftCalendarManager {url = data["@odata.nextLink"] || null;}+ // A full sync has no delta baseline, so deletions that happened while the+ // token was invalid never arrive as @removed — prune what the fresh+ // snapshot no longer contains.+ if (isFullSync) {+ this.databaseManager.removeStaleCalendarEvents(+ "microsoft",+ calendar.id,+ toUpsert.map((event) => event.id)+ );+ }if (toUpsert.length > 0) this.databaseManager.upsertCalendarEvents(toUpsert);if (toRemove.length > 0) this.databaseManager.removeCalendarEvents(toRemove);if (deltaLink) {@@ -336,3 +348,4 @@ class MicrosoftCalendarManager {}module.exports = MicrosoftCalendarManager;+module.exports.normalizeGraphDateTime = normalizeGraphDateTime;diff --git a/src/helpers/microsoftCalendarOAuth.js b/src/helpers/microsoftCalendarOAuth.jsindex 0e07000f8..4ceb9e155 100644--- a/src/helpers/microsoftCalendarOAuth.js+++ b/src/helpers/microsoftCalendarOAuth.js@@ -150,6 +150,7 @@ class MicrosoftCalendarOAuth {method: "POST",headers: { "Content-Type": "application/x-www-form-urlencoded" },body,+ signal: AbortSignal.timeout(10000),useSessionCookies: false,});const text = await response.text();diff --git a/src/services/tools/index.ts b/src/services/tools/index.tsindex 611af8585..27ff413ba 100644--- a/src/services/tools/index.ts+++ b/src/services/tools/index.ts@@ -14,7 +14,7 @@ export type { ToolDefinition, ToolResult } from "./ToolRegistry";interface ToolRegistrySettings {isSignedIn: boolean;- gcalConnected: boolean;+ calendarConnected: boolean;cloudBackupEnabled: boolean;/** Pins search_notes to a container (overview chat); the LLM cannot widen it. */searchScope?: ContainerScope;@@ -35,7 +35,7 @@ export function createToolRegistry(settings: ToolRegistrySettings): ToolRegistryregistry.register(webSearchTool);}- if (settings.gcalConnected) {+ if (settings.calendarConnected) {registry.register(calendarTool);}diff --git a/test/helpers/calendarDatabase.test.js b/test/helpers/calendarDatabase.test.jsindex 0b3cbcf16..cca63a1da 100644--- a/test/helpers/calendarDatabase.test.js+++ b/test/helpers/calendarDatabase.test.js@@ -75,6 +75,55 @@ test("Apple snapshots retain events referenced by meeting notes", (t) => {db.db.close();});+function restEvent(provider, calendarId, id) {+ return {+ id,+ calendar_id: calendarId,+ provider,+ summary: id,+ start_time: "2026-07-22T10:00:00Z",+ end_time: "2026-07-22T11:00:00Z",+ is_all_day: false,+ status: "confirmed",+ };+}++test("full-sync prune drops stale events but keeps fresh, note-linked, and other-scope rows", (t) => {+ const db = createDb(t);+ if (!db) return;++ db.upsertCalendarEvents([+ restEvent("microsoft", "ms-cal", "fresh"),+ restEvent("microsoft", "ms-cal", "stale"),+ restEvent("microsoft", "ms-cal", "stale-linked"),+ restEvent("microsoft", "other-cal", "other-calendar"),+ restEvent("google", "ms-cal", "other-provider"),+ ]);+ const note = db.saveNote("Linked meeting", "", "meeting").note;+ db.updateNote(note.id, { calendar_event_id: "stale-linked" });++ db.removeStaleCalendarEvents("microsoft", "ms-cal", ["fresh"]);++ assert.equal(db.getCalendarEventById("fresh")?.summary, "fresh");+ assert.equal(db.getCalendarEventById("stale"), null);+ assert.equal(db.getCalendarEventById("stale-linked")?.summary, "stale-linked");+ assert.equal(db.getCalendarEventById("other-calendar")?.summary, "other-calendar");+ assert.equal(db.getCalendarEventById("other-provider")?.summary, "other-provider");+ db.db.close();+});++test("full-sync prune with an empty fresh set clears the calendar's unlinked events", (t) => {+ const db = createDb(t);+ if (!db) return;++ db.upsertCalendarEvents([restEvent("microsoft", "ms-cal", "stale")]);++ db.removeStaleCalendarEvents("microsoft", "ms-cal", []);++ assert.equal(db.getCalendarEventById("stale"), null);+ db.db.close();+});+test("tentative Apple events remain visible in upcoming meetings", (t) => {const db = createDb(t);if (!db) return;diff --git a/test/helpers/calendarSyncInterval.test.js b/test/helpers/calendarSyncInterval.test.jsnew file mode 100644index 000000000..a8ba30f23--- /dev/null+++ b/test/helpers/calendarSyncInterval.test.js@@ -0,0 +1,81 @@+const test = require("node:test");+const assert = require("node:assert/strict");++const CalendarSyncInterval = require("../../src/helpers/calendarSyncInterval.js");+const { FOCUS_SYNC_THROTTLE_MS } = CalendarSyncInterval;++function createRunner(syncFn, overrides = {}) {+ return new CalendarSyncInterval(syncFn, {+ intervalMs: 1000,+ maxIntervalMs: 4000,+ logScope: "test",+ ...overrides,+ });+}++function flushPromises() {+ return new Promise((resolve) => setImmediate(resolve));+}++test("backoff doubles the interval per consecutive failure up to the cap", () => {+ const runner = createRunner(() => Promise.resolve());++ assert.equal(runner._getInterval(), 1000);+ runner._consecutiveFailures = 1;+ assert.equal(runner._getInterval(), 2000);+ runner._consecutiveFailures = 2;+ assert.equal(runner._getInterval(), 4000);+ runner._consecutiveFailures = 5;+ assert.equal(runner._getInterval(), 4000);+});++test("notifySuccess resets the backoff to the base interval", () => {+ const runner = createRunner(() => Promise.resolve());++ runner._consecutiveFailures = 3;+ runner.notifySuccess();++ assert.equal(runner._getInterval(), 1000);+ runner.stop();+});++test("a failed sync reschedules the next run at the backed-off interval", async (t) => {+ t.mock.timers.enable({ apis: ["setInterval"] });+ let calls = 0;+ const runner = createRunner(() => {+ calls += 1;+ return Promise.reject(new Error("boom"));+ });++ runner.start();+ t.mock.timers.tick(1000);+ assert.equal(calls, 1);+ await flushPromises();++ // The 1000ms interval was replaced by a 2000ms one after the failure+ t.mock.timers.tick(1000);+ assert.equal(calls, 1);+ t.mock.timers.tick(1000);+ assert.equal(calls, 2);++ runner.stop();+});++test("focus syncs are throttled to one per window", async () => {+ let calls = 0;+ const runner = createRunner(() => {+ calls += 1;+ return Promise.resolve();+ });++ runner.syncOnFocus();+ runner.syncOnFocus();+ assert.equal(calls, 1);++ runner._lastFocusSync = Date.now() - FOCUS_SYNC_THROTTLE_MS - 1;+ runner.syncOnFocus();+ assert.equal(calls, 2);++ await flushPromises();+ runner.stop();+});diff --git a/test/helpers/microsoftCalendarManager.test.js b/test/helpers/microsoftCalendarManager.test.jsnew file mode 100644index 000000000..6a7f8c1d0--- /dev/null+++ b/test/helpers/microsoftCalendarManager.test.js@@ -0,0 +1,102 @@+const test = require("node:test");+const assert = require("node:assert/strict");+const Module = require("node:module");++const managerModulePath = require.resolve("../../src/helpers/microsoftCalendarManager.js");+const originalLoad = Module._load;++function loadManagerModule() {+ delete require.cache[managerModulePath];+ Module._load = function loadWithElectronMock(request, parent, isMain) {+ if (request === "electron") {+ return { net: {}, BrowserWindow: { getAllWindows: () => [] } };+ }+ return originalLoad.call(this, request, parent, isMain);+ };+ try {+ return require(managerModulePath);+ } finally {+ Module._load = originalLoad;+ }+}++test("normalizeGraphDateTime converts Graph timestamps to SQLite-parseable UTC", () => {+ const { normalizeGraphDateTime } = loadManagerModule();++ assert.equal(+ normalizeGraphDateTime({ dateTime: "2026-07-20T17:00:00.0000000" }),+ "2026-07-20T17:00:00Z"+ );+ assert.equal(normalizeGraphDateTime({ dateTime: "2026-07-20T17:00:00" }), "2026-07-20T17:00:00Z");+});++test("_mapEvent maps a Graph event to the shared calendar_events shape", () => {+ const MicrosoftCalendarManager = loadManagerModule();+ const manager = new MicrosoftCalendarManager({}, {});+ const calendar = { id: "cal-1", account_email: "[email protected]" };++ const mapped = manager._mapEvent(+ {+ id: "evt-1",+ subject: "Standup",+ start: { dateTime: "2026-07-20T17:00:00.0000000" },+ end: { dateTime: "2026-07-20T17:30:00.0000000" },+ isAllDay: false,+ isCancelled: false,+ onlineMeeting: { joinUrl: "https://teams.microsoft.com/l/meetup-join/abc" },+ organizer: { emailAddress: { address: "[email protected]" } },+ attendees: [+ {+ emailAddress: { address: "[email protected]", name: "Me" },+ status: { response: "tentativelyAccepted" },+ },+ { emailAddress: { address: "[email protected]" }, status: { response: "notResponded" } },+ ],+ },+ calendar+ );++ assert.equal(mapped.provider, "microsoft");+ assert.equal(mapped.summary, "Standup");+ assert.equal(mapped.start_time, "2026-07-20T17:00:00Z");+ assert.equal(mapped.status, "confirmed");+ assert.equal(mapped.hangout_link, "https://teams.microsoft.com/l/meetup-join/abc");+ assert.equal(mapped.organizer_email, "[email protected]");+ assert.equal(mapped.attendees_count, 2);++ const attendees = JSON.parse(mapped.attendees);+ assert.deepEqual(attendees[0], {+ email: "[email protected]",+ displayName: "Me",+ responseStatus: "tentative",+ self: true,+ });+ assert.deepEqual(attendees[1], {+ email: "[email protected]",+ displayName: null,+ responseStatus: "needsAction",+ self: false,+ });+});++test("_mapEvent falls back to a meeting link found in location or body text", () => {+ const MicrosoftCalendarManager = loadManagerModule();+ const manager = new MicrosoftCalendarManager({}, {});++ const mapped = manager._mapEvent(+ {+ id: "evt-2",+ subject: "External call",+ start: { dateTime: "2026-07-21T09:00:00.0000000" },+ end: { dateTime: "2026-07-21T10:00:00.0000000" },+ isAllDay: false,+ isCancelled: true,+ bodyPreview: "Join here: https://example.zoom.us/j/123456789.",+ },+ { id: "cal-1", account_email: "[email protected]" }+ );++ assert.equal(mapped.status, "cancelled");+ assert.equal(mapped.hangout_link, "https://example.zoom.us/j/123456789");+ assert.equal(mapped.attendees, null);+});