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

refactor: simplify code and fix Google Calendar defaults

Adam Eivy142209add7e9
diff --git a/client/src/components/calendar/ConfigTab.jsx b/client/src/components/calendar/ConfigTab.jsx
index 0d20ed3148..d68b2503ca 100644
--- a/client/src/components/calendar/ConfigTab.jsx
+++ b/client/src/components/calendar/ConfigTab.jsx
@@ -4,7 +4,7 @@ import toast from 'react-hot-toast';
import * as api from '../../services/api';
const TYPE_ICONS = { 'outlook-calendar': Globe, 'google-calendar': Calendar };
-const TYPE_LABELS = { 'outlook-calendar': 'Outlook Calendar (API)', 'google-calendar': 'Google Calendar (MCP Push)' };
+const TYPE_LABELS = { 'outlook-calendar': 'Outlook Calendar (API)', 'google-calendar': 'Google Calendar' };
export default function ConfigTab({ accounts, setAccounts }) {
const [showForm, setShowForm] = useState(false);
@@ -19,7 +19,6 @@ export default function ConfigTab({ accounts, setAccounts }) {
const [oauthForm, setOauthForm] = useState({ clientId: '', clientSecret: '' });
const [savingOAuth, setSavingOAuth] = useState(false);
const [autoConfigStep, setAutoConfigStep] = useState(null); // null | 'launching' | 'login' | 'project' | 'api' | 'consent' | 'credentials' | 'capturing' | 'done'
- const [autoConfigBusy, setAutoConfigBusy] = useState(false);
const fetchGoogleAuth = async () => {
const status = await api.getGoogleAuthStatus().catch(() => null);
@@ -67,9 +66,7 @@ export default function ConfigTab({ accounts, setAccounts }) {
};
const handleAutoConfigStart = async () => {
- setAutoConfigBusy(true);
const result = await api.startGoogleAutoConfig().catch(() => null);
- setAutoConfigBusy(false);
if (!result || result.error) {
return toast.error(result?.error || 'Failed to open browser');
}
@@ -78,13 +75,11 @@ export default function ConfigTab({ accounts, setAccounts }) {
};
const handleAutoConfigContinue = async () => {
- setAutoConfigBusy(true);
setAutoConfigStep('running');
// Find the google account's email to pass as test user
const googleAccount = accounts.find(a => a.type === 'google-calendar');
const email = googleAccount?.email || '';
const result = await api.runGoogleAutoConfig(email).catch(() => null);
- setAutoConfigBusy(false);
if (!result || result.status === 'error') {
setAutoConfigStep('login');
return toast.error(result?.errors?.[0] || 'Automated setup failed. Try manual setup instead.');
@@ -375,10 +370,9 @@ export default function ConfigTab({ accounts, setAccounts }) {
{!autoConfigStep ? (
<button
onClick={handleAutoConfigStart}
- disabled={autoConfigBusy}
- className="flex items-center gap-1.5 w-full px-3 py-2 text-xs rounded bg-port-accent/10 text-port-accent hover:bg-port-accent/20 border border-port-accent/20 disabled:opacity-50"
+ className="flex items-center gap-1.5 w-full px-3 py-2 text-xs rounded bg-port-accent/10 text-port-accent hover:bg-port-accent/20 border border-port-accent/20"
>
- {autoConfigBusy ? <RefreshCw size={14} className="animate-spin" /> : <Monitor size={14} />}
+ <Monitor size={14} />
Setup with PortOS Browser (automated)
</button>
) : autoConfigStep === 'running' ? (
@@ -403,7 +397,7 @@ export default function ConfigTab({ accounts, setAccounts }) {
<div className="flex gap-2 pt-1">
<button
onClick={handleAutoConfigContinue}
- disabled={autoConfigBusy}
+ disabled={autoConfigStep === 'running'}
className="flex items-center gap-1 px-3 py-1.5 text-xs rounded bg-port-accent text-white hover:bg-port-accent/80 disabled:opacity-50"
>
<Wand2 size={12} /> Continue
diff --git a/client/src/components/calendar/DayView.jsx b/client/src/components/calendar/DayView.jsx
index 71698e14ce..cb62ea41cd 100644
--- a/client/src/components/calendar/DayView.jsx
+++ b/client/src/components/calendar/DayView.jsx
@@ -1,4 +1,4 @@
-import { useState, useEffect, useCallback } from 'react';
+import { useState, useEffect, useCallback, useMemo } from 'react';
import { ChevronLeft, ChevronRight, RefreshCw, MapPin } from 'lucide-react';
import * as api from '../../services/api';
import socket from '../../services/socket';
@@ -139,6 +139,7 @@ export default function DayView() {
const allDayEvents = events.filter(e => e.isAllDay);
const timedEvents = events.filter(e => !e.isAllDay);
+ const layout = useMemo(() => layoutEvents(timedEvents), [timedEvents]);
// Current time indicator
const now = new Date();
@@ -209,37 +210,34 @@ export default function DayView() {
{/* Events overlay */}
<div className="absolute top-0 left-16 right-0 bottom-0">
- {(() => {
- const layout = layoutEvents(timedEvents);
- return timedEvents.map(event => {
- const { top, height } = getEventPosition(event);
- const key = eventKey(event);
- const { column, totalColumns } = layout.get(key) || { column: 0, totalColumns: 1 };
- const widthPercent = 100 / totalColumns;
- const leftPercent = column * widthPercent;
- return (
- <button
- key={key}
- onClick={() => setSelectedEvent(event)}
- className="absolute px-1.5 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: PX_PER_15MIN,
- left: `calc(${leftPercent}% + 2px)`,
- width: `calc(${widthPercent}% - 4px)`
- }}
- >
- <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>
- );
- });
- })()}
+ {timedEvents.map(event => {
+ const { top, height } = getEventPosition(event);
+ const key = eventKey(event);
+ const { column, totalColumns } = layout.get(key) || { column: 0, totalColumns: 1 };
+ const widthPercent = 100 / totalColumns;
+ const leftPercent = column * widthPercent;
+ return (
+ <button
+ key={key}
+ onClick={() => setSelectedEvent(event)}
+ className="absolute px-1.5 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: PX_PER_15MIN,
+ left: `calc(${leftPercent}% + 2px)`,
+ width: `calc(${widthPercent}% - 4px)`
+ }}
+ >
+ <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 * PX_PER_HOUR && (
diff --git a/server/services/calendarAccounts.js b/server/services/calendarAccounts.js
index 994880eaa9..16140c8a6b 100644
--- a/server/services/calendarAccounts.js
+++ b/server/services/calendarAccounts.js
@@ -55,7 +55,10 @@ export async function createAccount(data) {
goalIds: sc.goalIds || [],
addedAt: sc.addedAt || new Date().toISOString()
}));
- accounts[id].syncMethod = 'claude-mcp'; // default, user can switch to 'google-api'
+ // Default to google-api if OAuth is configured, otherwise claude-mcp
+ const { getAuthStatus } = await import('./googleAuth.js');
+ const authStatus = await getAuthStatus().catch(() => ({}));
+ accounts[id].syncMethod = authStatus.hasTokens ? 'google-api' : 'claude-mcp';
}
await saveAccounts(accounts);
console.log(`📅 Calendar account created: ${data.name} (${data.type})`);
@@ -103,6 +106,22 @@ export async function updateSubcalendars(id, subcalendars) {
return accounts[id];
}
+export function mergeDiscoveredSubcalendars(existing, discovered) {
+ const existingMap = new Map((existing || []).map(sc => [sc.calendarId, sc]));
+ return discovered.map(cal => {
+ const prev = existingMap.get(cal.id);
+ return {
+ calendarId: cal.id,
+ name: cal.name || cal.id,
+ color: cal.color || prev?.color || '',
+ enabled: prev?.enabled ?? false,
+ dormant: prev?.dormant ?? false,
+ goalIds: prev?.goalIds || [],
+ addedAt: prev?.addedAt || new Date().toISOString()
+ };
+ });
+}
+
export async function updateSyncStatus(id, status) {
const accounts = await loadAccounts();
if (!accounts[id]) return null;
diff --git a/server/services/calendarGoogleApiSync.js b/server/services/calendarGoogleApiSync.js
index b0a49ba409..b5e8e56652 100644
--- a/server/services/calendarGoogleApiSync.js
+++ b/server/services/calendarGoogleApiSync.js
@@ -1,7 +1,7 @@
import { google } from 'googleapis';
import { getAuthenticatedClient } from './googleAuth.js';
-import { getAccount } from './calendarAccounts.js';
-import { pushSyncEvents } from './calendarGoogleSync.js';
+import { getAccount, mergeDiscoveredSubcalendars } from './calendarAccounts.js';
+import { pushSyncEvents, getSyncDateRange } from './calendarGoogleSync.js';
export async function apiSyncAccount(accountId, io) {
const account = await getAccount(accountId);
@@ -18,23 +18,17 @@ export async function apiSyncAccount(accountId, io) {
console.log(`📅 Starting Google API sync for ${account.name} (${enabledCalendars.length} calendars)`);
const calendar = google.calendar({ version: 'v3', auth });
- const now = new Date();
- const pastDate = new Date(now);
- pastDate.setDate(pastDate.getDate() - 7);
- const futureDate = new Date(now);
- futureDate.setDate(futureDate.getDate() + 30);
+ const { pastDate, futureDate } = getSyncDateRange();
let totalNew = 0;
let totalUpdated = 0;
let totalPruned = 0;
const results = [];
- for (const sc of enabledCalendars) {
+ const fetchResults = await Promise.all(enabledCalendars.map(async (sc) => {
io?.emit('calendar:sync:progress', { accountId, message: `Fetching ${sc.name}...` });
-
const allEvents = [];
let pageToken;
-
do {
const response = await calendar.events.list({
calendarId: sc.calendarId,
@@ -57,7 +51,10 @@ export async function apiSyncAccount(accountId, io) {
})));
pageToken = response.data.nextPageToken;
} while (pageToken);
+ return { sc, allEvents };
+ }));
+ for (const { sc, allEvents } of fetchResults) {
const syncResult = await pushSyncEvents(accountId, sc.calendarId, sc.name, allEvents, null);
totalNew += syncResult.newEvents;
totalUpdated += syncResult.updated;
@@ -89,20 +86,13 @@ export async function apiDiscoverCalendars(accountId) {
pageToken = response.data.nextPageToken;
} while (pageToken);
- // Merge with existing subcalendars
- const existingMap = new Map((account.subcalendars || []).map(sc => [sc.calendarId, sc]));
- const merged = allCalendars.map(cal => {
- const existing = existingMap.get(cal.id);
- return {
- calendarId: cal.id,
- name: cal.summaryOverride || cal.summary || cal.id,
- color: cal.backgroundColor || existing?.color || '',
- enabled: existing?.enabled ?? false,
- dormant: existing?.dormant ?? false,
- goalIds: existing?.goalIds || [],
- addedAt: existing?.addedAt || new Date().toISOString()
- };
- });
+ // Normalize to { id, name, color } shape for merge helper
+ const discovered = allCalendars.map(cal => ({
+ id: cal.id,
+ name: cal.summaryOverride || cal.summary || cal.id,
+ color: cal.backgroundColor || ''
+ }));
+ const merged = mergeDiscoveredSubcalendars(account.subcalendars, discovered);
const { updateSubcalendars } = await import('./calendarAccounts.js');
await updateSubcalendars(accountId, merged);
diff --git a/server/services/calendarGoogleSync.js b/server/services/calendarGoogleSync.js
index 5d11bdd24b..d4d8b41be8 100644
--- a/server/services/calendarGoogleSync.js
+++ b/server/services/calendarGoogleSync.js
@@ -1,12 +1,8 @@
import { v4 as uuidv4 } from 'uuid';
import { createHash } from 'crypto';
import { spawn } from 'child_process';
-import { getAccount, updateSyncStatus } from './calendarAccounts.js';
-import { writeFile } from 'fs/promises';
-import { join } from 'path';
-import { ensureDir, PATHS, readJSONFile } from '../lib/fileUtils.js';
-
-const CACHE_DIR = join(PATHS.calendar, 'cache');
+import { getAccount, updateSyncStatus, mergeDiscoveredSubcalendars } from './calendarAccounts.js';
+import { loadCache, saveCache } from './calendarSync.js';
function md5(str) {
return createHash('md5').update(str).digest('hex').slice(0, 12);
@@ -38,16 +34,13 @@ export function normalizeGoogleEvent(event, subcalendarId, subcalendarName) {
};
}
-async function loadCache(accountId) {
- await ensureDir(CACHE_DIR);
- const parsed = await readJSONFile(join(CACHE_DIR, `${accountId}.json`), { syncCursor: null, events: [] });
- if (!parsed || !Array.isArray(parsed.events)) return { syncCursor: null, events: [] };
- return parsed;
-}
-
-async function saveCache(accountId, cache) {
- await ensureDir(CACHE_DIR);
- await writeFile(join(CACHE_DIR, `${accountId}.json`), JSON.stringify(cache, null, 2));
+export function getSyncDateRange(pastDays = 7, futureDays = 30) {
+ const now = new Date();
+ const pastDate = new Date(now);
+ pastDate.setDate(pastDate.getDate() - pastDays);
+ const futureDate = new Date(now);
+ futureDate.setDate(futureDate.getDate() + futureDays);
+ return { pastDate, futureDate };
}
export async function pushSyncEvents(accountId, calendarId, calendarName, rawEvents, io) {
@@ -128,11 +121,7 @@ export async function mcpSyncAccount(accountId, io) {
io?.emit('calendar:sync:started', { accountId, method: 'mcp' });
console.log(`📅 Starting MCP sync for ${account.name} (${enabledCalendars.length} calendars)`);
- const now = new Date();
- const pastDate = new Date(now);
- pastDate.setDate(pastDate.getDate() - 7);
- const futureDate = new Date(now);
- futureDate.setDate(futureDate.getDate() + 30);
+ const { pastDate, futureDate } = getSyncDateRange();
const timeMin = pastDate.toISOString().slice(0, 19);
const timeMax = futureDate.toISOString().slice(0, 19);
@@ -244,19 +233,7 @@ Output NOTHING else — just the JSON array.`;
if (!Array.isArray(calendars)) return { error: 'Invalid calendar list format', status: 502 };
// Merge with existing subcalendars (preserve enabled/dormant state)
- const existingMap = new Map((account.subcalendars || []).map(sc => [sc.calendarId, sc]));
- const merged = calendars.map(cal => {
- const existing = existingMap.get(cal.id);
- return {
- calendarId: cal.id,
- name: cal.name || cal.id,
- color: cal.color || existing?.color || '',
- enabled: existing?.enabled ?? false,
- dormant: existing?.dormant ?? false,
- goalIds: existing?.goalIds || [],
- addedAt: existing?.addedAt || new Date().toISOString()
- };
- });
+ const merged = mergeDiscoveredSubcalendars(account.subcalendars, calendars);
// Save merged subcalendars
const { updateSubcalendars } = await import('./calendarAccounts.js');
diff --git a/server/services/calendarSync.js b/server/services/calendarSync.js
index df2e4827c8..5cd8157f33 100644
--- a/server/services/calendarSync.js
+++ b/server/services/calendarSync.js
@@ -3,7 +3,7 @@ import { join } from 'path';
import { ensureDir, PATHS, readJSONFile } from '../lib/fileUtils.js';
import { getAccount, updateSyncStatus } from './calendarAccounts.js';
-const CACHE_DIR = join(PATHS.calendar, 'cache');
+export 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();
@@ -38,7 +38,7 @@ function filterByDateRange(events, startDate, endDate) {
const DEFAULT_CACHE = { syncCursor: null, events: [] };
-async function loadCache(accountId) {
+export async function loadCache(accountId) {
if (!UUID_RE.test(accountId)) throw new Error(`Invalid accountId: ${accountId}`);
await ensureDir(CACHE_DIR);
const parsed = await readJSONFile(join(CACHE_DIR, `${accountId}.json`), DEFAULT_CACHE);
@@ -46,7 +46,7 @@ async function loadCache(accountId) {
return parsed;
}
-async function saveCache(accountId, cache) {
+export async function saveCache(accountId, cache) {
await ensureDir(CACHE_DIR);
const filePath = join(CACHE_DIR, `${accountId}.json`);
await writeFile(filePath, JSON.stringify(cache, null, 2));
diff --git a/server/services/dailyReview.js b/server/services/dailyReview.js
index 8abac4c305..c3bf242ddf 100644
--- a/server/services/dailyReview.js
+++ b/server/services/dailyReview.js
@@ -22,13 +22,12 @@ export async function getDailyReview(date) {
// Get all events for this date across all accounts
const startDate = `${date}T00:00:00`;
const endDate = `${date}T23:59:59`;
- const { events } = await calendarSync.getEvents({ startDate, endDate, limit: 200 });
-
- // Load existing review data for this date
- const existing = await loadReview(date) || { confirmations: {}, updatedAt: null };
-
- // Get accounts for subcalendar info
- const accounts = await calendarAccounts.listAccounts();
+ const [{ events }, existing, accounts, goalsData] = await Promise.all([
+ calendarSync.getEvents({ startDate, endDate, limit: 200 }),
+ loadReview(date).then(r => r || { confirmations: {}, updatedAt: null }),
+ calendarAccounts.listAccounts(),
+ getGoals()
+ ]);
const subcalendarMap = {};
for (const account of accounts) {
for (const sc of (account.subcalendars || [])) {
@@ -36,8 +35,7 @@ export async function getDailyReview(date) {
}
}
- // Get goals for linking info
- const goalsData = await getGoals();
+ // Build goal and subcalendar maps for linking info
const goalMap = {};
for (const goal of goalsData.goals) {
goalMap[goal.id] = goal;