Skip to content

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

feat(calendar): Microsoft Calendar (Graph) integration

Gabriel Stein702ef1a9f19c
diff --git a/main.js b/main.js
index ec2f648dd..e4aafba99 100644
--- a/main.js
+++ b/main.js
@@ -277,6 +277,7 @@ 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 MicrosoftCalendarManager = require("./src/helpers/microsoftCalendarManager");
const AppleCalendarManager = require("./src/helpers/appleCalendarManager");
const CalendarReminderScheduler = require("./src/helpers/calendarReminderScheduler");
const MeetingProcessDetector = require("./src/helpers/meetingProcessDetector");
@@ -311,6 +312,7 @@ let textEditMonitor = null;
let whisperCudaManager = null;
let whisperVulkanManager = null;
let googleCalendarManager = null;
+let microsoftCalendarManager = null;
let appleCalendarManager = null;
let calendarReminderScheduler = null;
let meetingDetectionEngine = null;
@@ -407,6 +409,10 @@ function initializeCoreManagers() {
windowManager,
calendarReminderScheduler
);
+ microsoftCalendarManager = new MicrosoftCalendarManager(
+ databaseManager,
+ calendarReminderScheduler
+ );
appleCalendarManager = new AppleCalendarManager(databaseManager, calendarReminderScheduler);
meetingDetectionEngine = new MeetingDetectionEngine(
calendarReminderScheduler,
@@ -450,6 +456,7 @@ function initializeCoreManagers() {
whisperCudaManager,
whisperVulkanManager,
googleCalendarManager,
+ microsoftCalendarManager,
appleCalendarManager,
meetingDetectionEngine,
audioTapManager,
@@ -515,6 +522,7 @@ function initializeDeferredManagers() {
}
googleCalendarManager.start();
+ microsoftCalendarManager.start();
appleCalendarManager.start();
meetingDetectionEngine.start();
}
@@ -1066,6 +1074,7 @@ async function startApp() {
app.on("browser-window-focus", () => {
if (googleCalendarManager) googleCalendarManager.syncOnFocus();
+ if (microsoftCalendarManager) microsoftCalendarManager.syncOnFocus();
if (appleCalendarManager) appleCalendarManager.syncOnFocus();
});
@@ -1075,6 +1084,7 @@ async function startApp() {
if (googleCalendarManager) {
googleCalendarManager.onWakeFromSleep();
}
+ if (microsoftCalendarManager) microsoftCalendarManager.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);
@@ -1807,6 +1817,7 @@ function performSyncTeardown() {
if (linuxKeyManager) linuxKeyManager.stop();
if (meetingDetectionEngine) meetingDetectionEngine.stop();
if (googleCalendarManager) googleCalendarManager.stop();
+ if (microsoftCalendarManager) microsoftCalendarManager.stop();
if (appleCalendarManager) appleCalendarManager.stop();
if (calendarReminderScheduler) calendarReminderScheduler.stop();
if (audioTapManager) audioTapManager.stop().catch(() => {});
diff --git a/preload.js b/preload.js
index 19ba45b58..d336caa85 100644
--- a/preload.js
+++ b/preload.js
@@ -1031,7 +1031,7 @@ contextBridge.exposeInMainWorld("electronAPI", {
// Google Calendar
gcalStartOAuth: () => ipcRenderer.invoke("gcal-start-oauth"),
- gcalDisconnect: () => ipcRenderer.invoke("gcal-disconnect"),
+ gcalDisconnect: (email) => ipcRenderer.invoke("gcal-disconnect", email),
gcalGetConnectionStatus: () => ipcRenderer.invoke("gcal-get-connection-status"),
gcalGetCalendars: () => ipcRenderer.invoke("gcal-get-calendars"),
gcalSetCalendarSelection: (calendarId, isSelected) =>
@@ -1042,6 +1042,12 @@ contextBridge.exposeInMainWorld("electronAPI", {
ipcRenderer.invoke("gcal-get-upcoming-events", windowMinutes),
gcalGetEvent: (eventId) => ipcRenderer.invoke("gcal-get-event", eventId),
+ // Microsoft Calendar
+ mcalStartOAuth: () => ipcRenderer.invoke("mcal-start-oauth"),
+ mcalDisconnect: (email) => ipcRenderer.invoke("mcal-disconnect", email),
+ mcalGetConnectionStatus: () => ipcRenderer.invoke("mcal-get-connection-status"),
+ mcalSetPrimaryOnly: (value) => ipcRenderer.invoke("mcal-set-primary-only", value),
+
// Apple Calendar (macOS EventKit)
acalConnect: () => ipcRenderer.invoke("acal-connect"),
acalDisconnect: () => ipcRenderer.invoke("acal-disconnect"),
@@ -1063,6 +1069,16 @@ contextBridge.exposeInMainWorld("electronAPI", {
(callback) => (_event, data) => callback(data)
),
+ // Microsoft Calendar event listeners
+ onMcalConnectionChanged: registerListener(
+ "mcal-connection-changed",
+ (callback) => (_event, data) => callback(data)
+ ),
+ onMcalEventsSynced: registerListener(
+ "mcal-events-synced",
+ (callback) => (_event, data) => callback(data)
+ ),
+
// Apple Calendar event listeners
onAcalConnectionChanged: registerListener(
"acal-connection-changed",
diff --git a/src/assets/icons/microsoft-calendar.svg b/src/assets/icons/microsoft-calendar.svg
new file mode 100644
index 000000000..e6bd9b7ea
--- /dev/null
+++ b/src/assets/icons/microsoft-calendar.svg
@@ -0,0 +1,22 @@
+<?xml version="1.0" encoding="utf-8"?>
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 200 200">
+ <defs>
+ <linearGradient id="mcal-tile" x1="0" y1="0" x2="0" y2="1">
+ <stop offset="0" stop-color="#2E9BE6"/>
+ <stop offset="1" stop-color="#0F6CBD"/>
+ </linearGradient>
+ </defs>
+ <rect x="14" y="14" width="172" height="172" rx="38" fill="url(#mcal-tile)"/>
+ <rect x="52" y="64" width="96" height="84" rx="10" fill="#FFFFFF"/>
+ <path d="M52 74a10 10 0 0 1 10-10h76a10 10 0 0 1 10 10v14H52z" fill="#0A4E8C"/>
+ <rect x="72" y="50" width="8" height="24" rx="4" fill="#FFFFFF"/>
+ <rect x="120" y="50" width="8" height="24" rx="4" fill="#FFFFFF"/>
+ <g fill="#0F6CBD" opacity="0.9">
+ <rect x="66" y="100" width="16" height="12" rx="2"/>
+ <rect x="92" y="100" width="16" height="12" rx="2"/>
+ <rect x="118" y="100" width="16" height="12" rx="2"/>
+ <rect x="66" y="122" width="16" height="12" rx="2"/>
+ <rect x="92" y="122" width="16" height="12" rx="2"/>
+ <rect x="118" y="122" width="16" height="12" rx="2"/>
+ </g>
+</svg>
diff --git a/src/components/IntegrationsView.tsx b/src/components/IntegrationsView.tsx
index f64d12899..e30dadcf6 100644
--- a/src/components/IntegrationsView.tsx
+++ b/src/components/IntegrationsView.tsx
@@ -17,10 +17,12 @@ import {
import { useSettingsStore } from "../stores/settingsStore";
import { useSystemAudioPermission } from "../hooks/useSystemAudioPermission";
import { canManageSystemAudioInApp } from "../utils/systemAudioAccess";
+import type { CalendarAccount } from "../types/calendar";
import ApiKeysSection from "./ApiKeysSection";
import CliIntegrationCard from "./CliIntegrationCard";
import McpIntegrationCard from "./McpIntegrationCard";
import googleCalendarIcon from "../assets/icons/google-calendar.svg";
+import microsoftCalendarIcon from "../assets/icons/microsoft-calendar.svg";
import appleCalendarIcon from "../assets/icons/apple-calendar.svg";
const API_DOCS_URL = "https://docs.openwhispr.com/api/overview";
@@ -38,6 +40,124 @@ function SectionLabel({ children }: { children: React.ReactNode }) {
);
}
+interface ProviderRowProps {
+ icon: string;
+ i18nKey: string;
+ connected: boolean;
+ isConnecting: boolean;
+ onConnect: () => void;
+}
+
+function ProviderRow({ icon, i18nKey, connected, isConnecting, onConnect }: ProviderRowProps) {
+ const { t } = useTranslation();
+ return (
+ <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={icon} 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(`${i18nKey}.title`)}</p>
+ <Badge variant="outline" className="text-[10px] px-1.5 py-0 font-normal">
+ {t(`${i18nKey}.optional`)}
+ </Badge>
+ </div>
+ <p className="text-xs text-muted-foreground/70 mt-0.5 leading-relaxed">
+ {t(`${i18nKey}.description`)}
+ </p>
+ </div>
+ {connected ? (
+ <Badge variant="success" className="shrink-0">
+ {t(`${i18nKey}.connected`)}
+ </Badge>
+ ) : (
+ <Button size="sm" onClick={onConnect} disabled={isConnecting} className="shrink-0">
+ {isConnecting ? (
+ <Loader2 className="h-3.5 w-3.5 animate-spin" />
+ ) : (
+ t(`${i18nKey}.connect`)
+ )}
+ </Button>
+ )}
+ </div>
+ </SettingsPanelRow>
+ );
+}
+
+interface CalendarAccountRowsProps {
+ i18nKey: string;
+ accounts: CalendarAccount[];
+ disconnectingEmail: string | null;
+ onUnlink: (email: string) => void;
+ primaryOnly: boolean;
+ onPrimaryOnlyChange: (value: boolean) => void;
+ isConnecting: boolean;
+ onAddAnother: () => void;
+}
+
+function CalendarAccountRows({
+ i18nKey,
+ accounts,
+ disconnectingEmail,
+ onUnlink,
+ primaryOnly,
+ onPrimaryOnlyChange,
+ isConnecting,
+ onAddAnother,
+}: CalendarAccountRowsProps) {
+ const { t } = useTranslation();
+ if (accounts.length === 0) return null;
+ return (
+ <>
+ {accounts.map((account) => (
+ <SettingsPanelRow key={account.email}>
+ <div className="group flex items-center gap-3 pl-12">
+ <Mail className="h-3.5 w-3.5 text-muted-foreground/50 shrink-0" />
+ <span className="text-xs text-muted-foreground truncate flex-1">{account.email}</span>
+ <button
+ onClick={() => onUnlink(account.email)}
+ disabled={disconnectingEmail === account.email}
+ className="opacity-0 group-hover:opacity-100 p-1 rounded-md text-muted-foreground hover:text-destructive hover:bg-destructive/10 transition-all disabled:opacity-50"
+ aria-label={t(`${i18nKey}.disconnect`)}
+ >
+ {disconnectingEmail === account.email ? (
+ <Loader2 className="h-3.5 w-3.5 animate-spin" />
+ ) : (
+ <Unlink className="h-3.5 w-3.5" />
+ )}
+ </button>
+ </div>
+ </SettingsPanelRow>
+ ))}
+
+ <SettingsPanelRow>
+ <SettingsRow
+ label={t(`${i18nKey}.primaryOnly`)}
+ description={t(`${i18nKey}.primaryOnlyDescription`)}
+ >
+ <Toggle checked={primaryOnly} onChange={onPrimaryOnlyChange} />
+ </SettingsRow>
+ </SettingsPanelRow>
+
+ <SettingsPanelRow>
+ <button
+ onClick={onAddAnother}
+ disabled={isConnecting}
+ className="flex items-center gap-2 pl-12 text-xs text-primary hover:text-primary/80 transition-colors disabled:opacity-50"
+ >
+ {isConnecting ? (
+ <Loader2 className="h-3.5 w-3.5 animate-spin" />
+ ) : (
+ <Plus className="h-3.5 w-3.5" />
+ )}
+ {t(`${i18nKey}.addAnother`)}
+ </button>
+ </SettingsPanelRow>
+ </>
+ );
+}
+
export default function IntegrationsView({ isPaid, onUpgrade }: IntegrationsViewProps) {
const { t } = useTranslation();
const {
@@ -45,12 +165,19 @@ export default function IntegrationsView({ isPaid, onUpgrade }: IntegrationsView
setGcalAccounts,
gcalPrimaryOnly,
setGcalPrimaryOnly,
+ mcalAccounts,
+ setMcalAccounts,
+ mcalPrimaryOnly,
+ setMcalPrimaryOnly,
appleCalendarConnected,
setAppleCalendarConnected,
} = useSettingsStore();
const [isConnecting, setIsConnecting] = useState(false);
const [disconnectingEmail, setDisconnectingEmail] = useState<string | null>(null);
const [confirmDisconnectEmail, setConfirmDisconnectEmail] = useState<string | null>(null);
+ const [isMsConnecting, setIsMsConnecting] = useState(false);
+ const [msDisconnectingEmail, setMsDisconnectingEmail] = useState<string | null>(null);
+ const [confirmMsDisconnectEmail, setConfirmMsDisconnectEmail] = useState<string | null>(null);
const [showPermissionDialog, setShowPermissionDialog] = useState(false);
const [isAppleConnecting, setIsAppleConnecting] = useState(false);
const [appleSourceNames, setAppleSourceNames] = useState<string[]>([]);
@@ -79,6 +206,22 @@ export default function IntegrationsView({ isPaid, onUpgrade }: IntegrationsView
}
}, [setGcalAccounts]);
+ const startMicrosoftOAuth = useCallback(async () => {
+ setIsMsConnecting(true);
+ try {
+ const result = await window.electronAPI?.mcalStartOAuth?.();
+ if (result?.success && result.email) {
+ const current = useSettingsStore.getState().mcalAccounts;
+ setMcalAccounts([
+ ...current.filter((a) => a.email !== result.email),
+ { email: result.email },
+ ]);
+ }
+ } finally {
+ setIsMsConnecting(false);
+ }
+ }, [setMcalAccounts]);
+
const connectAppleCalendar = useCallback(async () => {
setIsAppleConnecting(true);
try {
@@ -114,6 +257,11 @@ export default function IntegrationsView({ isPaid, onUpgrade }: IntegrationsView
[withSystemAudioGate, startOAuth]
);
+ const handleMicrosoftConnect = useCallback(
+ () => withSystemAudioGate(startMicrosoftOAuth),
+ [withSystemAudioGate, startMicrosoftOAuth]
+ );
+
const handleAppleConnect = useCallback(
() => withSystemAudioGate(connectAppleCalendar),
[withSystemAudioGate, connectAppleCalendar]
@@ -139,6 +287,20 @@ export default function IntegrationsView({ isPaid, onUpgrade }: IntegrationsView
[setGcalAccounts]
);
+ const handleMicrosoftDisconnect = useCallback(
+ async (email: string) => {
+ setMsDisconnectingEmail(email);
+ try {
+ await window.electronAPI?.mcalDisconnect?.(email);
+ const current = useSettingsStore.getState().mcalAccounts;
+ setMcalAccounts(current.filter((a) => a.email !== email));
+ } finally {
+ setMsDisconnectingEmail(null);
+ }
+ },
+ [setMcalAccounts]
+ );
+
useEffect(() => {
const unsub = window.electronAPI?.onGcalConnectionChanged?.(
(data: {
@@ -160,6 +322,15 @@ export default function IntegrationsView({ isPaid, onUpgrade }: IntegrationsView
return () => unsub?.();
}, [setGcalAccounts]);
+ useEffect(() => {
+ const unsub = window.electronAPI?.onMcalConnectionChanged?.(
+ (data: { accounts?: Array<{ email: string }> }) => {
+ if (data.accounts) setMcalAccounts(data.accounts);
+ }
+ );
+ return () => unsub?.();
+ }, [setMcalAccounts]);
+
useEffect(() => {
if (!isMac) return;
window.electronAPI?.acalGetConnectionStatus?.().then((status) => {
@@ -185,137 +356,50 @@ export default function IntegrationsView({ isPaid, onUpgrade }: IntegrationsView
<div>
<SectionLabel>{t("integrations.sections.calendar")}</SectionLabel>
<SettingsPanel>
- <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={googleCalendarIcon} 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.googleCalendar.title")}
- </p>
- <Badge variant="outline" className="text-[10px] px-1.5 py-0 font-normal">
- {t("integrations.googleCalendar.optional")}
- </Badge>
- </div>
- <p className="text-xs text-muted-foreground/70 mt-0.5 leading-relaxed">
- {t("integrations.googleCalendar.description")}
- </p>
- </div>
- {!hasAccounts && (
- <Button
- size="sm"
- onClick={handleConnect}
- disabled={isConnecting}
- className="shrink-0"
- >
- {isConnecting ? (
- <Loader2 className="h-3.5 w-3.5 animate-spin" />
- ) : (
- t("integrations.googleCalendar.connect")
- )}
- </Button>
- )}
- {hasAccounts && (
- <Badge variant="success" className="shrink-0">
- {t("integrations.googleCalendar.connected")}
- </Badge>
- )}
- </div>
- </SettingsPanelRow>
-
- {hasAccounts &&
- gcalAccounts.map((account) => (
- <SettingsPanelRow key={account.email}>
- <div className="group flex items-center gap-3 pl-12">
- <Mail className="h-3.5 w-3.5 text-muted-foreground/50 shrink-0" />
- <span className="text-xs text-muted-foreground truncate flex-1">
- {account.email}
- </span>
- <button
- onClick={() => setConfirmDisconnectEmail(account.email)}
- disabled={disconnectingEmail === account.email}
- className="opacity-0 group-hover:opacity-100 p-1 rounded-md text-muted-foreground hover:text-destructive hover:bg-destructive/10 transition-all disabled:opacity-50"
- aria-label={t("integrations.googleCalendar.disconnect")}
- >
- {disconnectingEmail === account.email ? (
- <Loader2 className="h-3.5 w-3.5 animate-spin" />
- ) : (
- <Unlink className="h-3.5 w-3.5" />
- )}
- </button>
- </div>
- </SettingsPanelRow>
- ))}
-
- {hasAccounts && (
- <SettingsPanelRow>
- <SettingsRow
- label={t("integrations.googleCalendar.primaryOnly")}
- description={t("integrations.googleCalendar.primaryOnlyDescription")}
- >
- <Toggle checked={gcalPrimaryOnly} onChange={setGcalPrimaryOnly} />
- </SettingsRow>
- </SettingsPanelRow>
- )}
+ <ProviderRow
+ icon={googleCalendarIcon}
+ i18nKey="integrations.googleCalendar"
+ connected={hasAccounts}
+ isConnecting={isConnecting}
+ onConnect={handleConnect}
+ />
+ <CalendarAccountRows
+ i18nKey="integrations.googleCalendar"
+ accounts={gcalAccounts}
+ disconnectingEmail={disconnectingEmail}
+ onUnlink={setConfirmDisconnectEmail}
+ primaryOnly={gcalPrimaryOnly}
+ onPrimaryOnlyChange={setGcalPrimaryOnly}
+ isConnecting={isConnecting}
+ onAddAnother={handleConnect}
+ />
- {hasAccounts && (
- <SettingsPanelRow>
- <button
- onClick={handleConnect}
- disabled={isConnecting}
- className="flex items-center gap-2 pl-12 text-xs text-primary hover:text-primary/80 transition-colors disabled:opacity-50"
- >
- {isConnecting ? (
- <Loader2 className="h-3.5 w-3.5 animate-spin" />
- ) : (
- <Plus className="h-3.5 w-3.5" />
- )}
- {t("integrations.googleCalendar.addAnother")}
- </button>
- </SettingsPanelRow>
- )}
+ <ProviderRow
+ icon={microsoftCalendarIcon}
+ i18nKey="integrations.microsoftCalendar"
+ connected={mcalAccounts.length > 0}
+ isConnecting={isMsConnecting}
+ onConnect={handleMicrosoftConnect}
+ />
+ <CalendarAccountRows
+ i18nKey="integrations.microsoftCalendar"
+ accounts={mcalAccounts}
+ disconnectingEmail={msDisconnectingEmail}
+ onUnlink={setConfirmMsDisconnectEmail}
+ primaryOnly={mcalPrimaryOnly}
+ onPrimaryOnlyChange={setMcalPrimaryOnly}
+ isConnecting={isMsConnecting}
+ onAddAnother={handleMicrosoftConnect}
+ />
{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>
+ <ProviderRow
+ icon={appleCalendarIcon}
+ i18nKey="integrations.appleCalendar"
+ connected={appleCalendarConnected}
+ isConnecting={isAppleConnecting}
+ onConnect={handleAppleConnect}
+ />
)}
{isMac && appleCalendarConnected && (
@@ -435,6 +519,22 @@ export default function IntegrationsView({ isPaid, onUpgrade }: IntegrationsView
}}
/>
+ <ConfirmDialog
+ open={!!confirmMsDisconnectEmail}
+ onOpenChange={(open) => {
+ if (!open) setConfirmMsDisconnectEmail(null);
+ }}
+ title={t("integrations.microsoftCalendar.disconnectConfirm", {
+ email: confirmMsDisconnectEmail,
+ })}
+ description={t("integrations.microsoftCalendar.disconnectDescription")}
+ confirmText={t("integrations.microsoftCalendar.disconnect")}
+ variant="destructive"
+ onConfirm={() => {
+ if (confirmMsDisconnectEmail) handleMicrosoftDisconnect(confirmMsDisconnectEmail);
+ }}
+ />
+
<ConfirmDialog
open={showPermissionDialog}
onOpenChange={setShowPermissionDialog}
diff --git a/src/helpers/calendarSyncInterval.js b/src/helpers/calendarSyncInterval.js
new file mode 100644
index 000000000..1cb286b60
--- /dev/null
+++ b/src/helpers/calendarSyncInterval.js
@@ -0,0 +1,86 @@
+const debugLogger = require("./debugLogger");
+
+const FOCUS_SYNC_THROTTLE_MS = 30 * 1000;
+
+// Interval runner for calendar REST providers: exponential backoff on
+// consecutive failures (intervalMs × 2 per failure, capped at maxIntervalMs)
+// and a 30s throttle on focus-triggered syncs.
+class CalendarSyncInterval {
+ constructor(syncFn, { intervalMs, maxIntervalMs, logScope }) {
+ this.syncFn = syncFn;
+ this.intervalMs = intervalMs;
+ this.maxIntervalMs = maxIntervalMs;
+ this.logScope = logScope;
+ this.timer = null;
+ this._consecutiveFailures = 0;
+ this._lastFocusSync = 0;
+ }
+
+ start() {
+ this._consecutiveFailures = 0;
+ this._schedule();
+ }
+
+ stop() {
+ if (this.timer) {
+ clearInterval(this.timer);
+ this.timer = null;
+ }
+ }
+
+ // Resets the backoff after an out-of-band successful sync.
+ notifySuccess() {
+ if (this._consecutiveFailures > 0) {
+ this._consecutiveFailures = 0;
+ this._schedule();
+ }
+ }
+
+ syncOnFocus() {
+ const now = Date.now();
+ if (now - this._lastFocusSync < FOCUS_SYNC_THROTTLE_MS) return;
+ this._lastFocusSync = now;
+
+ this.syncFn()
+ .then(() => this.notifySuccess())
+ .catch((err) =>
+ debugLogger.error("Focus-triggered sync failed", { error: err.message }, this.logScope)
+ );
+ }
+
+ _schedule() {
+ if (this.timer) clearInterval(this.timer);
+
+ const interval = this._getInterval();
+ debugLogger.info(
+ "Calendar sync scheduled",
+ { intervalMs: interval, consecutiveFailures: this._consecutiveFailures },
+ this.logScope
+ );
+
+ this.timer = setInterval(() => {
+ this.syncFn()
+ .then(() => this.notifySuccess())
+ .catch((err) => {
+ this._consecutiveFailures++;
+ debugLogger.error(
+ "Calendar sync failed",
+ {
+ error: err.message,
+ consecutiveFailures: this._consecutiveFailures,
+ nextIntervalMs: this._getInterval(),
+ },
+ this.logScope
+ );
+ this._schedule();
+ });
+ }, interval);
+ }
+
+ _getInterval() {
+ if (this._consecutiveFailures === 0) return this.intervalMs;
+ return Math.min(this.intervalMs * Math.pow(2, this._consecutiveFailures), this.maxIntervalMs);
+ }
+}
+
+module.exports = CalendarSyncInterval;
diff --git a/src/helpers/database.js b/src/helpers/database.js
index 7397d23ca..fab51dcd4 100644
--- a/src/helpers/database.js
+++ b/src/helpers/database.js
@@ -65,26 +65,33 @@ 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.
+// A meeting synced by both a REST provider (Google/Microsoft) and Apple
+// (Calendar.app mirrors the same accounts) would double-fire reminders and
+// duplicate UI rows; suppress the Apple copy when a REST row occupies the same
+// time slot + title (REST rows have richer conference data). datetime()
+// normalizes the providers' timestamp formats (Google stores offset-form
+// RFC3339, Apple/Microsoft store UTC "Z" form). REST rows are never collapsed
+// — Google and Microsoft are never mirrors of each other.
function dedupedEventsQuery(where) {
return `SELECT * FROM (
- SELECT *, MAX(provider = 'google') OVER (
+ SELECT *, MAX(provider != 'apple') OVER (
PARTITION BY datetime(start_time), datetime(end_time), COALESCE(summary, '')
- ) AS has_google
+ ) AS has_synced
FROM calendar_events
WHERE ${where}
- ) WHERE provider = 'google' OR has_google = 0 ORDER BY datetime(start_time) ASC`;
+ ) WHERE provider != 'apple' OR has_synced = 0 ORDER BY datetime(start_time) ASC`;
}
-function stripDedupeColumn({ has_google: _hasGoogle, ...event }) {
+function stripDedupeColumn({ has_synced: _hasSynced, ...event }) {
return event;
}
+// Whitelist for provider-scoped SQL against the per-provider calendars tables.
+const CALENDARS_TABLE_BY_PROVIDER = {
+ google: "google_calendars",
+ microsoft: "microsoft_calendars",
+};
+
class DatabaseManager {
constructor() {
this.db = null;
@@ -488,6 +495,33 @@ class DatabaseManager {
if (!err.message.includes("duplicate column")) throw err;
}
+ this.db.exec(`
+ CREATE TABLE IF NOT EXISTS microsoft_calendar_tokens (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ microsoft_email TEXT NOT NULL UNIQUE,
+ access_token TEXT NOT NULL,
+ refresh_token TEXT NOT NULL,
+ expires_at INTEGER NOT NULL,
+ scope TEXT NOT NULL,
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
+ updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
+ )
+ `);
+
+ this.db.exec(`
+ CREATE TABLE IF NOT EXISTS microsoft_calendars (
+ id TEXT PRIMARY KEY,
+ summary TEXT NOT NULL,
+ background_color TEXT,
+ is_selected INTEGER NOT NULL DEFAULT 1,
+ is_primary INTEGER NOT NULL DEFAULT 0,
+ sync_token TEXT,
+ sync_token_expires_at INTEGER,
+ account_email TEXT,
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP
+ )
+ `);
+
this.db.exec(`
CREATE TABLE IF NOT EXISTS calendar_events (
id TEXT PRIMARY KEY,
@@ -3482,25 +3516,201 @@ class DatabaseManager {
}
}
- removeEventsFromDeselectedCalendars() {
+ removeEventsFromDeselectedCalendars(provider) {
try {
if (!this.db) throw new Error("Database not initialized");
+ const calendarsTable = CALENDARS_TABLE_BY_PROVIDER[provider];
+ if (!calendarsTable) throw new Error(`Unknown calendar provider: ${provider}`);
this.db
.prepare(
- "DELETE FROM calendar_events WHERE provider = 'google' AND calendar_id NOT IN (SELECT id FROM google_calendars WHERE is_selected = 1)"
+ `DELETE FROM calendar_events WHERE provider = ? AND calendar_id NOT IN (SELECT id FROM ${calendarsTable} WHERE is_selected = 1)`
)
- .run();
+ .run(provider);
return { success: true };
} catch (error) {
debugLogger.error(
"Error removing events from deselected calendars",
{ error: error.message },
- "gcal"
+ provider === "microsoft" ? "mcal" : "gcal"
+ );
+ throw error;
+ }
+ }
+
+ saveMicrosoftTokens(tokens) {
+ try {
+ if (!this.db) throw new Error("Database not initialized");
+ const stmt = this.db.prepare(
+ `INSERT INTO microsoft_calendar_tokens (microsoft_email, access_token, refresh_token, expires_at, scope)
+ VALUES (?, ?, ?, ?, ?)
+ ON CONFLICT(microsoft_email) DO UPDATE SET
+ access_token = excluded.access_token,
+ refresh_token = excluded.refresh_token,
+ expires_at = excluded.expires_at,
+ scope = excluded.scope,
+ updated_at = CURRENT_TIMESTAMP`
+ );
+ stmt.run(
+ tokens.microsoft_email,
+ tokens.access_token,
+ tokens.refresh_token,
+ tokens.expires_at,
+ tokens.scope
+ );
+ return { success: true };
+ } catch (error) {
+ debugLogger.error("Error saving Microsoft tokens", { error: error.message }, "mcal");
+ throw error;
+ }
+ }
+
+ getMicrosoftTokensByEmail(email) {
+ try {
+ if (!this.db) throw new Error("Database not initialized");
+ return (
+ this.db
+ .prepare("SELECT * FROM microsoft_calendar_tokens WHERE microsoft_email = ?")
+ .get(email) || null
+ );
+ } catch (error) {
+ debugLogger.error(
+ "Error getting Microsoft tokens by email",
+ { error: error.message },
+ "mcal"
+ );
+ throw error;
+ }
+ }
+
+ getMicrosoftAccounts() {
+ try {
+ if (!this.db) throw new Error("Database not initialized");
+ return this.db
+ .prepare(
+ "SELECT microsoft_email AS email FROM microsoft_calendar_tokens ORDER BY created_at ASC"
+ )
+ .all();
+ } catch (error) {
+ debugLogger.error("Error getting Microsoft accounts", { error: error.message }, "mcal");
+ throw error;
+ }
+ }
+
+ removeMicrosoftAccount(email) {
+ try {
+ if (!this.db) throw new Error("Database not initialized");
+ const transaction = this.db.transaction(() => {
+ const calendarIds = this.db
+ .prepare("SELECT id FROM microsoft_calendars WHERE account_email = ?")
+ .all(email)
+ .map((c) => c.id);
+ if (calendarIds.length > 0) {
+ const placeholders = calendarIds.map(() => "?").join(", ");
+ this.db
+ .prepare(`DELETE FROM calendar_events WHERE calendar_id IN (${placeholders})`)
+ .run(...calendarIds);
+ }
+ this.db.prepare("DELETE FROM microsoft_calendars WHERE account_email = ?").run(email);
+ this.db
+ .prepare("DELETE FROM microsoft_calendar_tokens WHERE microsoft_email = ?")
+ .run(email);
+ });
+ transaction();
+ return { success: true };
+ } catch (error) {
+ debugLogger.error("Error removing Microsoft account", { error: error.message }, "mcal");
+ throw error;
+ }
+ }
+
+ saveMicrosoftCalendars(calendars, accountEmail = null) {
+ try {
+ if (!this.db) throw new Error("Database not initialized");
+ const stmt = this.db.prepare(
+ `INSERT INTO microsoft_calendars (id, summary, background_color, account_email, is_primary)
+ VALUES (?, ?, ?, ?, ?)
+ ON CONFLICT(id) DO UPDATE SET
+ summary = excluded.summary,
+ background_color = excluded.background_color,
+ account_email = excluded.account_email,
+ is_primary = excluded.is_primary`
+ );
+ for (const cal of calendars) {
+ stmt.run(
+ cal.id,
+ cal.summary,
+ cal.background_color || null,
+ accountEmail,
+ cal.is_primary ? 1 : 0
+ );
+ }
+ return { success: true };
+ } catch (error) {
+ debugLogger.error("Error saving Microsoft calendars", { error: error.message }, "mcal");
+ throw error;
+ }
+ }
+
+ applyMicrosoftPrimaryOnlyToSelection(primaryOnly) {
+ try {
+ if (!this.db) throw new Error("Database not initialized");
+ this.db
+ .prepare(
+ "UPDATE microsoft_calendars SET is_selected = CASE WHEN ? = 1 THEN is_primary ELSE 1 END"
+ )
+ .run(primaryOnly ? 1 : 0);
+ return { success: true };
+ } catch (error) {
+ debugLogger.error("Error applying primary-only selection", { error: error.message }, "mcal");
+ throw error;
+ }
+ }
+
+ getSelectedMicrosoftCalendars() {
+ try {
+ if (!this.db) throw new Error("Database not initialized");
+ return this.db.prepare("SELECT * FROM microsoft_calendars WHERE is_selected = 1").all();
+ } catch (error) {
+ debugLogger.error(
+ "Error getting selected Microsoft calendars",
+ { error: error.message },
+ "mcal"
);
throw error;
}
}
+ updateMicrosoftCalendarSyncToken(calendarId, syncToken, expiresAt) {
+ try {
+ if (!this.db) throw new Error("Database not initialized");
+ this.db
+ .prepare(
+ "UPDATE microsoft_calendars SET sync_token = ?, sync_token_expires_at = ? WHERE id = ?"
+ )
+ .run(syncToken, expiresAt, calendarId);
+ return { success: true };
+ } catch (error) {
+ debugLogger.error("Error updating sync token", { error: error.message }, "mcal");
+ throw error;
+ }
+ }
+
+ clearMicrosoftCalendarData() {
+ try {
+ if (!this.db) throw new Error("Database not initialized");
+ const transaction = this.db.transaction(() => {
+ this.db.prepare("DELETE FROM calendar_events WHERE provider = 'microsoft'").run();
+ this.db.prepare("DELETE FROM microsoft_calendars").run();
+ this.db.prepare("DELETE FROM microsoft_calendar_tokens").run();
+ });
+ transaction();
+ return { success: true };
+ } catch (error) {
+ debugLogger.error("Error clearing calendar data", { error: error.message }, "mcal");
+ throw error;
+ }
+ }
+
saveAppleCalendars(calendars) {
try {
if (!this.db) throw new Error("Database not initialized");
diff --git a/src/helpers/googleCalendarManager.js b/src/helpers/googleCalendarManager.js
index 96df97e3c..29834a836 100644
--- a/src/helpers/googleCalendarManager.js
+++ b/src/helpers/googleCalendarManager.js
@@ -1,6 +1,7 @@
const { net } = require("electron");
const debugLogger = require("./debugLogger");
const GoogleCalendarOAuth = require("./googleCalendarOAuth");
+const CalendarSyncInterval = require("./calendarSyncInterval");
const { broadcastToWindows } = require("./windowBroadcast");
const CALENDAR_API_BASE = "https://www.googleapis.com/calendar/v3";
@@ -12,11 +13,11 @@ class GoogleCalendarManager {
this.reminderScheduler = reminderScheduler;
this.oauth = new GoogleCalendarOAuth(databaseManager);
this.accounts = new Map();
- this.syncInterval = null;
- this.SYNC_INTERVAL_MS = 2 * 60 * 1000;
- this._consecutiveFailures = 0;
- this._lastFocusSync = 0;
this.primaryOnly = true;
+ this.syncRunner = new CalendarSyncInterval(
+ () => this.syncEvents().then(() => this.reminderScheduler.scheduleNextMeeting()),
+ { intervalMs: 2 * 60 * 1000, maxIntervalMs: 30 * 60 * 1000, logScope: "gcal" }
+ );
}
start() {
@@ -25,22 +26,16 @@ class GoogleCalendarManager {
this.fetchCalendars()
.then(() => this.syncEvents())
- .then(() => {
- this.reminderScheduler.scheduleNextMeeting();
- this._consecutiveFailures = 0;
- })
+ .then(() => this.reminderScheduler.scheduleNextMeeting())
.catch((err) =>
debugLogger.error("Initial calendar sync failed", { error: err.message }, "gcal")
);
- this._startSyncInterval();
+ this.syncRunner.start();
}
stop() {
- if (this.syncInterval) {
- clearInterval(this.syncInterval);
- this.syncInterval = null;
- }
+ this.syncRunner.stop();
}
isConnected() {
@@ -69,9 +64,8 @@ class GoogleCalendarManager {
await this.fetchCalendars(result.email);
await this.syncEvents();
- this._consecutiveFailures = 0;
this.reminderScheduler.scheduleNextMeeting();
- this._startSyncInterval();
+ this.syncRunner.start();
this._broadcastAccountsChanged();
return result;
@@ -136,7 +130,7 @@ class GoogleCalendarManager {
}
this.databaseManager.applyPrimaryOnlyToSelection(this.primaryOnly);
- this.databaseManager.removeEventsFromDeselectedCalendars();
+ this.databaseManager.removeEventsFromDeselectedCalendars("google");
return allCalendars;
}
@@ -255,30 +249,13 @@ class GoogleCalendarManager {
onWakeFromSleep() {
this.syncEvents()
- .then(() => {
- this._consecutiveFailures = 0;
- this._restartSyncInterval();
- })
+ .then(() => this.syncRunner.notifySuccess())
.catch((err) => debugLogger.error("Post-wake sync failed", { error: err.message }, "gcal"));
}
syncOnFocus() {
if (!this.isConnected()) return;
- const now = Date.now();
- if (now - this._lastFocusSync < 30000) return;
- this._lastFocusSync = now;
-
- this.syncEvents()
- .then(() => {
- this.reminderScheduler.scheduleNextMeeting();
- if (this._consecutiveFailures > 0) {
- this._consecutiveFailures = 0;
- this._restartSyncInterval();
- }
- })
- .catch((err) =>
- debugLogger.error("Focus-triggered sync failed", { error: err.message }, "gcal")
- );
+ this.syncRunner.syncOnFocus();
}
getCalendars() {
@@ -288,7 +265,7 @@ class GoogleCalendarManager {
async setCalendarSelection(calendarId, isSelected) {
this.databaseManager.updateCalendarSelection(calendarId, isSelected);
await this.syncEvents();
- this._consecutiveFailures = 0;
+ this.syncRunner.notifySuccess();
this.reminderScheduler.scheduleNextMeeting();
}
@@ -320,50 +297,6 @@ class GoogleCalendarManager {
return Array.from(this.accounts.keys());
}
- _startSyncInterval() {
- if (this.syncInterval) clearInterval(this.syncInterval);
-
- const interval = this._getSyncInterval();
- debugLogger.info(
- "Calendar sync scheduled",
- { intervalMs: interval, consecutiveFailures: this._consecutiveFailures },
- "gcal"
- );
-
- this.syncInterval = setInterval(() => {
- this.syncEvents()
- .then(() => {
- this.reminderScheduler.scheduleNextMeeting();
- if (this._consecutiveFailures > 0) {
- this._consecutiveFailures = 0;
- this._restartSyncInterval();
- }
- })
- .catch((err) => {
- this._consecutiveFailures++;
- debugLogger.error(
- "Calendar sync failed",
- {
- error: err.message,
- consecutiveFailures: this._consecutiveFailures,
- nextIntervalMs: this._getSyncInterval(),
- },
- "gcal"
- );
- this._restartSyncInterval();
- });
- }, interval);
- }
-
- _getSyncInterval() {
- if (this._consecutiveFailures === 0) return this.SYNC_INTERVAL_MS;
- return Math.min(this.SYNC_INTERVAL_MS * Math.pow(2, this._consecutiveFailures), 30 * 60 * 1000);
- }
-
- _restartSyncInterval() {
- this._startSyncInterval();
- }
-
_broadcastAccountsChanged() {
const accounts = this.getAccounts();
broadcastToWindows("gcal-connection-changed", { accounts });
diff --git a/src/helpers/googleCalendarOAuth.js b/src/helpers/googleCalendarOAuth.js
index 352a2f5da..e1b1b98a9 100644
--- a/src/helpers/googleCalendarOAuth.js
+++ b/src/helpers/googleCalendarOAuth.js
@@ -1,19 +1,10 @@
-const http = require("http");
-const crypto = require("crypto");
-const { net, shell } = require("electron");
+const { net } = require("electron");
+const { runOAuthLoopbackFlow, OAuthFlowError } = require("./oauthLoopbackFlow");
const GOOGLE_AUTH_URL = "https://accounts.google.com/o/oauth2/v2/auth";
const GOOGLE_TOKEN_URL = "https://oauth2.googleapis.com/token";
const CALENDAR_SCOPE =
"openid email https://www.googleapis.com/auth/calendar.events.readonly https://www.googleapis.com/auth/calendar.calendarlist.readonly";
-const OAUTH_TIMEOUT_MS = 120000;
-const DEFAULT_DESKTOP_CALLBACK_URL = "https://openwhispr.com/auth/desktop-callback";
-
-const PROTOCOL_BY_CHANNEL = {
- development: "openwhispr-dev",
- staging: "openwhispr-staging",
- production: "openwhispr",
-};
class GoogleCalendarOAuth {
constructor(databaseManager) {
@@ -28,114 +19,10 @@ class GoogleCalendarOAuth {
return process.env.GOOGLE_CALENDAR_CLIENT_SECRET;
}
- _getDesktopCallbackUrl() {
- return process.env.VITE_OPENWHISPR_OAUTH_CALLBACK_URL || DEFAULT_DESKTOP_CALLBACK_URL;
- }
-
- _getProtocol() {
- const channel = process.env.OPENWHISPR_CHANNEL || "production";
- return PROTOCOL_BY_CHANNEL[channel] || PROTOCOL_BY_CHANNEL.production;
- }
-
- _buildCallbackRedirect(params) {
- const url = new URL(this._getDesktopCallbackUrl());
- url.searchParams.set("protocol", this._getProtocol());
- for (const [key, value] of Object.entries(params)) {
- url.searchParams.set(key, value);
- }
- return url.toString();
- }
-
- _redirect(res, params) {
- res.writeHead(302, { Location: this._buildCallbackRedirect(params) });
- res.end();
- }
-
startOAuthFlow() {
- return new Promise((resolve, reject) => {
- const codeVerifier = crypto.randomBytes(32).toString("base64url").slice(0, 43);
- const codeChallenge = crypto.createHash("sha256").update(codeVerifier).digest("base64url");
- const state = crypto.randomBytes(32).toString("hex");
-
- const server = http.createServer(async (req, res) => {
- try {
- const url = new URL(req.url, `http://127.0.0.1`);
- const returnedState = url.searchParams.get("state");
- const code = url.searchParams.get("code");
- const error = url.searchParams.get("error");
-
- if (error) {
- this._redirect(res, { gcal_error: error });
- cleanup();
- reject(new Error(`OAuth error: ${error}`));
- return;
- }
-
- if (!code || returnedState !== state) {
- res.writeHead(400, { "Content-Type": "text/html" });
- res.end("<html><body><h3>Invalid request.</h3></body></html>");
- return;
- }
-
- const redirectUri = `http://127.0.0.1:${server.address().port}`;
- const tokenData = await this.exchangeCodeForTokens(code, redirectUri, codeVerifier);
-
- if (tokenData.error) {
- this._redirect(res, { gcal_error: "token_exchange_failed" });
- cleanup();
- reject(
- new Error(`Token exchange failed: ${tokenData.error_description || tokenData.error}`)
- );
- return;
- }
-
- let email = null;
- if (tokenData.id_token) {
- try {
- const payload = JSON.parse(
- Buffer.from(tokenData.id_token.split(".")[1], "base64url").toString()
- );
- email = payload.email;
- } catch {}
- }
-
- if (!email) {
- this._redirect(res, { gcal_error: "no_email" });
- cleanup();
- reject(new Error("Could not extract email from Google OAuth response"));
- return;
- }
-
- const expiresAt = Date.now() + tokenData.expires_in * 1000;
- this.databaseManager.saveGoogleTokens({
- google_email: email,
- access_token: tokenData.access_token,
- refresh_token: tokenData.refresh_token,
- expires_at: expiresAt,
- scope: tokenData.scope || CALENDAR_SCOPE,
- });
-
- this._redirect(res, { gcal_connected: "true" });
- cleanup();
- resolve({ success: true, email });
- } catch (err) {
- this._redirect(res, { gcal_error: "server_error" });
- cleanup();
- reject(err);
- }
- });
-
- let timeoutId;
-
- const cleanup = () => {
- clearTimeout(timeoutId);
- server.close();
- };
-
- server.listen(0, "127.0.0.1", () => {
- const port = server.address().port;
- const redirectUri = `http://127.0.0.1:${port}`;
-
+ return runOAuthLoopbackFlow({
+ errorParam: "gcal_error",
+ buildAuthUrl: (redirectUri, state, codeChallenge) => {
const params = new URLSearchParams({
client_id: this.getClientId(),
redirect_uri: redirectUri,
@@ -147,19 +34,45 @@ class GoogleCalendarOAuth {
code_challenge: codeChallenge,
code_challenge_method: "S256",
});
+ return `${GOOGLE_AUTH_URL}?${params.toString()}`;
+ },
+ handleCallback: async (code, redirectUri, codeVerifier) => {
+ const tokenData = await this.exchangeCodeForTokens(code, redirectUri, codeVerifier);
+
+ if (tokenData.error) {
+ throw new OAuthFlowError(
+ "token_exchange_failed",
+ `Token exchange failed: ${tokenData.error_description || tokenData.error}`
+ );
+ }
- shell.openExternal(`${GOOGLE_AUTH_URL}?${params.toString()}`);
- });
+ let email = null;
+ if (tokenData.id_token) {
+ try {
+ const payload = JSON.parse(
+ Buffer.from(tokenData.id_token.split(".")[1], "base64url").toString()
+ );
+ email = payload.email;
+ } catch {}
+ }
+
+ if (!email) {
+ throw new OAuthFlowError(
+ "no_email",
+ "Could not extract email from Google OAuth response"
+ );
+ }
- timeoutId = setTimeout(() => {
- server.close();
- reject(new Error("OAuth flow timed out"));
- }, OAUTH_TIMEOUT_MS);
+ this.databaseManager.saveGoogleTokens({
+ google_email: email,
+ access_token: tokenData.access_token,
+ refresh_token: tokenData.refresh_token,
+ expires_at: Date.now() + tokenData.expires_in * 1000,
+ scope: tokenData.scope || CALENDAR_SCOPE,
+ });
- server.on("error", (err) => {
- cleanup();
- reject(err);
- });
+ return { success: true, email };
+ },
});
}
diff --git a/src/helpers/ipcHandlers.js b/src/helpers/ipcHandlers.js
index 3ac551e74..39a031278 100644
--- a/src/helpers/ipcHandlers.js
+++ b/src/helpers/ipcHandlers.js
@@ -487,6 +487,7 @@ class IPCHandlers {
this.whisperCudaManager = managers.whisperCudaManager;
this.whisperVulkanManager = managers.whisperVulkanManager;
this.googleCalendarManager = managers.googleCalendarManager;
+ this.microsoftCalendarManager = managers.microsoftCalendarManager;
this.appleCalendarManager = managers.appleCalendarManager;
this.meetingDetectionEngine = managers.meetingDetectionEngine;
this.audioTapManager = managers.audioTapManager;
@@ -2918,6 +2919,11 @@ class IPCHandlers {
} catch (e) {
errors.push(`GCal stop: ${e.message}`);
}
+ try {
+ this.microsoftCalendarManager?.stop();
+ } catch (e) {
+ errors.push(`MCal stop: ${e.message}`);
+ }
// Revoke Google OAuth tokens before DB is closed
try {
@@ -8933,9 +8939,9 @@ class IPCHandlers {
}
});
- ipcMain.handle("gcal-disconnect", async () => {
+ ipcMain.handle("gcal-disconnect", async (_event, email) => {
try {
- this.googleCalendarManager.disconnect();
+ this.googleCalendarManager.disconnect(email);
return { success: true };
} catch (error) {
debugLogger.error(
@@ -9010,6 +9016,47 @@ class IPCHandlers {
}
});
+ // Microsoft Calendar
+ ipcMain.handle("mcal-start-oauth", async () => {
+ try {
+ return await this.microsoftCalendarManager.startOAuth();
+ } catch (error) {
+ debugLogger.error("Microsoft Calendar OAuth failed", { error: error.message }, "calendar");
+ return { success: false, error: error.message };
+ }
+ });
+
+ ipcMain.handle("mcal-disconnect", async (_event, email) => {
+ try {
+ this.microsoftCalendarManager.disconnect(email);
+ return { success: true };
+ } catch (error) {
+ debugLogger.error(
+ "Microsoft Calendar disconnect failed",
+ { error: error.message },
+ "calendar"
+ );
+ return { success: false, error: error.message };
+ }
+ });
+
+ ipcMain.handle("mcal-get-connection-status", async () => {
+ try {
+ return this.microsoftCalendarManager.getConnectionStatus();
+ } catch (error) {
+ return { connected: false, accounts: [] };
+ }
+ });
+
+ ipcMain.handle("mcal-set-primary-only", async (_event, value) => {
+ try {
+ await this.microsoftCalendarManager.setPrimaryOnly(value);
+ return { success: true };
+ } catch (error) {
+ return { success: false, error: error.message };
+ }
+ });
+
// Apple Calendar (macOS EventKit)
ipcMain.handle("acal-connect", async () => {
try {
diff --git a/src/helpers/microsoftCalendarManager.js b/src/helpers/microsoftCalendarManager.js
new file mode 100644
index 000000000..709a1c575
--- /dev/null
+++ b/src/helpers/microsoftCalendarManager.js
@@ -0,0 +1,338 @@
+const { net } = require("electron");
+const debugLogger = require("./debugLogger");
+const MicrosoftCalendarOAuth = require("./microsoftCalendarOAuth");
+const CalendarSyncInterval = require("./calendarSyncInterval");
+const { extractMeetingUrl } = require("./meetingJoinUrl");
+const { broadcastToWindows } = require("./windowBroadcast");
+
+const GRAPH_API_BASE = "https://graph.microsoft.com/v1.0";
+
+// Graph's deltaLink permanently encodes the calendarView window it was created
+// with — it never rolls forward. Sync a 14-day window and discard the token
+// after 7 days so coverage never drops below the app's 7-day lookahead.
+const DELTA_WINDOW_MS = 14 * 24 * 60 * 60 * 1000;
+const DELTA_TOKEN_TTL_MS = 7 * 24 * 60 * 60 * 1000;
+
+const RESPONSE_STATUS_BY_GRAPH = {
+ accepted: "accepted",
+ declined: "declined",
+ tentativelyAccepted: "tentative",
+};
+
+// Graph returns "2026-07-20T17:00:00.0000000" — no offset, 7-digit fraction —
+// which SQLite's datetime() cannot parse. Events are requested in UTC
+// (Prefer: outlook.timezone), so trim the fraction and append "Z".
+function normalizeGraphDateTime({ dateTime }) {
+ return `${dateTime.slice(0, 19)}Z`;
+}
+
+class MicrosoftCalendarManager {
+ constructor(databaseManager, reminderScheduler) {
+ this.databaseManager = databaseManager;
+ this.reminderScheduler = reminderScheduler;
+ this.oauth = new MicrosoftCalendarOAuth(databaseManager);
+ this.accounts = new Map();
+ this.primaryOnly = true;
+ this.syncRunner = new CalendarSyncInterval(
+ () => this.syncEvents().then(() => this.reminderScheduler.scheduleNextMeeting()),
+ { intervalMs: 2 * 60 * 1000, maxIntervalMs: 30 * 60 * 1000, logScope: "mcal" }
+ );
+ }
+
+ start() {
+ this._loadAccounts();
+ if (this.accounts.size === 0) return;
+
+ this.fetchCalendars()
+ .then(() => this.syncEvents())
+ .then(() => this.reminderScheduler.scheduleNextMeeting())
+ .catch((err) =>
+ debugLogger.error("Initial calendar sync failed", { error: err.message }, "mcal")
+ );
+
+ this.syncRunner.start();
+ }
+
+ stop() {
+ this.syncRunner.stop();
+ }
+
+ isConnected() {
+ return this.accounts.size > 0;
+ }
+
+ addAccount(email) {
+ this.accounts.set(email, { email });
+ }
+
+ removeAccount(email) {
+ this.accounts.delete(email);
+ this.databaseManager.removeMicrosoftAccount(email);
+ this._broadcastAccountsChanged();
+
+ if (this.accounts.size === 0) {
+ this.stop();
+ this.reminderScheduler.reset("microsoft");
+ this.reminderScheduler.scheduleNextMeeting();
+ }
+ }
+
+ async startOAuth() {
+ const result = await this.oauth.startOAuthFlow();
+ this.addAccount(result.email);
+
+ await this.fetchCalendars(result.email);
+ await this.syncEvents();
+ this.reminderScheduler.scheduleNextMeeting();
+ this.syncRunner.start();
+ this._broadcastAccountsChanged();
+
+ return result;
+ }
+
+ // Microsoft has no public token-revocation endpoint for this flow; deleting
+ // the local tokens severs access from our side.
+ disconnect(email) {
+ if (email) {
+ this.removeAccount(email);
+ } else {
+ this.stop();
+ this.accounts.clear();
+ this.databaseManager.clearMicrosoftCalendarData();
+ this.reminderScheduler.reset("microsoft");
+ this.reminderScheduler.scheduleNextMeeting();
+ this._broadcastAccountsChanged();
+ }
+ }
+
+ getConnectionStatus() {
+ const accounts = this.databaseManager.getMicrosoftAccounts();
+ return { connected: accounts.length > 0, accounts };
+ }
+
+ getAccounts() {
+ return this.databaseManager.getMicrosoftAccounts();
+ }
+
+ async fetchCalendars(accountEmail = null) {
+ const emails = accountEmail ? [accountEmail] : this._getAccountEmails();
+ const allCalendars = [];
+
+ for (const email of emails) {
+ try {
+ const calendars = [];
+ let url = "/me/calendars?$select=id,name,hexColor,isDefaultCalendar";
+ while (url) {
+ const data = await this._apiGet(url, email);
+ for (const item of data.value || []) {
+ calendars.push({
+ id: item.id,
+ summary: item.name,
+ background_color: item.hexColor || null,
+ is_primary: item.isDefaultCalendar === true,
+ });
+ }
+ url = data["@odata.nextLink"] || null;
+ }
+ this.databaseManager.saveMicrosoftCalendars(calendars, email);
+ allCalendars.push(...calendars);
+ } catch (err) {
+ debugLogger.error("Error fetching calendars", { email, error: err.message }, "mcal");
+ }
+ }
+
+ this.databaseManager.applyMicrosoftPrimaryOnlyToSelection(this.primaryOnly);
+ this.databaseManager.removeEventsFromDeselectedCalendars("microsoft");
+ return allCalendars;
+ }
+
+ async syncEvents() {
+ const selectedCalendars = this.databaseManager.getSelectedMicrosoftCalendars();
+ if (selectedCalendars.length === 0) return;
+
+ for (const calendar of selectedCalendars) {
+ try {
+ await this._syncCalendar(calendar);
+ } catch (err) {
+ debugLogger.error(
+ "Error syncing calendar",
+ { calendarId: calendar.id, error: err.message },
+ "mcal"
+ );
+ }
+ }
+
+ broadcastToWindows("mcal-events-synced", {});
+ this.reminderScheduler.scheduleNextMeeting();
+ }
+
+ async _syncCalendar(calendar) {
+ const accountEmail = calendar.account_email;
+
+ const toUpsert = [];
+ const toRemove = [];
+ const contactsToUpsert = [];
+ let deltaLink = null;
+
+ const hasFreshToken = calendar.sync_token && calendar.sync_token_expires_at > Date.now();
+ let url = hasFreshToken ? calendar.sync_token : this._deltaUrl(calendar.id);
+ let tokenExpiresAt = hasFreshToken
+ ? calendar.sync_token_expires_at
+ : Date.now() + DELTA_TOKEN_TTL_MS;
+
+ while (url) {
+ let data;
+ try {
+ data = await this._apiGet(url, accountEmail);
+ } catch (err) {
+ // 410 Gone means the delta token expired; fall back to a full sync
+ if (err.statusCode === 410 && url === calendar.sync_token) {
+ url = this._deltaUrl(calendar.id);
+ tokenExpiresAt = Date.now() + DELTA_TOKEN_TTL_MS;
+ continue;
+ }
+ throw err;
+ }
+
+ for (const item of data.value || []) {
+ if (item["@removed"]) {
+ toRemove.push(item.id);
+ continue;
+ }
+ toUpsert.push(this._mapEvent(item, calendar));
+ for (const a of item.attendees || []) {
+ if (a.emailAddress?.address) {
+ contactsToUpsert.push({
+ email: a.emailAddress.address,
+ displayName: a.emailAddress.name || null,
+ });
+ }
+ }
+ }
+
+ deltaLink = data["@odata.deltaLink"] || deltaLink;
+ url = data["@odata.nextLink"] || null;
+ }
+
+ if (toUpsert.length > 0) this.databaseManager.upsertCalendarEvents(toUpsert);
+ if (toRemove.length > 0) this.databaseManager.removeCalendarEvents(toRemove);
+ if (deltaLink) {
+ this.databaseManager.updateMicrosoftCalendarSyncToken(calendar.id, deltaLink, tokenExpiresAt);
+ }
+ if (contactsToUpsert.length > 0) this.databaseManager.upsertContacts(contactsToUpsert);
+ }
+
+ _mapEvent(item, calendar) {
+ const attendees = item.attendees || [];
+ const accountEmail = (calendar.account_email || "").toLowerCase();
+ return {
+ id: item.id,
+ calendar_id: calendar.id,
+ provider: "microsoft",
+ summary: item.subject || null,
+ start_time: normalizeGraphDateTime(item.start),
+ end_time: normalizeGraphDateTime(item.end),
+ is_all_day: item.isAllDay,
+ // showAs is deliberately ignored: unaccepted invitations arrive as
+ // showAs=tentative and must still surface (Google keeps them confirmed).
+ status: item.isCancelled ? "cancelled" : "confirmed",
+ hangout_link:
+ item.onlineMeeting?.joinUrl ||
+ item.onlineMeetingUrl ||
+ extractMeetingUrl([item.location?.displayName, item.bodyPreview]),
+ conference_data: null,
+ organizer_email: item.organizer?.emailAddress?.address || null,
+ attendees_count: attendees.length,
+ attendees: attendees.length
+ ? JSON.stringify(
+ attendees.map((a) => ({
+ email: a.emailAddress?.address || null,
+ displayName: a.emailAddress?.name || null,
+ responseStatus: RESPONSE_STATUS_BY_GRAPH[a.status?.response] || "needsAction",
+ self: (a.emailAddress?.address || "").toLowerCase() === accountEmail,
+ }))
+ )
+ : null,
+ };
+ }
+
+ onWakeFromSleep() {
+ this.syncEvents()
+ .then(() => this.syncRunner.notifySuccess())
+ .catch((err) => debugLogger.error("Post-wake sync failed", { error: err.message }, "mcal"));
+ }
+
+ syncOnFocus() {
+ if (!this.isConnected()) return;
+ this.syncRunner.syncOnFocus();
+ }
+
+ async setPrimaryOnly(value) {
+ if (this.primaryOnly === value) return;
+ this.primaryOnly = value;
+ if (!this.isConnected()) return;
+
+ await this.fetchCalendars();
+ this.reminderScheduler.reset("microsoft");
+ await this.syncEvents();
+ this.reminderScheduler.scheduleNextMeeting();
+ broadcastToWindows("mcal-events-synced", {});
+ }
+
+ _loadAccounts() {
+ const accounts = this.databaseManager.getMicrosoftAccounts();
+ this.accounts.clear();
+ for (const account of accounts) {
+ this.accounts.set(account.email, { email: account.email });
+ }
+ }
+
+ _getAccountEmails() {
+ return Array.from(this.accounts.keys());
+ }
+
+ // calendarView/delta expands recurrences into occurrences and returns a
+ // deltaLink for incremental syncs (stored in microsoft_calendars.sync_token).
+ _deltaUrl(calendarId) {
+ const params = new URLSearchParams({
+ startDateTime: new Date().toISOString(),
+ endDateTime: new Date(Date.now() + DELTA_WINDOW_MS).toISOString(),
+ });
+ return `/me/calendars/${encodeURIComponent(calendarId)}/calendarView/delta?${params.toString()}`;
+ }
+
+ _broadcastAccountsChanged() {
+ const accounts = this.getAccounts();
+ broadcastToWindows("mcal-connection-changed", { accounts });
+ }
+
+ async _apiGet(path, accountEmail) {
+ const accessToken = await this.oauth.getValidAccessToken(accountEmail);
+ const urlString = path.startsWith("http") ? path : `${GRAPH_API_BASE}${path}`;
+
+ const response = await net.fetch(urlString, {
+ method: "GET",
+ headers: {
+ Authorization: `Bearer ${accessToken}`,
+ Prefer: 'outlook.timezone="UTC"',
+ },
+ signal: AbortSignal.timeout(10000),
+ useSessionCookies: false,
+ });
+ const text = await response.text();
+ let parsed;
+ try {
+ parsed = JSON.parse(text);
+ } catch {
+ throw new Error(`Invalid JSON response: ${text.slice(0, 200)}`);
+ }
+ if (response.status >= 400) {
+ const err = new Error(parsed.error?.message || `API error ${response.status}`);
+ err.statusCode = response.status;
+ throw err;
+ }
+ return parsed;
+ }
+}
+
+module.exports = MicrosoftCalendarManager;
diff --git a/src/helpers/microsoftCalendarOAuth.js b/src/helpers/microsoftCalendarOAuth.js
new file mode 100644
index 000000000..0e07000f8
--- /dev/null
+++ b/src/helpers/microsoftCalendarOAuth.js
@@ -0,0 +1,164 @@
+const { net } = require("electron");
+const { runOAuthLoopbackFlow, OAuthFlowError } = require("./oauthLoopbackFlow");
+
+// The "common" tenant covers both work/school (M365) and personal
+// (outlook.com) accounts. Desktop apps are public clients: PKCE, no secret.
+const MICROSOFT_AUTH_URL = "https://login.microsoftonline.com/common/oauth2/v2.0/authorize";
+const MICROSOFT_TOKEN_URL = "https://login.microsoftonline.com/common/oauth2/v2.0/token";
+// "profile" puts preferred_username in the id_token and User.Read allows the
+// GET /me fallback — work accounts often omit the "email" claim.
+const CALENDAR_SCOPE =
+ "openid profile email offline_access https://graph.microsoft.com/User.Read https://graph.microsoft.com/Calendars.Read";
+
+class MicrosoftCalendarOAuth {
+ constructor(databaseManager) {
+ this.databaseManager = databaseManager;
+ }
+
+ getClientId() {
+ return process.env.MICROSOFT_CALENDAR_CLIENT_ID;
+ }
+
+ startOAuthFlow() {
+ return runOAuthLoopbackFlow({
+ errorParam: "mcal_error",
+ buildAuthUrl: (redirectUri, state, codeChallenge) => {
+ const params = new URLSearchParams({
+ client_id: this.getClientId(),
+ redirect_uri: redirectUri,
+ response_type: "code",
+ scope: CALENDAR_SCOPE,
+ // Without this, SSO silently re-links the signed-in account when
+ // the user tries to add another one.
+ prompt: "select_account",
+ state,
+ code_challenge: codeChallenge,
+ code_challenge_method: "S256",
+ });
+ return `${MICROSOFT_AUTH_URL}?${params.toString()}`;
+ },
+ handleCallback: async (code, redirectUri, codeVerifier) => {
+ const tokenData = await this.exchangeCodeForTokens(code, redirectUri, codeVerifier);
+
+ if (tokenData.error) {
+ throw new OAuthFlowError(
+ "token_exchange_failed",
+ `Token exchange failed: ${tokenData.error_description || tokenData.error}`
+ );
+ }
+
+ const email = await this._resolveEmail(tokenData);
+ if (!email) {
+ throw new OAuthFlowError(
+ "no_email",
+ "Could not extract email from Microsoft OAuth response"
+ );
+ }
+
+ this._saveTokens(email, tokenData);
+ return { success: true, email };
+ },
+ });
+ }
+
+ async exchangeCodeForTokens(code, redirectUri, codeVerifier) {
+ const body = new URLSearchParams({
+ code,
+ client_id: this.getClientId(),
+ redirect_uri: redirectUri,
+ grant_type: "authorization_code",
+ code_verifier: codeVerifier,
+ }).toString();
+
+ return this._httpsPost(MICROSOFT_TOKEN_URL, body);
+ }
+
+ async refreshAccessToken(refreshToken) {
+ const body = new URLSearchParams({
+ client_id: this.getClientId(),
+ refresh_token: refreshToken,
+ grant_type: "refresh_token",
+ scope: CALENDAR_SCOPE,
+ }).toString();
+
+ return this._httpsPost(MICROSOFT_TOKEN_URL, body);
+ }
+
+ async getValidAccessToken(accountEmail) {
+ const tokens = this.databaseManager.getMicrosoftTokensByEmail(accountEmail);
+ if (!tokens) throw new Error(`No Microsoft tokens found for ${accountEmail}`);
+
+ const fiveMinutes = 5 * 60 * 1000;
+ if (tokens.expires_at - fiveMinutes < Date.now()) {
+ const refreshed = await this.refreshAccessToken(tokens.refresh_token);
+ if (refreshed.error) {
+ throw new Error(`Token refresh failed: ${refreshed.error_description || refreshed.error}`);
+ }
+
+ // Microsoft rotates refresh tokens on every refresh; persist the new one
+ // or the old refresh token stops working within 24h.
+ this._saveTokens(tokens.microsoft_email, {
+ ...refreshed,
+ refresh_token: refreshed.refresh_token || tokens.refresh_token,
+ scope: refreshed.scope || tokens.scope,
+ });
+
+ return refreshed.access_token;
+ }
+
+ return tokens.access_token;
+ }
+
+ _saveTokens(email, tokenData) {
+ this.databaseManager.saveMicrosoftTokens({
+ microsoft_email: email,
+ access_token: tokenData.access_token,
+ refresh_token: tokenData.refresh_token,
+ expires_at: Date.now() + tokenData.expires_in * 1000,
+ scope: tokenData.scope || CALENDAR_SCOPE,
+ });
+ }
+
+ // Work accounts often omit the id_token "email" claim; fall back to
+ // preferred_username, then Graph /me.
+ async _resolveEmail(tokenData) {
+ if (tokenData.id_token) {
+ try {
+ const payload = JSON.parse(
+ Buffer.from(tokenData.id_token.split(".")[1], "base64url").toString()
+ );
+ if (payload.email) return payload.email;
+ if (payload.preferred_username?.includes("@")) return payload.preferred_username;
+ } catch {}
+ }
+
+ try {
+ const response = await net.fetch("https://graph.microsoft.com/v1.0/me", {
+ headers: { Authorization: `Bearer ${tokenData.access_token}` },
+ signal: AbortSignal.timeout(10000),
+ useSessionCookies: false,
+ });
+ const me = await response.json();
+ return me.mail || me.userPrincipalName || null;
+ } catch {
+ return null;
+ }
+ }
+
+ async _httpsPost(urlString, body) {
+ const response = await net.fetch(urlString, {
+ method: "POST",
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
+ body,
+ useSessionCookies: false,
+ });
+ const text = await response.text();
+ try {
+ return JSON.parse(text);
+ } catch {
+ throw new Error(`Invalid JSON response: ${text.slice(0, 200)}`);
+ }
+ }
+}
+
+module.exports = MicrosoftCalendarOAuth;
diff --git a/src/helpers/oauthLoopbackFlow.js b/src/helpers/oauthLoopbackFlow.js
new file mode 100644
index 000000000..e8bbeb1cf
--- /dev/null
+++ b/src/helpers/oauthLoopbackFlow.js
@@ -0,0 +1,119 @@
+const http = require("http");
+const crypto = require("crypto");
+const { shell } = require("electron");
+
+const OAUTH_TIMEOUT_MS = 120000;
+const DEFAULT_DESKTOP_CALLBACK_URL = "https://openwhispr.com/auth/desktop-callback";
+
+const PROTOCOL_BY_CHANNEL = {
+ development: "openwhispr-dev",
+ staging: "openwhispr-staging",
+ production: "openwhispr",
+};
+
+// Thrown by handleCallback to control the error code shown on the hosted
+// desktop-callback page (defaults to "server_error").
+class OAuthFlowError extends Error {
+ constructor(redirectCode, message) {
+ super(message);
+ this.redirectCode = redirectCode;
+ }
+}
+
+function getDesktopCallbackUrl() {
+ return process.env.VITE_OPENWHISPR_OAUTH_CALLBACK_URL || DEFAULT_DESKTOP_CALLBACK_URL;
+}
+
+function getProtocol() {
+ const channel = process.env.OPENWHISPR_CHANNEL || "production";
+ return PROTOCOL_BY_CHANNEL[channel] || PROTOCOL_BY_CHANNEL.production;
+}
+
+function buildCallbackRedirect(params) {
+ const url = new URL(getDesktopCallbackUrl());
+ url.searchParams.set("protocol", getProtocol());
+ for (const [key, value] of Object.entries(params)) {
+ url.searchParams.set(key, value);
+ }
+ return url.toString();
+}
+
+function redirect(res, params) {
+ res.writeHead(302, { Location: buildCallbackRedirect(params) });
+ res.end();
+}
+
+// Runs a PKCE auth-code flow through an ephemeral 127.0.0.1 server:
+// - buildAuthUrl(redirectUri, state, codeChallenge) → provider authorize URL
+// - handleCallback(code, redirectUri, codeVerifier) → resolves the flow result;
+// called once with a state-validated code, throws (OAuthFlowError for a
+// specific callback-page code) to reject.
+// - errorParam — query-param name for the hosted desktop-callback page
+// (e.g. "gcal_error"); the success param is derived from the same prefix.
+function runOAuthLoopbackFlow({ buildAuthUrl, handleCallback, errorParam }) {
+ const connectedParam = errorParam.replace(/_error$/, "_connected");
+
+ return new Promise((resolve, reject) => {
+ const codeVerifier = crypto.randomBytes(32).toString("base64url").slice(0, 43);
+ const codeChallenge = crypto.createHash("sha256").update(codeVerifier).digest("base64url");
+ const state = crypto.randomBytes(32).toString("hex");
+
+ const server = http.createServer(async (req, res) => {
+ try {
+ const url = new URL(req.url, `http://127.0.0.1`);
+ const returnedState = url.searchParams.get("state");
+ const code = url.searchParams.get("code");
+ const error = url.searchParams.get("error");
+
+ if (error) {
+ redirect(res, { [errorParam]: error });
+ cleanup();
+ reject(new Error(`OAuth error: ${error}`));
+ return;
+ }
+
+ if (!code || returnedState !== state) {
+ res.writeHead(400, { "Content-Type": "text/html" });
+ res.end("<html><body><h3>Invalid request.</h3></body></html>");
+ return;
+ }
+
+ const redirectUri = `http://127.0.0.1:${server.address().port}`;
+ const result = await handleCallback(code, redirectUri, codeVerifier);
+
+ redirect(res, { [connectedParam]: "true" });
+ cleanup();
+ resolve(result);
+ } catch (err) {
+ redirect(res, { [errorParam]: err.redirectCode || "server_error" });
+ cleanup();
+ reject(err);
+ }
+ });
+
+ let timeoutId;
+
+ const cleanup = () => {
+ clearTimeout(timeoutId);
+ server.close();
+ };
+
+ server.listen(0, "127.0.0.1", () => {
+ const port = server.address().port;
+ const redirectUri = `http://127.0.0.1:${port}`;
+ shell.openExternal(buildAuthUrl(redirectUri, state, codeChallenge));
+ });
+
+ timeoutId = setTimeout(() => {
+ server.close();
+ reject(new Error("OAuth flow timed out"));
+ }, OAUTH_TIMEOUT_MS);
+
+ server.on("error", (err) => {
+ cleanup();
+ reject(err);
+ });
+ });
+}
+
+module.exports = { runOAuthLoopbackFlow, OAuthFlowError };
diff --git a/src/hooks/useUpcomingEvents.ts b/src/hooks/useUpcomingEvents.ts
index f238c172b..d79a4a10d 100644
--- a/src/hooks/useUpcomingEvents.ts
+++ b/src/hooks/useUpcomingEvents.ts
@@ -20,8 +20,9 @@ function getLookaheadMinutes(): number {
export function useUpcomingEvents(): UseUpcomingEventsReturn {
const gcalAccounts = useSettingsStore((s) => s.gcalAccounts);
+ const mcalAccounts = useSettingsStore((s) => s.mcalAccounts);
const appleCalendarConnected = useSettingsStore((s) => s.appleCalendarConnected);
- const isConnected = gcalAccounts.length > 0 || appleCalendarConnected;
+ const isConnected = gcalAccounts.length > 0 || mcalAccounts.length > 0 || appleCalendarConnected;
const [events, setEvents] = useState<CalendarEvent[]>([]);
const [isLoading, setIsLoading] = useState(false);
@@ -52,17 +53,21 @@ export function useUpcomingEvents(): UseUpcomingEventsReturn {
fetchEvents();
}, [fetchEvents]);
- // Re-fetch when either provider syncs events
+ // Re-fetch when any provider syncs events
useEffect(() => {
if (!isConnected) return;
const unsubGcal = window.electronAPI?.onGcalEventsSynced?.(() => {
fetchEvents();
});
+ const unsubMcal = window.electronAPI?.onMcalEventsSynced?.(() => {
+ fetchEvents();
+ });
const unsubAcal = window.electronAPI?.onAcalEventsSynced?.(() => {
fetchEvents();
});
return () => {
unsubGcal?.();
+ unsubMcal?.();
unsubAcal?.();
};
}, [isConnected, fetchEvents]);
diff --git a/src/locales/de/translation.json b/src/locales/de/translation.json
index 52da2425d..f89456d0e 100644
--- a/src/locales/de/translation.json
+++ b/src/locales/de/translation.json
@@ -3181,6 +3181,19 @@
"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"
},
+ "microsoftCalendar": {
+ "title": "Microsoft Calendar",
+ "optional": "Optional",
+ "description": "Besprechungen aus deinem Outlook- oder Microsoft 365-Kalender lesen.",
+ "connect": "Microsoft Calendar verbinden",
+ "connected": "Verbunden",
+ "addAnother": "Weiteren Kalender hinzufügen",
+ "primaryOnly": "Nur Hauptkalender synchronisieren",
+ "primaryOnlyDescription": "Termine aus mit dir geteilten Kalendern ignorieren.",
+ "disconnect": "Trennen",
+ "disconnectConfirm": "{{email}} trennen?",
+ "disconnectDescription": "Besprechungsnotizen werden von diesem Kalender nicht mehr aufgezeichnet."
+ },
"appleCalendar": {
"title": "Apple Kalender",
"optional": "Optional",
diff --git a/src/locales/en/translation.json b/src/locales/en/translation.json
index 811dacfef..9eb524e2b 100644
--- a/src/locales/en/translation.json
+++ b/src/locales/en/translation.json
@@ -3181,6 +3181,19 @@
"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"
},
+ "microsoftCalendar": {
+ "title": "Microsoft Calendar",
+ "optional": "Optional",
+ "description": "Read meetings from your Outlook or Microsoft 365 calendar.",
+ "connect": "Connect Microsoft Calendar",
+ "connected": "Connected",
+ "addAnother": "Add another calendar",
+ "primaryOnly": "Sync primary calendar only",
+ "primaryOnlyDescription": "Ignore events from calendars shared with you.",
+ "disconnect": "Disconnect",
+ "disconnectConfirm": "Disconnect {{email}}?",
+ "disconnectDescription": "Meeting notes will no longer be recorded from this calendar."
+ },
"appleCalendar": {
"title": "Apple Calendar",
"optional": "Optional",
diff --git a/src/locales/es/translation.json b/src/locales/es/translation.json
index ef94b86f3..747283c4d 100644
--- a/src/locales/es/translation.json
+++ b/src/locales/es/translation.json
@@ -3081,6 +3081,19 @@
"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"
},
+ "microsoftCalendar": {
+ "title": "Microsoft Calendar",
+ "optional": "Opcional",
+ "description": "Lee reuniones de tu calendario de Outlook o Microsoft 365.",
+ "connect": "Conectar Microsoft Calendar",
+ "connected": "Conectado",
+ "addAnother": "Añadir otro calendario",
+ "primaryOnly": "Sincronizar solo el calendario principal",
+ "primaryOnlyDescription": "Ignorar los eventos de los calendarios compartidos contigo.",
+ "disconnect": "Desconectar",
+ "disconnectConfirm": "¿Desconectar {{email}}?",
+ "disconnectDescription": "Ya no se grabarán notas de reuniones de este calendario."
+ },
"appleCalendar": {
"title": "Calendario de Apple",
"optional": "Opcional",
diff --git a/src/locales/fr/translation.json b/src/locales/fr/translation.json
index cfe19c4ad..d61cd9519 100644
--- a/src/locales/fr/translation.json
+++ b/src/locales/fr/translation.json
@@ -3181,6 +3181,19 @@
"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"
},
+ "microsoftCalendar": {
+ "title": "Microsoft Calendar",
+ "optional": "Facultatif",
+ "description": "Lisez les réunions depuis votre calendrier Outlook ou Microsoft 365.",
+ "connect": "Connecter Microsoft Calendar",
+ "connected": "Connecté",
+ "addAnother": "Ajouter un autre calendrier",
+ "primaryOnly": "Synchroniser uniquement le calendrier principal",
+ "primaryOnlyDescription": "Ignorer les événements des calendriers partagés avec vous.",
+ "disconnect": "Déconnecter",
+ "disconnectConfirm": "Déconnecter {{email}} ?",
+ "disconnectDescription": "Les notes de réunion ne seront plus enregistrées depuis ce calendrier."
+ },
"appleCalendar": {
"title": "Calendrier Apple",
"optional": "Facultatif",
diff --git a/src/locales/it/translation.json b/src/locales/it/translation.json
index a68aca523..8466719b8 100644
--- a/src/locales/it/translation.json
+++ b/src/locales/it/translation.json
@@ -3033,6 +3033,19 @@
"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"
},
+ "microsoftCalendar": {
+ "title": "Microsoft Calendar",
+ "optional": "Opzionale",
+ "description": "Leggi le riunioni dal tuo calendario Outlook o Microsoft 365.",
+ "connect": "Collega Microsoft Calendar",
+ "connected": "Connesso",
+ "addAnother": "Aggiungi un altro calendario",
+ "primaryOnly": "Sincronizza solo il calendario principale",
+ "primaryOnlyDescription": "Ignora gli eventi dei calendari condivisi con te.",
+ "disconnect": "Disconnetti",
+ "disconnectConfirm": "Disconnettere {{email}}?",
+ "disconnectDescription": "Le note delle riunioni non saranno più registrate da questo calendario."
+ },
"appleCalendar": {
"title": "Calendario Apple",
"optional": "Opzionale",
diff --git a/src/locales/ja/translation.json b/src/locales/ja/translation.json
index 24e7ed5ca..9c44ee73b 100644
--- a/src/locales/ja/translation.json
+++ b/src/locales/ja/translation.json
@@ -3033,6 +3033,19 @@
"systemAudioDescription": "会議を文字起こしするには、OpenWhispr に他の参加者の音声を録音するためのシステムオーディオの権限が必要です。画面を録画することはありません。システム設定に移動して有効にします。",
"openSettings": "システム設定を開く"
},
+ "microsoftCalendar": {
+ "title": "Microsoft カレンダー",
+ "optional": "任意",
+ "description": "Outlook または Microsoft 365 のカレンダーから会議を読み取ります。",
+ "connect": "Microsoft カレンダーを接続",
+ "connected": "接続済み",
+ "addAnother": "別のカレンダーを追加",
+ "primaryOnly": "メインカレンダーのみ同期",
+ "primaryOnlyDescription": "共有されたカレンダーの予定は無視します。",
+ "disconnect": "切断",
+ "disconnectConfirm": "{{email}} を切断しますか?",
+ "disconnectDescription": "このカレンダーからの会議メモは記録されなくなります。"
+ },
"appleCalendar": {
"title": "Apple カレンダー",
"optional": "任意",
diff --git a/src/locales/pt/translation.json b/src/locales/pt/translation.json
index 4b79b1486..53f798220 100644
--- a/src/locales/pt/translation.json
+++ b/src/locales/pt/translation.json
@@ -3033,6 +3033,19 @@
"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"
},
+ "microsoftCalendar": {
+ "title": "Microsoft Calendar",
+ "optional": "Opcional",
+ "description": "Leia reuniões do seu calendário do Outlook ou Microsoft 365.",
+ "connect": "Conectar Microsoft Calendar",
+ "connected": "Conectado",
+ "addAnother": "Adicionar outro calendário",
+ "primaryOnly": "Sincronizar apenas o calendário principal",
+ "primaryOnlyDescription": "Ignorar eventos de calendários compartilhados com você.",
+ "disconnect": "Desconectar",
+ "disconnectConfirm": "Desconectar {{email}}?",
+ "disconnectDescription": "As notas de reunião não serão mais gravadas deste calendário."
+ },
"appleCalendar": {
"title": "Calendário da Apple",
"optional": "Opcional",
diff --git a/src/locales/ru/translation.json b/src/locales/ru/translation.json
index 934e706d1..4f101ebde 100644
--- a/src/locales/ru/translation.json
+++ b/src/locales/ru/translation.json
@@ -3063,6 +3063,19 @@
"systemAudioDescription": "Для транскрипции встреч OpenWhispr нужно разрешение «Системное аудио» для записи звука других участников. Мы никогда не записываем ваш экран. Вы будете перенаправлены в Системные настройки для включения.",
"openSettings": "Открыть Системные настройки"
},
+ "microsoftCalendar": {
+ "title": "Microsoft Calendar",
+ "optional": "Необязательно",
+ "description": "Читайте встречи из календаря Outlook или Microsoft 365.",
+ "connect": "Подключить Microsoft Calendar",
+ "connected": "Подключено",
+ "addAnother": "Добавить ещё один календарь",
+ "primaryOnly": "Синхронизировать только основной календарь",
+ "primaryOnlyDescription": "Игнорировать события из календарей, к которым вам открыли доступ.",
+ "disconnect": "Отключить",
+ "disconnectConfirm": "Отключить {{email}}?",
+ "disconnectDescription": "Заметки встреч больше не будут записываться из этого календаря."
+ },
"appleCalendar": {
"title": "Календарь Apple",
"optional": "Необязательно",
diff --git a/src/locales/zh-CN/translation.json b/src/locales/zh-CN/translation.json
index eb732ee1b4..68532c13b 100644
--- a/src/locales/zh-CN/translation.json
+++ b/src/locales/zh-CN/translation.json
@@ -3033,6 +3033,19 @@
"systemAudioDescription": "要转录会议,OpenWhispr 需要系统音频权限来录制其他参与者的音频。我们绝不会录制您的屏幕。您将被引导至系统设置以启用此权限。",
"openSettings": "打开系统设置"
},
+ "microsoftCalendar": {
+ "title": "Microsoft 日历",
+ "optional": "可选",
+ "description": "从 Outlook 或 Microsoft 365 日历读取会议。",
+ "connect": "连接 Microsoft 日历",
+ "connected": "已连接",
+ "addAnother": "添加其他日历",
+ "primaryOnly": "仅同步主日历",
+ "primaryOnlyDescription": "忽略他人共享给你的日历事件。",
+ "disconnect": "断开",
+ "disconnectConfirm": "断开 {{email}}?",
+ "disconnectDescription": "将不再从此日历记录会议笔记。"
+ },
"appleCalendar": {
"title": "Apple 日历",
"optional": "可选",
diff --git a/src/locales/zh-TW/translation.json b/src/locales/zh-TW/translation.json
index 0ea32af26..fa47bf6d2 100644
--- a/src/locales/zh-TW/translation.json
+++ b/src/locales/zh-TW/translation.json
@@ -3033,6 +3033,19 @@
"systemAudioDescription": "要轉錄會議,OpenWhispr 需要系統音訊權限來錄製其他參與者的音訊。我們絕不會錄製您的螢幕。您將被引導至系統設定以啟用此權限。",
"openSettings": "打開系統設定"
},
+ "microsoftCalendar": {
+ "title": "Microsoft 日曆",
+ "optional": "可選",
+ "description": "從 Outlook 或 Microsoft 365 日曆讀取會議。",
+ "connect": "連接 Microsoft 日曆",
+ "connected": "已連接",
+ "addAnother": "新增其他日曆",
+ "primaryOnly": "僅同步主要日曆",
+ "primaryOnlyDescription": "忽略他人分享給你的日曆事件。",
+ "disconnect": "中斷連接",
+ "disconnectConfirm": "中斷 {{email}} 的連接?",
+ "disconnectDescription": "將不再從此日曆記錄會議筆記。"
+ },
"appleCalendar": {
"title": "Apple 日曆",
"optional": "可選",
diff --git a/src/stores/settingsStore.ts b/src/stores/settingsStore.ts
index beb2f36d1..4285baac3 100644
--- a/src/stores/settingsStore.ts
+++ b/src/stores/settingsStore.ts
@@ -12,7 +12,7 @@ import type {
InferenceMode,
SelfHostedType,
} from "../types/electron";
-import type { GoogleCalendarAccount } from "../types/calendar";
+import type { CalendarAccount } from "../types/calendar";
import { PROMPT_KIND_LIST, type PromptKind } from "../config/prompts/registry";
import {
deriveReasoningMode,
@@ -162,6 +162,7 @@ const BOOLEAN_SETTINGS = new Set([
"notifyCalendarReminders",
"notifyUpdates",
"gcalPrimaryOnly",
+ "mcalPrimaryOnly",
"appleCalendarConnected",
]);
@@ -169,6 +170,7 @@ const ARRAY_SETTINGS = new Set([
"customDictionary",
"snippets",
"gcalAccounts",
+ "mcalAccounts",
"onboardingUseCases",
"translationTargets",
]);
@@ -432,14 +434,17 @@ export interface SettingsState
pauseMediaOnDictation: boolean;
floatingIconAutoHide: boolean;
startMinimized: boolean;
- gcalAccounts: GoogleCalendarAccount[];
+ gcalAccounts: CalendarAccount[];
gcalConnected: boolean;
gcalEmail: string;
+ mcalAccounts: CalendarAccount[];
+ mcalConnected: boolean;
notificationsEnabled: boolean;
notifyMeetingDetection: boolean;
notifyCalendarReminders: boolean;
notifyUpdates: boolean;
gcalPrimaryOnly: boolean;
+ mcalPrimaryOnly: boolean;
appleCalendarConnected: boolean;
meetingProcessDetection: boolean;
speakerDiarizationEnabled: boolean;
@@ -690,12 +695,14 @@ export interface SettingsState
setPauseMediaOnDictation: (value: boolean) => void;
setFloatingIconAutoHide: (enabled: boolean) => void;
setStartMinimized: (enabled: boolean) => void;
- setGcalAccounts: (accounts: GoogleCalendarAccount[]) => void;
+ setGcalAccounts: (accounts: CalendarAccount[]) => void;
+ setMcalAccounts: (accounts: CalendarAccount[]) => void;
setNotificationsEnabled: (value: boolean) => void;
setNotifyMeetingDetection: (value: boolean) => void;
setNotifyCalendarReminders: (value: boolean) => void;
setNotifyUpdates: (value: boolean) => void;
setGcalPrimaryOnly: (value: boolean) => void;
+ setMcalPrimaryOnly: (value: boolean) => void;
setAppleCalendarConnected: (value: boolean) => void;
setMeetingProcessDetection: (value: boolean) => void;
setSpeakerDiarizationEnabled: (value: boolean) => void;
@@ -1052,7 +1059,7 @@ export const useSettingsStore = create<SettingsState>()((set, get) => ({
notifyCalendarReminders: readBoolean("notifyCalendarReminders", true),
notifyUpdates: readBoolean("notifyUpdates", true),
...(() => {
- let accounts: GoogleCalendarAccount[] = [];
+ let accounts: CalendarAccount[] = [];
try {
const parsed = JSON.parse(readString("gcalAccounts", "[]"));
if (Array.isArray(parsed)) accounts = parsed;
@@ -1065,7 +1072,21 @@ export const useSettingsStore = create<SettingsState>()((set, get) => ({
gcalEmail: accounts[0]?.email ?? "",
};
})(),
+ ...(() => {
+ let accounts: CalendarAccount[] = [];
+ try {
+ const parsed = JSON.parse(readString("mcalAccounts", "[]"));
+ if (Array.isArray(parsed)) accounts = parsed;
+ } catch {
+ /* use empty default */
+ }
+ return {
+ mcalAccounts: accounts,
+ mcalConnected: accounts.length > 0,
+ };
+ })(),
gcalPrimaryOnly: readBoolean("gcalPrimaryOnly", true),
+ mcalPrimaryOnly: readBoolean("mcalPrimaryOnly", true),
appleCalendarConnected: readBoolean("appleCalendarConnected", false),
meetingProcessDetection: readBoolean("meetingProcessDetection", true),
speakerDiarizationEnabled: readBoolean("speakerDiarizationEnabled", true),
@@ -1682,7 +1703,7 @@ export const useSettingsStore = create<SettingsState>()((set, get) => ({
}
},
- setGcalAccounts: (accounts: GoogleCalendarAccount[]) => {
+ setGcalAccounts: (accounts: CalendarAccount[]) => {
if (isBrowser) localStorage.setItem("gcalAccounts", JSON.stringify(accounts));
useSettingsStore.setState({
gcalAccounts: accounts,
@@ -1690,6 +1711,13 @@ export const useSettingsStore = create<SettingsState>()((set, get) => ({
gcalEmail: accounts[0]?.email ?? "",
});
},
+ setMcalAccounts: (accounts: CalendarAccount[]) => {
+ if (isBrowser) localStorage.setItem("mcalAccounts", JSON.stringify(accounts));
+ useSettingsStore.setState({
+ mcalAccounts: accounts,
+ mcalConnected: accounts.length > 0,
+ });
+ },
setNotificationsEnabled: createBooleanSetter("notificationsEnabled"),
setNotifyMeetingDetection: createBooleanSetter("notifyMeetingDetection"),
setNotifyCalendarReminders: createBooleanSetter("notifyCalendarReminders"),
@@ -1699,6 +1727,11 @@ export const useSettingsStore = create<SettingsState>()((set, get) => ({
useSettingsStore.setState({ gcalPrimaryOnly: value });
if (isBrowser) window.electronAPI?.gcalSetPrimaryOnly?.(value);
},
+ setMcalPrimaryOnly: (value: boolean) => {
+ if (isBrowser) localStorage.setItem("mcalPrimaryOnly", String(value));
+ useSettingsStore.setState({ mcalPrimaryOnly: value });
+ if (isBrowser) window.electronAPI?.mcalSetPrimaryOnly?.(value);
+ },
setAppleCalendarConnected: createBooleanSetter("appleCalendarConnected"),
setMeetingProcessDetection: createBooleanSetter("meetingProcessDetection"),
setSpeakerDiarizationEnabled: (value: boolean) => {
@@ -2544,6 +2577,17 @@ export async function initializeSettings(): Promise<void> {
);
}
+ try {
+ const currentState = useSettingsStore.getState();
+ await window.electronAPI.mcalSetPrimaryOnly?.(currentState.mcalPrimaryOnly);
+ } catch (err) {
+ logger.warn(
+ "Failed to sync mcal primary-only on startup",
+ { error: (err as Error).message },
+ "settings"
+ );
+ }
+
try {
const currentState = useSettingsStore.getState();
await window.electronAPI.setSpeakerDiarizationEnabled?.(
@@ -2639,13 +2683,17 @@ export async function initializeSettings(): Promise<void> {
useSettingsStore.setState({ [key]: value });
if (key === "gcalAccounts" && Array.isArray(value)) {
- const accounts = value as GoogleCalendarAccount[];
+ const accounts = value as CalendarAccount[];
useSettingsStore.setState({
gcalConnected: accounts.length > 0,
gcalEmail: accounts[0]?.email ?? "",
});
}
+ if (key === "mcalAccounts" && Array.isArray(value)) {
+ useSettingsStore.setState({ mcalConnected: (value as CalendarAccount[]).length > 0 });
+ }
+
if (key === "uiLanguage" && typeof value === "string") {
void i18n.changeLanguage(value);
}
diff --git a/src/types/calendar.ts b/src/types/calendar.ts
index e32e6a6aa..a0db826b1 100644
--- a/src/types/calendar.ts
+++ b/src/types/calendar.ts
@@ -24,7 +24,7 @@ export interface CalendarEvent {
attendees: string | null;
}
-export interface GoogleCalendarAccount {
+export interface CalendarAccount {
email: string;
}
diff --git a/src/types/electron.ts b/src/types/electron.ts
index 589056768..b2a17cef6 100644
--- a/src/types/electron.ts
+++ b/src/types/electron.ts
@@ -2242,6 +2242,17 @@ declare global {
onGcalConnectionChanged?: (callback: (data: any) => void) => () => void;
onGcalEventsSynced?: (callback: (data: any) => void) => () => void;
+ // Microsoft Calendar
+ mcalStartOAuth?: () => Promise<{ success: boolean; email?: string; error?: string }>;
+ mcalDisconnect?: (email?: string) => Promise<{ success: boolean; error?: string }>;
+ mcalGetConnectionStatus?: () => Promise<{
+ connected: boolean;
+ accounts: Array<{ email: string }>;
+ }>;
+ mcalSetPrimaryOnly?: (value: boolean) => Promise<{ success: boolean; error?: string }>;
+ onMcalConnectionChanged?: (callback: (data: any) => void) => () => void;
+ onMcalEventsSynced?: (callback: (data: any) => void) => () => void;
+
// Apple Calendar (macOS EventKit)
acalConnect?: () => Promise<{ success: boolean; reason?: string; error?: string }>;
acalDisconnect?: () => Promise<{ success: boolean; error?: string }>;