Voice-to-text dictation app with local (Nvidia Parakeet/Whisper) and cloud models (BYOK). Privacy-first and available cross-platform.
JavaScript aianthropiccross-platformgeminigroqlinuxmacosnvidiaopen-sourceopenaiparakeetspeech-to-texttranscribewhisperwindows
feat(calendar): Apple Calendar (EventKit) integration for macOS (#1237)
Gabriel Stein5d69b75a2e26
diff --git a/electron-builder.json b/electron-builder.jsonindex 15c3e40bb..448bf0bf2 100644--- a/electron-builder.json+++ b/electron-builder.json@@ -110,6 +110,7 @@"macos-globe-listener","macos-fast-paste","macos-mic-listener",+ "macos-calendar-listener","macos-text-monitor","macos-media-remote","MediaRemoteAdapter.framework/**",@@ -161,7 +162,9 @@"CFBundleIconName": "openwhispr","NSMicrophoneUsageDescription": "OpenWhispr uses the microphone to capture your voice for transcription.","NSAudioCaptureUsageDescription": "OpenWhispr uses system audio to capture other participants' audio from calls and meetings.",- "NSAccessibilityUsageDescription": "OpenWhispr needs accessibility permissions to paste transcribed text into other applications."+ "NSAccessibilityUsageDescription": "OpenWhispr needs accessibility permissions to paste transcribed text into other applications.",+ "NSCalendarsUsageDescription": "OpenWhispr reads your calendar to detect upcoming meetings and link meeting notes to events.",+ "NSCalendarsFullAccessUsageDescription": "OpenWhispr reads your calendar to detect upcoming meetings and link meeting notes to events."}},"win": {diff --git a/main.js b/main.jsindex ff07b9065..ec2f648dd 100644--- a/main.js+++ b/main.js@@ -277,6 +277,8 @@ const TextEditMonitor = require("./src/helpers/textEditMonitor");const WhisperCudaManager = require("./src/helpers/whisperCudaManager");const WhisperVulkanManager = require("./src/helpers/whisperVulkanManager");const GoogleCalendarManager = require("./src/helpers/googleCalendarManager");+const AppleCalendarManager = require("./src/helpers/appleCalendarManager");+const CalendarReminderScheduler = require("./src/helpers/calendarReminderScheduler");const MeetingProcessDetector = require("./src/helpers/meetingProcessDetector");const AudioActivityDetector = require("./src/helpers/audioActivityDetector");const AudioTapManager = require("./src/helpers/audioTapManager");@@ -309,6 +311,8 @@ let textEditMonitor = null;let whisperCudaManager = null;let whisperVulkanManager = null;let googleCalendarManager = null;+let appleCalendarManager = null;+let calendarReminderScheduler = null;let meetingDetectionEngine = null;let audioTapManager = null;let linuxPortalAudioManager = null;@@ -397,16 +401,22 @@ function initializeCoreManagers() {}parakeetManager = new ParakeetManager();diarizationManager = new DiarizationManager();- googleCalendarManager = new GoogleCalendarManager(databaseManager, windowManager);+ calendarReminderScheduler = new CalendarReminderScheduler(databaseManager);+ googleCalendarManager = new GoogleCalendarManager(+ databaseManager,+ windowManager,+ calendarReminderScheduler+ );+ appleCalendarManager = new AppleCalendarManager(databaseManager, calendarReminderScheduler);meetingDetectionEngine = new MeetingDetectionEngine(- googleCalendarManager,+ calendarReminderScheduler,new MeetingProcessDetector(),new AudioActivityDetector(),windowManager,databaseManager);windowManager.meetingDetectionEngine = meetingDetectionEngine;- googleCalendarManager.meetingDetectionEngine = meetingDetectionEngine;+ calendarReminderScheduler.meetingDetectionEngine = meetingDetectionEngine;updateManager = new UpdateManager();updateManager.setWindowManager(windowManager);windowsKeyManager = new WindowsKeyManager();@@ -440,6 +450,7 @@ function initializeCoreManagers() {whisperCudaManager,whisperVulkanManager,googleCalendarManager,+ appleCalendarManager,meetingDetectionEngine,audioTapManager,linuxPortalAudioManager,@@ -504,6 +515,7 @@ function initializeDeferredManagers() {}googleCalendarManager.start();+ appleCalendarManager.start();meetingDetectionEngine.start();}@@ -1054,13 +1066,16 @@ async function startApp() {app.on("browser-window-focus", () => {if (googleCalendarManager) googleCalendarManager.syncOnFocus();+ if (appleCalendarManager) appleCalendarManager.syncOnFocus();});const { powerMonitor } = require("electron");powerMonitor.on("resume", () => {+ if (calendarReminderScheduler) calendarReminderScheduler.onWakeFromSleep();if (googleCalendarManager) {googleCalendarManager.onWakeFromSleep();}+ if (appleCalendarManager) appleCalendarManager.onWakeFromSleep();// Sleep evicts the local GPU model from VRAM; reload it once the driver settles. See #766.if (wakeRewarmTimer) clearTimeout(wakeRewarmTimer);wakeRewarmTimer = setTimeout(() => {@@ -1792,6 +1807,8 @@ function performSyncTeardown() {if (linuxKeyManager) linuxKeyManager.stop();if (meetingDetectionEngine) meetingDetectionEngine.stop();if (googleCalendarManager) googleCalendarManager.stop();+ if (appleCalendarManager) appleCalendarManager.stop();+ if (calendarReminderScheduler) calendarReminderScheduler.stop();if (audioTapManager) audioTapManager.stop().catch(() => {});if (linuxPortalAudioManager) linuxPortalAudioManager.stop().catch(() => {});if (windowsLoopbackAudioManager) windowsLoopbackAudioManager.stop().catch(() => {});diff --git a/package.json b/package.jsonindex 930458278..6aa0dd335 100644--- a/package.json+++ b/package.json@@ -19,8 +19,9 @@"compile:media-remote": "node scripts/build-media-remote.js","compile:mediaremote-adapter": "node scripts/build-mediaremote-adapter.js","compile:mic-listener": "node scripts/build-macos-mic-listener.js",+ "compile:calendar-listener": "node scripts/build-macos-calendar-listener.js","compile:audio-tap": "node scripts/build-macos-audio-tap.js",- "compile:native": "npm run compile:globe && npm run compile:fast-paste && npm run compile:winkeys && npm run compile:linuxkeys && npm run compile:winpaste && npm run compile:linux-paste && npm run compile:linux-system-audio && npm run compile:text-monitor && npm run compile:media-remote && npm run compile:mediaremote-adapter && npm run compile:mic-listener && npm run compile:audio-tap",+ "compile:native": "npm run compile:globe && npm run compile:fast-paste && npm run compile:winkeys && npm run compile:linuxkeys && npm run compile:winpaste && npm run compile:linux-paste && npm run compile:linux-system-audio && npm run compile:text-monitor && npm run compile:media-remote && npm run compile:mediaremote-adapter && npm run compile:mic-listener && npm run compile:calendar-listener && npm run compile:audio-tap","prestart": "npm run compile:native && npm run download:meeting-aec-helper && npm run download:sherpa-onnx && npm run download:yt-dlp && npm run download:qdrant && npm run download:embedding-model && npm run download:whisper-vad-model","start": "electron .","dev": "concurrently -k -r \"npm:dev:renderer\" \"npm:dev:main\"",diff --git a/preload.js b/preload.jsindex 85451465d..19ba45b58 100644--- a/preload.js+++ b/preload.js@@ -1042,6 +1042,12 @@ contextBridge.exposeInMainWorld("electronAPI", {ipcRenderer.invoke("gcal-get-upcoming-events", windowMinutes),gcalGetEvent: (eventId) => ipcRenderer.invoke("gcal-get-event", eventId),+ // Apple Calendar (macOS EventKit)+ acalConnect: () => ipcRenderer.invoke("acal-connect"),+ acalDisconnect: () => ipcRenderer.invoke("acal-disconnect"),+ acalGetConnectionStatus: () => ipcRenderer.invoke("acal-get-connection-status"),+ openCalendarPrivacySettings: () => ipcRenderer.invoke("open-calendar-privacy-settings"),+// ContactssearchContacts: (query) => ipcRenderer.invoke("search-contacts", query),upsertContact: (contact) => ipcRenderer.invoke("upsert-contact", contact),@@ -1057,6 +1063,16 @@ contextBridge.exposeInMainWorld("electronAPI", {(callback) => (_event, data) => callback(data)),+ // Apple Calendar event listeners+ onAcalConnectionChanged: registerListener(+ "acal-connection-changed",+ (callback) => (_event, data) => callback(data)+ ),+ onAcalEventsSynced: registerListener(+ "acal-events-synced",+ (callback) => (_event, data) => callback(data)+ ),+// Meeting detectionmeetingDetectionGetPreferences: () => ipcRenderer.invoke("meeting-detection-get-preferences"),meetingDetectionSetPreferences: (prefs) =>diff --git a/resources/mac/entitlements.mac.plist b/resources/mac/entitlements.mac.plistindex fe379b9a2..9cc29aaa7 100644--- a/resources/mac/entitlements.mac.plist+++ b/resources/mac/entitlements.mac.plist@@ -17,5 +17,9 @@<!-- Audio input for microphone recording --><key>com.apple.security.device.audio-input</key><true/>++ <!-- Calendar access for the EventKit calendar listener helper -->+ <key>com.apple.security.personal-information.calendars</key>+ <true/></dict></plist>\ No newline at end of filediff --git a/resources/macos-calendar-listener-Info.plist b/resources/macos-calendar-listener-Info.plistnew file mode 100644index 000000000..bba1a858e--- /dev/null+++ b/resources/macos-calendar-listener-Info.plist@@ -0,0 +1,14 @@+<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">+<plist version="1.0">+<dict>+ <key>CFBundleIdentifier</key>+ <string>com.openwhispr.calendar-listener</string>+ <key>CFBundleName</key>+ <string>OpenWhispr Calendar Listener</string>+ <key>NSCalendarsUsageDescription</key>+ <string>OpenWhispr reads your calendar to detect upcoming meetings and link meeting notes to events.</string>+ <key>NSCalendarsFullAccessUsageDescription</key>+ <string>OpenWhispr reads your calendar to detect upcoming meetings and link meeting notes to events.</string>+</dict>+</plist>diff --git a/resources/macos-calendar-listener.swift b/resources/macos-calendar-listener.swiftnew file mode 100644index 000000000..3965de004--- /dev/null+++ b/resources/macos-calendar-listener.swift@@ -0,0 +1,334 @@+/**+ * macOS Calendar Listener+ *+ * Long-running process that reads the local EventKit store and emits+ * line-delimited JSON on stdout: a permission message on launch, then a+ * calendars+events snapshot whenever the store changes, "sync" arrives on+ * stdin, or a 5-minute timer rolls the 7-day window forward.+ *+ * Pass --request to prompt for calendar access when it is not determined.+ * macOS reads the usage strings from the TCC "responsible process": the+ * OpenWhispr app bundle in packaged builds, or this binary's embedded+ * __info_plist in dev, where the manager spawns it via macos-disclaim-exec+ * (see build-macos-calendar-listener.js).+ *+ * Compile: see scripts/build-macos-calendar-listener.js (embeds the Info.plist)+ */++import CoreGraphics+import EventKit+import Foundation++// MARK: - State++let eventStore = EKEventStore()+let requestAccess = CommandLine.arguments.contains("--request")+let LOOKAHEAD_DAYS = 7.0+let REFRESH_INTERVAL_SECONDS = 300.0++let isoFormatter: ISO8601DateFormatter = {+ let formatter = ISO8601DateFormatter()+ formatter.timeZone = TimeZone(identifier: "UTC")+ return formatter+}()++let jsonEncoder = JSONEncoder()++// MARK: - Output++func emit(_ message: String) {+ print(message)+ fflush(stdout)+}++func emitError(_ message: String) {+ FileHandle.standardError.write((message + "\n").data(using: .utf8)!)+}++func emitJSON<T: Encodable>(_ value: T) {+ guard let data = try? jsonEncoder.encode(value),+ let json = String(data: data, encoding: .utf8)+ else {+ emitError("Failed to encode JSON message")+ return+ }+ emit(json)+}++// MARK: - Messages++struct PermissionMessage: Encodable {+ let type = "permission"+ let status: String+}++struct CalendarOut: Encodable {+ let id: String+ let title: String+ let color: String?+ let source_name: String?+}++struct AttendeeOut: Encodable {+ let email: String?+ let name: String?+ let status: String+ let isSelf: Bool++ enum CodingKeys: String, CodingKey {+ case email, name, status+ case isSelf = "self"+ }+}++struct EventOut: Encodable {+ let id: String+ let calendar_id: String+ let title: String?+ let start: String+ let end: String+ let is_all_day: Bool+ let status: String+ let organizer_email: String?+ let url: String?+ let location: String?+ let notes_urls: [String]+ let attendees: [AttendeeOut]+}++struct SnapshotMessage: Encodable {+ let type = "snapshot"+ let calendars: [CalendarOut]+ let events: [EventOut]+}++// MARK: - Permission++func permissionStatus() -> String {+ let status = EKEventStore.authorizationStatus(for: .event)+ if #available(macOS 14.0, *) {+ switch status {+ case .fullAccess: return "granted"+ case .writeOnly, .denied: return "denied"+ case .restricted: return "restricted"+ case .notDetermined: return "notDetermined"+ default: return "denied"+ }+ }+ switch status {+ case .authorized: return "granted"+ case .denied: return "denied"+ case .restricted: return "restricted"+ case .notDetermined: return "notDetermined"+ default: return "denied"+ }+}++func emitPermission() -> String {+ let status = permissionStatus()+ emitJSON(PermissionMessage(status: status))+ return status+}++// MARK: - Mapping++func hexColor(_ cgColor: CGColor?) -> String? {+ guard let cgColor,+ let sRGB = CGColorSpace(name: CGColorSpace.sRGB),+ let converted = cgColor.converted(to: sRGB, intent: .defaultIntent, options: nil),+ let components = converted.components, components.count >= 3+ else { return nil }+ return String(+ format: "#%02X%02X%02X",+ Int(round(components[0] * 255)),+ Int(round(components[1] * 255)),+ Int(round(components[2] * 255))+ )+}++func mailtoEmail(_ url: URL?) -> String? {+ guard let url, url.scheme?.lowercased() == "mailto" else { return nil }+ let email = url.absoluteString.dropFirst("mailto:".count)+ return email.isEmpty ? nil : String(email)+}++func participantStatus(_ status: EKParticipantStatus) -> String {+ switch status {+ case .accepted: return "accepted"+ case .declined: return "declined"+ case .tentative: return "tentative"+ default: return "needsAction"+ }+}++func eventStatus(_ status: EKEventStatus) -> String {+ switch status {+ case .tentative: return "tentative"+ case .canceled: return "cancelled"+ default: return "confirmed"+ }+}++let linkDetector = try? NSDataDetector(types: NSTextCheckingResult.CheckingType.link.rawValue)++func extractURLs(from text: String?) -> [String] {+ guard let text, !text.isEmpty, let linkDetector else { return [] }+ let range = NSRange(text.startIndex..., in: text)+ return linkDetector.matches(in: text, options: [], range: range).compactMap { match in+ guard let url = match.url, url.scheme == "https" || url.scheme == "http" else { return nil }+ return url.absoluteString+ }+}++func mapEvent(_ event: EKEvent) -> EventOut? {+ guard let eventIdentifier = event.eventIdentifier,+ let calendarId = event.calendar?.calendarIdentifier,+ let startDate = event.startDate,+ let endDate = event.endDate+ else { return nil }++ let attendees = (event.attendees ?? []).map { participant in+ AttendeeOut(+ email: mailtoEmail(participant.url),+ name: participant.name,+ status: participantStatus(participant.participantStatus),+ isSelf: participant.isCurrentUser+ )+ }++ return EventOut(+ id: "\(eventIdentifier):\(Int(startDate.timeIntervalSince1970))",+ calendar_id: calendarId,+ title: event.title,+ start: isoFormatter.string(from: startDate),+ end: isoFormatter.string(from: endDate),+ is_all_day: event.isAllDay,+ status: eventStatus(event.status),+ organizer_email: mailtoEmail(event.organizer?.url),+ url: event.url?.absoluteString,+ location: event.location,+ notes_urls: extractURLs(from: event.notes),+ attendees: attendees+ )+}++// MARK: - Snapshot++func emitSnapshot() {+ let calendars = eventStore.calendars(for: .event)++ let calendarsOut = calendars.map { calendar in+ CalendarOut(+ id: calendar.calendarIdentifier,+ title: calendar.title,+ color: hexColor(calendar.cgColor),+ source_name: calendar.source?.title+ )+ }++ let start = Date()+ let end = start.addingTimeInterval(LOOKAHEAD_DAYS * 24 * 60 * 60)+ let predicate = eventStore.predicateForEvents(withStart: start, end: end, calendars: calendars)+ let eventsOut = eventStore.events(matching: predicate).compactMap(mapEvent)++ emitJSON(SnapshotMessage(calendars: calendarsOut, events: eventsOut))+}++// MARK: - Change Observation++var pendingSnapshot: DispatchWorkItem?+var timers: [DispatchSourceTimer] = []+var storeObservers: [NSObjectProtocol] = []++func scheduleSnapshot(debounce: TimeInterval = 1.0) {+ pendingSnapshot?.cancel()+ let work = DispatchWorkItem { emitSnapshot() }+ pendingSnapshot = work+ DispatchQueue.main.asyncAfter(deadline: .now() + debounce, execute: work)+}++func startStreaming() {+ emitSnapshot()++ // The observer token must stay retained or the observation ends immediately+ storeObservers.append(+ NotificationCenter.default.addObserver(+ forName: .EKEventStoreChanged,+ object: eventStore,+ queue: .main+ ) { _ in+ scheduleSnapshot()+ }+ )++ // Roll the 7-day window forward even without store changes+ let refreshTimer = DispatchSource.makeTimerSource(queue: .main)+ refreshTimer.schedule(+ deadline: .now() + REFRESH_INTERVAL_SECONDS,+ repeating: REFRESH_INTERVAL_SECONDS+ )+ refreshTimer.setEventHandler { emitSnapshot() }+ refreshTimer.resume()+ timers.append(refreshTimer)++ // "sync" on stdin forces an immediate snapshot; EOF means the parent died+ FileHandle.standardInput.readabilityHandler = { handle in+ let data = handle.availableData+ if data.isEmpty {+ DispatchQueue.main.async { exit(0) }+ return+ }+ guard let input = String(data: data, encoding: .utf8) else { return }+ if input.split(separator: "\n").contains(where: { $0.trimmingCharacters(in: .whitespaces) == "sync" }) {+ DispatchQueue.main.async { scheduleSnapshot(debounce: 0) }+ }+ }+}++// MARK: - Signal Handling++var signalSources: [DispatchSourceSignal] = []++func setupSignalHandlers() {+ for sig in [SIGTERM, SIGINT] {+ signal(sig, SIG_IGN)+ let source = DispatchSource.makeSignalSource(signal: sig, queue: .main)+ source.setEventHandler { exit(0) }+ source.resume()+ signalSources.append(source)+ }+}++// MARK: - Main++setupSignalHandlers()++let initialStatus = emitPermission()++switch initialStatus {+case "granted":+ startStreaming()+case "notDetermined" where requestAccess:+ let completion: (Bool, Error?) -> Void = { _, error in+ if let error {+ emitError("Calendar access request failed: \(error.localizedDescription)")+ }+ DispatchQueue.main.async {+ if emitPermission() == "granted" {+ startStreaming()+ } else {+ exit(0)+ }+ }+ }+ if #available(macOS 14.0, *) {+ eventStore.requestFullAccessToEvents(completion: completion)+ } else {+ eventStore.requestAccess(to: .event, completion: completion)+ }+default:+ // denied / restricted / notDetermined without --request: nothing to stream+ exit(0)+}++CFRunLoopRun()diff --git a/resources/macos-disclaim-exec.c b/resources/macos-disclaim-exec.cnew file mode 100644index 000000000..fab6632b5--- /dev/null+++ b/resources/macos-disclaim-exec.c@@ -0,0 +1,37 @@+/*+ * macos-disclaim-exec: exec a program as its own TCC "responsible process".+ *+ * A process spawned from a terminal-launched app inherits the terminal as its+ * responsible process, so macOS reads privacy usage strings (and attributes+ * permission prompts) from the terminal's Info.plist instead of the target+ * binary's. Disclaiming responsibility before exec makes the target process+ * responsible for itself, so its embedded __info_plist usage strings apply.+ *+ * Dev-only: used when spawning macos-calendar-listener from a non-packaged+ * app. Packaged builds are launched via LaunchServices and are already+ * self-responsible.+ *+ * Compile: cc -O2 macos-disclaim-exec.c -o macos-disclaim-exec+ */++#include <spawn.h>+#include <stdio.h>++extern char **environ;+extern int responsibility_spawnattrs_setdisclaim(posix_spawnattr_t *attrs, int disclaim);++int main(int argc, char *argv[]) {+ if (argc < 2) {+ fprintf(stderr, "usage: %s <program> [args...]\n", argv[0]);+ return 64;+ }+ posix_spawnattr_t attr;+ posix_spawnattr_init(&attr);+ /* SETEXEC replaces this process instead of forking, so the caller keeps the+ same pid, stdio pipes, and exit semantics as a direct spawn. */+ posix_spawnattr_setflags(&attr, POSIX_SPAWN_SETEXEC);+ responsibility_spawnattrs_setdisclaim(&attr, 1);+ int rc = posix_spawn(NULL, argv[1], NULL, &attr, &argv[1], environ);+ fprintf(stderr, "disclaim-exec: failed to exec %s: %d\n", argv[1], rc);+ return 127;+}diff --git a/scripts/build-globe-listener.js b/scripts/build-globe-listener.jsindex 98700bd5d..7abb6be87 100644--- a/scripts/build-globe-listener.js+++ b/scripts/build-globe-listener.js@@ -1,183 +1,9 @@#!/usr/bin/env node-const { spawnSync } = require("child_process");-const crypto = require("crypto");-const fs = require("fs");-const path = require("path");+const { buildMacosSwiftBinary } = require("./lib/build-macos-swift-binary");-const isMac = process.platform === "darwin";-if (!isMac) {- process.exit(0);-}--// Support cross-compilation via --arch flag or TARGET_ARCH env var-const archIndex = process.argv.indexOf("--arch");-const targetArch =- (archIndex !== -1 && process.argv[archIndex + 1]) || process.env.TARGET_ARCH || process.arch;--const ARCH_TO_TARGET = {- arm64: "arm64-apple-macosx11.0",- x64: "x86_64-apple-macosx10.15",-};-const swiftTarget = ARCH_TO_TARGET[targetArch];-if (!swiftTarget) {- console.error(`[globe-listener] Unsupported architecture: ${targetArch}`);- process.exit(1);-}--const projectRoot = path.resolve(__dirname, "..");-const swiftSource = path.join(projectRoot, "resources", "macos-globe-listener.swift");-const outputDir = path.join(projectRoot, "resources", "bin");-const outputBinary = path.join(outputDir, "macos-globe-listener");-const hashFile = path.join(outputDir, `.macos-globe-listener.${targetArch}.hash`);-const moduleCacheDir = path.join(outputDir, ".swift-module-cache");--// Mach-O CPU type constants for architecture verification-const ARCH_CPU_TYPE = {- arm64: 0x0100000c, // CPU_TYPE_ARM64- x64: 0x01000007, // CPU_TYPE_X86_64-};--function log(message) {- console.log(`[globe-listener] ${message}`);-}--function ensureDir(dirPath) {- if (!fs.existsSync(dirPath)) {- fs.mkdirSync(dirPath, { recursive: true });- }-}--function verifyBinaryArch(binaryPath, expectedArch) {- try {- const fd = fs.openSync(binaryPath, "r");- const header = Buffer.alloc(8);- fs.readSync(fd, header, 0, 8, 0);- fs.closeSync(fd);-- const magic = header.readUInt32LE(0);- if (magic !== 0xfeedfacf) {- // Not a 64-bit Mach-O- return false;- }- const cpuType = header.readInt32LE(4);- const expectedCpu = ARCH_CPU_TYPE[expectedArch];- return cpuType === expectedCpu;- } catch {- return false;- }-}--if (!fs.existsSync(swiftSource)) {- console.error(`[globe-listener] Swift source not found at ${swiftSource}`);- process.exit(1);-}--ensureDir(outputDir);-ensureDir(moduleCacheDir);--let needsBuild = true;-if (fs.existsSync(outputBinary)) {- // Verify existing binary matches the target architecture- if (!verifyBinaryArch(outputBinary, targetArch)) {- log(`Existing binary is wrong architecture (expected ${targetArch}), rebuild needed`);- needsBuild = true;- } else {- try {- const binaryStat = fs.statSync(outputBinary);- const sourceStat = fs.statSync(swiftSource);- if (binaryStat.mtimeMs >= sourceStat.mtimeMs) {- needsBuild = false;- }- } catch {- needsBuild = true;- }- }-}--// Secondary check: compare source hash-if (!needsBuild && fs.existsSync(outputBinary)) {- try {- const sourceContent = fs.readFileSync(swiftSource, "utf8");- const currentHash = crypto.createHash("sha256").update(sourceContent).digest("hex");-- if (fs.existsSync(hashFile)) {- const savedHash = fs.readFileSync(hashFile, "utf8").trim();- if (savedHash !== currentHash) {- log("Source hash changed, rebuild needed");- needsBuild = true;- }- } else {- // No hash file for this architecture — force rebuild to ensure correct arch- log(`No hash file for ${targetArch}, rebuild needed`);- needsBuild = true;- }- } catch (err) {- log(`Hash check failed: ${err.message}, forcing rebuild`);- needsBuild = true;- }-}--if (!needsBuild) {- process.exit(0);-}--function attemptCompile(command, args) {- log(`Compiling with ${[command, ...args].join(" ")}`);- return spawnSync(command, args, {- stdio: "inherit",- env: {- ...process.env,- SWIFT_MODULE_CACHE_PATH: moduleCacheDir,- },- });-}--const compileArgs = [- swiftSource,- "-O",- "-target",- swiftTarget,- "-module-cache-path",- moduleCacheDir,- "-o",- outputBinary,-];--let result = attemptCompile("xcrun", ["swiftc", ...compileArgs]);--if (result.status !== 0) {- result = attemptCompile("swiftc", compileArgs);-}--if (result.status !== 0) {- console.error("[globe-listener] Failed to compile macOS Globe listener binary.");- process.exit(result.status ?? 1);-}--try {- fs.chmodSync(outputBinary, 0o755);-} catch (error) {- console.warn(`[globe-listener] Unable to set executable permissions: ${error.message}`);-}--// Verify the compiled binary matches the target architecture-if (!verifyBinaryArch(outputBinary, targetArch)) {- console.error(- `[globe-listener] FATAL: Compiled binary architecture does not match target (${targetArch}). ` +- `This can happen when cross-compiling without setting TARGET_ARCH env var.`- );- process.exit(1);-}--// Save source hash after successful build-try {- const sourceContent = fs.readFileSync(swiftSource, "utf8");- const hash = crypto.createHash("sha256").update(sourceContent).digest("hex");- fs.writeFileSync(hashFile, hash);-} catch (err) {- // Non-critical, just log- log(`Warning: Could not save source hash: ${err.message}`);-}--log(`Successfully built macOS Globe listener binary (${targetArch}).`);+buildMacosSwiftBinary({+ label: "globe-listener",+ sourceName: "macos-globe-listener.swift",+ binaryName: "macos-globe-listener",+});diff --git a/scripts/build-macos-calendar-listener.js b/scripts/build-macos-calendar-listener.jsnew file mode 100644index 000000000..294bc1105--- /dev/null+++ b/scripts/build-macos-calendar-listener.js@@ -0,0 +1,55 @@+#!/usr/bin/env node++const { spawnSync } = require("child_process");+const fs = require("fs");+const path = require("path");+const { buildMacosSwiftBinary } = require("./lib/build-macos-swift-binary");++const projectRoot = path.resolve(__dirname, "..");++// Dev builds are launched from a terminal, so macOS attributes the helper's+// calendar permission request to the terminal app, which lacks calendar usage+// strings — the TCC prompt is silently aborted. The manager therefore spawns+// the helper through this shim in dev, disclaiming responsibility so the+// helper's embedded Info.plist usage strings apply. Packaged builds are+// self-responsible (usage strings via electron-builder's mac.extendInfo) and+// don't use the shim, so it is not in the electron-builder bin filter.+function buildDisclaimShim() {+ if (process.platform !== "darwin") return;++ const source = path.join(projectRoot, "resources", "macos-disclaim-exec.c");+ const output = path.join(projectRoot, "resources", "bin", "macos-disclaim-exec");+ try {+ if (fs.existsSync(output) && fs.statSync(output).mtimeMs >= fs.statSync(source).mtimeMs) {+ return;+ }+ } catch {+ // fall through to rebuild+ }++ fs.mkdirSync(path.dirname(output), { recursive: true });+ const result = spawnSync("cc", ["-O2", "-o", output, source], { stdio: "inherit" });+ if (result.status !== 0) {+ console.warn(+ "[calendar-listener] Warning: failed to compile macos-disclaim-exec; " ++ "calendar permission prompts will not work in dev."+ );+ return;+ }+ try {+ fs.chmodSync(output, 0o755);+ } catch (error) {+ console.warn(`[calendar-listener] Unable to set shim permissions: ${error.message}`);+ }+ console.log("[calendar-listener] Built macos-disclaim-exec.");+}++buildDisclaimShim();++buildMacosSwiftBinary({+ label: "calendar-listener",+ sourceName: "macos-calendar-listener.swift",+ binaryName: "macos-calendar-listener",+ frameworks: ["EventKit", "Foundation"],+ linkerInfoPlist: path.join(projectRoot, "resources", "macos-calendar-listener-Info.plist"),+});diff --git a/scripts/build-macos-mic-listener.js b/scripts/build-macos-mic-listener.jsindex 0571dd429..99a517381 100644--- a/scripts/build-macos-mic-listener.js+++ b/scripts/build-macos-mic-listener.js@@ -1,187 +1,10 @@#!/usr/bin/env node-const { spawnSync } = require("child_process");-const crypto = require("crypto");-const fs = require("fs");-const path = require("path");--const isMac = process.platform === "darwin";-if (!isMac) {- process.exit(0);-}--// Support cross-compilation via --arch flag or TARGET_ARCH env var-const archIndex = process.argv.indexOf("--arch");-const targetArch =- (archIndex !== -1 && process.argv[archIndex + 1]) || process.env.TARGET_ARCH || process.arch;--const ARCH_TO_TARGET = {- arm64: "arm64-apple-macosx11.0",- x64: "x86_64-apple-macosx10.15",-};-const swiftTarget = ARCH_TO_TARGET[targetArch];-if (!swiftTarget) {- console.error(`[mic-listener] Unsupported architecture: ${targetArch}`);- process.exit(1);-}--const projectRoot = path.resolve(__dirname, "..");-const swiftSource = path.join(projectRoot, "resources", "macos-mic-listener.swift");-const outputDir = path.join(projectRoot, "resources", "bin");-const outputBinary = path.join(outputDir, "macos-mic-listener");-const hashFile = path.join(outputDir, `.macos-mic-listener.${targetArch}.hash`);-const moduleCacheDir = path.join(outputDir, ".swift-module-cache");--// Mach-O CPU type constants for architecture verification-const ARCH_CPU_TYPE = {- arm64: 0x0100000c, // CPU_TYPE_ARM64- x64: 0x01000007, // CPU_TYPE_X86_64-};--function log(message) {- console.log(`[mic-listener] ${message}`);-}--function ensureDir(dirPath) {- if (!fs.existsSync(dirPath)) {- fs.mkdirSync(dirPath, { recursive: true });- }-}--function verifyBinaryArch(binaryPath, expectedArch) {- try {- const fd = fs.openSync(binaryPath, "r");- const header = Buffer.alloc(8);- fs.readSync(fd, header, 0, 8, 0);- fs.closeSync(fd);-- const magic = header.readUInt32LE(0);- if (magic !== 0xfeedfacf) {- // Not a 64-bit Mach-O- return false;- }- const cpuType = header.readInt32LE(4);- const expectedCpu = ARCH_CPU_TYPE[expectedArch];- return cpuType === expectedCpu;- } catch {- return false;- }-}--if (!fs.existsSync(swiftSource)) {- console.error(`[mic-listener] Swift source not found at ${swiftSource}`);- process.exit(1);-}--ensureDir(outputDir);-ensureDir(moduleCacheDir);--let needsBuild = true;-if (fs.existsSync(outputBinary)) {- // Verify existing binary matches the target architecture- if (!verifyBinaryArch(outputBinary, targetArch)) {- log(`Existing binary is wrong architecture (expected ${targetArch}), rebuild needed`);- needsBuild = true;- } else {- try {- const binaryStat = fs.statSync(outputBinary);- const sourceStat = fs.statSync(swiftSource);- if (binaryStat.mtimeMs >= sourceStat.mtimeMs) {- needsBuild = false;- }- } catch {- needsBuild = true;- }- }-}--// Secondary check: compare source hash-if (!needsBuild && fs.existsSync(outputBinary)) {- try {- const sourceContent = fs.readFileSync(swiftSource, "utf8");- const currentHash = crypto.createHash("sha256").update(sourceContent).digest("hex");-- if (fs.existsSync(hashFile)) {- const savedHash = fs.readFileSync(hashFile, "utf8").trim();- if (savedHash !== currentHash) {- log("Source hash changed, rebuild needed");- needsBuild = true;- }- } else {- // No hash file for this architecture — force rebuild to ensure correct arch- log(`No hash file for ${targetArch}, rebuild needed`);- needsBuild = true;- }- } catch (err) {- log(`Hash check failed: ${err.message}, forcing rebuild`);- needsBuild = true;- }-}--if (!needsBuild) {- process.exit(0);-}--function attemptCompile(command, args) {- log(`Compiling with ${[command, ...args].join(" ")}`);- return spawnSync(command, args, {- stdio: "inherit",- env: {- ...process.env,- SWIFT_MODULE_CACHE_PATH: moduleCacheDir,- },- });-}--const compileArgs = [- swiftSource,- "-O",- "-target",- swiftTarget,- "-module-cache-path",- moduleCacheDir,- "-o",- outputBinary,- "-framework",- "CoreAudio",- "-framework",- "Foundation",-];--let result = attemptCompile("xcrun", ["swiftc", ...compileArgs]);--if (result.status !== 0) {- result = attemptCompile("swiftc", compileArgs);-}--if (result.status !== 0) {- console.error("[mic-listener] Failed to compile macOS mic listener binary.");- process.exit(result.status ?? 1);-}--try {- fs.chmodSync(outputBinary, 0o755);-} catch (error) {- console.warn(`[mic-listener] Unable to set executable permissions: ${error.message}`);-}--// Verify the compiled binary matches the target architecture-if (!verifyBinaryArch(outputBinary, targetArch)) {- console.error(- `[mic-listener] FATAL: Compiled binary architecture does not match target (${targetArch}). ` +- `This can happen when cross-compiling without setting TARGET_ARCH env var.`- );- process.exit(1);-}--// Save source hash after successful build-try {- const sourceContent = fs.readFileSync(swiftSource, "utf8");- const hash = crypto.createHash("sha256").update(sourceContent).digest("hex");- fs.writeFileSync(hashFile, hash);-} catch (err) {- // Non-critical, just log- log(`Warning: Could not save source hash: ${err.message}`);-}--log(`Successfully built macOS mic listener binary (${targetArch}).`);+const { buildMacosSwiftBinary } = require("./lib/build-macos-swift-binary");++buildMacosSwiftBinary({+ label: "mic-listener",+ sourceName: "macos-mic-listener.swift",+ binaryName: "macos-mic-listener",+ frameworks: ["CoreAudio", "Foundation"],+});diff --git a/scripts/build-macos-text-monitor.js b/scripts/build-macos-text-monitor.jsindex 9b60a9f9e..a6e7589ee 100644--- a/scripts/build-macos-text-monitor.js+++ b/scripts/build-macos-text-monitor.js@@ -1,183 +1,9 @@#!/usr/bin/env node-const { spawnSync } = require("child_process");-const crypto = require("crypto");-const fs = require("fs");-const path = require("path");+const { buildMacosSwiftBinary } = require("./lib/build-macos-swift-binary");-const isMac = process.platform === "darwin";-if (!isMac) {- process.exit(0);-}--// Support cross-compilation via --arch flag or TARGET_ARCH env var-const archIndex = process.argv.indexOf("--arch");-const targetArch =- (archIndex !== -1 && process.argv[archIndex + 1]) || process.env.TARGET_ARCH || process.arch;--const ARCH_TO_TARGET = {- arm64: "arm64-apple-macosx11.0",- x64: "x86_64-apple-macosx10.15",-};-const swiftTarget = ARCH_TO_TARGET[targetArch];-if (!swiftTarget) {- console.error(`[text-monitor] Unsupported architecture: ${targetArch}`);- process.exit(1);-}--const projectRoot = path.resolve(__dirname, "..");-const swiftSource = path.join(projectRoot, "resources", "macos-text-monitor.swift");-const outputDir = path.join(projectRoot, "resources", "bin");-const outputBinary = path.join(outputDir, "macos-text-monitor");-const hashFile = path.join(outputDir, `.macos-text-monitor.${targetArch}.hash`);-const moduleCacheDir = path.join(outputDir, ".swift-module-cache");--// Mach-O CPU type constants for architecture verification-const ARCH_CPU_TYPE = {- arm64: 0x0100000c, // CPU_TYPE_ARM64- x64: 0x01000007, // CPU_TYPE_X86_64-};--function log(message) {- console.log(`[text-monitor] ${message}`);-}--function ensureDir(dirPath) {- if (!fs.existsSync(dirPath)) {- fs.mkdirSync(dirPath, { recursive: true });- }-}--function verifyBinaryArch(binaryPath, expectedArch) {- try {- const fd = fs.openSync(binaryPath, "r");- const header = Buffer.alloc(8);- fs.readSync(fd, header, 0, 8, 0);- fs.closeSync(fd);-- const magic = header.readUInt32LE(0);- if (magic !== 0xfeedfacf) {- // Not a 64-bit Mach-O- return false;- }- const cpuType = header.readInt32LE(4);- const expectedCpu = ARCH_CPU_TYPE[expectedArch];- return cpuType === expectedCpu;- } catch {- return false;- }-}--if (!fs.existsSync(swiftSource)) {- console.error(`[text-monitor] Swift source not found at ${swiftSource}`);- process.exit(1);-}--ensureDir(outputDir);-ensureDir(moduleCacheDir);--let needsBuild = true;-if (fs.existsSync(outputBinary)) {- // Verify existing binary matches the target architecture- if (!verifyBinaryArch(outputBinary, targetArch)) {- log(`Existing binary is wrong architecture (expected ${targetArch}), rebuild needed`);- needsBuild = true;- } else {- try {- const binaryStat = fs.statSync(outputBinary);- const sourceStat = fs.statSync(swiftSource);- if (binaryStat.mtimeMs >= sourceStat.mtimeMs) {- needsBuild = false;- }- } catch {- needsBuild = true;- }- }-}--// Secondary check: compare source hash-if (!needsBuild && fs.existsSync(outputBinary)) {- try {- const sourceContent = fs.readFileSync(swiftSource, "utf8");- const currentHash = crypto.createHash("sha256").update(sourceContent).digest("hex");-- if (fs.existsSync(hashFile)) {- const savedHash = fs.readFileSync(hashFile, "utf8").trim();- if (savedHash !== currentHash) {- log("Source hash changed, rebuild needed");- needsBuild = true;- }- } else {- // No hash file for this architecture — force rebuild to ensure correct arch- log(`No hash file for ${targetArch}, rebuild needed`);- needsBuild = true;- }- } catch (err) {- log(`Hash check failed: ${err.message}, forcing rebuild`);- needsBuild = true;- }-}--if (!needsBuild) {- process.exit(0);-}--function attemptCompile(command, args) {- log(`Compiling with ${[command, ...args].join(" ")}`);- return spawnSync(command, args, {- stdio: "inherit",- env: {- ...process.env,- SWIFT_MODULE_CACHE_PATH: moduleCacheDir,- },- });-}--const compileArgs = [- swiftSource,- "-O",- "-target",- swiftTarget,- "-module-cache-path",- moduleCacheDir,- "-o",- outputBinary,-];--let result = attemptCompile("xcrun", ["swiftc", ...compileArgs]);--if (result.status !== 0) {- result = attemptCompile("swiftc", compileArgs);-}--if (result.status !== 0) {- console.error("[text-monitor] Failed to compile macOS text monitor binary.");- process.exit(result.status ?? 1);-}--try {- fs.chmodSync(outputBinary, 0o755);-} catch (error) {- console.warn(`[text-monitor] Unable to set executable permissions: ${error.message}`);-}--// Verify the compiled binary matches the target architecture-if (!verifyBinaryArch(outputBinary, targetArch)) {- console.error(- `[text-monitor] FATAL: Compiled binary architecture does not match target (${targetArch}). ` +- `This can happen when cross-compiling without setting TARGET_ARCH env var.`- );- process.exit(1);-}--// Save source hash after successful build-try {- const sourceContent = fs.readFileSync(swiftSource, "utf8");- const hash = crypto.createHash("sha256").update(sourceContent).digest("hex");- fs.writeFileSync(hashFile, hash);-} catch (err) {- // Non-critical, just log- log(`Warning: Could not save source hash: ${err.message}`);-}--log(`Successfully built macOS text monitor binary (${targetArch}).`);+buildMacosSwiftBinary({+ label: "text-monitor",+ sourceName: "macos-text-monitor.swift",+ binaryName: "macos-text-monitor",+});diff --git a/scripts/lib/build-macos-swift-binary.js b/scripts/lib/build-macos-swift-binary.jsnew file mode 100644index 000000000..701c87a25--- /dev/null+++ b/scripts/lib/build-macos-swift-binary.js@@ -0,0 +1,201 @@+const { spawnSync } = require("child_process");+const crypto = require("crypto");+const fs = require("fs");+const path = require("path");++const ARCH_TO_TARGET = {+ arm64: "arm64-apple-macosx11.0",+ x64: "x86_64-apple-macosx10.15",+};++// Mach-O CPU type constants for architecture verification+const ARCH_CPU_TYPE = {+ arm64: 0x0100000c, // CPU_TYPE_ARM64+ x64: 0x01000007, // CPU_TYPE_X86_64+};++function ensureDir(dirPath) {+ if (!fs.existsSync(dirPath)) {+ fs.mkdirSync(dirPath, { recursive: true });+ }+}++function verifyBinaryArch(binaryPath, expectedArch) {+ try {+ const fd = fs.openSync(binaryPath, "r");+ const header = Buffer.alloc(8);+ fs.readSync(fd, header, 0, 8, 0);+ fs.closeSync(fd);++ const magic = header.readUInt32LE(0);+ if (magic !== 0xfeedfacf) {+ // Not a 64-bit Mach-O+ return false;+ }+ const cpuType = header.readInt32LE(4);+ const expectedCpu = ARCH_CPU_TYPE[expectedArch];+ return cpuType === expectedCpu;+ } catch {+ return false;+ }+}++// Shared build flow for the macOS Swift helper binaries (mic listener, globe+// listener, text monitor, calendar listener). Compiles resources/<sourceName>+// to resources/bin/<binaryName> for the target arch, skipping the build when+// the binary is up to date (mtime + source hash + arch check). Exits the+// process on failure, matching the original standalone scripts.+// linkerInfoPlist embeds the given plist as a __TEXT,__info_plist section so+// unbundled binaries can carry a bundle id and privacy usage strings.+function buildMacosSwiftBinary({ label, sourceName, binaryName, frameworks = [], linkerInfoPlist }) {+ if (process.platform !== "darwin") {+ process.exit(0);+ }++ // Support cross-compilation via --arch flag or TARGET_ARCH env var+ const archIndex = process.argv.indexOf("--arch");+ const targetArch =+ (archIndex !== -1 && process.argv[archIndex + 1]) || process.env.TARGET_ARCH || process.arch;++ const swiftTarget = ARCH_TO_TARGET[targetArch];+ if (!swiftTarget) {+ console.error(`[${label}] Unsupported architecture: ${targetArch}`);+ process.exit(1);+ }++ const projectRoot = path.resolve(__dirname, "..", "..");+ const swiftSource = path.join(projectRoot, "resources", sourceName);+ const outputDir = path.join(projectRoot, "resources", "bin");+ const outputBinary = path.join(outputDir, binaryName);+ const hashFile = path.join(outputDir, `.${binaryName}.${targetArch}.hash`);+ const moduleCacheDir = path.join(outputDir, ".swift-module-cache");++ function log(message) {+ console.log(`[${label}] ${message}`);+ }++ if (!fs.existsSync(swiftSource)) {+ console.error(`[${label}] Swift source not found at ${swiftSource}`);+ process.exit(1);+ }++ ensureDir(outputDir);+ ensureDir(moduleCacheDir);++ let needsBuild = true;+ if (fs.existsSync(outputBinary)) {+ // Verify existing binary matches the target architecture+ if (!verifyBinaryArch(outputBinary, targetArch)) {+ log(`Existing binary is wrong architecture (expected ${targetArch}), rebuild needed`);+ needsBuild = true;+ } else {+ try {+ const binaryStat = fs.statSync(outputBinary);+ const sourceStat = fs.statSync(swiftSource);+ if (binaryStat.mtimeMs >= sourceStat.mtimeMs) {+ needsBuild = false;+ }+ } catch {+ needsBuild = true;+ }+ }+ }++ // Hash the Swift source plus any embedded plist, so edits to either rebuild+ function computeSourceHash() {+ let content = fs.readFileSync(swiftSource, "utf8");+ if (linkerInfoPlist) content += fs.readFileSync(linkerInfoPlist, "utf8");+ return crypto.createHash("sha256").update(content).digest("hex");+ }++ // Secondary check: compare source hash+ if (!needsBuild && fs.existsSync(outputBinary)) {+ try {+ const currentHash = computeSourceHash();++ if (fs.existsSync(hashFile)) {+ const savedHash = fs.readFileSync(hashFile, "utf8").trim();+ if (savedHash !== currentHash) {+ log("Source hash changed, rebuild needed");+ needsBuild = true;+ }+ } else {+ // No hash file for this architecture — force rebuild to ensure correct arch+ log(`No hash file for ${targetArch}, rebuild needed`);+ needsBuild = true;+ }+ } catch (err) {+ log(`Hash check failed: ${err.message}, forcing rebuild`);+ needsBuild = true;+ }+ }++ if (!needsBuild) {+ process.exit(0);+ }++ function attemptCompile(command, args) {+ log(`Compiling with ${[command, ...args].join(" ")}`);+ return spawnSync(command, args, {+ stdio: "inherit",+ env: {+ ...process.env,+ SWIFT_MODULE_CACHE_PATH: moduleCacheDir,+ },+ });+ }++ const infoPlistArgs = linkerInfoPlist+ ? ["-Xlinker", "-sectcreate", "-Xlinker", "__TEXT", "-Xlinker", "__info_plist", "-Xlinker", linkerInfoPlist]+ : [];+ const compileArgs = [+ swiftSource,+ "-O",+ "-target",+ swiftTarget,+ "-module-cache-path",+ moduleCacheDir,+ "-o",+ outputBinary,+ ...infoPlistArgs,+ ...frameworks.flatMap((framework) => ["-framework", framework]),+ ];++ let result = attemptCompile("xcrun", ["swiftc", ...compileArgs]);++ if (result.status !== 0) {+ result = attemptCompile("swiftc", compileArgs);+ }++ if (result.status !== 0) {+ console.error(`[${label}] Failed to compile ${binaryName} binary.`);+ process.exit(result.status ?? 1);+ }++ try {+ fs.chmodSync(outputBinary, 0o755);+ } catch (error) {+ console.warn(`[${label}] Unable to set executable permissions: ${error.message}`);+ }++ // Verify the compiled binary matches the target architecture+ if (!verifyBinaryArch(outputBinary, targetArch)) {+ console.error(+ `[${label}] FATAL: Compiled binary architecture does not match target (${targetArch}). ` ++ `This can happen when cross-compiling without setting TARGET_ARCH env var.`+ );+ process.exit(1);+ }++ // Save source hash after successful build+ try {+ fs.writeFileSync(hashFile, computeSourceHash());+ } catch (err) {+ // Non-critical, just log+ log(`Warning: Could not save source hash: ${err.message}`);+ }++ log(`Successfully built ${binaryName} (${targetArch}).`);+}++module.exports = { buildMacosSwiftBinary };diff --git a/src/assets/icons/apple-calendar.svg b/src/assets/icons/apple-calendar.svgnew file mode 100644index 000000000..e45db8e60--- /dev/null+++ b/src/assets/icons/apple-calendar.svg@@ -0,0 +1,12 @@+<?xml version="1.0" encoding="utf-8"?>+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 200 200">+ <defs>+ <clipPath id="tile">+ <rect x="14" y="14" width="172" height="172" rx="38"/>+ </clipPath>+ </defs>+ <rect x="14" y="14" width="172" height="172" rx="38" fill="#FFFFFF" stroke="#E5E5EA" stroke-width="4"/>+ <rect x="14" y="14" width="172" height="54" clip-path="url(#tile)" fill="#FF3B30"/>+ <text x="100" y="53" text-anchor="middle" font-family="-apple-system, 'Helvetica Neue', Arial, sans-serif" font-size="28" font-weight="600" letter-spacing="3" fill="#FFFFFF">TUE</text>+ <text x="100" y="156" text-anchor="middle" font-family="-apple-system, 'Helvetica Neue', Arial, sans-serif" font-size="92" font-weight="300" fill="#1C1C1E">17</text>+</svg>diff --git a/src/components/IntegrationsView.tsx b/src/components/IntegrationsView.tsxindex 6170bd7e1..f64d12899 100644--- a/src/components/IntegrationsView.tsx+++ b/src/components/IntegrationsView.tsx@@ -1,11 +1,12 @@import { useState, useEffect, useCallback } from "react";import { useTranslation } from "react-i18next";-import { Code2, Info, Loader2, Mail, Plus, Unlink } from "lucide-react";+import { CalendarDays, Code2, Info, Loader2, Mail, Plus, Unlink } from "lucide-react";import { Button } from "./ui/button";import { Badge } from "./ui/badge";import { SettingsPanel, SettingsPanelRow, SettingsRow } from "./ui/SettingsSection";import { Toggle } from "./ui/toggle";import {+ AlertDialog,ConfirmDialog,Dialog,DialogContent,@@ -20,6 +21,7 @@ import ApiKeysSection from "./ApiKeysSection";import CliIntegrationCard from "./CliIntegrationCard";import McpIntegrationCard from "./McpIntegrationCard";import googleCalendarIcon from "../assets/icons/google-calendar.svg";+import appleCalendarIcon from "../assets/icons/apple-calendar.svg";const API_DOCS_URL = "https://docs.openwhispr.com/api/overview";@@ -38,16 +40,28 @@ function SectionLabel({ children }: { children: React.ReactNode }) {export default function IntegrationsView({ isPaid, onUpgrade }: IntegrationsViewProps) {const { t } = useTranslation();- const { gcalAccounts, setGcalAccounts, gcalPrimaryOnly, setGcalPrimaryOnly } = useSettingsStore();+ const {+ gcalAccounts,+ setGcalAccounts,+ gcalPrimaryOnly,+ setGcalPrimaryOnly,+ appleCalendarConnected,+ setAppleCalendarConnected,+ } = useSettingsStore();const [isConnecting, setIsConnecting] = useState(false);const [disconnectingEmail, setDisconnectingEmail] = useState<string | null>(null);const [confirmDisconnectEmail, setConfirmDisconnectEmail] = useState<string | null>(null);const [showPermissionDialog, setShowPermissionDialog] = useState(false);+ const [isAppleConnecting, setIsAppleConnecting] = useState(false);+ const [appleSourceNames, setAppleSourceNames] = useState<string[]>([]);+ const [confirmAppleDisconnect, setConfirmAppleDisconnect] = useState(false);+ const [appleConnectError, setAppleConnectError] = useState<"denied" | "failed" | null>(null);const [apiKeysDialogOpen, setApiKeysDialogOpen] = useState(false);const systemAudio = useSystemAudioPermission();const { request: requestSystemAudioAccess } = systemAudio;const hasAccounts = gcalAccounts.length > 0;const needsSystemAudioGrant = !systemAudio.granted && canManageSystemAudioInApp(systemAudio);+ const isMac = window.electronAPI?.getPlatform?.() === "darwin";const startOAuth = useCallback(async () => {setIsConnecting(true);@@ -65,16 +79,51 @@ export default function IntegrationsView({ isPaid, onUpgrade }: IntegrationsView}}, [setGcalAccounts]);- const handleConnect = useCallback(async () => {- if (needsSystemAudioGrant) {- const granted = await requestSystemAudioAccess();- if (!granted) {- setShowPermissionDialog(true);- return;+ const connectAppleCalendar = useCallback(async () => {+ setIsAppleConnecting(true);+ try {+ const result = await window.electronAPI?.acalConnect?.();+ if (result?.success) {+ setAppleCalendarConnected(true);+ } else {+ // Only send the user to Privacy settings when access was actually+ // denied; helper-missing/snapshot-failed are not permission problems.+ setAppleConnectError(result?.reason === "denied" ? "denied" : "failed");}+ } finally {+ setIsAppleConnecting(false);}- await startOAuth();- }, [needsSystemAudioGrant, requestSystemAudioAccess, startOAuth]);+ }, [setAppleCalendarConnected]);++ const withSystemAudioGate = useCallback(+ async (connect: () => Promise<void>) => {+ if (needsSystemAudioGrant) {+ const granted = await requestSystemAudioAccess();+ if (!granted) {+ setShowPermissionDialog(true);+ return;+ }+ }+ await connect();+ },+ [needsSystemAudioGrant, requestSystemAudioAccess]+ );++ const handleConnect = useCallback(+ () => withSystemAudioGate(startOAuth),+ [withSystemAudioGate, startOAuth]+ );++ const handleAppleConnect = useCallback(+ () => withSystemAudioGate(connectAppleCalendar),+ [withSystemAudioGate, connectAppleCalendar]+ );++ const handleAppleDisconnect = useCallback(async () => {+ await window.electronAPI?.acalDisconnect?.();+ setAppleCalendarConnected(false);+ setAppleSourceNames([]);+ }, [setAppleCalendarConnected]);const handleDisconnect = useCallback(async (email: string) => {@@ -111,6 +160,21 @@ export default function IntegrationsView({ isPaid, onUpgrade }: IntegrationsViewreturn () => unsub?.();}, [setGcalAccounts]);+ useEffect(() => {+ if (!isMac) return;+ window.electronAPI?.acalGetConnectionStatus?.().then((status) => {+ if (status) {+ setAppleCalendarConnected(status.connected);+ setAppleSourceNames(status.sourceNames);+ }+ });+ const unsub = window.electronAPI?.onAcalConnectionChanged?.((data) => {+ setAppleCalendarConnected(data.connected);+ setAppleSourceNames(data.sourceNames ?? []);+ });+ return () => unsub?.();+ }, [isMac, setAppleCalendarConnected]);+return (<div className="max-w-lg mx-auto w-full px-6 py-6 space-y-5"><div>@@ -212,6 +276,65 @@ export default function IntegrationsView({ isPaid, onUpgrade }: IntegrationsView</button></SettingsPanelRow>)}++ {isMac && (+ <SettingsPanelRow>+ <div className="flex items-center gap-3">+ <div className="w-9 h-9 rounded-lg bg-white dark:bg-surface-raised shadow-[0_0_0_1px_rgba(0,0,0,0.04)] dark:shadow-none dark:border dark:border-white/5 flex items-center justify-center shrink-0">+ <img src={appleCalendarIcon} alt="" className="w-5 h-5" />+ </div>+ <div className="flex-1 min-w-0">+ <div className="flex items-center gap-1.5">+ <p className="text-xs font-semibold text-foreground">+ {t("integrations.appleCalendar.title")}+ </p>+ <Badge variant="outline" className="text-[10px] px-1.5 py-0 font-normal">+ {t("integrations.appleCalendar.optional")}+ </Badge>+ </div>+ <p className="text-xs text-muted-foreground/70 mt-0.5 leading-relaxed">+ {t("integrations.appleCalendar.description")}+ </p>+ </div>+ {appleCalendarConnected ? (+ <Badge variant="success" className="shrink-0">+ {t("integrations.appleCalendar.connected")}+ </Badge>+ ) : (+ <Button+ size="sm"+ onClick={handleAppleConnect}+ disabled={isAppleConnecting}+ className="shrink-0"+ >+ {isAppleConnecting ? (+ <Loader2 className="h-3.5 w-3.5 animate-spin" />+ ) : (+ t("integrations.appleCalendar.connect")+ )}+ </Button>+ )}+ </div>+ </SettingsPanelRow>+ )}++ {isMac && appleCalendarConnected && (+ <SettingsPanelRow>+ <div className="group flex items-center gap-3 pl-12">+ <CalendarDays className="h-3.5 w-3.5 text-muted-foreground/50 shrink-0" />+ <span className="text-xs text-muted-foreground truncate flex-1">+ {appleSourceNames.join(" · ")}+ </span>+ <button+ onClick={() => setConfirmAppleDisconnect(true)}+ className="opacity-0 group-hover:opacity-100 p-1 rounded-md text-muted-foreground hover:text-destructive hover:bg-destructive/10 transition-all"+ aria-label={t("integrations.appleCalendar.disconnect")}+ >+ <Unlink className="h-3.5 w-3.5" />+ </button>+ </div>+ </SettingsPanelRow>+ )}</SettingsPanel></div>@@ -324,6 +447,33 @@ export default function IntegrationsView({ isPaid, onUpgrade }: IntegrationsView}onConfirm={systemAudio.mode === "native" ? systemAudio.openSettings : systemAudio.request}/>++ <ConfirmDialog+ open={confirmAppleDisconnect}+ onOpenChange={setConfirmAppleDisconnect}+ title={t("integrations.appleCalendar.disconnectConfirm")}+ description={t("integrations.appleCalendar.disconnectDescription")}+ confirmText={t("integrations.appleCalendar.disconnect")}+ variant="destructive"+ onConfirm={handleAppleDisconnect}+ />++ <ConfirmDialog+ open={appleConnectError === "denied"}+ onOpenChange={(open) => !open && setAppleConnectError(null)}+ title={t("integrations.appleCalendar.permissionDenied")}+ description={t("integrations.appleCalendar.permissionDeniedDescription")}+ confirmText={t("integrations.appleCalendar.openSettings")}+ onConfirm={() => window.electronAPI?.openCalendarPrivacySettings?.()}+ />++ <AlertDialog+ open={appleConnectError === "failed"}+ onOpenChange={(open) => !open && setAppleConnectError(null)}+ title={t("integrations.appleCalendar.connectFailed")}+ description={t("integrations.appleCalendar.connectFailedDescription")}+ onOk={() => {}}+ /></div>);}diff --git a/src/components/UpcomingMeetings.tsx b/src/components/UpcomingMeetings.tsxindex 17f17a409..7a803b9c0 100644--- a/src/components/UpcomingMeetings.tsx+++ b/src/components/UpcomingMeetings.tsx@@ -28,6 +28,7 @@ export default function UpcomingMeetings({ events, isLoading }: UpcomingMeetingsconst [hoveredEventId, setHoveredEventId] = useState<string | null>(null);const systemAudio = useSystemAudioPermission();const isSignedIn = useSettingsStore((s) => s.isSignedIn);+ const appleCalendarConnected = useSettingsStore((s) => s.appleCalendarConnected);const needsSystemAudioGrant = !systemAudio.granted && canManageSystemAudioInApp(systemAudio);const now = useMemo(() => new Date(), []);@@ -109,7 +110,7 @@ export default function UpcomingMeetings({ events, isLoading }: UpcomingMeetings: t("onboarding.permissions.grantAccess")}</Button></>- ) : !isSignedIn ? (+ ) : !isSignedIn && !appleCalendarConnected ? (<><LogIn size={24} className="text-muted-foreground/30 mb-2.5" /><p className="text-xs font-medium text-muted-foreground/70 text-center mb-1">diff --git a/src/helpers/appleCalendarManager.js b/src/helpers/appleCalendarManager.jsnew file mode 100644index 000000000..93a804b65--- /dev/null+++ b/src/helpers/appleCalendarManager.js@@ -0,0 +1,346 @@+const { spawn } = require("child_process");+const { app } = require("electron");+const debugLogger = require("./debugLogger");+const { resolveBundledBinary } = require("./binaryResolver");+const { extractMeetingUrl } = require("./meetingJoinUrl");+const { broadcastToWindows } = require("./windowBroadcast");++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;++// Reads the local EventKit store (all accounts Calendar.app aggregates) via a+// bundled Swift helper that pushes calendars+events snapshots as line-delimited+// JSON. "Connected" means apple_calendars has rows — no tokens or settings.+class AppleCalendarManager {+ constructor(databaseManager, reminderScheduler) {+ this.databaseManager = databaseManager;+ this.reminderScheduler = reminderScheduler;+ this._helperProcess = null;+ this._pendingConnect = null;+ this._lastFocusSync = 0;+ this._restartTimer = null;+ this._restartAttempts = 0;+ }++ isConnected() {+ return this.databaseManager.getAppleCalendars().length > 0;+ }++ getConnectionStatus() {+ const calendars = this.databaseManager.getAppleCalendars();+ return {+ connected: calendars.length > 0,+ sourceNames: [...new Set(calendars.map((cal) => cal.source_name).filter(Boolean))],+ };+ }++ start() {+ if (process.platform !== "darwin" || !this.isConnected()) return;+ this._spawnHelper(false);+ }++ // User-initiated: spawns the helper with --request so the TCC prompt shows.+ // Resolves after the first snapshot lands (success) or access is denied.+ connect() {+ if (process.platform !== "darwin") {+ return Promise.resolve({ success: false, reason: "unsupported" });+ }+ this._restartAttempts = 0;+ return new Promise((resolve) => {+ this._pendingConnect = { resolve, awaitingSnapshot: false };+ if (!this._spawnHelper(true)) {+ this._pendingConnect = null;+ resolve({ success: false, reason: "helper-missing" });+ }+ });+ }++ disconnect() {+ this.stop();+ this._clearStoredCalendarData();+ return { success: true };+ }++ stop() {+ if (this._restartTimer) {+ clearTimeout(this._restartTimer);+ this._restartTimer = null;+ }+ this._restartAttempts = 0;+ this._stopHelperProcess();+ }++ _stopHelperProcess() {+ if (this._helperProcess) {+ const child = this._helperProcess;+ this._helperProcess = null;+ try {+ child.kill();+ } catch {+ // already exited+ }+ }+ }++ syncOnFocus() {+ if (!this._helperProcess) return;+ const now = Date.now();+ if (now - this._lastFocusSync < FOCUS_SYNC_THROTTLE_MS) return;+ this._lastFocusSync = now;+ this._requestSync();+ }++ onWakeFromSleep() {+ this._requestSync();+ }++ _requestSync() {+ try {+ this._helperProcess?.stdin.write("sync\n");+ } catch (err) {+ debugLogger.debug("Calendar listener sync request failed", { error: err.message }, "acal");+ }+ }++ _spawnHelper(requestAccess) {+ if (this._restartTimer) {+ clearTimeout(this._restartTimer);+ this._restartTimer = null;+ }+ this._stopHelperProcess();++ const binaryPath = resolveBundledBinary(BINARY_NAME, "acal");+ if (!binaryPath) {+ debugLogger.warn("macos-calendar-listener binary not found", {}, "acal");+ return false;+ }++ let command = binaryPath;+ let args = requestAccess ? ["--request"] : [];+ if (!app.isPackaged) {+ // A terminal-launched dev app makes the terminal the helper's TCC+ // "responsible process", and its missing calendar usage strings abort+ // the permission prompt. The disclaim shim makes the helper responsible+ // for itself so its embedded Info.plist usage strings apply. Packaged+ // builds are self-responsible and keep OpenWhispr as the prompt source.+ const shimPath = resolveBundledBinary("macos-disclaim-exec", "acal");+ if (shimPath) {+ args = [binaryPath, ...args];+ command = shimPath;+ } else {+ debugLogger.warn(+ "macos-disclaim-exec not found; calendar permission prompt may not appear in dev",+ {},+ "acal"+ );+ }+ }++ try {+ // stdin stays open for "sync" requests; its EOF also ends the helper+ const child = spawn(command, args, {+ stdio: ["pipe", "pipe", "pipe"],+ });+ this._helperProcess = child;++ let buffer = "";+ child.stdout.on("data", (data) => {+ buffer += data.toString();+ let newlineIdx;+ while ((newlineIdx = buffer.indexOf("\n")) !== -1) {+ const line = buffer.slice(0, newlineIdx).trim();+ buffer = buffer.slice(newlineIdx + 1);+ if (!line) continue;+ try {+ this._handleMessage(JSON.parse(line));+ } catch (err) {+ debugLogger.warn(+ "Unparseable calendar listener output",+ { line, error: err.message },+ "acal"+ );+ }+ }+ });++ child.stderr.on("data", (data) => {+ debugLogger.debug(+ "macos-calendar-listener stderr",+ { output: data.toString().trim() },+ "acal"+ );+ });++ child.on("error", (err) => {+ debugLogger.warn("macos-calendar-listener error", { error: err.message }, "acal");+ this._onHelperGone(child);+ });++ child.on("exit", (code) => {+ debugLogger.info("macos-calendar-listener exited", { code }, "acal");+ this._onHelperGone(child);+ });++ return true;+ } catch (err) {+ debugLogger.warn("Failed to spawn macos-calendar-listener", { error: err.message }, "acal");+ return false;+ }+ }++ _onHelperGone(child) {+ if (this._helperProcess !== child) return;+ this._helperProcess = null;++ if (this._pendingConnect) {+ const pending = this._pendingConnect;+ this._pendingConnect = null;+ pending.resolve({ success: false, reason: "denied" });+ }++ this._scheduleHelperRestart();+ }++ _scheduleHelperRestart() {+ if (process.platform !== "darwin" || this._restartTimer || this._helperProcess) return;++ try {+ if (!this.isConnected()) return;+ } catch (err) {+ debugLogger.warn(+ "Could not determine whether calendar listener should restart",+ { error: err.message },+ "acal"+ );+ return;+ }++ const delay = Math.min(+ HELPER_RESTART_BASE_MS * Math.pow(2, this._restartAttempts),+ HELPER_RESTART_MAX_MS+ );+ this._restartAttempts += 1;+ debugLogger.info(+ "Scheduling calendar listener restart",+ { delayMs: delay, attempt: this._restartAttempts },+ "acal"+ );++ this._restartTimer = setTimeout(() => {+ this._restartTimer = null;+ if (!this._spawnHelper(false)) this._scheduleHelperRestart();+ }, delay);+ }++ _handleMessage(message) {+ if (message.type === "permission") {+ this._handlePermission(message.status);+ } else if (message.type === "snapshot") {+ this._applySnapshot(message);+ }+ }++ _handlePermission(status) {+ debugLogger.info("Calendar permission status", { status }, "acal");+ const pending = this._pendingConnect;++ if (pending) {+ if (status === "granted") {+ pending.awaitingSnapshot = true;+ } else if (status !== "notDetermined") {+ // notDetermined means the TCC prompt is up; wait for the re-emit+ this._pendingConnect = null;+ if (this.isConnected()) this._clearStoredCalendarData();+ pending.resolve({ success: false, reason: "denied" });+ }+ return;+ }++ if (status !== "granted" && this.isConnected()) {+ // Access revoked in System Settings; a full re-connect is required+ debugLogger.warn("Calendar access no longer granted", { status }, "acal");+ this._clearStoredCalendarData();+ }+ }++ _applySnapshot({ calendars, events }) {+ try {+ this._restartAttempts = 0;+ this.databaseManager.saveAppleCalendars(calendars);+ this.databaseManager.replaceAppleCalendarEvents(events.map((event) => this._mapEvent(event)));++ const contacts = [];+ for (const event of events) {+ for (const attendee of event.attendees || []) {+ if (attendee.email) contacts.push({ email: attendee.email, displayName: attendee.name });+ }+ }+ if (contacts.length > 0) this.databaseManager.upsertContacts(contacts);++ broadcastToWindows("acal-events-synced", {});+ this.reminderScheduler.reconcileProvider("apple");+ this.reminderScheduler.scheduleNextMeeting();++ if (this._pendingConnect?.awaitingSnapshot) {+ const pending = this._pendingConnect;+ this._pendingConnect = null;+ pending.resolve({ success: true });+ this._broadcastConnectionChanged();+ }+ } catch (err) {+ debugLogger.error("Error applying calendar snapshot", { error: err.message }, "acal");+ if (this._pendingConnect) {+ const pending = this._pendingConnect;+ this._pendingConnect = null;+ pending.resolve({ success: false, reason: "snapshot-failed" });+ }+ }+ }++ _mapEvent(event) {+ const attendees = event.attendees || [];+ return {+ id: event.id,+ calendar_id: event.calendar_id,+ provider: "apple",+ summary: event.title || null,+ start_time: event.start,+ end_time: event.end,+ is_all_day: event.is_all_day,+ status: event.status,+ hangout_link:+ extractMeetingUrl([event.url, event.location, ...(event.notes_urls || [])]) ??+ // Generic fallback only for the event's own URL field+ (event.url?.startsWith("https://") ? event.url : null),+ conference_data: null,+ organizer_email: event.organizer_email || null,+ attendees_count: attendees.length,+ attendees: attendees.length+ ? JSON.stringify(+ attendees.map((a) => ({+ email: a.email || null,+ displayName: a.name || null,+ responseStatus: a.status || null,+ self: a.self || false,+ }))+ )+ : null,+ };+ }++ _broadcastConnectionChanged() {+ broadcastToWindows("acal-connection-changed", this.getConnectionStatus());+ }++ _clearStoredCalendarData() {+ this.databaseManager.clearAppleCalendarData();+ this.reminderScheduler.reset("apple");+ this.reminderScheduler.scheduleNextMeeting();+ this._broadcastConnectionChanged();+ broadcastToWindows("acal-events-synced", {});+ }+}++module.exports = AppleCalendarManager;diff --git a/src/helpers/audioActivityDetector.js b/src/helpers/audioActivityDetector.jsindex 1bc49cb3c..91704e1a5 100644--- a/src/helpers/audioActivityDetector.js+++ b/src/helpers/audioActivityDetector.js@@ -1,9 +1,8 @@const { exec, spawn } = require("child_process");const { promisify } = require("util");-const path = require("path");-const fs = require("fs");const EventEmitter = require("events");const debugLogger = require("./debugLogger");+const { resolveBundledBinary } = require("./binaryResolver");const execAsync = promisify(exec);@@ -169,35 +168,6 @@ class AudioActivityDetector extends EventEmitter {}}- _resolveBinary(binaryName) {- const candidates = [- path.join(__dirname, "..", "..", "resources", "bin", binaryName),- path.join(__dirname, "..", "..", "resources", binaryName),- ];-- if (process.resourcesPath) {- candidates.push(- path.join(process.resourcesPath, binaryName),- path.join(process.resourcesPath, "bin", binaryName),- path.join(process.resourcesPath, "resources", "bin", binaryName),- path.join(process.resourcesPath, "app.asar.unpacked", "resources", "bin", binaryName)- );- }-- for (const candidate of candidates) {- try {- if (fs.existsSync(candidate)) {- fs.accessSync(candidate, fs.constants.X_OK);- debugLogger.info("Resolved binary", { name: binaryName, path: candidate }, "meeting");- return candidate;- }- } catch {- // continue- }- }- return null;- }-// Spawns a listener and resolves only once the OS has confirmed it started, so a// failure to launch (missing binary, not executable) is reported as false instead// of being raced by the asynchronous "error" event.@@ -275,7 +245,7 @@ class AudioActivityDetector extends EventEmitter {}_tryEventDrivenDarwin(generation) {- const binaryPath = this._resolveBinary("macos-mic-listener");+ const binaryPath = resolveBundledBinary("macos-mic-listener", "meeting");if (!binaryPath) {debugLogger.warn("macos-mic-listener binary not found, will use polling", {}, "meeting");return false;@@ -297,7 +267,7 @@ class AudioActivityDetector extends EventEmitter {}_tryEventDrivenWin32(generation) {- const binaryPath = this._resolveBinary("windows-mic-listener.exe");+ const binaryPath = resolveBundledBinary("windows-mic-listener.exe", "meeting");if (!binaryPath) {debugLogger.warn("windows-mic-listener.exe not found, will use polling", {}, "meeting");return false;diff --git a/src/helpers/binaryResolver.js b/src/helpers/binaryResolver.jsnew file mode 100644index 000000000..031b69221--- /dev/null+++ b/src/helpers/binaryResolver.js@@ -0,0 +1,37 @@+const fs = require("fs");+const path = require("path");+const debugLogger = require("./debugLogger");++// Resolves a bundled helper binary across the dev layout (resources/) and the+// packaged layouts (process.resourcesPath, asar-unpacked). Returns null when+// no executable candidate exists so callers can fall back gracefully.+function resolveBundledBinary(binaryName, logContext) {+ const candidates = [+ path.join(__dirname, "..", "..", "resources", "bin", binaryName),+ path.join(__dirname, "..", "..", "resources", binaryName),+ ];++ if (process.resourcesPath) {+ candidates.push(+ path.join(process.resourcesPath, binaryName),+ path.join(process.resourcesPath, "bin", binaryName),+ path.join(process.resourcesPath, "resources", "bin", binaryName),+ path.join(process.resourcesPath, "app.asar.unpacked", "resources", "bin", binaryName)+ );+ }++ for (const candidate of candidates) {+ try {+ if (fs.existsSync(candidate)) {+ fs.accessSync(candidate, fs.constants.X_OK);+ debugLogger.info("Resolved binary", { name: binaryName, path: candidate }, logContext);+ return candidate;+ }+ } catch {+ // continue+ }+ }+ return null;+}++module.exports = { resolveBundledBinary };diff --git a/src/helpers/calendarReminderScheduler.js b/src/helpers/calendarReminderScheduler.jsnew file mode 100644index 000000000..7da9f5b25--- /dev/null+++ b/src/helpers/calendarReminderScheduler.js@@ -0,0 +1,167 @@+const debugLogger = require("./debugLogger");++const MEETING_REMINDER_LEAD_MS = 60 * 1000;++function notificationKey(event) {+ return `${event.provider || "google"}:${event.id}`;+}++// Provider-agnostic meeting reminder scheduling. Reads only the shared+// calendar_events table (deduped across providers), so a single scheduler+// serves both calendar managers without double-firing reminders.+class CalendarReminderScheduler {+ constructor(databaseManager) {+ this.databaseManager = databaseManager;+ this.nextMeetingTimer = null;+ this.meetingEndTimer = null;+ this.activeMeeting = null;+ this.notifiedMeetings = new Set();+ }++ scheduleNextMeeting() {+ if (this.nextMeetingTimer) {+ clearTimeout(this.nextMeetingTimer);+ this.nextMeetingTimer = null;+ }++ const upcoming = this.databaseManager.getUpcomingEvents(1440);+ const next = upcoming.find((e) => !this.notifiedMeetings.has(notificationKey(e)));+ if (!next) return;++ const delay = new Date(next.start_time).getTime() - MEETING_REMINDER_LEAD_MS - Date.now();+ if (delay <= 0) {+ this.onMeetingStart(next);+ return;+ }++ this.nextMeetingTimer = setTimeout(() => {+ this.onMeetingStart(next);+ }, delay);+ }++ onMeetingStart(event) {+ const events = this.databaseManager.getActiveEvents();+ const stillExists =+ events.some((e) => notificationKey(e) === notificationKey(event)) ||+ this.databaseManager+ .getUpcomingEvents(1)+ .some((e) => notificationKey(e) === notificationKey(event));++ if (!stillExists) {+ this.scheduleNextMeeting();+ return;+ }++ this.activeMeeting = event;+ this.notifiedMeetings.add(notificationKey(event));++ debugLogger.info("Calendar meeting reminder due", { summary: event.summary }, "calendar");+ this.meetingDetectionEngine?.handleCalendarReminder(event);++ this._scheduleMeetingEnd(event);++ this.scheduleNextMeeting();+ }++ onMeetingEnd() {+ debugLogger.info(+ "Calendar meeting ended",+ { summary: this.activeMeeting?.summary },+ "calendar"+ );+ this.activeMeeting = null;+ this._clearMeetingEndTimer();+ this.scheduleNextMeeting();+ }++ onWakeFromSleep() {+ const activeEvents = this.databaseManager.getActiveEvents();+ if (activeEvents.length > 0 && !this.activeMeeting) {+ this.onMeetingStart(activeEvents[0]);+ }+ this.scheduleNextMeeting();+ }++ getActiveMeetingState() {+ return {+ activeMeeting: this.activeMeeting,+ activeEvents: this.databaseManager.getActiveEvents(),+ upcomingEvents: this.databaseManager.getUpcomingEvents(15),+ };+ }++ // Refresh or clear the cached active event after a provider replaces its+ // rows. Keep notifiedMeetings intact so periodic snapshots cannot re-fire a+ // reminder that was already delivered.+ reconcileProvider(provider) {+ if (!this.activeMeeting || this.activeMeeting.provider !== provider) return;++ const key = notificationKey(this.activeMeeting);+ const currentEvent = [+ ...this.databaseManager.getActiveEvents(),+ ...this.databaseManager.getUpcomingEvents(1),+ ].find((event) => notificationKey(event) === key);++ if (!currentEvent) {+ this.activeMeeting = null;+ this._clearMeetingEndTimer();+ return;+ }++ this.activeMeeting = currentEvent;+ this._scheduleMeetingEnd(currentEvent);+ }++ _scheduleMeetingEnd(event) {+ this._clearMeetingEndTimer();+ const endDelay = new Date(event.end_time).getTime() - Date.now();+ if (endDelay > 0) {+ this.meetingEndTimer = setTimeout(() => {+ this.onMeetingEnd();+ }, endDelay);+ }+ }++ _clearMeetingEndTimer() {+ if (this.meetingEndTimer) {+ clearTimeout(this.meetingEndTimer);+ this.meetingEndTimer = null;+ }+ }++ stop() {+ if (this.nextMeetingTimer) {+ clearTimeout(this.nextMeetingTimer);+ this.nextMeetingTimer = null;+ }+ this._clearMeetingEndTimer();+ this.activeMeeting = null;+ }++ // Re-arm after one provider's data changes without forgetting reminders+ // already delivered by the other provider.+ reset(provider = null) {+ if (!provider) {+ this.stop();+ this.notifiedMeetings.clear();+ return;+ }++ if (this.nextMeetingTimer) {+ clearTimeout(this.nextMeetingTimer);+ this.nextMeetingTimer = null;+ }++ if (this.activeMeeting?.provider === provider) {+ this.activeMeeting = null;+ this._clearMeetingEndTimer();+ }++ const prefix = `${provider}:`;+ for (const key of this.notifiedMeetings) {+ if (key.startsWith(prefix)) this.notifiedMeetings.delete(key);+ }+ }+}++module.exports = CalendarReminderScheduler;diff --git a/src/helpers/cliBridge.js b/src/helpers/cliBridge.jsindex 591eca2bd..68e6fa75d 100644--- a/src/helpers/cliBridge.js+++ b/src/helpers/cliBridge.js@@ -5,6 +5,7 @@ const path = require("path");const crypto = require("crypto");const debugLogger = require("./debugLogger");const { isPortAvailable } = require("../utils/serverUtils");+const { broadcastToWindows } = require("./windowBroadcast");const PORT_RANGE_START = 8200;const PORT_RANGE_END = 8219;@@ -323,7 +324,7 @@ class CliBridge {body.folder_id ?? null);const note = unwrapMutationResult(result, "note");- setImmediate(() => ipc.broadcastToWindows("note-added", note));+ setImmediate(() => broadcastToWindows("note-added", note));ipc._asyncVectorUpsert(note);ipc._asyncMirrorWrite(note);return { data: note };@@ -334,7 +335,7 @@ class CliBridge {const id = requireId(params, "note");const result = db.updateNote(id, body || {});const note = unwrapMutationResult(result, "note");- setImmediate(() => ipc.broadcastToWindows("note-updated", note));+ setImmediate(() => broadcastToWindows("note-updated", note));ipc._asyncVectorUpsert(note);ipc._asyncMirrorWrite(note);return { data: note };@@ -354,7 +355,7 @@ class CliBridge {({ body }) => {const result = db.createFolder(body?.name);const folder = unwrapMutationResult(result, "folder");- setImmediate(() => ipc.broadcastToWindows("folder-created", folder));+ setImmediate(() => broadcastToWindows("folder-created", folder));return { data: folder };},201@@ -375,7 +376,7 @@ class CliBridge {}const result = db.applyDictionaryChanges({ add, remove });const words = db.getDictionary();- setImmediate(() => ipc.broadcastToWindows("dictionary-updated", words));+ setImmediate(() => broadcastToWindows("dictionary-updated", words));return { data: { words, added: result.added, removed: result.removed } };}),exact("GET", "/v1/transcriptions/list", ({ query }) => {diff --git a/src/helpers/database.js b/src/helpers/database.jsindex de36b4bbf..7397d23ca 100644--- a/src/helpers/database.js+++ b/src/helpers/database.js@@ -65,6 +65,26 @@ const FOLDER_NAME_TAKEN_FILTER = `(deleted_at IS NULL OR EXISTS (WHERE r.folder_id = folders.id AND r.entity_type = 'folder'))`;+// A meeting synced by both Google and Apple (Calendar.app mirroring the same+// account) would double-fire reminders and duplicate UI rows; suppress the+// Apple copy when a Google row occupies the same time slot + title (Google has+// richer conference data). datetime() normalizes the providers' timestamp+// formats (Google stores offset-form RFC3339, Apple stores UTC "Z" form), and+// Google rows are never collapsed so Google-only behavior is unchanged.+function dedupedEventsQuery(where) {+ return `SELECT * FROM (+ SELECT *, MAX(provider = 'google') OVER (+ PARTITION BY datetime(start_time), datetime(end_time), COALESCE(summary, '')+ ) AS has_google+ FROM calendar_events+ WHERE ${where}+ ) WHERE provider = 'google' OR has_google = 0 ORDER BY datetime(start_time) ASC`;+}++function stripDedupeColumn({ has_google: _hasGoogle, ...event }) {+ return event;+}+class DatabaseManager {constructor() {this.db = null;@@ -485,6 +505,24 @@ class DatabaseManager {)`);+ try {+ this.db.exec(+ "ALTER TABLE calendar_events ADD COLUMN provider TEXT NOT NULL DEFAULT 'google'"+ );+ } catch (err) {+ if (!err.message.includes("duplicate column")) throw err;+ }++ this.db.exec(`+ CREATE TABLE IF NOT EXISTS apple_calendars (+ id TEXT PRIMARY KEY,+ title TEXT NOT NULL,+ color TEXT,+ source_name TEXT,+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP+ )+ `);+try {this.db.exec("ALTER TABLE notes ADD COLUMN transcript TEXT");} catch (err) {@@ -3245,12 +3283,13 @@ class DatabaseManager {if (!this.db) throw new Error("Database not initialized");const transaction = this.db.transaction((eventList) => {const stmt = this.db.prepare(- "INSERT OR REPLACE INTO calendar_events (id, calendar_id, summary, start_time, end_time, is_all_day, status, hangout_link, conference_data, organizer_email, attendees_count, attendees, synced_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP)"+ "INSERT OR REPLACE INTO calendar_events (id, calendar_id, provider, summary, start_time, end_time, is_all_day, status, hangout_link, conference_data, organizer_email, attendees_count, attendees, synced_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP)");for (const e of eventList) {stmt.run(e.id,e.calendar_id,+ e.provider || "google",e.summary || null,e.start_time,e.end_time,@@ -3277,9 +3316,12 @@ class DatabaseManager {if (!this.db) throw new Error("Database not initialized");return this.db.prepare(- "SELECT * FROM calendar_events WHERE datetime(start_time) <= datetime('now') AND datetime(end_time) > datetime('now') AND is_all_day = 0 AND status = 'confirmed' ORDER BY start_time ASC"+ dedupedEventsQuery(+ "datetime(start_time) <= datetime('now') AND datetime(end_time) > datetime('now') AND is_all_day = 0 AND status IN ('confirmed', 'tentative')"+ ))- .all();+ .all()+ .map(stripDedupeColumn);} catch (error) {debugLogger.error("Error getting active events", { error: error.message }, "gcal");throw error;@@ -3325,9 +3367,12 @@ class DatabaseManager {if (!this.db) throw new Error("Database not initialized");return this.db.prepare(- "SELECT * FROM calendar_events WHERE ((datetime(start_time) > datetime('now') AND datetime(start_time) <= datetime('now', '+' || ? || ' minutes')) OR (datetime(start_time) <= datetime('now') AND datetime(end_time) > datetime('now'))) AND is_all_day = 0 AND status = 'confirmed' ORDER BY start_time ASC"+ dedupedEventsQuery(+ "((datetime(start_time) > datetime('now') AND datetime(start_time) <= datetime('now', '+' || ? || ' minutes')) OR (datetime(start_time) <= datetime('now') AND datetime(end_time) > datetime('now'))) AND is_all_day = 0 AND status IN ('confirmed', 'tentative')"+ ))- .all(windowMinutes);+ .all(windowMinutes)+ .map(stripDedupeColumn);} catch (error) {debugLogger.error("Error getting upcoming events", { error: error.message }, "gcal");throw error;@@ -3396,11 +3441,11 @@ class DatabaseManager {}}- clearCalendarData() {+ clearGoogleCalendarData() {try {if (!this.db) throw new Error("Database not initialized");const transaction = this.db.transaction(() => {- this.db.prepare("DELETE FROM calendar_events").run();+ this.db.prepare("DELETE FROM calendar_events WHERE provider = 'google'").run();this.db.prepare("DELETE FROM google_calendars").run();this.db.prepare("DELETE FROM google_calendar_tokens").run();});@@ -3442,7 +3487,7 @@ class DatabaseManager {if (!this.db) throw new Error("Database not initialized");this.db.prepare(- "DELETE FROM calendar_events WHERE calendar_id NOT IN (SELECT id FROM google_calendars WHERE is_selected = 1)"+ "DELETE FROM calendar_events WHERE provider = 'google' AND calendar_id NOT IN (SELECT id FROM google_calendars WHERE is_selected = 1)").run();return { success: true };@@ -3456,6 +3501,96 @@ class DatabaseManager {}}+ saveAppleCalendars(calendars) {+ try {+ if (!this.db) throw new Error("Database not initialized");+ const transaction = this.db.transaction((list) => {+ // Snapshots are complete: prune calendars removed from Calendar.app,+ // upsert the rest so created_at survives.+ if (list.length === 0) {+ this.db.prepare("DELETE FROM apple_calendars").run();+ return;+ }+ const placeholders = list.map(() => "?").join(", ");+ this.db+ .prepare(`DELETE FROM apple_calendars WHERE id NOT IN (${placeholders})`)+ .run(...list.map((cal) => cal.id));++ const stmt = this.db.prepare(+ `INSERT INTO apple_calendars (id, title, color, source_name)+ VALUES (?, ?, ?, ?)+ ON CONFLICT(id) DO UPDATE SET+ title = excluded.title,+ color = excluded.color,+ source_name = excluded.source_name`+ );+ for (const cal of list) {+ stmt.run(cal.id, cal.title, cal.color || null, cal.source_name || null);+ }+ });+ transaction(calendars);+ return { success: true };+ } catch (error) {+ debugLogger.error("Error saving Apple calendars", { error: error.message }, "acal");+ throw error;+ }+ }++ getAppleCalendars() {+ try {+ if (!this.db) throw new Error("Database not initialized");+ return this.db.prepare("SELECT * FROM apple_calendars").all();+ } catch (error) {+ debugLogger.error("Error getting Apple calendars", { error: error.message }, "acal");+ throw error;+ }+ }++ // Snapshots cover the full current/future window, so missing unreferenced+ // events can be removed while note-linked history is retained.+ replaceAppleCalendarEvents(events) {+ try {+ if (!this.db) throw new Error("Database not initialized");+ const transaction = this.db.transaction((list) => {+ // The helper snapshot only contains current/future events. Keep past or+ // rescheduled rows that are still referenced by meeting notes so those+ // notes retain their calendar metadata.+ this.db+ .prepare(+ `DELETE FROM calendar_events+ WHERE provider = 'apple'+ AND id NOT IN (+ SELECT calendar_event_id+ FROM notes+ WHERE calendar_event_id IS NOT NULL AND deleted_at IS NULL+ )`+ )+ .run();+ if (list.length > 0) this.upsertCalendarEvents(list);+ });+ transaction(events);+ return { success: true };+ } catch (error) {+ debugLogger.error("Error replacing Apple calendar events", { error: error.message }, "acal");+ throw error;+ }+ }++ clearAppleCalendarData() {+ try {+ if (!this.db) throw new Error("Database not initialized");+ const transaction = this.db.transaction(() => {+ this.db.prepare("DELETE FROM calendar_events WHERE provider = 'apple'").run();+ this.db.prepare("DELETE FROM apple_calendars").run();+ });+ transaction();+ return { success: true };+ } catch (error) {+ debugLogger.error("Error clearing Apple calendar data", { error: error.message }, "acal");+ throw error;+ }+ }+getMeetingsFolder(spaceId = null) {try {if (!this.db) throw new Error("Database not initialized");diff --git a/src/helpers/googleCalendarManager.js b/src/helpers/googleCalendarManager.jsindex d2035f6c9..96df97e3c 100644--- a/src/helpers/googleCalendarManager.js+++ b/src/helpers/googleCalendarManager.js@@ -1,21 +1,18 @@-const { net, BrowserWindow } = require("electron");+const { net } = require("electron");const debugLogger = require("./debugLogger");const GoogleCalendarOAuth = require("./googleCalendarOAuth");+const { broadcastToWindows } = require("./windowBroadcast");const CALENDAR_API_BASE = "https://www.googleapis.com/calendar/v3";-const MEETING_REMINDER_LEAD_MS = 60 * 1000;class GoogleCalendarManager {- constructor(databaseManager, windowManager) {+ constructor(databaseManager, windowManager, reminderScheduler) {this.databaseManager = databaseManager;this.windowManager = windowManager;+ this.reminderScheduler = reminderScheduler;this.oauth = new GoogleCalendarOAuth(databaseManager);this.accounts = new Map();this.syncInterval = null;- this.nextMeetingTimer = null;- this.meetingEndTimer = null;- this.activeMeeting = null;- this.notifiedMeetings = new Set();this.SYNC_INTERVAL_MS = 2 * 60 * 1000;this._consecutiveFailures = 0;this._lastFocusSync = 0;@@ -29,7 +26,7 @@ class GoogleCalendarManager {this.fetchCalendars().then(() => this.syncEvents()).then(() => {- this.scheduleNextMeeting();+ this.reminderScheduler.scheduleNextMeeting();this._consecutiveFailures = 0;}).catch((err) =>@@ -44,15 +41,6 @@ class GoogleCalendarManager {clearInterval(this.syncInterval);this.syncInterval = null;}- if (this.nextMeetingTimer) {- clearTimeout(this.nextMeetingTimer);- this.nextMeetingTimer = null;- }- if (this.meetingEndTimer) {- clearTimeout(this.meetingEndTimer);- this.meetingEndTimer = null;- }- this.activeMeeting = null;}isConnected() {@@ -70,7 +58,8 @@ class GoogleCalendarManager {if (this.accounts.size === 0) {this.stop();- this.notifiedMeetings.clear();+ this.reminderScheduler.reset("google");+ this.reminderScheduler.scheduleNextMeeting();}}@@ -81,7 +70,7 @@ class GoogleCalendarManager {await this.fetchCalendars(result.email);await this.syncEvents();this._consecutiveFailures = 0;- this.scheduleNextMeeting();+ this.reminderScheduler.scheduleNextMeeting();this._startSyncInterval();this._broadcastAccountsChanged();@@ -104,8 +93,9 @@ class GoogleCalendarManager {} else {this.stop();this.accounts.clear();- this.databaseManager.clearCalendarData();- this.notifiedMeetings.clear();+ this.databaseManager.clearGoogleCalendarData();+ this.reminderScheduler.reset("google");+ this.reminderScheduler.scheduleNextMeeting();this._broadcastAccountsChanged();}}@@ -166,8 +156,8 @@ class GoogleCalendarManager {}}- this.broadcastToWindows("gcal-events-synced", {});- this.scheduleNextMeeting();+ broadcastToWindows("gcal-events-synced", {});+ this.reminderScheduler.scheduleNextMeeting();}async _syncCalendar(calendar) {@@ -223,6 +213,7 @@ class GoogleCalendarManager {toUpsert.push({id: item.id,calendar_id: calendar.id,+ provider: "google",summary: item.summary || null,start_time: item.start?.dateTime || item.start?.date,end_time: item.end?.dateTime || item.end?.date,@@ -262,74 +253,7 @@ class GoogleCalendarManager {if (contactsToUpsert.length > 0) this.databaseManager.upsertContacts(contactsToUpsert);}- scheduleNextMeeting() {- if (this.nextMeetingTimer) {- clearTimeout(this.nextMeetingTimer);- this.nextMeetingTimer = null;- }-- const upcoming = this.databaseManager.getUpcomingEvents(1440);- const next = upcoming.find((e) => !this.notifiedMeetings.has(e.id));- if (!next) return;-- const delay = new Date(next.start_time).getTime() - MEETING_REMINDER_LEAD_MS - Date.now();- if (delay <= 0) {- this.onMeetingStart(next);- return;- }-- this.nextMeetingTimer = setTimeout(() => {- this.onMeetingStart(next);- }, delay);- }-- onMeetingStart(event) {- const events = this.databaseManager.getActiveEvents();- const stillExists =- events.some((e) => e.id === event.id) ||- this.databaseManager.getUpcomingEvents(1).some((e) => e.id === event.id);-- if (!stillExists) {- this.scheduleNextMeeting();- return;- }-- this.activeMeeting = event;- this.notifiedMeetings.add(event.id);-- debugLogger.info("Calendar meeting reminder due", { summary: event.summary }, "gcal");- this.meetingDetectionEngine?.handleCalendarReminder(event);-- if (this.meetingEndTimer) {- clearTimeout(this.meetingEndTimer);- }- const endDelay = new Date(event.end_time).getTime() - Date.now();- if (endDelay > 0) {- this.meetingEndTimer = setTimeout(() => {- this.onMeetingEnd();- }, endDelay);- }-- this.scheduleNextMeeting();- }-- onMeetingEnd() {- debugLogger.info("Calendar meeting ended", { summary: this.activeMeeting?.summary }, "gcal");- this.activeMeeting = null;- if (this.meetingEndTimer) {- clearTimeout(this.meetingEndTimer);- this.meetingEndTimer = null;- }- this.scheduleNextMeeting();- }-onWakeFromSleep() {- const activeEvents = this.databaseManager.getActiveEvents();- if (activeEvents.length > 0 && !this.activeMeeting) {- this.onMeetingStart(activeEvents[0]);- }- this.scheduleNextMeeting();-this.syncEvents().then(() => {this._consecutiveFailures = 0;@@ -346,7 +270,7 @@ class GoogleCalendarManager {this.syncEvents().then(() => {- this.scheduleNextMeeting();+ this.reminderScheduler.scheduleNextMeeting();if (this._consecutiveFailures > 0) {this._consecutiveFailures = 0;this._restartSyncInterval();@@ -357,14 +281,6 @@ class GoogleCalendarManager {);}- getActiveMeetingState() {- return {- activeMeeting: this.activeMeeting,- activeEvents: this.databaseManager.getActiveEvents(),- upcomingEvents: this.databaseManager.getUpcomingEvents(15),- };- }-getCalendars() {return this.databaseManager.getGoogleCalendars();}@@ -373,7 +289,7 @@ class GoogleCalendarManager {this.databaseManager.updateCalendarSelection(calendarId, isSelected);await this.syncEvents();this._consecutiveFailures = 0;- this.scheduleNextMeeting();+ this.reminderScheduler.scheduleNextMeeting();}async setPrimaryOnly(value) {@@ -382,25 +298,16 @@ class GoogleCalendarManager {if (!this.isConnected()) return;await this.fetchCalendars();- this.notifiedMeetings.clear();+ this.reminderScheduler.reset("google");await this.syncEvents();- this.scheduleNextMeeting();- this.broadcastToWindows("gcal-events-synced", {});+ this.reminderScheduler.scheduleNextMeeting();+ broadcastToWindows("gcal-events-synced", {});}async getUpcomingEvents(windowMinutes) {return this.databaseManager.getUpcomingEvents(windowMinutes);}- broadcastToWindows(channel, data) {- const windows = BrowserWindow.getAllWindows();- windows.forEach((win) => {- if (!win.isDestroyed()) {- win.webContents.send(channel, data);- }- });- }-_loadAccounts() {const accounts = this.databaseManager.getGoogleAccounts();this.accounts.clear();@@ -426,7 +333,7 @@ class GoogleCalendarManager {this.syncInterval = setInterval(() => {this.syncEvents().then(() => {- this.scheduleNextMeeting();+ this.reminderScheduler.scheduleNextMeeting();if (this._consecutiveFailures > 0) {this._consecutiveFailures = 0;this._restartSyncInterval();@@ -459,7 +366,7 @@ class GoogleCalendarManager {_broadcastAccountsChanged() {const accounts = this.getAccounts();- this.broadcastToWindows("gcal-connection-changed", { accounts });+ broadcastToWindows("gcal-connection-changed", { accounts });}async _apiGet(path, accountEmail = null) {diff --git a/src/helpers/ipcHandlers.js b/src/helpers/ipcHandlers.jsindex bf70f5388..3ac551e74 100644--- a/src/helpers/ipcHandlers.js+++ b/src/helpers/ipcHandlers.js@@ -4,6 +4,7 @@ const fs = require("fs");const os = require("os");const crypto = require("crypto");const debugLogger = require("./debugLogger");+const { broadcastToWindows } = require("./windowBroadcast");const { BYOK_API_KEYS } = require("../config/secretKeys");const tokenStore = require("./tokenStore");const { createCloudApiRequestHandler } = require("./cloudApiRequest");@@ -486,6 +487,7 @@ class IPCHandlers {this.whisperCudaManager = managers.whisperCudaManager;this.whisperVulkanManager = managers.whisperVulkanManager;this.googleCalendarManager = managers.googleCalendarManager;+ this.appleCalendarManager = managers.appleCalendarManager;this.meetingDetectionEngine = managers.meetingDetectionEngine;this.audioTapManager = managers.audioTapManager;this.linuxPortalAudioManager = managers.linuxPortalAudioManager;@@ -531,7 +533,7 @@ class IPCHandlers {this.setupHandlers();// Lives for the app's lifetime; IPCHandlers has no teardown path.tokenStore.subscribe(({ generation, token }) => {- this.broadcastToWindows("auth-token-state-changed", {+ broadcastToWindows("auth-token-state-changed", {generation,hasToken: Boolean(token),});@@ -539,10 +541,10 @@ class IPCHandlers {if (this.whisperManager?.serverManager) {this.whisperManager.serverManager.on("cuda-fallback", () => {- this.broadcastToWindows("cuda-fallback-notification", {});+ broadcastToWindows("cuda-fallback-notification", {});});this.whisperManager.serverManager.on("gpu-fallback", () => {- this.broadcastToWindows("gpu-fallback-notification", {});+ broadcastToWindows("gpu-fallback-notification", {});});}}@@ -841,7 +843,7 @@ class IPCHandlers {this.databaseManager.deleteTranscriptionsExpiredBefore(transcriptRetentionDays);for (const id of ids) {this.audioStorageManager.deleteAudio(id);- this.broadcastToWindows("transcription-deleted", { id });+ broadcastToWindows("transcription-deleted", { id });}}if (audioRetentionDays > 0) {@@ -920,11 +922,11 @@ class IPCHandlers {// Broadcast the post-save normalized list, not the raw input (which// still has case-variant dupes), so renderers don't flash ghost rows.- this.broadcastToWindows("dictionary-updated", this.databaseManager.getDictionary());+ broadcastToWindows("dictionary-updated", this.databaseManager.getDictionary());// Show the overlay so the toast is visible (it may have been hidden after dictation)this.windowManager.showDictationPanel();- this.broadcastToWindows("corrections-learned", corrections);+ broadcastToWindows("corrections-learned", corrections);debugLogger.debug("[AutoLearn] Saved corrections", { corrections });}} catch (error) {@@ -1048,7 +1050,7 @@ class IPCHandlers {const result = this.databaseManager.saveTranscription(text, rawText, options);if (result?.success && result?.transcription) {setImmediate(() => {- this.broadcastToWindows("transcription-added", result.transcription);+ broadcastToWindows("transcription-added", result.transcription);});}return result;@@ -1063,7 +1065,7 @@ class IPCHandlers {const result = this.databaseManager.clearTranscriptions();if (result?.success) {setImmediate(() => {- this.broadcastToWindows("transcriptions-cleared", {+ broadcastToWindows("transcriptions-cleared", {cleared: result.cleared,});});@@ -1088,7 +1090,7 @@ class IPCHandlers {model: metadata?.model || null,});const updated = this.databaseManager.getTranscriptionById(id);- if (updated) this.broadcastToWindows("transcription-updated", updated);+ if (updated) broadcastToWindows("transcription-updated", updated);}return result;});@@ -1252,7 +1254,7 @@ class IPCHandlers {// Emit the normalized list straight from SQLite so renderers see the// post-dedupe truth, never a caller-supplied payload.const words = this.databaseManager.getDictionary();- this.broadcastToWindows("dictionary-updated", words);+ broadcastToWindows("dictionary-updated", words);return { success: true };});@@ -1306,7 +1308,7 @@ class IPCHandlers {ipcMain.handle("db-broadcast-snippets-updated", async () => {const snippets = this.databaseManager.getSnippets();- this.broadcastToWindows("snippets-updated", snippets);+ broadcastToWindows("snippets-updated", snippets);return { success: true };});@@ -1326,7 +1328,7 @@ class IPCHandlers {});return { success: false };}- this.broadcastToWindows("dictionary-updated", this.databaseManager.getDictionary());+ broadcastToWindows("dictionary-updated", this.databaseManager.getDictionary());debugLogger.debug("[AutoLearn] Undo: removed words", { words: validWords });return { success: true };} catch (err) {@@ -1348,7 +1350,7 @@ class IPCHandlers {spaceId);if (result?.success && result?.note) {- setImmediate(() => this.broadcastToWindows("note-added", result.note));+ setImmediate(() => broadcastToWindows("note-added", result.note));this._asyncVectorUpsert(result.note);this._asyncMirrorWrite(result.note);}@@ -1371,7 +1373,7 @@ class IPCHandlers {ipcMain.handle("db-update-note", async (event, id, updates) => {const result = this.databaseManager.updateNote(id, updates);if (result?.success && result?.note) {- setImmediate(() => this.broadcastToWindows("note-updated", result.note));+ setImmediate(() => broadcastToWindows("note-updated", result.note));this._asyncVectorUpsert(result.note);this._asyncMirrorWrite(result.note);if (updates.participants) this._tryAutoLabelOneOnOne(id);@@ -1462,7 +1464,7 @@ class IPCHandlers {let done = 0;const { failed } = await vectorIndex.reindexAll(notes, (completed, total) => {done = completed;- this.broadcastToWindows("semantic-reindex-progress", { done: completed, total });+ 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 };@@ -1475,7 +1477,7 @@ class IPCHandlers {ipcMain.handle("db-update-note-share-state", async (event, id, state) => {const note = this.databaseManager.updateNoteShareState(id, state);if (note) {- setImmediate(() => this.broadcastToWindows("note-updated", note));+ setImmediate(() => broadcastToWindows("note-updated", note));}return note;});@@ -1488,7 +1490,7 @@ class IPCHandlers {const result = this.databaseManager.createFolder(name, spaceId);if (result?.success && result?.folder) {setImmediate(() => {- this.broadcastToWindows("folder-created", result.folder);+ broadcastToWindows("folder-created", result.folder);if (this._noteFilesEnabled) {const markdownMirror = require("./markdownMirror");markdownMirror.ensureFolder(result.folder.name);@@ -1506,7 +1508,7 @@ class IPCHandlers {this._asyncVectorDelete(noteId);}setImmediate(() => {- this.broadcastToWindows("folder-deleted", { id });+ broadcastToWindows("folder-deleted", { id });if (folderName) this._mirrorDeleteFolderIfUnshared(folderName);});}@@ -1518,7 +1520,7 @@ class IPCHandlers {const result = this.databaseManager.renameFolder(id, name);if (result?.success && result?.folder) {setImmediate(() => {- this.broadcastToWindows("folder-renamed", result.folder);+ broadcastToWindows("folder-renamed", result.folder);if (this._noteFilesEnabled && oldName) {const markdownMirror = require("./markdownMirror");markdownMirror.renameFolder(oldName, name);@@ -1536,7 +1538,7 @@ class IPCHandlers {this._asyncVectorUpsert(note);}if (result.folder) {- setImmediate(() => this.broadcastToWindows("folder-synced", result.folder));+ setImmediate(() => broadcastToWindows("folder-synced", result.folder));}}return result;@@ -1553,7 +1555,7 @@ class IPCHandlers {ipcMain.handle("db-update-space", async (event, id, updates) => {const result = this.databaseManager.updateSpace(id, updates);if (result?.success && result.space) {- setImmediate(() => this.broadcastToWindows("space-synced", result.space));+ setImmediate(() => broadcastToWindows("space-synced", result.space));}return result;});@@ -1581,7 +1583,7 @@ class IPCHandlers {this._asyncMirrorDelete(noteId);}setImmediate(() => {- this.broadcastToWindows("space-purged", { spaceId: result.spaceId });+ broadcastToWindows("space-purged", { spaceId: result.spaceId });for (const folderName of result.folderNames ?? []) {this._mirrorDeleteFolderIfUnshared(folderName);}@@ -1602,7 +1604,7 @@ class IPCHandlers {const result = this.databaseManager.createAction(name, description, prompt, icon);if (result?.success && result?.action) {setImmediate(() => {- this.broadcastToWindows("action-created", result.action);+ broadcastToWindows("action-created", result.action);});}return result;@@ -1612,7 +1614,7 @@ class IPCHandlers {const result = this.databaseManager.updateAction(id, updates);if (result?.success && result?.action) {setImmediate(() => {- this.broadcastToWindows("action-updated", result.action);+ broadcastToWindows("action-updated", result.action);});}return result;@@ -1622,7 +1624,7 @@ class IPCHandlers {const result = this.databaseManager.deleteAction(id);if (result?.success) {setImmediate(() => {- this.broadcastToWindows("action-deleted", { id });+ broadcastToWindows("action-deleted", { id });});}return result;@@ -1755,7 +1757,7 @@ class IPCHandlers {ipcMain.handle("db-upsert-note-from-cloud", (_, cloudNote, localFolderId, localSpaceId) => {const note = this.databaseManager.upsertNoteFromCloud(cloudNote, localFolderId, localSpaceId);if (note) {- setImmediate(() => this.broadcastToWindows("note-synced", note));+ setImmediate(() => broadcastToWindows("note-synced", note));this._asyncVectorUpsert(note);}return note;@@ -1803,7 +1805,7 @@ class IPCHandlers {if (result?.success) {this._asyncVectorDelete(id);this._asyncMirrorDelete(id);- setImmediate(() => this.broadcastToWindows("note-deleted", { id }));+ setImmediate(() => broadcastToWindows("note-deleted", { id }));}return result;});@@ -1817,7 +1819,7 @@ class IPCHandlers {);ipcMain.handle("db-upsert-folder-from-cloud", (_, cloudFolder, localSpaceId) => {const folder = this.databaseManager.upsertFolderFromCloud(cloudFolder, localSpaceId);- if (folder) setImmediate(() => this.broadcastToWindows("folder-synced", folder));+ if (folder) setImmediate(() => broadcastToWindows("folder-synced", folder));return folder;});ipcMain.handle(@@ -1847,9 +1849,9 @@ class IPCHandlers {this._asyncMirrorWrite(note);}setImmediate(() => {- if (result.folder) this.broadcastToWindows("folder-synced", result.folder);+ if (result.folder) broadcastToWindows("folder-synced", result.folder);for (const note of result.notes ?? []) {- this.broadcastToWindows("note-synced", note);+ broadcastToWindows("note-synced", note);}});}@@ -1862,7 +1864,7 @@ class IPCHandlers {this._asyncVectorDelete(noteId);}setImmediate(() => {- this.broadcastToWindows("folder-deleted", { id });+ broadcastToWindows("folder-deleted", { id });if (result.name) this._mirrorDeleteFolderIfUnshared(result.name);});}@@ -1882,13 +1884,13 @@ class IPCHandlers {this._asyncMirrorDelete(noteId);}setImmediate(() => {- if (result.folder) this.broadcastToWindows("folder-synced", result.folder);- else this.broadcastToWindows("folder-deleted", { id });+ if (result.folder) broadcastToWindows("folder-synced", result.folder);+ else broadcastToWindows("folder-deleted", { id });for (const note of result.relocatedNotes ?? []) {- this.broadcastToWindows("note-updated", note);+ broadcastToWindows("note-updated", note);}for (const noteId of result.deletedNoteIds ?? []) {- this.broadcastToWindows("note-deleted", { id: noteId });+ broadcastToWindows("note-deleted", { id: noteId });}const folderGone = !result.folder || result.folder.name !== result.folderName;if (result.folderName && folderGone) {@@ -1902,21 +1904,21 @@ class IPCHandlers {// Renderer-side sync events (conflicts, revocation toasts, …) happen in// whichever window ran the pass — rebroadcast them to ALL windows.ipcMain.handle("broadcast-sync-event", (_, name, payload) => {- this.broadcastToWindows("sync-event", { name, payload });+ broadcastToWindows("sync-event", { name, payload });return { success: true };});// Spaces syncipcMain.handle("db-upsert-space-from-cloud", (_, cloudSpace) => {const space = this.databaseManager.upsertSpaceFromCloud(cloudSpace);- if (space) setImmediate(() => this.broadcastToWindows("space-synced", space));+ if (space) setImmediate(() => broadcastToWindows("space-synced", space));return space;});ipcMain.handle("db-set-space-sync-status", (_, id, status) => {const result = this.databaseManager.setSpaceSyncStatus(id, status);if (result?.success && result.space) {// Live skeleton toggling: the tree keys pending/synced off this flag.- setImmediate(() => this.broadcastToWindows("space-synced", result.space));+ setImmediate(() => broadcastToWindows("space-synced", result.space));}return result;});@@ -1940,7 +1942,7 @@ class IPCHandlers {ipcMain.handle("db-hard-delete-conversation", (_, id) => {const result = this.databaseManager.hardDeleteConversation(id);if (result?.success) {- setImmediate(() => this.broadcastToWindows("conversation-deleted", { id }));+ setImmediate(() => broadcastToWindows("conversation-deleted", { id }));}return result;});@@ -1964,7 +1966,7 @@ class IPCHandlers {ipcMain.handle("db-hard-delete-transcription", (_, id) => {const result = this.databaseManager.hardDeleteTranscription(id);if (result?.success) {- setImmediate(() => this.broadcastToWindows("transcription-deleted", { id }));+ setImmediate(() => broadcastToWindows("transcription-deleted", { id }));}return result;});@@ -4237,6 +4239,7 @@ class IPCHandlers {"x-apple.systempreferences:com.apple.preference.security?Privacy_Accessibility",systemAudio:"x-apple.systempreferences:com.apple.preference.security?Privacy_ScreenCapture",+ calendars: "x-apple.systempreferences:com.apple.preference.security?Privacy_Calendars",},win32: {microphone: "ms-settings:privacy-microphone",@@ -4277,6 +4280,7 @@ class IPCHandlers {ipcMain.handle("open-sound-input-settings", () => openSystemSettings("sound"));ipcMain.handle("open-accessibility-settings", () => openSystemSettings("accessibility"));ipcMain.handle("open-system-audio-settings", () => openSystemSettings("systemAudio"));+ ipcMain.handle("open-calendar-privacy-settings", () => openSystemSettings("calendars"));ipcMain.handle("show-emoji-panel", () => {try {@@ -4893,7 +4897,7 @@ class IPCHandlers {const updated = this.databaseManager.getTranscriptionById(id);if (updated) {setImmediate(() => {- this.broadcastToWindows("transcription-updated", updated);+ broadcastToWindows("transcription-updated", updated);});}return { success: true, transcription: updated };@@ -9006,6 +9010,38 @@ class IPCHandlers {}});+ // Apple Calendar (macOS EventKit)+ ipcMain.handle("acal-connect", async () => {+ try {+ return await this.appleCalendarManager.connect();+ } catch (error) {+ debugLogger.error("Apple Calendar connect failed", { error: error.message }, "acal");+ return { success: false, error: error.message };+ }+ });++ ipcMain.handle("acal-disconnect", async () => {+ try {+ return this.appleCalendarManager.disconnect();+ } catch (error) {+ debugLogger.error("Apple Calendar disconnect failed", { error: error.message }, "acal");+ return { success: false, error: error.message };+ }+ });++ ipcMain.handle("acal-get-connection-status", async () => {+ try {+ return this.appleCalendarManager.getConnectionStatus();+ } catch (error) {+ debugLogger.error(+ "Apple Calendar connection status failed",+ { error: error.message },+ "acal"+ );+ return { connected: false, sourceNames: [] };+ }+ });+ipcMain.handle("search-contacts", async (_event, query) => {try {const contacts = this.databaseManager.searchContacts(query);@@ -9468,7 +9504,7 @@ class IPCHandlers {if (changed) {this.databaseManager.updateNote(noteId, { transcript: JSON.stringify(transcript) });const updated = this.databaseManager.getNote(noteId);- if (updated) this.broadcastToWindows("note-updated", updated);+ if (updated) broadcastToWindows("note-updated", updated);}if (profile) this._retroactiveMapping(profile);@@ -9828,7 +9864,7 @@ class IPCHandlers {const result = this.databaseManager.deleteTranscription(id);if (result?.success) {setImmediate(() => {- this.broadcastToWindows("transcription-deleted", { id });+ broadcastToWindows("transcription-deleted", { id });});}return result;@@ -9837,21 +9873,12 @@ class IPCHandlers {deleteNoteInternal(id) {const result = this.databaseManager.deleteNote(id);if (result?.success) {- setImmediate(() => this.broadcastToWindows("note-deleted", { id }));+ setImmediate(() => broadcastToWindows("note-deleted", { id }));this._asyncVectorDelete(id);this._asyncMirrorDelete(id);}return result;}-- broadcastToWindows(channel, payload) {- const windows = BrowserWindow.getAllWindows();- windows.forEach((win) => {- if (!win.isDestroyed()) {- win.webContents.send(channel, payload);- }- });- }}module.exports = IPCHandlers;diff --git a/src/helpers/meetingDetectionEngine.js b/src/helpers/meetingDetectionEngine.jsindex 860e1f26b..829d30c71 100644--- a/src/helpers/meetingDetectionEngine.js+++ b/src/helpers/meetingDetectionEngine.js@@ -1,6 +1,7 @@-const { BrowserWindow, shell } = require("electron");+const { shell } = require("electron");const debugLogger = require("./debugLogger");const { getMeetingJoinUrl } = require("./meetingJoinUrl");+const { broadcastToWindows } = require("./windowBroadcast");const IMMINENT_THRESHOLD_MS = 5 * 60 * 1000;@@ -25,13 +26,13 @@ function placeholderEvent(calendarId) {class MeetingDetectionEngine {constructor(- googleCalendarManager,+ reminderScheduler,meetingProcessDetector,audioActivityDetector,windowManager,databaseManager) {- this.googleCalendarManager = googleCalendarManager;+ this.reminderScheduler = reminderScheduler;this.meetingProcessDetector = meetingProcessDetector;this.audioActivityDetector = audioActivityDetector;this.windowManager = windowManager;@@ -124,8 +125,7 @@ class MeetingDetectionEngine {// activeMeeting only means the event's scheduled window is open — actual meeting// recordings are tracked by _meetingModeActive._findCalendarEvent() {- const calendarState = this.googleCalendarManager?.getActiveMeetingState?.();- if (!calendarState) return null;+ const calendarState = this.reminderScheduler.getActiveMeetingState();if (calendarState.activeMeeting) return calendarState.activeMeeting;const now = Date.now();@@ -212,7 +212,7 @@ class MeetingDetectionEngine {this._meetingModeActive = true;- this.broadcastToWindows("note-added", noteResult.note);+ broadcastToWindows("note-added", noteResult.note);const isRealEvent =detection.event?.calendar_id &&@@ -227,7 +227,7 @@ class MeetingDetectionEngine {}const updateResult = this.databaseManager.updateNote(noteResult.note.id, updates);if (updateResult?.success && updateResult?.note) {- this.broadcastToWindows("note-updated", updateResult.note);+ broadcastToWindows("note-updated", updateResult.note);}}@@ -284,7 +284,7 @@ class MeetingDetectionEngine {return;}- this.broadcastToWindows("note-added", noteResult.note);+ broadcastToWindows("note-added", noteResult.note);await this.windowManager.queueMeetingNoteNavigation({noteId: noteResult.note.id,@@ -324,7 +324,7 @@ class MeetingDetectionEngine {}const updateResult = this.databaseManager.updateNote(noteResult.note.id, updates);- this.broadcastToWindows("note-added", updateResult?.note || noteResult.note);+ broadcastToWindows("note-added", updateResult?.note || noteResult.note);await this.windowManager.queueMeetingNoteNavigation({noteId: noteResult.note.id,@@ -450,15 +450,6 @@ class MeetingDetectionEngine {}this._notificationQueue = [];}-- broadcastToWindows(channel, data) {- const windows = BrowserWindow.getAllWindows();- windows.forEach((win) => {- if (!win.isDestroyed()) {- win.webContents.send(channel, data);- }- });- }}module.exports = MeetingDetectionEngine;diff --git a/src/helpers/meetingJoinUrl.js b/src/helpers/meetingJoinUrl.jsindex 23e9f3241..ac27bca5b 100644--- a/src/helpers/meetingJoinUrl.js+++ b/src/helpers/meetingJoinUrl.js@@ -1,3 +1,6 @@+const MEETING_URL_PATTERN =+ /https?:\/\/[^\s<>"']*(?:zoom\.us\/j\/|meet\.google\.com\/|teams\.microsoft\.com\/l\/meetup-join|teams\.live\.com\/meet\/|\.webex\.com\/|chime\.aws\/)[^\s<>"']*/i;+export function getMeetingJoinUrl(event) {if (!event) return null;if (event.hangout_link) return event.hangout_link;@@ -9,3 +12,13 @@ export function getMeetingJoinUrl(event) {return null;}}++// Finds a meeting link in loose text (EventKit has no structured conference+// data — Zoom/Meet/Teams/Webex links live in url, location, or notes).+export function extractMeetingUrl(candidates) {+ for (const candidate of candidates) {+ const match = candidate?.match?.(MEETING_URL_PATTERN);+ if (match) return match[0].replace(/[),.;:!?]+$/, "");+ }+ return null;+}diff --git a/src/helpers/windowBroadcast.js b/src/helpers/windowBroadcast.jsnew file mode 100644index 000000000..0b081c252--- /dev/null+++ b/src/helpers/windowBroadcast.js@@ -0,0 +1,12 @@+const { BrowserWindow } = require("electron");++function broadcastToWindows(channel, data) {+ const windows = BrowserWindow.getAllWindows();+ windows.forEach((win) => {+ if (!win.isDestroyed()) {+ win.webContents.send(channel, data);+ }+ });+}++module.exports = { broadcastToWindows };diff --git a/src/hooks/useUpcomingEvents.ts b/src/hooks/useUpcomingEvents.tsindex a6c9af84a..f238c172b 100644--- a/src/hooks/useUpcomingEvents.ts+++ b/src/hooks/useUpcomingEvents.ts@@ -20,7 +20,8 @@ function getLookaheadMinutes(): number {export function useUpcomingEvents(): UseUpcomingEventsReturn {const gcalAccounts = useSettingsStore((s) => s.gcalAccounts);- const isConnected = gcalAccounts.length > 0;+ const appleCalendarConnected = useSettingsStore((s) => s.appleCalendarConnected);+ const isConnected = gcalAccounts.length > 0 || appleCalendarConnected;const [events, setEvents] = useState<CalendarEvent[]>([]);const [isLoading, setIsLoading] = useState(false);@@ -51,13 +52,19 @@ export function useUpcomingEvents(): UseUpcomingEventsReturn {fetchEvents();}, [fetchEvents]);- // Re-fetch when events are synced from Google Calendar+ // Re-fetch when either provider syncs eventsuseEffect(() => {if (!isConnected) return;- const unsub = window.electronAPI?.onGcalEventsSynced?.(() => {+ const unsubGcal = window.electronAPI?.onGcalEventsSynced?.(() => {fetchEvents();});- return () => unsub?.();+ const unsubAcal = window.electronAPI?.onAcalEventsSynced?.(() => {+ fetchEvents();+ });+ return () => {+ unsubGcal?.();+ unsubAcal?.();+ };}, [isConnected, fetchEvents]);return { events, isLoading, isConnected };diff --git a/src/locales/de/translation.json b/src/locales/de/translation.jsonindex fc659dcfe..e477f3c83 100644--- a/src/locales/de/translation.json+++ b/src/locales/de/translation.json@@ -3176,6 +3176,21 @@"systemAudioDescription": "Zum Transkribieren von Meetings benötigt OpenWhispr die Systemaudio-Berechtigung, um den Ton anderer Teilnehmer aufzunehmen. Wir nehmen Ihren Bildschirm nie auf. Sie werden zu den Systemeinstellungen weitergeleitet, um diese zu aktivieren.","openSettings": "Systemeinstellungen öffnen"},+ "appleCalendar": {+ "title": "Apple Kalender",+ "optional": "Optional",+ "description": "Termine aus Calendar.app lesen — iCloud, Google, Exchange und Outlook an einem Ort.",+ "connect": "Apple Kalender verbinden",+ "connected": "Verbunden",+ "disconnect": "Trennen",+ "disconnectConfirm": "Apple Kalender trennen?",+ "disconnectDescription": "Besprechungsnotizen werden von deinem Apple Kalender nicht mehr aufgezeichnet.",+ "permissionDenied": "Kalenderzugriff erforderlich",+ "permissionDeniedDescription": "OpenWhispr benötigt Kalenderzugriff, um Besprechungen zu erkennen. Aktiviere OpenWhispr in den Systemeinstellungen unter Datenschutz & Sicherheit → Kalender.",+ "openSettings": "Systemeinstellungen öffnen",+ "connectFailed": "Verbindung fehlgeschlagen",+ "connectFailedDescription": "Beim Verbinden mit Calendar.app ist ein Fehler aufgetreten. Starte OpenWhispr neu und versuche es erneut."+ },"sections": {"calendar": "Kalender","api": "API",diff --git a/src/locales/en/translation.json b/src/locales/en/translation.jsonindex 253d42777..37d5b15b2 100644--- a/src/locales/en/translation.json+++ b/src/locales/en/translation.json@@ -3176,6 +3176,21 @@"systemAudioDescription": "To transcribe meetings, OpenWhispr needs the System Audio permission to capture other participants' audio. We never record your screen. You'll be taken to System Settings to enable it.","openSettings": "Open System Settings"},+ "appleCalendar": {+ "title": "Apple Calendar",+ "optional": "Optional",+ "description": "Read meetings from Calendar.app — iCloud, Google, Exchange, and Outlook in one place.",+ "connect": "Connect Apple Calendar",+ "connected": "Connected",+ "disconnect": "Disconnect",+ "disconnectConfirm": "Disconnect Apple Calendar?",+ "disconnectDescription": "Meeting notes will no longer be recorded from your Apple Calendar.",+ "permissionDenied": "Calendar Access Required",+ "permissionDeniedDescription": "OpenWhispr needs calendar access to detect meetings. Enable OpenWhispr in System Settings under Privacy & Security → Calendars.",+ "openSettings": "Open System Settings",+ "connectFailed": "Connection Failed",+ "connectFailedDescription": "Something went wrong while connecting to Calendar.app. Please restart OpenWhispr and try again."+ },"sections": {"calendar": "Calendar","api": "API",diff --git a/src/locales/es/translation.json b/src/locales/es/translation.jsonindex 24871f3f7..34144fa43 100644--- a/src/locales/es/translation.json+++ b/src/locales/es/translation.json@@ -3076,6 +3076,21 @@"systemAudioDescription": "Para transcribir reuniones, OpenWhispr necesita el permiso de Audio del Sistema para capturar el audio de otros participantes. Nunca grabamos tu pantalla. Serás dirigido a Ajustes del Sistema para activarlo.","openSettings": "Abrir Ajustes del Sistema"},+ "appleCalendar": {+ "title": "Calendario de Apple",+ "optional": "Opcional",+ "description": "Lee reuniones de Calendar.app — iCloud, Google, Exchange y Outlook en un solo lugar.",+ "connect": "Conectar Calendario de Apple",+ "connected": "Conectado",+ "disconnect": "Desconectar",+ "disconnectConfirm": "¿Desconectar el Calendario de Apple?",+ "disconnectDescription": "Ya no se grabarán notas de reuniones de tu Calendario de Apple.",+ "permissionDenied": "Se requiere acceso al calendario",+ "permissionDeniedDescription": "OpenWhispr necesita acceso al calendario para detectar reuniones. Activa OpenWhispr en Ajustes del Sistema, en Privacidad y seguridad → Calendarios.",+ "openSettings": "Abrir Ajustes del Sistema",+ "connectFailed": "Error de conexión",+ "connectFailedDescription": "Se produjo un error al conectar con Calendar.app. Reinicia OpenWhispr e inténtalo de nuevo."+ },"sections": {"calendar": "Calendario","api": "API",diff --git a/src/locales/fr/translation.json b/src/locales/fr/translation.jsonindex 2a2167617..c278b65be 100644--- a/src/locales/fr/translation.json+++ b/src/locales/fr/translation.json@@ -3176,6 +3176,21 @@"systemAudioDescription": "Pour transcrire les réunions, OpenWhispr a besoin de l'autorisation Audio Système pour capturer l'audio des autres participants. Nous n'enregistrons jamais votre écran. Vous serez dirigé vers les Réglages Système pour l'activer.","openSettings": "Ouvrir les Réglages Système"},+ "appleCalendar": {+ "title": "Calendrier Apple",+ "optional": "Facultatif",+ "description": "Lisez les réunions depuis Calendar.app — iCloud, Google, Exchange et Outlook au même endroit.",+ "connect": "Connecter le Calendrier Apple",+ "connected": "Connecté",+ "disconnect": "Déconnecter",+ "disconnectConfirm": "Déconnecter le Calendrier Apple ?",+ "disconnectDescription": "Les notes de réunion ne seront plus enregistrées depuis votre Calendrier Apple.",+ "permissionDenied": "Accès au calendrier requis",+ "permissionDeniedDescription": "OpenWhispr a besoin d'accéder au calendrier pour détecter les réunions. Activez OpenWhispr dans Réglages Système, sous Confidentialité et sécurité → Calendriers.",+ "openSettings": "Ouvrir les Réglages Système",+ "connectFailed": "Échec de la connexion",+ "connectFailedDescription": "Une erreur s'est produite lors de la connexion à Calendar.app. Redémarrez OpenWhispr et réessayez."+ },"sections": {"calendar": "Calendrier","api": "API",diff --git a/src/locales/it/translation.json b/src/locales/it/translation.jsonindex 979f5a1de..d0538d61f 100644--- a/src/locales/it/translation.json+++ b/src/locales/it/translation.json@@ -3028,6 +3028,21 @@"systemAudioDescription": "Per trascrivere le riunioni, OpenWhispr necessita dell'autorizzazione Audio di Sistema per catturare l'audio degli altri partecipanti. Non registriamo mai il tuo schermo. Verrai reindirizzato alle Impostazioni di Sistema per attivarla.","openSettings": "Apri Impostazioni di Sistema"},+ "appleCalendar": {+ "title": "Calendario Apple",+ "optional": "Opzionale",+ "description": "Leggi le riunioni da Calendar.app — iCloud, Google, Exchange e Outlook in un unico posto.",+ "connect": "Collega Calendario Apple",+ "connected": "Connesso",+ "disconnect": "Disconnetti",+ "disconnectConfirm": "Disconnettere il Calendario Apple?",+ "disconnectDescription": "Le note delle riunioni non saranno più registrate dal tuo Calendario Apple.",+ "permissionDenied": "Accesso al calendario richiesto",+ "permissionDeniedDescription": "OpenWhispr ha bisogno dell'accesso al calendario per rilevare le riunioni. Attiva OpenWhispr in Impostazioni di Sistema, in Privacy e sicurezza → Calendari.",+ "openSettings": "Apri Impostazioni di Sistema",+ "connectFailed": "Connessione non riuscita",+ "connectFailedDescription": "Si è verificato un errore durante la connessione a Calendar.app. Riavvia OpenWhispr e riprova."+ },"sections": {"calendar": "Calendario","api": "API",diff --git a/src/locales/ja/translation.json b/src/locales/ja/translation.jsonindex a61f24d74..f7ae81ff7 100644--- a/src/locales/ja/translation.json+++ b/src/locales/ja/translation.json@@ -3028,6 +3028,21 @@"systemAudioDescription": "会議を文字起こしするには、OpenWhispr に他の参加者の音声を録音するためのシステムオーディオの権限が必要です。画面を録画することはありません。システム設定に移動して有効にします。","openSettings": "システム設定を開く"},+ "appleCalendar": {+ "title": "Apple カレンダー",+ "optional": "任意",+ "description": "Calendar.app から会議を読み取ります — iCloud、Google、Exchange、Outlook をまとめて。",+ "connect": "Apple カレンダーを接続",+ "connected": "接続済み",+ "disconnect": "切断",+ "disconnectConfirm": "Apple カレンダーを切断しますか?",+ "disconnectDescription": "Apple カレンダーからの会議メモは記録されなくなります。",+ "permissionDenied": "カレンダーへのアクセスが必要です",+ "permissionDeniedDescription": "会議を検出するには、OpenWhispr にカレンダーへのアクセスが必要です。システム設定の「プライバシーとセキュリティ」→「カレンダー」で OpenWhispr を有効にしてください。",+ "openSettings": "システム設定を開く",+ "connectFailed": "接続に失敗しました",+ "connectFailedDescription": "Calendar.app への接続中にエラーが発生しました。OpenWhispr を再起動してもう一度お試しください。"+ },"sections": {"calendar": "カレンダー","api": "API",diff --git a/src/locales/pt/translation.json b/src/locales/pt/translation.jsonindex 9aecfefb8..0edf01369 100644--- a/src/locales/pt/translation.json+++ b/src/locales/pt/translation.json@@ -3028,6 +3028,21 @@"systemAudioDescription": "Para transcrever reuniões, o OpenWhispr precisa da permissão de Áudio do Sistema para capturar o áudio dos outros participantes. Nunca gravamos a sua tela. Você será levado às Configurações do Sistema para ativá-la.","openSettings": "Abrir Configurações do Sistema"},+ "appleCalendar": {+ "title": "Calendário da Apple",+ "optional": "Opcional",+ "description": "Leia reuniões do Calendar.app — iCloud, Google, Exchange e Outlook em um só lugar.",+ "connect": "Conectar Calendário da Apple",+ "connected": "Conectado",+ "disconnect": "Desconectar",+ "disconnectConfirm": "Desconectar o Calendário da Apple?",+ "disconnectDescription": "As notas de reunião não serão mais gravadas do seu Calendário da Apple.",+ "permissionDenied": "Acesso ao calendário necessário",+ "permissionDeniedDescription": "O OpenWhispr precisa de acesso ao calendário para detectar reuniões. Ative o OpenWhispr em Configurações do Sistema, em Privacidade e Segurança → Calendários.",+ "openSettings": "Abrir Configurações do Sistema",+ "connectFailed": "Falha na conexão",+ "connectFailedDescription": "Ocorreu um erro ao conectar ao Calendar.app. Reinicie o OpenWhispr e tente novamente."+ },"sections": {"calendar": "Calendário","api": "API",diff --git a/src/locales/ru/translation.json b/src/locales/ru/translation.jsonindex 3ee2cbf2b..44a9a6865 100644--- a/src/locales/ru/translation.json+++ b/src/locales/ru/translation.json@@ -3058,6 +3058,21 @@"systemAudioDescription": "Для транскрипции встреч OpenWhispr нужно разрешение «Системное аудио» для записи звука других участников. Мы никогда не записываем ваш экран. Вы будете перенаправлены в Системные настройки для включения.","openSettings": "Открыть Системные настройки"},+ "appleCalendar": {+ "title": "Календарь Apple",+ "optional": "Необязательно",+ "description": "Читайте встречи из Calendar.app — iCloud, Google, Exchange и Outlook в одном месте.",+ "connect": "Подключить Календарь Apple",+ "connected": "Подключено",+ "disconnect": "Отключить",+ "disconnectConfirm": "Отключить Календарь Apple?",+ "disconnectDescription": "Заметки встреч больше не будут записываться из вашего Календаря Apple.",+ "permissionDenied": "Требуется доступ к календарю",+ "permissionDeniedDescription": "OpenWhispr нужен доступ к календарю для обнаружения встреч. Включите OpenWhispr в Системных настройках: Конфиденциальность и безопасность → Календари.",+ "openSettings": "Открыть Системные настройки",+ "connectFailed": "Ошибка подключения",+ "connectFailedDescription": "При подключении к Calendar.app произошла ошибка. Перезапустите OpenWhispr и попробуйте снова."+ },"sections": {"calendar": "Календарь","api": "API",diff --git a/src/locales/zh-CN/translation.json b/src/locales/zh-CN/translation.jsonindex 4cf2321de..fc402b4df 100644--- a/src/locales/zh-CN/translation.json+++ b/src/locales/zh-CN/translation.json@@ -3028,6 +3028,21 @@"systemAudioDescription": "要转录会议,OpenWhispr 需要系统音频权限来录制其他参与者的音频。我们绝不会录制您的屏幕。您将被引导至系统设置以启用此权限。","openSettings": "打开系统设置"},+ "appleCalendar": {+ "title": "Apple 日历",+ "optional": "可选",+ "description": "从 Calendar.app 读取会议 — iCloud、Google、Exchange 和 Outlook 一站式接入。",+ "connect": "连接 Apple 日历",+ "connected": "已连接",+ "disconnect": "断开",+ "disconnectConfirm": "断开 Apple 日历?",+ "disconnectDescription": "将不再从 Apple 日历记录会议笔记。",+ "permissionDenied": "需要日历访问权限",+ "permissionDeniedDescription": "OpenWhispr 需要日历访问权限来检测会议。请在系统设置的「隐私与安全性」→「日历」中启用 OpenWhispr。",+ "openSettings": "打开系统设置",+ "connectFailed": "连接失败",+ "connectFailedDescription": "连接 Calendar.app 时出错。请重启 OpenWhispr 后重试。"+ },"sections": {"calendar": "日历","api": "API",diff --git a/src/locales/zh-TW/translation.json b/src/locales/zh-TW/translation.jsonindex 2087fcb0d..cc1d1c81c 100644--- a/src/locales/zh-TW/translation.json+++ b/src/locales/zh-TW/translation.json@@ -3028,6 +3028,21 @@"systemAudioDescription": "要轉錄會議,OpenWhispr 需要系統音訊權限來錄製其他參與者的音訊。我們絕不會錄製您的螢幕。您將被引導至系統設定以啟用此權限。","openSettings": "打開系統設定"},+ "appleCalendar": {+ "title": "Apple 日曆",+ "optional": "可選",+ "description": "從 Calendar.app 讀取會議 — iCloud、Google、Exchange 和 Outlook 一站式接入。",+ "connect": "連接 Apple 日曆",+ "connected": "已連接",+ "disconnect": "中斷連接",+ "disconnectConfirm": "中斷 Apple 日曆的連接?",+ "disconnectDescription": "將不再從 Apple 日曆記錄會議筆記。",+ "permissionDenied": "需要日曆存取權限",+ "permissionDeniedDescription": "OpenWhispr 需要日曆存取權限來偵測會議。請在系統設定的「隱私權與安全性」→「日曆」中啟用 OpenWhispr。",+ "openSettings": "打開系統設定",+ "connectFailed": "連線失敗",+ "connectFailedDescription": "連線 Calendar.app 時發生錯誤。請重新啟動 OpenWhispr 後再試一次。"+ },"sections": {"calendar": "行事曆","api": "API",diff --git a/src/stores/settingsStore.ts b/src/stores/settingsStore.tsindex c12975096..8b14a7a95 100644--- a/src/stores/settingsStore.ts+++ b/src/stores/settingsStore.ts@@ -156,6 +156,7 @@ const BOOLEAN_SETTINGS = new Set(["notifyCalendarReminders","notifyUpdates","gcalPrimaryOnly",+ "appleCalendarConnected",]);const ARRAY_SETTINGS = new Set([@@ -433,6 +434,7 @@ export interface SettingsStatenotifyCalendarReminders: boolean;notifyUpdates: boolean;gcalPrimaryOnly: boolean;+ appleCalendarConnected: boolean;meetingProcessDetection: boolean;speakerDiarizationEnabled: boolean;dictationSileroEnabled: boolean;@@ -687,6 +689,7 @@ export interface SettingsStatesetNotifyCalendarReminders: (value: boolean) => void;setNotifyUpdates: (value: boolean) => void;setGcalPrimaryOnly: (value: boolean) => void;+ setAppleCalendarConnected: (value: boolean) => void;setMeetingProcessDetection: (value: boolean) => void;setSpeakerDiarizationEnabled: (value: boolean) => void;setDictationSileroEnabled: (value: boolean) => void;@@ -1053,6 +1056,7 @@ export const useSettingsStore = create<SettingsState>()((set, get) => ({};})(),gcalPrimaryOnly: readBoolean("gcalPrimaryOnly", true),+ appleCalendarConnected: readBoolean("appleCalendarConnected", false),meetingProcessDetection: readBoolean("meetingProcessDetection", true),speakerDiarizationEnabled: readBoolean("speakerDiarizationEnabled", true),dictationSileroEnabled: readBoolean("dictationSileroEnabled", true),@@ -1683,6 +1687,7 @@ export const useSettingsStore = create<SettingsState>()((set, get) => ({useSettingsStore.setState({ gcalPrimaryOnly: value });if (isBrowser) window.electronAPI?.gcalSetPrimaryOnly?.(value);},+ setAppleCalendarConnected: createBooleanSetter("appleCalendarConnected"),setMeetingProcessDetection: createBooleanSetter("meetingProcessDetection"),setSpeakerDiarizationEnabled: (value: boolean) => {if (isBrowser) localStorage.setItem("speakerDiarizationEnabled", String(value));@@ -2500,6 +2505,20 @@ export async function initializeSettings(): Promise<void> {);}+ // The main-process DB is the source of truth for the Apple Calendar connection+ try {+ const status = await window.electronAPI.acalGetConnectionStatus?.();+ if (status) {+ useSettingsStore.getState().setAppleCalendarConnected(status.connected);+ }+ } catch (err) {+ logger.warn(+ "Failed to hydrate Apple Calendar connection status",+ { error: (err as Error).message },+ "settings"+ );+ }+try {const currentState = useSettingsStore.getState();await window.electronAPI.gcalSetPrimaryOnly?.(currentState.gcalPrimaryOnly);diff --git a/src/types/calendar.ts b/src/types/calendar.tsindex 39db58321..e32e6a6aa 100644--- a/src/types/calendar.ts+++ b/src/types/calendar.ts@@ -11,6 +11,7 @@ export interface GoogleCalendar {export interface CalendarEvent {id: string;calendar_id: string;+ provider: string;summary: string | null;start_time: string;end_time: string;diff --git a/src/types/electron.ts b/src/types/electron.tsindex 480783f36..d0330c747 100644--- a/src/types/electron.ts+++ b/src/types/electron.ts@@ -2240,6 +2240,16 @@ declare global {onGcalConnectionChanged?: (callback: (data: any) => void) => () => void;onGcalEventsSynced?: (callback: (data: any) => void) => () => void;+ // Apple Calendar (macOS EventKit)+ acalConnect?: () => Promise<{ success: boolean; reason?: string; error?: string }>;+ acalDisconnect?: () => Promise<{ success: boolean; error?: string }>;+ acalGetConnectionStatus?: () => Promise<{ connected: boolean; sourceNames: string[] }>;+ openCalendarPrivacySettings?: () => Promise<{ success: boolean; error?: string }>;+ onAcalConnectionChanged?: (+ callback: (data: { connected: boolean; sourceNames: string[] }) => void+ ) => () => void;+ onAcalEventsSynced?: (callback: (data: any) => void) => () => void;+meetingDetectionGetPreferences?: () => Promise<{ success: boolean; preferences?: any }>;meetingDetectionSetPreferences?: (prefs: Record<string, boolean>diff --git a/test/helpers/appleCalendarManager.test.js b/test/helpers/appleCalendarManager.test.jsnew file mode 100644index 000000000..20c7f5149--- /dev/null+++ b/test/helpers/appleCalendarManager.test.js@@ -0,0 +1,65 @@+const test = require("node:test");+const assert = require("node:assert/strict");+const Module = require("node:module");++const managerModulePath = require.resolve("../../src/helpers/appleCalendarManager.js");+const originalLoad = Module._load;++function loadManager() {+ delete require.cache[managerModulePath];+ Module._load = function loadWithElectronMock(request, parent, isMain) {+ if (request === "electron") {+ return { BrowserWindow: { getAllWindows: () => [] } };+ }+ return originalLoad.call(this, request, parent, isMain);+ };+ try {+ return require(managerModulePath);+ } finally {+ Module._load = originalLoad;+ }+}++test("an unexpected helper exit schedules a restart while Apple Calendar is connected", () => {+ const originalPlatform = process.platform;+ Object.defineProperty(process, "platform", { value: "darwin" });+ try {+ const AppleCalendarManager = loadManager();+ const databaseManager = {+ getAppleCalendars: () => [{ id: "calendar-1" }],+ };+ const manager = new AppleCalendarManager(databaseManager, {});+ const child = {};+ let restartCount = 0;+ manager._helperProcess = child;+ manager._scheduleHelperRestart = () => {+ restartCount += 1;+ };++ manager._onHelperGone(child);++ assert.equal(manager._helperProcess, null);+ assert.equal(restartCount, 1);+ } finally {+ Object.defineProperty(process, "platform", { value: originalPlatform });+ }+});++test("a deliberate stop prevents the exited child from scheduling a restart", () => {+ const AppleCalendarManager = loadManager();+ const databaseManager = {+ getAppleCalendars: () => [{ id: "calendar-1" }],+ };+ const manager = new AppleCalendarManager(databaseManager, {});+ const child = { kill: () => {} };+ let restartCount = 0;+ manager._helperProcess = child;+ manager._scheduleHelperRestart = () => {+ restartCount += 1;+ };++ manager.stop();+ manager._onHelperGone(child);++ assert.equal(restartCount, 0);+});diff --git a/test/helpers/audioActivityDetector.test.js b/test/helpers/audioActivityDetector.test.jsindex 48ac0056d..c7ec94928 100644--- a/test/helpers/audioActivityDetector.test.js+++ b/test/helpers/audioActivityDetector.test.js@@ -28,6 +28,12 @@ function loadDetector(platform, spawn) {if (request === "child_process") {return { ...childProcess, spawn };}+ // Binary resolution hits the real filesystem, so without this the platform+ // under test would be decided by which listener binaries happen to be built+ // on the host rather than by setPlatform().+ if (request === "./binaryResolver") {+ return { resolveBundledBinary: (name) => `/fake/bin/${name}` };+ }return originalLoad.call(this, request, parent, isMain);};@@ -68,7 +74,6 @@ function createDetector(platform, { spawnError } = {}) {});const detector = new AudioActivityDetector();- detector._resolveBinary = (name) => `/fake/bin/${name}`;detector._isMicActive = async () => false;return { detector, children, calls };}diff --git a/test/helpers/calendarDatabase.test.js b/test/helpers/calendarDatabase.test.jsnew file mode 100644index 000000000..0b3cbcf16--- /dev/null+++ b/test/helpers/calendarDatabase.test.js@@ -0,0 +1,97 @@+const test = require("node:test");+const assert = require("node:assert/strict");+const fs = require("node:fs");+const os = require("node:os");+const path = require("node:path");+const Module = require("node:module");++let userDataDir = fs.mkdtempSync(path.join(os.tmpdir(), "openwhispr-calendar-db-"));+const originalLoad = Module._load;++Module._load = function patchedLoad(request, parent, isMain) {+ if (request === "electron") {+ return {+ app: {+ getPath: () => userDataDir,+ getAppPath: () => process.cwd(),+ isReady: () => false,+ },+ };+ }+ return originalLoad.call(this, request, parent, isMain);+};++process.env.NODE_ENV = "test";++const DatabaseManager = require("../../src/helpers/database.js");++function isNativeBindingUnavailable(error) {+ const message = String(error?.message || error);+ return (+ message.includes("NODE_MODULE_VERSION") ||+ message.includes("Could not locate the bindings file")+ );+}++function createDb(t) {+ userDataDir = fs.mkdtempSync(path.join(os.tmpdir(), "openwhispr-calendar-db-"));+ try {+ return new DatabaseManager();+ } catch (error) {+ if (isNativeBindingUnavailable(error)) {+ t.skip("better-sqlite3 native binding is not available for this Node runtime");+ return null;+ }+ throw error;+ }+}++function appleEvent(id, overrides = {}) {+ return {+ id,+ calendar_id: "apple-calendar",+ provider: "apple",+ summary: id,+ start_time: "2026-07-20T10:00:00Z",+ end_time: "2026-07-20T11:00:00Z",+ is_all_day: false,+ status: "confirmed",+ ...overrides,+ };+}++test("Apple snapshots retain events referenced by meeting notes", (t) => {+ const db = createDb(t);+ if (!db) return;++ db.upsertCalendarEvents([appleEvent("linked-event"), appleEvent("unlinked-event")]);+ const note = db.saveNote("Linked meeting", "", "meeting").note;+ db.updateNote(note.id, { calendar_event_id: "linked-event" });++ db.replaceAppleCalendarEvents([]);++ assert.equal(db.getCalendarEventById("linked-event")?.summary, "linked-event");+ assert.equal(db.getCalendarEventById("unlinked-event"), null);+ db.db.close();+});++test("tentative Apple events remain visible in upcoming meetings", (t) => {+ const db = createDb(t);+ if (!db) return;++ const now = Date.now();+ db.upsertCalendarEvents([+ appleEvent("tentative-event", {+ start_time: new Date(now + 5 * 60_000).toISOString(),+ end_time: new Date(now + 35 * 60_000).toISOString(),+ status: "tentative",+ }),+ ]);++ const events = db.getUpcomingEvents(15);+ assert.equal(+ events.some((event) => event.id === "tentative-event"),+ true+ );+ db.db.close();+});diff --git a/test/helpers/calendarReminderScheduler.test.js b/test/helpers/calendarReminderScheduler.test.jsnew file mode 100644index 000000000..8710d03bf--- /dev/null+++ b/test/helpers/calendarReminderScheduler.test.js@@ -0,0 +1,88 @@+const test = require("node:test");+const assert = require("node:assert/strict");++const CalendarReminderScheduler = require("../../src/helpers/calendarReminderScheduler.js");++function activeEvent(provider, id) {+ const now = Date.now();+ return {+ id,+ provider,+ summary: `${provider} meeting`,+ start_time: new Date(now - 1000).toISOString(),+ end_time: new Date(now + 60_000).toISOString(),+ };+}++test("resetting one provider preserves reminders delivered by another provider", () => {+ const googleEvent = activeEvent("google", "meeting-1");+ const databaseManager = {+ getUpcomingEvents: () => [googleEvent],+ getActiveEvents: () => [googleEvent],+ };+ const scheduler = new CalendarReminderScheduler(databaseManager);+ let promptCount = 0;+ scheduler.meetingDetectionEngine = {+ handleCalendarReminder: () => {+ promptCount += 1;+ },+ };++ scheduler.scheduleNextMeeting();+ scheduler.reset("apple");+ scheduler.scheduleNextMeeting();++ assert.equal(promptCount, 1);+ assert.equal(scheduler.activeMeeting, googleEvent);+ scheduler.stop();+});++test("resetting a provider lets that provider's remaining event be re-armed", () => {+ const appleEvent = activeEvent("apple", "meeting-1");+ const databaseManager = {+ getUpcomingEvents: () => [appleEvent],+ getActiveEvents: () => [appleEvent],+ };+ const scheduler = new CalendarReminderScheduler(databaseManager);+ let promptCount = 0;+ scheduler.meetingDetectionEngine = {+ handleCalendarReminder: () => {+ promptCount += 1;+ },+ };++ scheduler.scheduleNextMeeting();+ scheduler.reset("apple");+ scheduler.scheduleNextMeeting();++ assert.equal(promptCount, 2);+ scheduler.stop();+});++test("reconciling a provider clears an active event removed by a snapshot", () => {+ const appleEvent = activeEvent("apple", "meeting-1");+ let activeEvents = [appleEvent];+ const databaseManager = {+ getUpcomingEvents: () => activeEvents,+ getActiveEvents: () => activeEvents,+ };+ const scheduler = new CalendarReminderScheduler(databaseManager);+ let promptCount = 0;+ scheduler.meetingDetectionEngine = {+ handleCalendarReminder: () => {+ promptCount += 1;+ },+ };++ scheduler.scheduleNextMeeting();+ activeEvents = [];+ scheduler.reconcileProvider("apple");++ assert.equal(promptCount, 1);+ assert.equal(scheduler.activeMeeting, null);++ activeEvents = [appleEvent];+ scheduler.scheduleNextMeeting();+ assert.equal(promptCount, 1, "a periodic snapshot must not re-fire an old reminder");+ scheduler.stop();+});diff --git a/test/helpers/cliBridgeDictionary.test.js b/test/helpers/cliBridgeDictionary.test.jsindex fc9b67eb7..63677b739 100644--- a/test/helpers/cliBridgeDictionary.test.js+++ b/test/helpers/cliBridgeDictionary.test.js@@ -7,6 +7,9 @@ const Module = require("node:module");let userDataDir = fs.mkdtempSync(path.join(os.tmpdir(), "openwhispr-cli-dict-"));const originalLoad = Module._load;+// Routes broadcast through the shared windowBroadcast module, which reaches for+// Electron's BrowserWindow; capture the calls so they can be asserted here.+const broadcasts = [];Module._load = function patchedLoad(request, parent, isMain) {if (request === "electron") {@@ -18,6 +21,11 @@ Module._load = function patchedLoad(request, parent, isMain) {},};}+ if (request === "./windowBroadcast") {+ return {+ broadcastToWindows: (channel, payload) => broadcasts.push({ channel, payload }),+ };+ }return originalLoad.call(this, request, parent, isMain);};@@ -52,11 +60,8 @@ function createBridge(t) {throw error;}- const broadcasts = [];- const bridge = new CliBridge({- databaseManager: db,- broadcastToWindows: (channel, payload) => broadcasts.push({ channel, payload }),- });+ broadcasts.length = 0;+ const bridge = new CliBridge({ databaseManager: db });return { bridge, db, broadcasts };}diff --git a/test/helpers/meetingJoinUrl.test.js b/test/helpers/meetingJoinUrl.test.jsindex 349a558fe..732a58799 100644--- a/test/helpers/meetingJoinUrl.test.js+++ b/test/helpers/meetingJoinUrl.test.js@@ -47,3 +47,51 @@ test("returns null for missing event or links", async () => {assert.equal(getMeetingJoinUrl(null), null);assert.equal(getMeetingJoinUrl({}), null);});++test("extractMeetingUrl matches known meeting vendors", async () => {+ const { extractMeetingUrl } = await load();+ const urls = [+ "https://zoom.us/j/123456789",+ "https://us02web.zoom.us/j/123456789?pwd=abc",+ "https://meet.google.com/abc-defg-hij",+ "https://teams.microsoft.com/l/meetup-join/19%3ameeting_x/0",+ "https://teams.live.com/meet/9876543210",+ "https://company.webex.com/meet/jdoe",+ "https://chime.aws/1234567890",+ ];+ for (const url of urls) {+ assert.equal(extractMeetingUrl([url]), url);+ }+});++test("extractMeetingUrl finds a link inside a location string", async () => {+ const { extractMeetingUrl } = await load();+ assert.equal(+ extractMeetingUrl(["Join here: https://meet.google.com/abc-defg-hij (passcode 42)"]),+ "https://meet.google.com/abc-defg-hij"+ );+ assert.equal(+ extractMeetingUrl(["Zoom: https://zoom.us/j/123456789, dial-in below"]),+ "https://zoom.us/j/123456789"+ );+});++test("extractMeetingUrl returns the first matching candidate", async () => {+ const { extractMeetingUrl } = await load();+ assert.equal(+ extractMeetingUrl([+ null,+ "Conference Room 4B",+ "https://zoom.us/j/111",+ "https://meet.google.com/zzz",+ ]),+ "https://zoom.us/j/111"+ );+});++test("extractMeetingUrl returns null when nothing matches", async () => {+ const { extractMeetingUrl } = await load();+ assert.equal(extractMeetingUrl([]), null);+ assert.equal(extractMeetingUrl([null, undefined, ""]), null);+ assert.equal(extractMeetingUrl(["Conference Room 4B", "https://example.com/agenda"]), null);+});