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

fix: filter events by enabled subcalendars and auto-purge disabled ones

Adam Eivyf1d9207179e7
diff --git a/client/src/components/calendar/ConfigTab.jsx b/client/src/components/calendar/ConfigTab.jsx
index d68b2503ca..8ce1110e1a 100644
--- a/client/src/components/calendar/ConfigTab.jsx
+++ b/client/src/components/calendar/ConfigTab.jsx
@@ -211,18 +211,16 @@ export default function ConfigTab({ accounts, setAccounts }) {
<option value="google-calendar">Google Calendar (MCP Push)</option>
</select>
</div>
- {form.type === 'outlook-calendar' && (
- <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>
+ <label className="block text-sm text-gray-400 mb-1">Email{form.type === 'google-calendar' ? ' (used as OAuth test user)' : ''}</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}
diff --git a/client/src/components/calendar/SyncTab.jsx b/client/src/components/calendar/SyncTab.jsx
index 6888ecf8ec..4a070b7db1 100644
--- a/client/src/components/calendar/SyncTab.jsx
+++ b/client/src/components/calendar/SyncTab.jsx
@@ -8,7 +8,7 @@ export default function SyncTab({ accounts, onRefresh }) {
const [syncing, setSyncing] = useState({});
const [tokenStatus, setTokenStatus] = useState(null);
const [tokenLoading, setTokenLoading] = useState(true);
- const [mcpProgress, setMcpProgress] = useState(null);
+ const [mcpProgress, setMcpProgress] = useState({});
const fetchTokenStatus = useCallback(async () => {
const data = await api.getCalendarTokenStatus().catch(() => null);
@@ -24,6 +24,7 @@ export default function SyncTab({ accounts, onRefresh }) {
};
const onSyncCompleted = ({ accountId, newEvents }) => {
setSyncing(prev => ({ ...prev, [accountId]: null }));
+ setMcpProgress(prev => { const next = {...prev}; delete next[accountId]; return next; });
toast.success(`Calendar sync complete: ${newEvents ?? 0} events`);
onRefresh();
};
@@ -33,7 +34,7 @@ export default function SyncTab({ accounts, onRefresh }) {
};
const onSyncProgress = ({ accountId, message }) => {
- setMcpProgress(message);
+ setMcpProgress(prev => ({ ...prev, [accountId]: message }));
};
socket.on('calendar:sync:started', onSyncStarted);
@@ -58,14 +59,14 @@ export default function SyncTab({ accounts, onRefresh }) {
const handleGoogleSync = async (account) => {
setSyncing(prev => ({ ...prev, [account.id]: 'syncing' }));
- setMcpProgress('Starting Google Calendar sync...');
+ setMcpProgress(prev => ({ ...prev, [account.id]: 'Starting Google Calendar sync...' }));
const useApi = account.syncMethod === 'google-api';
const result = useApi
? await api.apiSyncGoogleCalendar(account.id).catch(() => null)
: await api.mcpSyncGoogleCalendar(account.id).catch(() => null);
- setMcpProgress(null);
+ setMcpProgress(prev => { const next = {...prev}; delete next[account.id]; return next; });
if (!result || result.error) {
setSyncing(prev => ({ ...prev, [account.id]: null }));
if (result?.error?.includes('spawn Claude')) {
@@ -124,8 +125,8 @@ export default function SyncTab({ accounts, onRefresh }) {
{syncing[account.id] === 'syncing' ? (
<div className="flex items-center gap-2">
<RefreshCw size={16} className="text-port-accent animate-spin" />
- {mcpProgress && account.type === 'google-calendar' && (
- <span className="text-xs text-gray-500">{mcpProgress}</span>
+ {mcpProgress[account.id] && account.type === 'google-calendar' && (
+ <span className="text-xs text-gray-500">{mcpProgress[account.id]}</span>
)}
</div>
) : account.type === 'google-calendar' ? (
diff --git a/client/src/services/api.js b/client/src/services/api.js
index c118f885c9..37c9c00850 100644
--- a/client/src/services/api.js
+++ b/client/src/services/api.js
@@ -1742,7 +1742,6 @@ export const clearGoogleAuth = () => request('/calendar/google/auth/clear', { me
export const apiSyncGoogleCalendar = (accountId) => request(`/calendar/sync/${accountId}/api`, { method: 'POST' });
export const apiDiscoverCalendars = (accountId) => request(`/calendar/sync/${accountId}/discover-api`, { method: 'POST' });
export const startGoogleAutoConfig = () => request('/calendar/google/auto-configure/start', { method: 'POST' });
-export const navigateGoogleAutoConfig = (step) => request('/calendar/google/auto-configure/navigate', { method: 'POST', body: JSON.stringify({ step }) });
export const captureGoogleCredentials = () => request('/calendar/google/auto-configure/capture', { method: 'POST' });
export const runGoogleAutoConfig = (email) => request('/calendar/google/auto-configure/run', { method: 'POST', body: JSON.stringify({ email }) });
export const getDailyReview = (date) => request(`/calendar/review/${date}`);
diff --git a/server/package.json b/server/package.json
index ad5b907ed8..e748dd1f5d 100644
--- a/server/package.json
+++ b/server/package.json
@@ -14,6 +14,7 @@
"axios": "^1.7.9",
"cors": "^2.8.5",
"express": "^5.2.1",
+ "googleapis": "^171.4.0",
"multer": "^2.0.2",
"node-pty": "^1.2.0-beta.10",
"pg": "^8.19.0",
diff --git a/server/routes/calendar.js b/server/routes/calendar.js
index 23c039fa31..13b4cbd6bb 100644
--- a/server/routes/calendar.js
+++ b/server/routes/calendar.js
@@ -183,6 +183,8 @@ router.put('/accounts/:id/subcalendars', asyncHandler(async (req, res) => {
const { subcalendars } = validateRequest(updateSubcalendarsSchema, req.body);
const account = await calendarAccounts.updateSubcalendars(req.params.id, subcalendars);
if (!account) throw new ServerError('Account not found', { status: 404, code: 'NOT_FOUND' });
+ // Auto-purge cached events for disabled subcalendars
+ await calendarSync.purgeDisabledSubcalendars(req.params.id);
req.app.get('io')?.emit('calendar:changed', {});
res.json(account);
}));
@@ -265,15 +267,6 @@ router.post('/google/auto-configure/start', asyncHandler(async (req, res) => {
res.json(result);
}));
-router.post('/google/auto-configure/navigate', asyncHandler(async (req, res) => {
- const { step } = req.body;
- if (!step) throw new ServerError('Step is required', { status: 400, code: 'VALIDATION_ERROR' });
- const io = req.app.get('io');
- const result = await googleOAuthAutoConfig.navigateToStep(step, io);
- if (result.error) return res.status(result.status || 500).json({ error: result.error });
- res.json(result);
-}));
-
router.post('/google/auto-configure/capture', asyncHandler(async (req, res) => {
const io = req.app.get('io');
const result = await googleOAuthAutoConfig.captureCredentials(io);
@@ -285,7 +278,7 @@ router.post('/google/auto-configure/run', asyncHandler(async (req, res) => {
const io = req.app.get('io');
const email = req.body?.email || '';
const result = await googleOAuthAutoConfig.runAutomatedSetup(email, io);
- if (result.status === 'error') return res.status(500).json(result);
+ if (result.error) return res.status(result.status || 500).json({ error: result.error });
res.json(result);
}));
diff --git a/server/services/calendarGoogleSync.js b/server/services/calendarGoogleSync.js
index ebfff80f3b..15c9e9f78c 100644
--- a/server/services/calendarGoogleSync.js
+++ b/server/services/calendarGoogleSync.js
@@ -3,6 +3,7 @@ import { createHash } from 'crypto';
import { spawn } from 'child_process';
import { getAccount, updateSyncStatus, updateSubcalendars, mergeDiscoveredSubcalendars } from './calendarAccounts.js';
import { loadCache, saveCache } from './calendarSync.js';
+import { safeJSONParse } from '../lib/fileUtils.js';
function md5(str) {
return createHash('md5').update(str).digest('hex').slice(0, 12);
@@ -122,8 +123,8 @@ export async function mcpSyncAccount(accountId, io) {
console.log(`📅 Starting MCP sync for ${account.name} (${enabledCalendars.length} calendars)`);
const { pastDate, futureDate } = getSyncDateRange();
- const timeMin = pastDate.toISOString().slice(0, 19);
- const timeMax = futureDate.toISOString().slice(0, 19);
+ const timeMin = pastDate.toISOString();
+ const timeMax = futureDate.toISOString();
const calendarList = enabledCalendars.map(sc => `- Calendar: "${sc.name}", ID: "${sc.calendarId}"`).join('\n');
@@ -187,11 +188,11 @@ function parseCalendarJson(output) {
// Look for {"calendars":...} pattern
const jsonMatch = output.match(/\{[\s\S]*"calendars"\s*:\s*\[[\s\S]*\]\s*\}/);
if (jsonMatch) {
- const parsed = JSON.parse(jsonMatch[0]);
+ const parsed = safeJSONParse(jsonMatch[0], null);
if (parsed?.calendars) return parsed;
}
// Try parsing the entire output as JSON
- const parsed = JSON.parse(output);
+ const parsed = safeJSONParse(output, null);
if (parsed?.calendars) return parsed;
return null;
}
@@ -229,7 +230,7 @@ Output NOTHING else — just the JSON array.`;
const match = result.output.match(/\[[\s\S]*\]/);
if (!match) return { error: 'Failed to parse calendar list from Claude response', status: 502 };
- const calendars = JSON.parse(match[0]);
+ const calendars = safeJSONParse(match[0], null);
if (!Array.isArray(calendars)) return { error: 'Invalid calendar list format', status: 502 };
// Merge with existing subcalendars (preserve enabled/dormant state)
diff --git a/server/services/calendarSync.js b/server/services/calendarSync.js
index 5cd8157f33..0975635bc6 100644
--- a/server/services/calendarSync.js
+++ b/server/services/calendarSync.js
@@ -52,12 +52,23 @@ export async function saveCache(accountId, cache) {
await writeFile(filePath, JSON.stringify(cache, null, 2));
}
+function filterByEnabledSubcalendars(events, account) {
+ if (!account?.subcalendars?.length) return events;
+ const enabledIds = new Set(
+ account.subcalendars.filter(sc => sc.enabled && !sc.dormant).map(sc => sc.calendarId)
+ );
+ // Only filter events that have a subcalendarId (google-calendar events)
+ return events.filter(e => !e.subcalendarId || enabledIds.has(e.subcalendarId));
+}
+
export async function getEvents(options = {}) {
const { accountId, search, startDate, endDate, limit = 50, offset = 0 } = options;
if (accountId) {
const cache = await loadCache(accountId);
+ const account = await getAccount(accountId);
let events = cache.events.map(e => ({ ...e, accountId: e.accountId || accountId }));
+ events = filterByEnabledSubcalendars(events, account);
events = filterBySearch(events, search);
events = filterByDateRange(events, startDate, endDate);
return {
@@ -69,13 +80,19 @@ export async function getEvents(options = {}) {
// Aggregate across all account caches
await ensureDir(CACHE_DIR);
const files = await readdir(CACHE_DIR).catch(() => []);
+ const { listAccounts } = await import('./calendarAccounts.js');
+ const accounts = await listAccounts();
+ const accountMap = new Map(accounts.map(a => [a.id, a]));
+
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 })));
+ let events = cache.events.map(e => ({ ...e, accountId: e.accountId || fileAccountId }));
+ events = filterByEnabledSubcalendars(events, accountMap.get(fileAccountId));
+ allEvents.push(...events);
}
allEvents = filterBySearch(allEvents, search);
allEvents = filterByDateRange(allEvents, startDate, endDate);
@@ -86,6 +103,24 @@ export async function getEvents(options = {}) {
};
}
+export async function purgeDisabledSubcalendars(accountId) {
+ const account = await getAccount(accountId);
+ if (!account?.subcalendars?.length) return { purged: 0 };
+
+ const enabledIds = new Set(
+ account.subcalendars.filter(sc => sc.enabled && !sc.dormant).map(sc => sc.calendarId)
+ );
+ const cache = await loadCache(accountId);
+ const before = cache.events.length;
+ cache.events = cache.events.filter(e => !e.subcalendarId || enabledIds.has(e.subcalendarId));
+ const purged = before - cache.events.length;
+ if (purged > 0) {
+ await saveCache(accountId, cache);
+ console.log(`🧹 Purged ${purged} events from disabled subcalendars for account ${accountId}`);
+ }
+ return { purged, remaining: cache.events.length };
+}
+
export async function getEvent(accountId, eventId) {
const cache = await loadCache(accountId);
const event = cache.events.find(e => e.id === eventId);
diff --git a/server/services/dailyReview.js b/server/services/dailyReview.js
index c3bf242ddf..6a99530466 100644
--- a/server/services/dailyReview.js
+++ b/server/services/dailyReview.js
@@ -1,6 +1,5 @@
import { writeFile } from 'fs/promises';
import { join } from 'path';
-import { v4 as uuidv4 } from 'uuid';
import { ensureDir, PATHS, readJSONFile } from '../lib/fileUtils.js';
import * as calendarSync from './calendarSync.js';
import * as calendarAccounts from './calendarAccounts.js';
diff --git a/server/services/googleOAuthAutoConfig.js b/server/services/googleOAuthAutoConfig.js
index a07120d29a..9da62990e4 100644
--- a/server/services/googleOAuthAutoConfig.js
+++ b/server/services/googleOAuthAutoConfig.js
@@ -81,19 +81,23 @@ async function clickByText(page, texts, maxWait = 10000) {
* Fill a textbox found by its accessible name.
*/
async function fillByName(page, name, value) {
+ const safeName = JSON.stringify(name.toLowerCase());
+ const safeValue = JSON.stringify(value);
return evaluateOnPage(page, `
(function() {
+ const nameToMatch = ${safeName};
+ const valueToSet = ${safeValue};
const inputs = document.querySelectorAll('input[type="text"], input:not([type]), textarea');
for (const input of inputs) {
const label = input.getAttribute('aria-label') || '';
const placeholder = input.getAttribute('placeholder') || '';
const id = input.id || '';
const formLabel = input.closest('[class*="form"]')?.querySelector('label')?.textContent || '';
- if ([label, placeholder, formLabel].some(t => t.toLowerCase().includes('${name.toLowerCase()}'))) {
+ if ([label, placeholder, formLabel].some(t => t.toLowerCase().includes(nameToMatch))) {
input.focus();
const setter = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, 'value')?.set;
- if (setter) { setter.call(input, '${value}'); }
- else { input.value = '${value}'; }
+ if (setter) { setter.call(input, valueToSet); }
+ else { input.value = valueToSet; }
input.dispatchEvent(new Event('input', { bubbles: true }));
input.dispatchEvent(new Event('change', { bubbles: true }));
return true;