Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

feat(calendar): unified Google/Outlook calendar page with agenda and grid views

Adam Eivycd2f45860850
diff --git a/client/src/App.jsx b/client/src/App.jsx
index 8b22842bb6..34d07bc4d4 100644
--- a/client/src/App.jsx
+++ b/client/src/App.jsx
@@ -52,6 +52,7 @@ const CyberCity = lazyWithReload(() => import('./pages/CyberCity'));
const AppDetail = lazyWithReload(() => import('./pages/AppDetail'));
const FeatureAgents = lazyWithReload(() => import('./pages/FeatureAgents'));
const FeatureAgentDetail = lazyWithReload(() => import('./pages/FeatureAgentDetail'));
+const CalendarPage = lazyWithReload(() => import('./pages/Calendar'));
const Messages = lazyWithReload(() => import('./pages/Messages'));
const Goals = lazyWithReload(() => import('./pages/Goals'));
@@ -87,6 +88,8 @@ export default function App() {
<Route path="prompts" element={<PromptManager />} />
<Route path="cos" element={<Navigate to="/cos/tasks" replace />} />
<Route path="cos/:tab" element={<ChiefOfStaff />} />
+ <Route path="calendar" element={<Navigate to="/calendar/agenda" replace />} />
+ <Route path="calendar/:tab" element={<CalendarPage />} />
<Route path="brain" element={<Navigate to="/brain/inbox" replace />} />
<Route path="brain/:tab" element={<Brain />} />
<Route path="digital-twin" element={<Navigate to="/digital-twin/overview" replace />} />
diff --git a/client/src/components/Layout.jsx b/client/src/components/Layout.jsx
index c804050ac0..be9f037b7a 100644
--- a/client/src/components/Layout.jsx
+++ b/client/src/components/Layout.jsx
@@ -33,6 +33,7 @@ import {
Target,
Clock,
Calendar,
+ CalendarDays,
GraduationCap,
Settings,
Users,
@@ -100,6 +101,18 @@ const navItems = [
{ to: '/brain/trust', label: 'Trust', icon: Shield }
]
},
+ {
+ label: 'Calendar',
+ icon: CalendarDays,
+ children: [
+ { to: '/calendar/agenda', label: 'Agenda', icon: CalendarDays },
+ { to: '/calendar/config', label: 'Config', icon: Settings },
+ { to: '/calendar/day', label: 'Day', icon: Calendar },
+ { to: '/calendar/month', label: 'Month', icon: CalendarDays },
+ { to: '/calendar/sync', label: 'Sync', icon: RefreshCw },
+ { to: '/calendar/week', label: 'Week', icon: CalendarDays }
+ ]
+ },
{
label: 'Chief of Staff',
icon: Crown,
@@ -612,7 +625,8 @@ export default function Layout() {
{/* Main content */}
{(() => {
- const isFullWidth = location.pathname.startsWith('/cos') ||
+ const isFullWidth = location.pathname.startsWith('/calendar') ||
+ location.pathname.startsWith('/cos') ||
location.pathname.startsWith('/brain') ||
location.pathname.startsWith('/digital-twin') ||
location.pathname.startsWith('/feature-agents') ||
diff --git a/client/src/components/calendar/AgendaTab.jsx b/client/src/components/calendar/AgendaTab.jsx
new file mode 100644
index 0000000000..3098a46b99
--- /dev/null
+++ b/client/src/components/calendar/AgendaTab.jsx
@@ -0,0 +1,199 @@
+import { useState, useEffect, useCallback } from 'react';
+import { RefreshCw, Search, MapPin, Users, Clock } from 'lucide-react';
+import toast from 'react-hot-toast';
+import * as api from '../../services/api';
+import socket from '../../services/socket';
+import EventDetail from './EventDetail';
+
+const RSVP_STYLES = {
+ accepted: 'bg-port-success/20 text-port-success',
+ declined: 'bg-port-error/20 text-port-error',
+ tentative: 'bg-port-warning/20 text-port-warning',
+ none: 'bg-gray-700 text-gray-400'
+};
+
+function formatTime(dateStr) {
+ return new Date(dateStr).toLocaleTimeString([], { hour: 'numeric', minute: '2-digit' });
+}
+
+function formatDayHeader(dateStr) {
+ const date = new Date(dateStr);
+ const today = new Date();
+ const tomorrow = new Date(today);
+ tomorrow.setDate(tomorrow.getDate() + 1);
+
+ if (date.toDateString() === today.toDateString()) return 'Today';
+ if (date.toDateString() === tomorrow.toDateString()) return 'Tomorrow';
+ return date.toLocaleDateString([], { weekday: 'long', month: 'short', day: 'numeric' });
+}
+
+function groupEventsByDay(events) {
+ const groups = {};
+ for (const event of events) {
+ const dayKey = new Date(event.startTime).toDateString();
+ if (!groups[dayKey]) groups[dayKey] = [];
+ groups[dayKey].push(event);
+ }
+ return Object.entries(groups)
+ .sort(([a], [b]) => new Date(a) - new Date(b))
+ .map(([dayKey, dayEvents]) => ({
+ date: dayKey,
+ events: dayEvents.sort((a, b) => new Date(a.startTime) - new Date(b.startTime))
+ }));
+}
+
+export default function AgendaTab({ accounts }) {
+ const [events, setEvents] = useState([]);
+ const [loading, setLoading] = useState(true);
+ const [search, setSearch] = useState('');
+ const [accountFilter, setAccountFilter] = useState('');
+ const [selectedEvent, setSelectedEvent] = useState(null);
+ const [syncing, setSyncing] = useState(false);
+
+ const fetchEvents = useCallback(async () => {
+ const params = {};
+ if (accountFilter) params.accountId = accountFilter;
+ if (search) params.search = search;
+ const data = await api.getCalendarEvents(params).catch(() => ({ events: [] }));
+ setEvents(data?.events || []);
+ setLoading(false);
+ }, [accountFilter, search]);
+
+ useEffect(() => {
+ fetchEvents();
+ }, [fetchEvents]);
+
+ useEffect(() => {
+ const onSyncCompleted = () => {
+ fetchEvents();
+ };
+ socket.on('calendar:sync:completed', onSyncCompleted);
+ return () => {
+ socket.off('calendar:sync:completed', onSyncCompleted);
+ };
+ }, [fetchEvents]);
+
+ const handleSync = async () => {
+ setSyncing(true);
+ const enabledAccounts = accounts.filter(a => a.enabled);
+ for (const account of enabledAccounts) {
+ await api.syncCalendarAccount(account.id).catch(() => null);
+ }
+ setSyncing(false);
+ toast.success('Calendar sync started');
+ };
+
+ const filtered = events;
+ const grouped = groupEventsByDay(filtered);
+
+ return (
+ <div className="space-y-4">
+ {/* Controls */}
+ <div className="flex flex-wrap items-center gap-3">
+ <div className="relative flex-1 min-w-[200px]">
+ <Search size={16} className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-500" />
+ <input
+ type="text"
+ value={search}
+ onChange={(e) => setSearch(e.target.value)}
+ placeholder="Search events..."
+ className="w-full pl-9 pr-3 py-2 bg-port-card border border-port-border rounded-lg text-sm text-white placeholder-gray-500 focus:outline-none focus:border-port-accent"
+ />
+ </div>
+ {accounts.length > 1 && (
+ <select
+ value={accountFilter}
+ onChange={(e) => setAccountFilter(e.target.value)}
+ className="px-3 py-2 bg-port-card border border-port-border rounded-lg text-sm text-white focus:outline-none focus:border-port-accent"
+ >
+ <option value="">All accounts</option>
+ {accounts.map(a => (
+ <option key={a.id} value={a.id}>{a.name}</option>
+ ))}
+ </select>
+ )}
+ <button
+ onClick={handleSync}
+ disabled={syncing || accounts.filter(a => a.enabled).length === 0}
+ className="flex items-center gap-2 px-3 py-2 bg-port-accent/10 text-port-accent rounded-lg text-sm hover:bg-port-accent/20 transition-colors disabled:opacity-50"
+ >
+ <RefreshCw size={14} className={syncing ? 'animate-spin' : ''} />
+ Sync
+ </button>
+ </div>
+
+ {/* Event list */}
+ {loading ? (
+ <div className="flex items-center justify-center py-12">
+ <RefreshCw size={24} className="text-port-accent animate-spin" />
+ </div>
+ ) : grouped.length === 0 ? (
+ <div className="text-center py-12 text-gray-500">
+ <Clock size={48} className="mx-auto mb-4 opacity-50" />
+ <p>No upcoming events</p>
+ <p className="text-sm mt-1">Sync your calendar accounts to see events here</p>
+ </div>
+ ) : (
+ <div className="space-y-6">
+ {grouped.map((group) => (
+ <div key={group.date}>
+ <h3 className="text-sm font-semibold text-gray-400 mb-2 sticky top-0 bg-port-bg py-1">
+ {formatDayHeader(group.date)}
+ </h3>
+ <div className="space-y-1">
+ {group.events.map((event) => (
+ <button
+ key={`${event.accountId}-${event.id}`}
+ onClick={() => setSelectedEvent(event)}
+ className="w-full text-left flex items-center gap-3 p-3 bg-port-card rounded-lg border border-port-border hover:border-port-accent/50 transition-colors"
+ >
+ <div className="flex-1 min-w-0">
+ <div className="flex items-center gap-2">
+ <span className="text-sm font-medium text-white truncate">{event.title}</span>
+ {event.isAllDay && (
+ <span className="px-1.5 py-0.5 text-[10px] font-medium bg-port-accent/20 text-port-accent rounded">
+ All day
+ </span>
+ )}
+ </div>
+ <div className="flex items-center gap-3 mt-1 text-xs text-gray-500">
+ {!event.isAllDay && (
+ <span className="flex items-center gap-1">
+ <Clock size={12} />
+ {formatTime(event.startTime)} - {formatTime(event.endTime)}
+ </span>
+ )}
+ {event.location && (
+ <span className="flex items-center gap-1 truncate">
+ <MapPin size={12} />
+ {event.location}
+ </span>
+ )}
+ {event.attendees?.length > 0 && (
+ <span className="flex items-center gap-1">
+ <Users size={12} />
+ {event.attendees.length}
+ </span>
+ )}
+ </div>
+ </div>
+ {event.myStatus && event.myStatus !== 'none' && event.myStatus !== 'unknown' && (
+ <span className={`px-2 py-0.5 text-[10px] font-medium rounded ${RSVP_STYLES[event.myStatus] || RSVP_STYLES.none}`}>
+ {event.myStatus}
+ </span>
+ )}
+ </button>
+ ))}
+ </div>
+ </div>
+ ))}
+ </div>
+ )}
+
+ {/* Event detail slide-out */}
+ {selectedEvent && (
+ <EventDetail event={selectedEvent} onClose={() => setSelectedEvent(null)} />
+ )}
+ </div>
+ );
+}
diff --git a/client/src/components/calendar/ConfigTab.jsx b/client/src/components/calendar/ConfigTab.jsx
new file mode 100644
index 0000000000..9841284065
--- /dev/null
+++ b/client/src/components/calendar/ConfigTab.jsx
@@ -0,0 +1,170 @@
+import { useState } from 'react';
+import { Plus, Trash2, RefreshCw, Globe, Mail } from 'lucide-react';
+import toast from 'react-hot-toast';
+import * as api from '../../services/api';
+
+const TYPE_ICONS = { 'outlook-calendar': Globe, 'gmail-calendar': Mail };
+const TYPE_LABELS = { 'outlook-calendar': 'Outlook Calendar (API)', 'gmail-calendar': 'Google Calendar (API)' };
+
+export default function ConfigTab({ accounts, setAccounts }) {
+ const [showForm, setShowForm] = useState(false);
+ const [form, setForm] = useState({ name: '', type: 'outlook-calendar', email: '' });
+ const [saving, setSaving] = useState(false);
+ const [deleting, setDeleting] = useState(null);
+
+ const handleCreate = async () => {
+ if (!form.name) return toast.error('Name is required');
+ setSaving(true);
+ const result = await api.createCalendarAccount(form).catch(() => null);
+ setSaving(false);
+ if (!result) return toast.error('Failed to create account');
+ setShowForm(false);
+ setForm({ name: '', type: 'outlook-calendar', email: '' });
+ toast.success('Account created');
+ setAccounts(prev => [...prev, result]);
+ };
+
+ const handleDelete = async (id) => {
+ setDeleting(id);
+ const ok = await api.deleteCalendarAccount(id).then(() => true).catch(() => false);
+ setDeleting(null);
+ if (!ok) return;
+ toast.success('Account deleted');
+ setAccounts(prev => prev.filter(a => a.id !== id));
+ };
+
+ const handleToggle = async (account) => {
+ const result = await api.updateCalendarAccount(account.id, { enabled: !account.enabled }).catch(() => null);
+ if (!result) return toast.error('Failed to update account');
+ toast.success(account.enabled ? 'Account disabled' : 'Account enabled');
+ setAccounts(prev => prev.map(a => a.id === account.id ? { ...a, enabled: !a.enabled } : a));
+ };
+
+ return (
+ <div className="space-y-8">
+ {/* Accounts */}
+ <section>
+ <div className="flex items-center justify-between mb-3">
+ <h2 className="text-lg font-semibold text-white">Calendar Accounts</h2>
+ <button
+ onClick={() => setShowForm(!showForm)}
+ className="flex items-center gap-2 px-3 py-2 bg-port-accent text-white rounded-lg text-sm hover:bg-port-accent/80 transition-colors"
+ >
+ <Plus size={16} />
+ Add Account
+ </button>
+ </div>
+
+ {showForm && (
+ <div className="p-4 bg-port-card rounded-lg border border-port-border space-y-3 mb-4">
+ <div>
+ <label className="block text-sm text-gray-400 mb-1">Name</label>
+ <input
+ type="text"
+ value={form.name}
+ onChange={(e) => setForm(f => ({ ...f, name: e.target.value }))}
+ placeholder="e.g. Work Calendar"
+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-sm text-white placeholder-gray-500 focus:outline-none focus:border-port-accent"
+ />
+ </div>
+ <div>
+ <label className="block text-sm text-gray-400 mb-1">Type</label>
+ <select
+ value={form.type}
+ onChange={(e) => setForm(f => ({ ...f, type: e.target.value }))}
+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-sm text-white focus:outline-none focus:border-port-accent"
+ >
+ <option value="outlook-calendar">Outlook Calendar (API)</option>
+ <option value="gmail-calendar">Google Calendar (API)</option>
+ </select>
+ </div>
+ <div>
+ <label className="block text-sm text-gray-400 mb-1">Email</label>
+ <input
+ type="email"
+ value={form.email}
+ onChange={(e) => setForm(f => ({ ...f, email: e.target.value }))}
+ placeholder="[email protected]"
+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-sm text-white placeholder-gray-500 focus:outline-none focus:border-port-accent"
+ />
+ </div>
+ <div className="flex gap-2">
+ <button
+ onClick={handleCreate}
+ disabled={saving}
+ className="px-4 py-2 bg-port-accent text-white rounded-lg text-sm hover:bg-port-accent/80 transition-colors disabled:opacity-50"
+ >
+ {saving ? 'Creating...' : 'Create'}
+ </button>
+ <button
+ onClick={() => setShowForm(false)}
+ className="px-4 py-2 bg-port-border text-gray-300 rounded-lg text-sm hover:bg-port-border/80 transition-colors"
+ >
+ Cancel
+ </button>
+ </div>
+ </div>
+ )}
+
+ {accounts.length === 0 && !showForm && (
+ <div className="text-center py-12 text-gray-500">
+ <Globe size={48} className="mx-auto mb-4 opacity-50" />
+ <p>No calendar accounts configured</p>
+ <p className="text-sm mt-1">Add an Outlook or Google Calendar account to get started</p>
+ </div>
+ )}
+
+ <div className="space-y-2">
+ {accounts.map((account) => {
+ const Icon = TYPE_ICONS[account.type] || Globe;
+ return (
+ <div
+ key={account.id}
+ className="flex items-center justify-between p-4 bg-port-card rounded-lg border border-port-border"
+ >
+ <div className="flex items-center gap-3">
+ <Icon size={20} className={account.enabled ? 'text-port-accent' : 'text-gray-600'} />
+ <div>
+ <div className="text-sm font-medium text-white">{account.name}</div>
+ <div className="text-xs text-gray-500">
+ {TYPE_LABELS[account.type]} · {account.email || 'No email set'}
+ </div>
+ {account.lastSyncAt && (
+ <div className="text-xs text-gray-600">
+ Last sync: {new Date(account.lastSyncAt).toLocaleString()} ({account.lastSyncStatus})
+ </div>
+ )}
+ </div>
+ </div>
+ <div className="flex items-center gap-2">
+ <button
+ onClick={() => handleToggle(account)}
+ className={`px-2 py-1 rounded text-xs transition-colors ${
+ account.enabled
+ ? 'bg-port-success/20 text-port-success'
+ : 'bg-gray-700 text-gray-400'
+ }`}
+ >
+ {account.enabled ? 'Enabled' : 'Disabled'}
+ </button>
+ <button
+ onClick={() => handleDelete(account.id)}
+ disabled={deleting === account.id}
+ className="p-1 text-gray-500 hover:text-port-error transition-colors"
+ title="Delete account"
+ >
+ {deleting === account.id ? (
+ <RefreshCw size={16} className="animate-spin" />
+ ) : (
+ <Trash2 size={16} />
+ )}
+ </button>
+ </div>
+ </div>
+ );
+ })}
+ </div>
+ </section>
+ </div>
+ );
+}
diff --git a/client/src/components/calendar/DayView.jsx b/client/src/components/calendar/DayView.jsx
new file mode 100644
index 0000000000..6a7f211449
--- /dev/null
+++ b/client/src/components/calendar/DayView.jsx
@@ -0,0 +1,166 @@
+import { useState, useEffect, useCallback } from 'react';
+import { ChevronLeft, ChevronRight, RefreshCw, MapPin, Users } from 'lucide-react';
+import * as api from '../../services/api';
+import socket from '../../services/socket';
+import EventDetail from './EventDetail';
+
+const HOURS = Array.from({ length: 17 }, (_, i) => i + 6); // 6am to 10pm
+
+function formatHour(hour) {
+ if (hour === 0) return '12 AM';
+ if (hour < 12) return `${hour} AM`;
+ if (hour === 12) return '12 PM';
+ return `${hour - 12} PM`;
+}
+
+function getEventPosition(event) {
+ const start = new Date(event.startTime);
+ const end = new Date(event.endTime);
+ const startMinutes = start.getHours() * 60 + start.getMinutes();
+ const endMinutes = end.getHours() * 60 + end.getMinutes();
+ const top = ((startMinutes - 360) / 60) * 64; // 64px per hour, starting at 6am (360min)
+ const height = Math.max(((endMinutes - startMinutes) / 60) * 64, 24);
+ return { top: Math.max(top, 0), height };
+}
+
+function formatDate(date) {
+ return date.toLocaleDateString([], { weekday: 'long', month: 'long', day: 'numeric', year: 'numeric' });
+}
+
+export default function DayView({ accounts }) {
+ const [date, setDate] = useState(() => {
+ const d = new Date();
+ d.setHours(0, 0, 0, 0);
+ return d;
+ });
+ const [events, setEvents] = useState([]);
+ const [loading, setLoading] = useState(true);
+ const [selectedEvent, setSelectedEvent] = useState(null);
+
+ const fetchEvents = useCallback(async () => {
+ const startDate = date.toISOString();
+ const endDate = new Date(date.getTime() + 24 * 60 * 60 * 1000).toISOString();
+ const data = await api.getCalendarEvents({ startDate, endDate, limit: 200 }).catch(() => ({ events: [] }));
+ setEvents(data?.events || []);
+ setLoading(false);
+ }, [date]);
+
+ useEffect(() => { fetchEvents(); }, [fetchEvents]);
+ useEffect(() => {
+ socket.on('calendar:sync:completed', fetchEvents);
+ return () => socket.off('calendar:sync:completed', fetchEvents);
+ }, [fetchEvents]);
+
+ const navigate = (days) => {
+ setDate(prev => {
+ const d = new Date(prev);
+ d.setDate(d.getDate() + days);
+ return d;
+ });
+ setLoading(true);
+ };
+
+ const goToday = () => {
+ const d = new Date();
+ d.setHours(0, 0, 0, 0);
+ setDate(d);
+ setLoading(true);
+ };
+
+ const allDayEvents = events.filter(e => e.isAllDay);
+ const timedEvents = events.filter(e => !e.isAllDay);
+
+ // Current time indicator
+ const now = new Date();
+ const isToday = date.toDateString() === now.toDateString();
+ const nowMinutes = now.getHours() * 60 + now.getMinutes();
+ const nowTop = ((nowMinutes - 360) / 60) * 64;
+
+ return (
+ <div className="space-y-4">
+ {/* Nav header */}
+ <div className="flex items-center justify-between">
+ <div className="flex items-center gap-2">
+ <button onClick={() => navigate(-1)} className="p-1.5 text-gray-400 hover:text-white rounded hover:bg-port-border transition-colors">
+ <ChevronLeft size={18} />
+ </button>
+ <button onClick={() => navigate(1)} className="p-1.5 text-gray-400 hover:text-white rounded hover:bg-port-border transition-colors">
+ <ChevronRight size={18} />
+ </button>
+ <h2 className="text-lg font-semibold text-white ml-2">{formatDate(date)}</h2>
+ </div>
+ <button onClick={goToday} className="px-3 py-1.5 text-sm text-gray-400 hover:text-white bg-port-card border border-port-border rounded hover:bg-port-border transition-colors">
+ Today
+ </button>
+ </div>
+
+ {loading ? (
+ <div className="flex items-center justify-center py-12">
+ <RefreshCw size={24} className="text-port-accent animate-spin" />
+ </div>
+ ) : (
+ <>
+ {/* All-day events */}
+ {allDayEvents.length > 0 && (
+ <div className="space-y-1">
+ <span className="text-xs text-gray-500 uppercase">All Day</span>
+ {allDayEvents.map(event => (
+ <button
+ key={`${event.accountId}-${event.id}`}
+ onClick={() => setSelectedEvent(event)}
+ className="w-full text-left px-3 py-2 bg-port-accent/10 text-port-accent rounded text-sm hover:bg-port-accent/20 transition-colors"
+ >
+ {event.title}
+ </button>
+ ))}
+ </div>
+ )}
+
+ {/* Time grid */}
+ <div className="relative border border-port-border rounded-lg overflow-hidden bg-port-card">
+ {HOURS.map(hour => (
+ <div key={hour} className="flex border-b border-port-border last:border-b-0" style={{ height: 64 }}>
+ <div className="w-16 shrink-0 text-xs text-gray-500 text-right pr-2 pt-1">
+ {formatHour(hour)}
+ </div>
+ <div className="flex-1 border-l border-port-border" />
+ </div>
+ ))}
+
+ {/* Events overlay */}
+ <div className="absolute top-0 left-16 right-0 bottom-0">
+ {timedEvents.map(event => {
+ const { top, height } = getEventPosition(event);
+ return (
+ <button
+ key={`${event.accountId}-${event.id}`}
+ onClick={() => setSelectedEvent(event)}
+ className="absolute left-1 right-1 px-2 py-1 bg-port-accent/20 border-l-2 border-port-accent rounded text-left overflow-hidden hover:bg-port-accent/30 transition-colors"
+ style={{ top, height, minHeight: 24 }}
+ >
+ <div className="text-xs font-medium text-white truncate">{event.title}</div>
+ {height > 32 && event.location && (
+ <div className="flex items-center gap-1 text-[10px] text-gray-400 truncate">
+ <MapPin size={10} /> {event.location}
+ </div>
+ )}
+ </button>
+ );
+ })}
+
+ {/* Current time line */}
+ {isToday && nowTop >= 0 && nowTop <= HOURS.length * 64 && (
+ <div className="absolute left-0 right-0 flex items-center pointer-events-none" style={{ top: nowTop }}>
+ <div className="w-2 h-2 rounded-full bg-port-error -ml-1" />
+ <div className="flex-1 h-px bg-port-error" />
+ </div>
+ )}
+ </div>
+ </div>
+ </>
+ )}
+
+ {selectedEvent && <EventDetail event={selectedEvent} onClose={() => setSelectedEvent(null)} />}
+ </div>
+ );
+}
diff --git a/client/src/components/calendar/EventDetail.jsx b/client/src/components/calendar/EventDetail.jsx
new file mode 100644
index 0000000000..998aa052f9
--- /dev/null
+++ b/client/src/components/calendar/EventDetail.jsx
@@ -0,0 +1,138 @@
+import { X, MapPin, Clock, Users, Repeat, CalendarDays } from 'lucide-react';
+
+const RSVP_STYLES = {
+ accepted: 'bg-port-success/20 text-port-success',
+ declined: 'bg-port-error/20 text-port-error',
+ tentative: 'bg-port-warning/20 text-port-warning',
+ none: 'bg-gray-700 text-gray-400'
+};
+
+function formatDateTime(dateStr, isAllDay) {
+ if (isAllDay) return new Date(dateStr).toLocaleDateString([], { weekday: 'long', month: 'long', day: 'numeric', year: 'numeric' });
+ return new Date(dateStr).toLocaleString([], { weekday: 'short', month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit' });
+}
+
+export default function EventDetail({ event, onClose }) {
+ return (
+ <div className="fixed inset-0 z-50 flex justify-end">
+ <div
+ role="button"
+ tabIndex={0}
+ aria-label="Close panel"
+ className="absolute inset-0 bg-black/50"
+ onClick={onClose}
+ onKeyDown={(e) => e.key === 'Escape' && onClose()}
+ />
+ <div className="relative w-full max-w-md bg-port-card border-l border-port-border overflow-y-auto animate-slide-in-right">
+ <div className="sticky top-0 bg-port-card border-b border-port-border p-4 flex items-center justify-between">
+ <h2 className="text-lg font-semibold text-white truncate">{event.title}</h2>
+ <button
+ onClick={onClose}
+ className="p-1 text-gray-400 hover:text-white transition-colors"
+ aria-label="Close"
+ >
+ <X size={20} />
+ </button>
+ </div>
+
+ <div className="p-4 space-y-4">
+ {/* Time */}
+ <div className="flex items-start gap-3">
+ <Clock size={16} className="text-gray-500 mt-0.5 shrink-0" />
+ <div className="text-sm text-gray-300">
+ {event.isAllDay ? (
+ <div className="flex items-center gap-2">
+ <CalendarDays size={14} className="text-port-accent" />
+ <span>All day</span>
+ </div>
+ ) : (
+ <>
+ <div>{formatDateTime(event.startTime, false)}</div>
+ <div className="text-gray-500">to</div>
+ <div>{formatDateTime(event.endTime, false)}</div>
+ </>
+ )}
+ {event.isAllDay && (
+ <div className="mt-1 text-gray-500">{formatDateTime(event.startTime, true)}</div>
+ )}
+ </div>
+ </div>
+
+ {/* Location */}
+ {event.location && (
+ <div className="flex items-start gap-3">
+ <MapPin size={16} className="text-gray-500 mt-0.5 shrink-0" />
+ <span className="text-sm text-gray-300">{event.location}</span>
+ </div>
+ )}
+
+ {/* Recurrence */}
+ {event.recurrence && (
+ <div className="flex items-start gap-3">
+ <Repeat size={16} className="text-gray-500 mt-0.5 shrink-0" />
+ <span className="text-sm text-gray-300">Recurring event</span>
+ </div>
+ )}
+
+ {/* Description */}
+ {event.description && (
+ <div className="p-3 bg-port-bg rounded-lg border border-port-border">
+ <p className="text-sm text-gray-400 whitespace-pre-wrap break-words">{event.description}</p>
+ </div>
+ )}
+
+ {/* Organizer */}
+ {event.organizer && (
+ <div>
+ <h3 className="text-xs font-medium text-gray-500 uppercase mb-2">Organizer</h3>
+ <div className="text-sm text-gray-300">
+ {event.organizer.name || event.organizer.email}
+ {event.organizer.name && event.organizer.email && (
+ <span className="text-gray-500 ml-1">({event.organizer.email})</span>
+ )}
+ </div>
+ </div>
+ )}
+
+ {/* Attendees */}
+ {event.attendees?.length > 0 && (
+ <div>
+ <h3 className="text-xs font-medium text-gray-500 uppercase mb-2 flex items-center gap-2">
+ <Users size={14} />
+ Attendees ({event.attendees.length})
+ </h3>
+ <div className="space-y-1.5">
+ {event.attendees.map((attendee, i) => (
+ <div
+ key={i}
+ className="flex items-center justify-between p-2 bg-port-bg rounded border border-port-border"
+ >
+ <div className="text-sm text-gray-300 truncate">
+ {attendee.name || attendee.email}
+ {attendee.name && attendee.email && (
+ <span className="text-gray-500 ml-1 text-xs">({attendee.email})</span>
+ )}
+ </div>
+ <span className={`px-2 py-0.5 text-[10px] font-medium rounded shrink-0 ${RSVP_STYLES[attendee.status] || RSVP_STYLES.none}`}>
+ {attendee.status || 'none'}
+ </span>
+ </div>
+ ))}
+ </div>
+ </div>
+ )}
+
+ {/* Response status */}
+ {event.myStatus && event.myStatus !== 'none' && event.myStatus !== 'unknown' && (
+ <div>
+ <h3 className="text-xs font-medium text-gray-500 uppercase mb-2">Your Response</h3>
+ <span className={`px-2 py-1 text-xs font-medium rounded ${RSVP_STYLES[event.myStatus] || RSVP_STYLES.none}`}>
+ {event.myStatus}
+ </span>
+ </div>
+ )}
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/client/src/components/calendar/MonthView.jsx b/client/src/components/calendar/MonthView.jsx
new file mode 100644
index 0000000000..b011331a88
--- /dev/null
+++ b/client/src/components/calendar/MonthView.jsx
@@ -0,0 +1,167 @@
+import { useState, useEffect, useCallback } from 'react';
+import { ChevronLeft, ChevronRight, RefreshCw } from 'lucide-react';
+import * as api from '../../services/api';
+import socket from '../../services/socket';
+import EventDetail from './EventDetail';
+
+function getMonthGrid(year, month) {
+ const firstDay = new Date(year, month, 1);
+ const lastDay = new Date(year, month + 1, 0);
+ const startOffset = firstDay.getDay();
+ const totalDays = lastDay.getDate();
+
+ const cells = [];
+ // Leading empty cells
+ for (let i = 0; i < startOffset; i++) {
+ const d = new Date(year, month, -startOffset + i + 1);
+ cells.push({ date: d, isCurrentMonth: false });
+ }
+ // Current month
+ for (let i = 1; i <= totalDays; i++) {
+ cells.push({ date: new Date(year, month, i), isCurrentMonth: true });
+ }
+ // Trailing empty cells to fill 6 rows
+ while (cells.length < 42) {
+ const d = new Date(year, month + 1, cells.length - startOffset - totalDays + 1);
+ cells.push({ date: d, isCurrentMonth: false });
+ }
+ return cells;
+}
+
+const DAY_NAMES = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
+
+export default function MonthView({ accounts }) {
+ const now = new Date();
+ const [year, setYear] = useState(now.getFullYear());
+ const [month, setMonth] = useState(now.getMonth());
+ const [events, setEvents] = useState([]);
+ const [loading, setLoading] = useState(true);
+ const [selectedEvent, setSelectedEvent] = useState(null);
+
+ const cells = getMonthGrid(year, month);
+ const monthLabel = new Date(year, month).toLocaleDateString([], { month: 'long', year: 'numeric' });
+
+ const fetchEvents = useCallback(async () => {
+ const startDate = cells[0].date.toISOString();
+ const endDate = new Date(cells[cells.length - 1].date.getTime() + 24 * 60 * 60 * 1000).toISOString();
+ const data = await api.getCalendarEvents({ startDate, endDate, limit: 500 }).catch(() => ({ events: [] }));
+ setEvents(data?.events || []);
+ setLoading(false);
+ }, [year, month]);
+
+ useEffect(() => { fetchEvents(); }, [fetchEvents]);
+ useEffect(() => {
+ socket.on('calendar:sync:completed', fetchEvents);
+ return () => socket.off('calendar:sync:completed', fetchEvents);
+ }, [fetchEvents]);
+
+ const navigate = (dir) => {
+ setLoading(true);
+ if (dir === -1) {
+ if (month === 0) { setMonth(11); setYear(y => y - 1); }
+ else setMonth(m => m - 1);
+ } else {
+ if (month === 11) { setMonth(0); setYear(y => y + 1); }
+ else setMonth(m => m + 1);
+ }
+ };
+
+ const goToday = () => {
+ setYear(now.getFullYear());
+ setMonth(now.getMonth());
+ setLoading(true);
+ };
+
+ // Group events by day string
+ const eventsByDay = {};
+ for (const event of events) {
+ const dayKey = new Date(event.startTime).toDateString();
+ if (!eventsByDay[dayKey]) eventsByDay[dayKey] = [];
+ eventsByDay[dayKey].push(event);
+ }
+
+ const todayStr = now.toDateString();
+
+ return (
+ <div className="space-y-4">
+ {/* Nav header */}
+ <div className="flex items-center justify-between">
+ <div className="flex items-center gap-2">
+ <button onClick={() => navigate(-1)} className="p-1.5 text-gray-400 hover:text-white rounded hover:bg-port-border transition-colors">
+ <ChevronLeft size={18} />
+ </button>
+ <button onClick={() => navigate(1)} className="p-1.5 text-gray-400 hover:text-white rounded hover:bg-port-border transition-colors">
+ <ChevronRight size={18} />
+ </button>
+ <h2 className="text-lg font-semibold text-white ml-2">{monthLabel}</h2>
+ </div>
+ <button onClick={goToday} className="px-3 py-1.5 text-sm text-gray-400 hover:text-white bg-port-card border border-port-border rounded hover:bg-port-border transition-colors">
+ Today
+ </button>
+ </div>
+
+ {loading ? (
+ <div className="flex items-center justify-center py-12">
+ <RefreshCw size={24} className="text-port-accent animate-spin" />
+ </div>
+ ) : (
+ <div className="border border-port-border rounded-lg overflow-hidden bg-port-card">
+ {/* Day name headers */}
+ <div className="grid grid-cols-7 border-b border-port-border">
+ {DAY_NAMES.map(name => (
+ <div key={name} className="text-center py-2 text-xs font-medium text-gray-400">
+ {name}
+ </div>
+ ))}
+ </div>
+
+ {/* Day cells */}
+ <div className="grid grid-cols-7">
+ {cells.map((cell, i) => {
+ const dayStr = cell.date.toDateString();
+ const dayEvents = eventsByDay[dayStr] || [];
+ const isToday = dayStr === todayStr;
+ return (
+ <div
+ key={i}
+ className={`min-h-[80px] p-1 border-b border-r border-port-border/50 ${
+ !cell.isCurrentMonth ? 'bg-port-bg/50' : ''
+ } ${i % 7 === 6 ? 'border-r-0' : ''}`}
+ >
+ <div className={`text-xs mb-0.5 ${
+ isToday
+ ? 'bg-port-accent text-white rounded-full w-6 h-6 flex items-center justify-center'
+ : cell.isCurrentMonth ? 'text-gray-300' : 'text-gray-600'
+ }`}>
+ {cell.date.getDate()}
+ </div>
+ <div className="space-y-0.5">
+ {dayEvents.slice(0, 3).map(event => (
+ <button
+ key={`${event.accountId}-${event.id}`}
+ onClick={() => setSelectedEvent(event)}
+ className="w-full text-left px-1 py-0.5 bg-port-accent/15 text-port-accent rounded text-[10px] truncate hover:bg-port-accent/25 transition-colors"
+ >
+ {!event.isAllDay && (
+ <span className="text-gray-500 mr-1">
+ {new Date(event.startTime).toLocaleTimeString([], { hour: 'numeric', minute: '2-digit' })}
+ </span>
+ )}
+ {event.title}
+ </button>
+ ))}
+ {dayEvents.length > 3 && (
+ <div className="text-[10px] text-gray-500 pl-1">+{dayEvents.length - 3} more</div>
+ )}
+ </div>
+ </div>
+ );
+ })}
+ </div>
+ </div>
+ )}
+
+ {selectedEvent && <EventDetail event={selectedEvent} onClose={() => setSelectedEvent(null)} />}
+ </div>
+ );
+}
diff --git a/client/src/components/calendar/SyncTab.jsx b/client/src/components/calendar/SyncTab.jsx
new file mode 100644
index 0000000000..184aedf0b7
--- /dev/null
+++ b/client/src/components/calendar/SyncTab.jsx
@@ -0,0 +1,172 @@
+import { useState, useEffect, useCallback } from 'react';
+import { RefreshCw, AlertCircle, Key, Trash2, TestTube } from 'lucide-react';
+import toast from 'react-hot-toast';
+import * as api from '../../services/api';
+import socket from '../../services/socket';
+
+export default function SyncTab({ accounts, onRefresh }) {
+ const [syncing, setSyncing] = useState({});
+ const [tokenStatus, setTokenStatus] = useState(null);
+ const [tokenLoading, setTokenLoading] = useState(true);
+
+ const fetchTokenStatus = useCallback(async () => {
+ const data = await api.getCalendarTokenStatus().catch(() => null);
+ setTokenStatus(data);
+ setTokenLoading(false);
+ }, []);
+
+ useEffect(() => {
+ fetchTokenStatus();
+
+ const onSyncStarted = ({ accountId }) => {
+ setSyncing(prev => ({ ...prev, [accountId]: 'syncing' }));
+ };
+ const onSyncCompleted = ({ accountId, newEvents }) => {
+ setSyncing(prev => ({ ...prev, [accountId]: null }));
+ toast.success(`Calendar sync complete: ${newEvents ?? 0} events`);
+ onRefresh();
+ };
+ const onSyncFailed = ({ accountId, error }) => {
+ setSyncing(prev => ({ ...prev, [accountId]: null }));
+ toast.error(`Calendar sync failed: ${error ?? 'unknown error'}`);
+ };
+
+ socket.on('calendar:sync:started', onSyncStarted);
+ socket.on('calendar:sync:completed', onSyncCompleted);
+ socket.on('calendar:sync:failed', onSyncFailed);
+
+ return () => {
+ socket.off('calendar:sync:started', onSyncStarted);
+ socket.off('calendar:sync:completed', onSyncCompleted);
+ socket.off('calendar:sync:failed', onSyncFailed);
+ };
+ }, [fetchTokenStatus, onRefresh]);
+
+ const handleSync = async (accountId) => {
+ setSyncing(prev => ({ ...prev, [accountId]: 'syncing' }));
+ await api.syncCalendarAccount(accountId).catch(() => {
+ setSyncing(prev => ({ ...prev, [accountId]: null }));
+ });
+ };
+
+ const handleTestToken = async (provider) => {
+ const result = await api.testCalendarToken(provider).catch(() => null);
+ if (result?.valid) {
+ toast.success(`${provider} token is valid`);
+ } else {
+ toast.error(`${provider} token is invalid or expired`);
+ }
+ fetchTokenStatus();
+ };
+
+ const handleClearToken = async (provider) => {
+ await api.clearCalendarToken(provider).catch(() => null);
+ toast.success(`${provider} token cleared`);
+ fetchTokenStatus();
+ };
+
+ return (
+ <div className="space-y-6">
+ {/* Sync Status */}
+ <div>
+ <h2 className="text-lg font-semibold text-white mb-3">Sync Status</h2>
+ {accounts.length === 0 && (
+ <p className="text-gray-500 text-sm">No accounts configured. Add one in the Config tab.</p>
+ )}
+ <div className="space-y-2">
+ {accounts.map((account) => (
+ <div
+ key={account.id}
+ className="flex items-center justify-between p-4 bg-port-card rounded-lg border border-port-border"
+ >
+ <div>
+ <div className="text-sm font-medium text-white">{account.name}</div>
+ <div className="text-xs text-gray-500">
+ {account.lastSyncAt
+ ? `Last sync: ${new Date(account.lastSyncAt).toLocaleString()}`
+ : 'Never synced'}
+ {account.lastSyncStatus && ` (${account.lastSyncStatus})`}
+ </div>
+ </div>
+ <div className="flex items-center gap-2">
+ {syncing[account.id] === 'auth-required' && (
+ <span className="flex items-center gap-1 text-xs text-port-warning">
+ <AlertCircle size={14} /> Auth required
+ </span>
+ )}
+ {syncing[account.id] === 'syncing' ? (
+ <RefreshCw size={16} className="text-port-accent animate-spin" />
+ ) : (
+ <button
+ onClick={() => handleSync(account.id)}
+ disabled={!account.enabled}
+ className="flex items-center gap-1 px-3 py-1.5 bg-port-accent/10 text-port-accent rounded text-sm hover:bg-port-accent/20 transition-colors disabled:opacity-50"
+ title="Sync calendar events"
+ >
+ <RefreshCw size={14} /> Sync
+ </button>
+ )}
+ </div>
+ </div>
+ ))}
+ </div>
+ </div>
+
+ {/* Token Debug */}
+ <div>
+ <h2 className="text-lg font-semibold text-white mb-3">Token Debug</h2>
+ <p className="text-sm text-gray-500 mb-3">
+ Calendar API tokens extracted from browser sessions. These are shared with the Messages module.
+ </p>
+ {tokenLoading ? (
+ <RefreshCw size={16} className="text-port-accent animate-spin" />
+ ) : !tokenStatus ? (
+ <p className="text-sm text-gray-500">Could not load token status</p>
+ ) : (
+ <div className="space-y-2">
+ {(tokenStatus.providers || []).map((status) => (
+ <div
+ key={status.provider}
+ className="flex items-center justify-between p-4 bg-port-card rounded-lg border border-port-border"
+ >
+ <div>
+ <div className="text-sm font-medium text-white capitalize">{status.provider}</div>
+ <div className="text-xs text-gray-500">
+ {status.hasToken ? (
+ <span className="text-port-success">Token present</span>
+ ) : (
+ <span className="text-gray-500">No token</span>
+ )}
+ {status.expiresAt && (
+ <span className="ml-2">
+ Expires: {new Date(status.expiresAt).toLocaleString()}
+ </span>
+ )}
+ </div>
+ </div>
+ <div className="flex items-center gap-2">
+ <button
+ onClick={() => handleTestToken(status.provider)}
+ className="flex items-center gap-1 px-2 py-1 text-xs text-gray-400 hover:text-white bg-port-border rounded transition-colors"
+ title="Test token"
+ >
+ <TestTube size={12} /> Test
+ </button>
+ {status.hasToken && (
+ <button
+ onClick={() => handleClearToken(status.provider)}
+ className="flex items-center gap-1 px-2 py-1 text-xs text-gray-400 hover:text-port-error bg-port-border rounded transition-colors"
+ title="Clear token"
+ >
+ <Trash2 size={12} /> Clear
+ </button>
+ )}
+ </div>
+ </div>
+ ))}
+ </div>
+ )}
+ </div>
+ </div>
+ );
+}
diff --git a/client/src/components/calendar/WeekView.jsx b/client/src/components/calendar/WeekView.jsx
new file mode 100644
index 0000000000..fb3c3c5720
--- /dev/null
+++ b/client/src/components/calendar/WeekView.jsx
@@ -0,0 +1,212 @@
+import { useState, useEffect, useCallback } from 'react';
+import { ChevronLeft, ChevronRight, RefreshCw } from 'lucide-react';
+import * as api from '../../services/api';
+import socket from '../../services/socket';
+import EventDetail from './EventDetail';
+
+const HOURS = Array.from({ length: 17 }, (_, i) => i + 6); // 6am to 10pm
+
+function formatHour(hour) {
+ if (hour === 0) return '12 AM';
+ if (hour < 12) return `${hour} AM`;
+ if (hour === 12) return '12 PM';
+ return `${hour - 12} PM`;
+}
+
+function getWeekStart(date) {
+ const d = new Date(date);
+ d.setDate(d.getDate() - d.getDay());
+ d.setHours(0, 0, 0, 0);
+ return d;
+}
+
+function getWeekDays(weekStart) {
+ return Array.from({ length: 7 }, (_, i) => {
+ const d = new Date(weekStart);
+ d.setDate(d.getDate() + i);
+ return d;
+ });
+}
+
+function getEventPosition(event) {
+ const start = new Date(event.startTime);
+ const end = new Date(event.endTime);
+ const startMinutes = start.getHours() * 60 + start.getMinutes();
+ const endMinutes = end.getHours() * 60 + end.getMinutes();
+ const top = ((startMinutes - 360) / 60) * 48; // 48px per hour, starting at 6am
+ const height = Math.max(((endMinutes - startMinutes) / 60) * 48, 18);
+ return { top: Math.max(top, 0), height };
+}
+
+export default function WeekView({ accounts }) {
+ const [weekStart, setWeekStart] = useState(() => getWeekStart(new Date()));
+ const [events, setEvents] = useState([]);
+ const [loading, setLoading] = useState(true);
+ const [selectedEvent, setSelectedEvent] = useState(null);
+
+ const weekDays = getWeekDays(weekStart);
+ const weekEnd = new Date(weekStart);
+ weekEnd.setDate(weekEnd.getDate() + 7);
+
+ const fetchEvents = useCallback(async () => {
+ const data = await api.getCalendarEvents({
+ startDate: weekStart.toISOString(),
+ endDate: weekEnd.toISOString(),
+ limit: 200
+ }).catch(() => ({ events: [] }));
+ setEvents(data?.events || []);
+ setLoading(false);
+ }, [weekStart.getTime()]);
+
+ useEffect(() => { fetchEvents(); }, [fetchEvents]);
+ useEffect(() => {
+ socket.on('calendar:sync:completed', fetchEvents);
+ return () => socket.off('calendar:sync:completed', fetchEvents);
+ }, [fetchEvents]);
+
+ const navigate = (weeks) => {
+ setWeekStart(prev => {
+ const d = new Date(prev);
+ d.setDate(d.getDate() + weeks * 7);
+ return d;
+ });
+ setLoading(true);
+ };
+
+ const goToday = () => {
+ setWeekStart(getWeekStart(new Date()));
+ setLoading(true);
+ };
+
+ // Group events by day
+ const eventsByDay = weekDays.map(day => {
+ const dayStr = day.toDateString();
+ return events.filter(e => new Date(e.startTime).toDateString() === dayStr);
+ });
+
+ const allDayByDay = weekDays.map(day => {
+ const dayStr = day.toDateString();
+ return events.filter(e => e.isAllDay && new Date(e.startTime).toDateString() === dayStr);
+ });
+
+ const now = new Date();
+ const todayStr = now.toDateString();
+ const nowMinutes = now.getHours() * 60 + now.getMinutes();
+ const nowTop = ((nowMinutes - 360) / 60) * 48;
+
+ const weekLabel = `${weekDays[0].toLocaleDateString([], { month: 'short', day: 'numeric' })} - ${weekDays[6].toLocaleDateString([], { month: 'short', day: 'numeric', year: 'numeric' })}`;
+
+ return (
+ <div className="space-y-4">
+ {/* Nav header */}
+ <div className="flex items-center justify-between">
+ <div className="flex items-center gap-2">
+ <button onClick={() => navigate(-1)} className="p-1.5 text-gray-400 hover:text-white rounded hover:bg-port-border transition-colors">
+ <ChevronLeft size={18} />
+ </button>
+ <button onClick={() => navigate(1)} className="p-1.5 text-gray-400 hover:text-white rounded hover:bg-port-border transition-colors">
+ <ChevronRight size={18} />
+ </button>
+ <h2 className="text-lg font-semibold text-white ml-2">{weekLabel}</h2>
+ </div>
+ <button onClick={goToday} className="px-3 py-1.5 text-sm text-gray-400 hover:text-white bg-port-card border border-port-border rounded hover:bg-port-border transition-colors">
+ Today
+ </button>
+ </div>
+
+ {loading ? (
+ <div className="flex items-center justify-center py-12">
+ <RefreshCw size={24} className="text-port-accent animate-spin" />
+ </div>
+ ) : (
+ <div className="border border-port-border rounded-lg overflow-auto bg-port-card">
+ {/* Day headers */}
+ <div className="flex border-b border-port-border sticky top-0 bg-port-card z-10">
+ <div className="w-14 shrink-0" />
+ {weekDays.map((day, i) => {
+ const isToday = day.toDateString() === todayStr;
+ return (
+ <div
+ key={i}
+ className={`flex-1 text-center py-2 text-xs font-medium border-l border-port-border ${isToday ? 'text-port-accent' : 'text-gray-400'}`}
+ >
+ <div>{day.toLocaleDateString([], { weekday: 'short' })}</div>
+ <div className={`text-lg ${isToday ? 'bg-port-accent text-white rounded-full w-8 h-8 flex items-center justify-center mx-auto' : ''}`}>
+ {day.getDate()}
+ </div>
+ </div>
+ );
+ })}
+ </div>
+
+ {/* All-day row */}
+ {allDayByDay.some(d => d.length > 0) && (
+ <div className="flex border-b border-port-border">
+ <div className="w-14 shrink-0 text-[10px] text-gray-500 text-right pr-1 pt-1">All day</div>
+ {allDayByDay.map((dayEvents, i) => (
+ <div key={i} className="flex-1 border-l border-port-border p-0.5 min-h-[28px]">
+ {dayEvents.map(event => (
+ <button
+ key={`${event.accountId}-${event.id}`}
+ onClick={() => setSelectedEvent(event)}
+ className="w-full text-left px-1 py-0.5 bg-port-accent/15 text-port-accent rounded text-[10px] truncate hover:bg-port-accent/25 transition-colors"
+ >
+ {event.title}
+ </button>
+ ))}
+ </div>
+ ))}
+ </div>
+ )}
+
+ {/* Time grid */}
+ <div className="relative">
+ {HOURS.map(hour => (
+ <div key={hour} className="flex border-b border-port-border/50 last:border-b-0" style={{ height: 48 }}>
+ <div className="w-14 shrink-0 text-[10px] text-gray-500 text-right pr-1 -mt-1.5">
+ {formatHour(hour)}
+ </div>
+ {weekDays.map((_, i) => (
+ <div key={i} className="flex-1 border-l border-port-border/50" />
+ ))}
+ </div>
+ ))}
+
+ {/* Events overlay per column */}
+ <div className="absolute top-0 bottom-0 left-14 right-0 flex">
+ {eventsByDay.map((dayEvents, dayIndex) => {
+ const isToday = weekDays[dayIndex].toDateString() === todayStr;
+ return (
+ <div key={dayIndex} className="flex-1 relative border-l border-port-border/50">
+ {dayEvents.filter(e => !e.isAllDay).map(event => {
+ const { top, height } = getEventPosition(event);
+ return (
+ <button
+ key={`${event.accountId}-${event.id}`}
+ onClick={() => setSelectedEvent(event)}
+ className="absolute left-0.5 right-0.5 px-1 py-0.5 bg-port-accent/20 border-l-2 border-port-accent rounded text-left overflow-hidden hover:bg-port-accent/30 transition-colors"
+ style={{ top, height, minHeight: 18 }}
+ >
+ <div className="text-[10px] font-medium text-white truncate">{event.title}</div>
+ </button>
+ );
+ })}
+ {/* Current time line */}
+ {isToday && nowTop >= 0 && nowTop <= HOURS.length * 48 && (
+ <div className="absolute left-0 right-0 flex items-center pointer-events-none z-10" style={{ top: nowTop }}>
+ <div className="w-1.5 h-1.5 rounded-full bg-port-error -ml-0.5" />
+ <div className="flex-1 h-px bg-port-error" />
+ </div>
+ )}
+ </div>
+ );
+ })}
+ </div>
+ </div>
+ </div>
+ )}
+
+ {selectedEvent && <EventDetail event={selectedEvent} onClose={() => setSelectedEvent(null)} />}
+ </div>
+ );
+}
diff --git a/client/src/pages/Calendar.jsx b/client/src/pages/Calendar.jsx
new file mode 100644
index 0000000000..eba44627e3
--- /dev/null
+++ b/client/src/pages/Calendar.jsx
@@ -0,0 +1,114 @@
+import { useParams, useNavigate } from 'react-router-dom';
+import { CalendarDays, Calendar as CalendarIcon, Columns, LayoutGrid, RefreshCw, Settings } from 'lucide-react';
+import { useState, useEffect, useCallback } from 'react';
+import * as api from '../services/api';
+
+import AgendaTab from '../components/calendar/AgendaTab';
+import DayView from '../components/calendar/DayView';
+import WeekView from '../components/calendar/WeekView';
+import MonthView from '../components/calendar/MonthView';
+import ConfigTab from '../components/calendar/ConfigTab';
+import SyncTab from '../components/calendar/SyncTab';
+
+const TABS = [
+ { id: 'agenda', label: 'Agenda', icon: CalendarDays },
+ { id: 'day', label: 'Day', icon: CalendarIcon },
+ { id: 'week', label: 'Week', icon: Columns },
+ { id: 'month', label: 'Month', icon: LayoutGrid },
+ { id: 'sync', label: 'Sync', icon: RefreshCw },
+ { id: 'config', label: 'Config', icon: Settings }
+];
+
+export default function Calendar() {
+ const { tab } = useParams();
+ const navigate = useNavigate();
+ const VALID_TABS = TABS.map(t => t.id);
+ const activeTab = VALID_TABS.includes(tab) ? tab : 'agenda';
+ const [accounts, setAccounts] = useState([]);
+ const [loading, setLoading] = useState(true);
+
+ const fetchAccounts = useCallback(async () => {
+ const data = await api.getCalendarAccounts().catch(() => []);
+ setAccounts(data || []);
+ setLoading(false);
+ }, []);
+
+ useEffect(() => {
+ fetchAccounts();
+ }, [fetchAccounts]);
+
+ const handleTabChange = (tabId) => {
+ navigate(`/calendar/${tabId}`);
+ };
+
+ const renderTabContent = () => {
+ switch (activeTab) {
+ case 'agenda':
+ return <AgendaTab accounts={accounts} />;
+ case 'day':
+ return <DayView accounts={accounts} />;
+ case 'week':
+ return <WeekView accounts={accounts} />;
+ case 'month':
+ return <MonthView accounts={accounts} />;
+ case 'config':
+ return <ConfigTab accounts={accounts} setAccounts={setAccounts} />;
+ case 'sync':
+ return <SyncTab accounts={accounts} onRefresh={fetchAccounts} />;
+ default:
+ return <AgendaTab accounts={accounts} />;
+ }
+ };
+
+ if (loading) {
+ return (
+ <div className="flex items-center justify-center h-full">
+ <RefreshCw className="w-8 h-8 text-port-accent animate-spin" />
+ </div>
+ );
+ }
+
+ return (
+ <div className="flex flex-col h-full">
+ <div className="flex items-center justify-between p-4 border-b border-port-border">
+ <div className="flex items-center gap-3">
+ <CalendarDays className="w-8 h-8 text-port-accent" />
+ <div>
+ <h1 className="text-xl font-bold text-white">Calendar</h1>
+ <p className="text-sm text-gray-500">Unified calendar and event management</p>
+ </div>
+ </div>
+ <div className="flex items-center gap-4 text-sm">
+ <span className="text-gray-500">{accounts.length} accounts</span>
+ </div>
+ </div>
+
+ <div className="flex border-b border-port-border">
+ {TABS.map((tabItem) => {
+ const Icon = tabItem.icon;
+ const isActive = activeTab === tabItem.id;
+ return (
+ <button
+ key={tabItem.id}
+ onClick={() => handleTabChange(tabItem.id)}
+ className={`flex items-center gap-2 px-4 py-3 text-sm font-medium transition-colors ${
+ isActive
+ ? 'text-port-accent border-b-2 border-port-accent bg-port-accent/5'
+ : 'text-gray-400 hover:text-white hover:bg-port-card'
+ }`}
+ role="tab"
+ aria-selected={isActive}
+ >
+ <Icon size={16} aria-hidden="true" />
+ {tabItem.label}
+ </button>
+ );
+ })}
+ </div>
+
+ <div className="flex-1 overflow-auto p-4">
+ {renderTabContent()}
+ </div>
+ </div>
+ );
+}
diff --git a/client/src/services/api.js b/client/src/services/api.js
index 53f09550ea..1e5482610f 100644
--- a/client/src/services/api.js
+++ b/client/src/services/api.js
@@ -1721,6 +1721,22 @@ export const executeMessageAction = (accountId, messageId, action) =>
export const clearMessageCache = (accountId) =>
request(`/messages/accounts/${accountId}/cache/clear`, { method: 'POST' });
+// Calendar
+export const getCalendarAccounts = () => request('/calendar/accounts');
+export const createCalendarAccount = (data) => request('/calendar/accounts', { method: 'POST', body: JSON.stringify(data) });
+export const updateCalendarAccount = (id, data) => request(`/calendar/accounts/${id}`, { method: 'PUT', body: JSON.stringify(data) });
+export const deleteCalendarAccount = (id) => request(`/calendar/accounts/${id}`, { method: 'DELETE' });
+export const syncCalendarAccount = (accountId) => request(`/calendar/sync/${accountId}`, { method: 'POST' });
+export const getCalendarSyncStatus = (accountId) => request(`/calendar/sync/${accountId}/status`);
+export const getCalendarEvents = (params = {}) => {
+ const str = new URLSearchParams(Object.entries(params).filter(([, v]) => v != null)).toString();
+ return request(`/calendar/events${str ? `?${str}` : ''}`);
+};
+export const getCalendarEvent = (accountId, eventId) => request(`/calendar/events/${accountId}/${eventId}`);
+export const getCalendarTokenStatus = () => request('/calendar/debug/token-status');
+export const testCalendarToken = (provider) => request('/calendar/debug/test-token', { method: 'POST', body: JSON.stringify({ provider }) });
+export const clearCalendarToken = (provider) => request('/calendar/debug/clear-token', { method: 'POST', body: JSON.stringify({ provider }) });
+
// Default export for simplified imports
export default {
get: (endpoint, options) => request(endpoint, { method: 'GET', ...options }),
diff --git a/server/index.js b/server/index.js
index 1625fa5b4c..158f30bafd 100644
--- a/server/index.js
+++ b/server/index.js
@@ -36,6 +36,7 @@ import notificationsRoutes from './routes/notifications.js';
import standardizeRoutes from './routes/standardize.js';
import brainRoutes from './routes/brain.js';
import mediaRoutes from './routes/media.js';
+import calendarRoutes from './routes/calendar.js';
import messagesRoutes from './routes/messages.js';
import genomeRoutes from './routes/genome.js';
import digitalTwinRoutes from './routes/digital-twin.js';
@@ -227,6 +228,7 @@ app.use('/api/notifications', notificationsRoutes);
app.use('/api/standardize', standardizeRoutes);
app.use('/api/brain', brainRoutes);
app.use('/api/media', mediaRoutes);
+app.use('/api/calendar', calendarRoutes);
app.use('/api/messages', messagesRoutes);
app.use('/api/digital-twin/social-accounts', socialAccountsRoutes);
app.use('/api/meatspace/genome', genomeRoutes);
diff --git a/server/lib/fileUtils.js b/server/lib/fileUtils.js
index 4e5d60b3ee..dfd804554a 100644
--- a/server/lib/fileUtils.js
+++ b/server/lib/fileUtils.js
@@ -30,6 +30,7 @@ export const PATHS = {
// AI Agent Personalities data
agentPersonalities: join(__lib_dirname, '../../data/agents'),
meatspace: join(__lib_dirname, '../../data/meatspace'),
+ calendar: join(__lib_dirname, '../../data/calendar'),
messages: join(__lib_dirname, '../../data/messages')
};
diff --git a/server/routes/calendar.js b/server/routes/calendar.js
new file mode 100644
index 0000000000..b5e47853e1
--- /dev/null
+++ b/server/routes/calendar.js
@@ -0,0 +1,149 @@
+import express from 'express';
+import { z } from 'zod';
+import { asyncHandler } from '../lib/errorHandler.js';
+import { validateRequest } from '../lib/validation.js';
+import * as calendarAccounts from '../services/calendarAccounts.js';
+import * as calendarSync from '../services/calendarSync.js';
+import { getToken, getTokenStatus, testApi, clearTokenCache } from '../services/messageTokenExtractor.js';
+
+const router = express.Router();
+
+// === Validation Schemas ===
+const createAccountSchema = z.object({
+ name: z.string().min(1),
+ type: z.enum(['outlook-calendar', 'gmail-calendar']),
+ email: z.union([z.string().email(), z.literal('')]).optional().default(''),
+ syncConfig: z.object({
+ maxAge: z.string().optional(),
+ syncInterval: z.number().int().positive().optional(),
+ calendarIds: z.array(z.string()).optional()
+ }).optional()
+});
+
+const updateAccountSchema = z.object({
+ name: z.string().min(1).optional(),
+ email: z.union([z.string().email(), z.literal('')]).optional(),
+ enabled: z.boolean().optional(),
+ syncConfig: z.object({
+ maxAge: z.string().optional(),
+ syncInterval: z.number().int().positive().optional(),
+ calendarIds: z.array(z.string()).optional()
+ }).optional()
+});
+
+// === Account Routes ===
+router.get('/accounts', asyncHandler(async (req, res) => {
+ const accounts = await calendarAccounts.listAccounts();
+ res.json(accounts);
+}));
+
+router.post('/accounts', asyncHandler(async (req, res) => {
+ const data = validateRequest(createAccountSchema, req.body);
+ const account = await calendarAccounts.createAccount(data);
+ req.app.get('io')?.emit('calendar:changed', {});
+ res.status(201).json(account);
+}));
+
+router.put('/accounts/:id', asyncHandler(async (req, res) => {
+ if (!z.string().uuid().safeParse(req.params.id).success) {
+ return res.status(400).json({ error: 'Invalid account ID format' });
+ }
+ const updates = validateRequest(updateAccountSchema, req.body);
+ const account = await calendarAccounts.updateAccount(req.params.id, updates);
+ if (!account) return res.status(404).json({ error: 'Account not found' });
+ req.app.get('io')?.emit('calendar:changed', {});
+ res.json(account);
+}));
+
+router.delete('/accounts/:id', asyncHandler(async (req, res) => {
+ if (!z.string().uuid().safeParse(req.params.id).success) {
+ return res.status(400).json({ error: 'Invalid account ID format' });
+ }
+ const deleted = await calendarAccounts.deleteAccount(req.params.id);
+ if (!deleted) return res.status(404).json({ error: 'Account not found' });
+ await calendarSync.deleteCache(req.params.id).catch(() => {});
+ req.app.get('io')?.emit('calendar:changed', {});
+ res.status(204).send();
+}));
+
+// === Sync Routes ===
+router.post('/sync/:accountId', asyncHandler(async (req, res) => {
+ if (!z.string().uuid().safeParse(req.params.accountId).success) {
+ return res.status(400).json({ error: 'Invalid account ID format' });
+ }
+ const io = req.app.get('io');
+ const result = await calendarSync.syncAccount(req.params.accountId, io);
+ if (result.error) return res.status(result.status || 404).json({ error: result.error });
+ res.json(result);
+}));
+
+router.get('/sync/:accountId/status', asyncHandler(async (req, res) => {
+ if (!z.string().uuid().safeParse(req.params.accountId).success) {
+ return res.status(400).json({ error: 'Invalid account ID format' });
+ }
+ const status = await calendarSync.getSyncStatus(req.params.accountId);
+ if (!status) return res.status(404).json({ error: 'Account not found' });
+ res.json(status);
+}));
+
+// === Event Routes ===
+router.get('/events', asyncHandler(async (req, res) => {
+ const { accountId, search, startDate, endDate, limit, offset } = req.query;
+ if (accountId && !z.string().uuid().safeParse(accountId).success) {
+ return res.status(400).json({ error: 'Invalid accountId format' });
+ }
+ let parsedLimit = limit !== undefined ? parseInt(limit, 10) : 50;
+ if (Number.isNaN(parsedLimit) || parsedLimit <= 0) parsedLimit = 50;
+ if (parsedLimit > 200) parsedLimit = 200;
+ let parsedOffset = offset !== undefined ? parseInt(offset, 10) : 0;
+ if (Number.isNaN(parsedOffset) || parsedOffset < 0) parsedOffset = 0;
+ const result = await calendarSync.getEvents({
+ accountId,
+ search,
+ startDate,
+ endDate,
+ limit: parsedLimit,
+ offset: parsedOffset
+ });
+ res.json(result);
+}));
+
+router.get('/events/:accountId/:eventId', asyncHandler(async (req, res) => {
+ if (!z.string().uuid().safeParse(req.params.accountId).success) {
+ return res.status(400).json({ error: 'Invalid accountId format' });
+ }
+ const event = await calendarSync.getEvent(req.params.accountId, req.params.eventId);
+ if (!event) return res.status(404).json({ error: 'Event not found' });
+ res.json(event);
+}));
+
+// === Debug: Token Status (reuse message token extractor) ===
+router.get('/debug/token-status', asyncHandler(async (req, res) => {
+ const statuses = ['outlook'].map(p => getTokenStatus(p));
+ res.json({ providers: statuses });
+}));
+
+router.post('/debug/test-token', asyncHandler(async (req, res) => {
+ const provider = 'outlook';
+ const tokenResult = await getToken(provider);
+ if (tokenResult.error) return res.status(503).json(tokenResult);
+
+ const decoded = tokenResult.decoded || {};
+ const tokenInfo = {
+ provider,
+ fresh: tokenResult.fresh,
+ length: tokenResult.token.length,
+ expires: decoded.exp ? new Date(decoded.exp * 1000).toISOString() : 'unknown',
+ audience: decoded.aud || 'unknown',
+ scopes: decoded.scp || decoded.roles || 'unknown'
+ };
+
+ res.json({ token: tokenInfo });
+}));
+
+router.post('/debug/clear-token', asyncHandler(async (req, res) => {
+ clearTokenCache('outlook');
+ res.json({ cleared: true, provider: 'outlook' });
+}));
+
+export default router;
diff --git a/server/services/calendarAccounts.js b/server/services/calendarAccounts.js
new file mode 100644
index 0000000000..dc0bfee939
--- /dev/null
+++ b/server/services/calendarAccounts.js
@@ -0,0 +1,83 @@
+import { readFile, writeFile } from 'fs/promises';
+import { join } from 'path';
+import { v4 as uuidv4 } from 'uuid';
+import { ensureDir, PATHS, safeJSONParse } from '../lib/fileUtils.js';
+
+const ACCOUNTS_FILE = join(PATHS.calendar, 'accounts.json');
+
+async function loadAccounts() {
+ await ensureDir(PATHS.calendar);
+ const content = await readFile(ACCOUNTS_FILE, 'utf-8').catch(() => null);
+ if (!content) return {};
+ const parsed = safeJSONParse(content, {}, { context: 'calendarAccounts' });
+ return (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) ? parsed : {};
+}
+
+async function saveAccounts(accounts) {
+ await ensureDir(PATHS.calendar);
+ await writeFile(ACCOUNTS_FILE, JSON.stringify(accounts, null, 2));
+}
+
+export async function listAccounts() {
+ const accounts = await loadAccounts();
+ return Object.values(accounts).sort((a, b) => a.name.localeCompare(b.name));
+}
+
+export async function getAccount(id) {
+ const accounts = await loadAccounts();
+ return accounts[id] || null;
+}
+
+export async function createAccount(data) {
+ const accounts = await loadAccounts();
+ const id = uuidv4();
+ accounts[id] = {
+ id,
+ name: data.name,
+ type: data.type, // outlook-calendar, gmail-calendar
+ email: data.email || '',
+ enabled: true,
+ syncConfig: {
+ maxAge: data.syncConfig?.maxAge || '90d',
+ syncInterval: data.syncConfig?.syncInterval || 300000,
+ calendarIds: data.syncConfig?.calendarIds || ['default']
+ },
+ lastSyncAt: null,
+ lastSyncStatus: null,
+ createdAt: new Date().toISOString()
+ };
+ await saveAccounts(accounts);
+ console.log(`📅 Calendar account created: ${data.name} (${data.type})`);
+ return accounts[id];
+}
+
+export async function updateAccount(id, updates) {
+ const accounts = await loadAccounts();
+ if (!accounts[id]) return null;
+ const { name, email, enabled, syncConfig } = updates;
+ if (name !== undefined) accounts[id].name = name;
+ if (email !== undefined) accounts[id].email = email;
+ if (enabled !== undefined) accounts[id].enabled = enabled;
+ if (syncConfig) accounts[id].syncConfig = { ...accounts[id].syncConfig, ...syncConfig };
+ accounts[id].updatedAt = new Date().toISOString();
+ await saveAccounts(accounts);
+ return accounts[id];
+}
+
+export async function deleteAccount(id) {
+ const accounts = await loadAccounts();
+ if (!accounts[id]) return false;
+ delete accounts[id];
+ await saveAccounts(accounts);
+ console.log(`🗑️ Calendar account deleted: ${id}`);
+ return true;
+}
+
+export async function updateSyncStatus(id, status) {
+ const accounts = await loadAccounts();
+ if (!accounts[id]) return null;
+ accounts[id].lastSyncAt = new Date().toISOString();
+ accounts[id].lastSyncStatus = status;
+ await saveAccounts(accounts);
+ return accounts[id];
+}
diff --git a/server/services/calendarApiSync.js b/server/services/calendarApiSync.js
new file mode 100644
index 0000000000..959d89d2b7
--- /dev/null
+++ b/server/services/calendarApiSync.js
@@ -0,0 +1,128 @@
+import { v4 as uuidv4 } from 'uuid';
+import crypto from 'crypto';
+import { getToken } from './messageTokenExtractor.js';
+
+function makeExternalId(id) {
+ const hash = crypto.createHash('md5').update(id).digest('hex').slice(0, 12);
+ return `api-cal-${hash}`;
+}
+
+function mapResponseStatus(status) {
+ const map = {
+ None: 'none',
+ Organizer: 'organizer',
+ TentativelyAccepted: 'tentative',
+ Accepted: 'accepted',
+ Declined: 'declined',
+ NotResponded: 'notResponded'
+ };
+ return map[status?.Response] || 'unknown';
+}
+
+function mapAttendeeStatus(status) {
+ const map = {
+ None: 'none',
+ Accepted: 'accepted',
+ Declined: 'declined',
+ TentativelyAccepted: 'tentative'
+ };
+ return map[status?.Response] || 'unknown';
+}
+
+export async function syncOutlookCalendarApi(account, cache, io, options = {}) {
+ const tokenResult = await getToken('outlook');
+
+ if (tokenResult.error) {
+ console.log(`📅 Calendar API sync unavailable for ${account.email}: ${tokenResult.message}`);
+ return null;
+ }
+
+ const token = tokenResult.token;
+ const now = new Date();
+ const startRange = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000); // -7d
+ const endRange = new Date(now.getTime() + 90 * 24 * 60 * 60 * 1000); // +90d
+ const startDateTime = startRange.toISOString();
+ const endDateTime = endRange.toISOString();
+
+ console.log(`📅 Calendar API sync for ${account.email} (${startDateTime} to ${endDateTime})`);
+
+ const select = '$select=Subject,Start,End,Location,Organizer,Attendees,IsAllDay,Importance,Categories,IsCancelled,Recurrence,ResponseStatus,Body,ShowAs';
+ const orderBy = '$orderby=Start/DateTime asc';
+ const baseUrl = `https://outlook.office.com/api/v2.0/me/calendarview?startDateTime=${encodeURIComponent(startDateTime)}&endDateTime=${encodeURIComponent(endDateTime)}&${select}&${orderBy}&$top=200`;
+
+ const events = [];
+ let url = baseUrl;
+ let page = 0;
+
+ while (url) {
+ page++;
+ io?.emit('calendar:sync:event', { accountId: account.id, current: events.length, page });
+
+ const controller = new AbortController();
+ const timeout = setTimeout(() => controller.abort(), 30000);
+
+ const response = await fetch(url, {
+ headers: { Authorization: `Bearer ${token}`, Prefer: 'outlook.body-content-type="Text"' },
+ signal: controller.signal
+ }).finally(() => clearTimeout(timeout));
+
+ if (!response.ok) {
+ const text = await response.text().catch(() => '');
+ console.log(`📅 Calendar API sync failed (${response.status}): ${text.slice(0, 200)}`);
+ if (response.status === 401) {
+ const { clearTokenCache } = await import('./messageTokenExtractor.js');
+ clearTokenCache('outlook');
+ return null;
+ }
+ return { events: [], status: 'api-error' };
+ }
+
+ const data = await response.json();
+ const items = data.value || [];
+
+ for (const item of items) {
+ const extId = makeExternalId(item.Id);
+ const event = {
+ id: uuidv4(),
+ externalId: extId,
+ apiId: item.Id,
+ accountId: account.id,
+ title: item.Subject || '',
+ description: item.Body?.Content || '',
+ location: item.Location?.DisplayName || '',
+ startTime: item.Start?.DateTime ? new Date(item.Start.DateTime + 'Z').toISOString() : null,
+ endTime: item.End?.DateTime ? new Date(item.End.DateTime + 'Z').toISOString() : null,
+ isAllDay: item.IsAllDay || false,
+ timeZone: item.Start?.TimeZone || 'UTC',
+ organizer: {
+ name: item.Organizer?.EmailAddress?.Name || '',
+ email: item.Organizer?.EmailAddress?.Address || ''
+ },
+ attendees: (item.Attendees || []).map(a => ({
+ name: a.EmailAddress?.Name || '',
+ email: a.EmailAddress?.Address || '',
+ status: mapAttendeeStatus(a.Status)
+ })),
+ myStatus: mapResponseStatus(item.ResponseStatus),
+ recurrence: item.Recurrence || null,
+ isRecurring: !!item.Recurrence,
+ isCancelled: item.IsCancelled || false,
+ categories: item.Categories || [],
+ importance: item.Importance || 'Normal',
+ source: 'outlook-calendar',
+ syncMethod: 'api',
+ syncedAt: new Date().toISOString()
+ };
+ events.push(event);
+ }
+
+ url = data['@odata.nextLink'] || null;
+ }
+
+ if (io && events.length > 0) {
+ io.emit('calendar:sync:event', { accountId: account.id, events });
+ }
+
+ console.log(`📅 Calendar API sync complete: ${events.length} events fetched in ${page} page(s)`);
+ return { events, status: 'success', syncMethod: 'api' };
+}
diff --git a/server/services/calendarSync.js b/server/services/calendarSync.js
new file mode 100644
index 0000000000..bdabd0d276
--- /dev/null
+++ b/server/services/calendarSync.js
@@ -0,0 +1,201 @@
+import { readFile, writeFile } from 'fs/promises';
+import { join } from 'path';
+import { ensureDir, PATHS, safeJSONParse } from '../lib/fileUtils.js';
+import { getAccount, updateSyncStatus } from './calendarAccounts.js';
+
+const CACHE_DIR = join(PATHS.calendar, 'cache');
+const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
+const syncLocks = new Map();
+
+function safeDate(d) {
+ const t = new Date(d).getTime();
+ return Number.isNaN(t) ? 0 : t;
+}
+
+function filterBySearch(events, search) {
+ if (!search) return events;
+ const q = search.toLowerCase();
+ return events.filter(e =>
+ e.title?.toLowerCase().includes(q) ||
+ e.description?.toLowerCase().includes(q) ||
+ e.location?.toLowerCase().includes(q) ||
+ e.organizer?.name?.toLowerCase().includes(q)
+ );
+}
+
+function filterByDateRange(events, startDate, endDate) {
+ let filtered = events;
+ if (startDate) {
+ const start = safeDate(startDate);
+ filtered = filtered.filter(e => safeDate(e.endTime || e.startTime) >= start);
+ }
+ if (endDate) {
+ const end = safeDate(endDate);
+ filtered = filtered.filter(e => safeDate(e.startTime) <= end);
+ }
+ return filtered;
+}
+
+async function loadCache(accountId) {
+ if (!UUID_RE.test(accountId)) throw new Error(`Invalid accountId: ${accountId}`);
+ await ensureDir(CACHE_DIR);
+ const filePath = join(CACHE_DIR, `${accountId}.json`);
+ const content = await readFile(filePath, 'utf-8').catch(() => null);
+ if (!content) return { syncCursor: null, events: [] };
+ const parsed = safeJSONParse(content, { syncCursor: null, events: [] }, { context: `calendarCache:${accountId}` });
+ if (!parsed || !Array.isArray(parsed.events)) return { syncCursor: null, events: [] };
+ return parsed;
+}
+
+async function saveCache(accountId, cache) {
+ await ensureDir(CACHE_DIR);
+ const filePath = join(CACHE_DIR, `${accountId}.json`);
+ await writeFile(filePath, JSON.stringify(cache, null, 2));
+}
+
+export async function getEvents(options = {}) {
+ const { accountId, search, startDate, endDate, limit = 50, offset = 0 } = options;
+
+ if (accountId) {
+ const cache = await loadCache(accountId);
+ let events = cache.events.map(e => ({ ...e, accountId: e.accountId || accountId }));
+ events = filterBySearch(events, search);
+ events = filterByDateRange(events, startDate, endDate);
+ return {
+ events: events.sort((a, b) => safeDate(a.startTime) - safeDate(b.startTime)).slice(offset, offset + limit),
+ total: events.length
+ };
+ }
+
+ // Aggregate across all account caches
+ await ensureDir(CACHE_DIR);
+ const { readdir } = await import('fs/promises');
+ const files = await readdir(CACHE_DIR).catch(() => []);
+ let allEvents = [];
+ for (const file of files) {
+ if (!file.endsWith('.json')) continue;
+ const fileAccountId = file.replace('.json', '');
+ if (!UUID_RE.test(fileAccountId)) continue;
+ const cache = await loadCache(fileAccountId);
+ allEvents.push(...cache.events.map(e => ({ ...e, accountId: e.accountId || fileAccountId })));
+ }
+ allEvents = filterBySearch(allEvents, search);
+ allEvents = filterByDateRange(allEvents, startDate, endDate);
+ allEvents.sort((a, b) => safeDate(a.startTime) - safeDate(b.startTime));
+ return {
+ events: allEvents.slice(offset, offset + limit),
+ total: allEvents.length
+ };
+}
+
+export async function getEvent(accountId, eventId) {
+ const cache = await loadCache(accountId);
+ const event = cache.events.find(e => e.id === eventId);
+ if (!event) return null;
+ return { ...event, accountId: event.accountId || accountId };
+}
+
+export async function deleteCache(accountId) {
+ if (!UUID_RE.test(accountId)) return;
+ const { unlink } = await import('fs/promises');
+ const filePath = join(CACHE_DIR, `${accountId}.json`);
+ try {
+ await unlink(filePath);
+ console.log(`🗑️ Calendar cache deleted for account ${accountId}`);
+ } catch (err) {
+ if (err.code === 'ENOENT') {
+ console.log(`🗑️ No calendar cache to delete for account ${accountId}`);
+ } else {
+ console.error(`❌ Failed to delete calendar cache for account ${accountId}: ${err.message}`);
+ }
+ }
+}
+
+export async function syncAccount(accountId, io, options = {}) {
+ if (syncLocks.has(accountId)) return { error: 'Sync already in progress', status: 409 };
+
+ const account = await getAccount(accountId);
+ if (!account) return { error: 'Account not found' };
+ if (!account.enabled) return { error: 'Account is disabled', status: 400 };
+
+ syncLocks.set(accountId, true);
+ io?.emit('calendar:sync:started', { accountId });
+ console.log(`📅 Starting calendar sync for ${account.name} (${account.type})`);
+
+ const providerSync = async () => {
+ const cache = await loadCache(accountId);
+ let providerResult;
+ if (account.type === 'outlook-calendar') {
+ const { syncOutlookCalendarApi } = await import('./calendarApiSync.js');
+ providerResult = await syncOutlookCalendarApi(account, cache, io, options);
+ } else {
+ throw new Error(`Unsupported calendar account type: ${account.type}`);
+ }
+
+ const newEvents = Array.isArray(providerResult) ? providerResult : providerResult?.events ?? [];
+ const providerStatus = Array.isArray(providerResult) ? 'success' : providerResult?.status ?? 'success';
+
+ // Deduplicate by externalId; update fields on existing events
+ const existingMap = new Map(cache.events.filter(e => e.externalId).map(e => [e.externalId, e]));
+ const uniqueNew = [];
+ for (const event of newEvents) {
+ if (!event.externalId || !existingMap.has(event.externalId)) {
+ uniqueNew.push(event);
+ } else {
+ const existing = existingMap.get(event.externalId);
+ // Update mutable fields
+ if (event.title !== undefined) existing.title = event.title;
+ if (event.description !== undefined) existing.description = event.description;
+ if (event.location !== undefined) existing.location = event.location;
+ if (event.startTime !== undefined) existing.startTime = event.startTime;
+ if (event.endTime !== undefined) existing.endTime = event.endTime;
+ if (event.isAllDay !== undefined) existing.isAllDay = event.isAllDay;
+ if (event.isCancelled !== undefined) existing.isCancelled = event.isCancelled;
+ if (event.attendees !== undefined) existing.attendees = event.attendees;
+ if (event.myStatus !== undefined) existing.myStatus = event.myStatus;
+ if (event.categories !== undefined) existing.categories = event.categories;
+ if (event.importance !== undefined) existing.importance = event.importance;
+ }
+ }
+ cache.events.push(...uniqueNew);
+
+ // Reconcile: remove cached events no longer present
+ let pruned = 0;
+ if (providerStatus === 'success' && newEvents.length > 0) {
+ const fetchedIds = new Set(newEvents.filter(e => e.externalId).map(e => e.externalId));
+ const before = cache.events.length;
+ cache.events = cache.events.filter(e => !e.externalId || fetchedIds.has(e.externalId));
+ pruned = before - cache.events.length;
+ if (pruned > 0) console.log(`🧹 Pruned ${pruned} stale calendar events from ${account.name}`);
+ }
+
+ await saveCache(accountId, cache);
+ await updateSyncStatus(accountId, providerStatus === 'success' ? 'success' : providerStatus);
+
+ io?.emit('calendar:sync:completed', { accountId, newEvents: uniqueNew.length, pruned, status: providerStatus });
+ console.log(`📅 Sync complete for ${account.name}: ${uniqueNew.length} new, ${pruned} pruned, status=${providerStatus}`);
+
+ return { newEvents: uniqueNew.length, pruned, total: cache.events.length, status: providerStatus };
+ };
+
+ const result = await providerSync().catch(async (error) => {
+ console.error(`📅 Sync failed for ${account.name} (${account.type}): ${error.message}`);
+ await updateSyncStatus(accountId, 'error').catch(() => {});
+ io?.emit('calendar:sync:failed', { accountId, error: error.message });
+ return { error: error.message, status: 502 };
+ }).finally(() => {
+ syncLocks.delete(accountId);
+ });
+
+ return result;
+}
+
+export async function getSyncStatus(accountId) {
+ const account = await getAccount(accountId);
+ if (!account) return null;
+ return {
+ accountId,
+ lastSyncAt: account.lastSyncAt,
+ lastSyncStatus: account.lastSyncStatus
+ };
+}