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([issue-1149]): calendar services throw ServerError instead of returning {error,status}

[._.]/ Adam Eivyfaedfd101d23
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 1dfa5ea714..c814422622 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -35,6 +35,8 @@
## Changed
+- **[issue-1149] Calendar errors are now consistent everywhere** — calendar sync, discovery, and Google OAuth setup failures all come back in the same structured shape the rest of the app uses (instead of a mix of formats), and a failed Google sign-in now lands you back on the Calendar Config page with a clear error message instead of a raw error page.
+
- **[issue-1148] Internal reorganization of the scheduled-task prompt catalog** — the default prompts and their cross-install upgrade bookkeeping now live in separate files, with a new integrity check that guarantees the prompts your install upgrades against are exactly the shipped ones. No behavior change.
- **[issue-1144] Internal cleanup of live-progress streams and tab handling** — consolidated duplicated client plumbing for streamed progress (installs, renders, pipeline runs) and tabbed-page URL validation onto shared building blocks; no change to how any page behaves.
diff --git a/client/src/components/calendar/ConfigTab.jsx b/client/src/components/calendar/ConfigTab.jsx
index f1ca0d594e..567b38c9d6 100644
--- a/client/src/components/calendar/ConfigTab.jsx
+++ b/client/src/components/calendar/ConfigTab.jsx
@@ -1,4 +1,5 @@
import { useState, useEffect } from 'react';
+import { useSearchParams } from 'react-router-dom';
import { Plus, Trash2, RefreshCw, Globe, Calendar, Eye, EyeOff, ChevronDown, ChevronRight, Search, Key, ExternalLink, Wand2, Monitor } from 'lucide-react';
import toast from '../ui/Toast';
import * as api from '../../services/api';
@@ -27,6 +28,21 @@ export default function ConfigTab({ accounts, setAccounts }) {
useEffect(() => { fetchGoogleAuth(); }, []);
+ // The Google OAuth callback is a browser redirect (not an SPA fetch) — a
+ // failure lands back here as ?oauthError=… . Toast it once and strip the
+ // param so a reload doesn't re-toast.
+ const [searchParams, setSearchParams] = useSearchParams();
+ const oauthError = searchParams.get('oauthError');
+ useEffect(() => {
+ if (!oauthError) return;
+ toast.error(`Google OAuth failed: ${oauthError}`);
+ setSearchParams((prev) => {
+ const next = new URLSearchParams(prev);
+ next.delete('oauthError');
+ return next;
+ }, { replace: true });
+ }, [oauthError, setSearchParams]);
+
const handleSaveOAuthCredentials = async () => {
if (!oauthForm.clientId || !oauthForm.clientSecret) return toast.error('Both Client ID and Client Secret are required');
setSavingOAuth(true);
diff --git a/server/routes/calendar.js b/server/routes/calendar.js
index 4bd1b3bfc1..583559f02d 100644
--- a/server/routes/calendar.js
+++ b/server/routes/calendar.js
@@ -123,7 +123,6 @@ router.post('/sync/:accountId', asyncHandler(async (req, res) => {
}
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);
}));
@@ -204,7 +203,6 @@ router.post('/sync/:accountId/discover', asyncHandler(async (req, res) => {
}
const io = req.app.get('io');
const result = await calendarGoogleSync.mcpDiscoverCalendars(req.params.accountId, io);
- if (result.error) return res.status(result.status || 500).json({ error: result.error });
req.app.get('io')?.emit('calendar:changed', {});
res.json(result);
}));
@@ -216,7 +214,6 @@ router.post('/sync/:accountId/google', asyncHandler(async (req, res) => {
}
const io = req.app.get('io');
const result = await calendarGoogleSync.mcpSyncAccount(req.params.accountId, io);
- if (result.error) return res.status(result.status || 500).json({ error: result.error });
res.json(result);
}));
@@ -238,17 +235,21 @@ router.post('/google/auth/credentials', asyncHandler(async (req, res) => {
router.get('/google/auth/url', asyncHandler(async (req, res) => {
const result = await googleAuth.getAuthUrl();
- if (result.error) throw new ServerError(result.error, { status: 400 });
res.json(result);
}));
router.get('/google/oauth/callback', asyncHandler(async (req, res) => {
+ // This endpoint is hit by a BROWSER redirect from Google, not by the SPA —
+ // render every outcome as a redirect to the config page (which toasts the
+ // oauthError param) instead of the JSON envelope the middleware would send.
+ const configUrl = (error) => error
+ ? `/calendar/config?oauthError=${encodeURIComponent(error)}`
+ : '/calendar/config';
const code = req.query.code;
- if (!code) return res.status(400).send('Missing authorization code');
- const result = await googleAuth.handleCallback(code);
- if (result.error) return res.status(500).send(result.error);
- // Redirect to calendar config page after successful auth
- res.redirect('/calendar/config');
+ if (!code) return res.redirect(configUrl('Missing authorization code'));
+ const error = await googleAuth.handleCallback(code).then(() => null)
+ .catch((err) => err.message || 'Google OAuth callback failed');
+ res.redirect(configUrl(error));
}));
router.post('/google/auth/clear', asyncHandler(async (req, res) => {
@@ -260,14 +261,12 @@ router.post('/google/auth/clear', asyncHandler(async (req, res) => {
router.post('/google/auto-configure/start', asyncHandler(async (req, res) => {
const io = req.app.get('io');
const result = await googleOAuthAutoConfig.startAutoConfig(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);
- if (result.error) return res.status(result.status || 500).json({ error: result.error });
res.json(result);
}));
@@ -275,7 +274,6 @@ 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.error) return res.status(result.status || 500).json({ error: result.error });
res.json(result);
}));
@@ -286,7 +284,6 @@ router.post('/sync/:accountId/api', asyncHandler(async (req, res) => {
}
const io = req.app.get('io');
const result = await calendarGoogleApiSync.apiSyncAccount(req.params.accountId, io);
- if (result.error) return res.status(result.status || 500).json({ error: result.error });
res.json(result);
}));
@@ -295,7 +292,6 @@ router.post('/sync/:accountId/discover-api', asyncHandler(async (req, res) => {
throw new ServerError('Invalid account ID format', { status: 400, code: 'VALIDATION_ERROR' });
}
const result = await calendarGoogleApiSync.apiDiscoverCalendars(req.params.accountId);
- if (result.error) return res.status(result.status || 500).json({ error: result.error });
req.app.get('io')?.emit('calendar:changed', {});
res.json(result);
}));
diff --git a/server/routes/calendar.test.js b/server/routes/calendar.test.js
new file mode 100644
index 0000000000..035abd1e2b
--- /dev/null
+++ b/server/routes/calendar.test.js
@@ -0,0 +1,187 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import express from 'express';
+import { request } from '../lib/testHelper.js';
+import { ServerError } from '../lib/errorHandler.js';
+
+vi.mock('../services/calendarAccounts.js', () => ({
+ listAccounts: vi.fn(),
+ createAccount: vi.fn(),
+ updateAccount: vi.fn(),
+ deleteAccount: vi.fn(),
+ getAccount: vi.fn(),
+ updateSubcalendars: vi.fn()
+}));
+
+vi.mock('../services/calendarSync.js', () => ({
+ syncAccount: vi.fn(),
+ getSyncStatus: vi.fn(),
+ getEvents: vi.fn(),
+ getEvent: vi.fn(),
+ deleteCache: vi.fn(),
+ purgeDisabledSubcalendars: vi.fn()
+}));
+
+vi.mock('../services/calendarGoogleSync.js', () => ({
+ pushSyncEvents: vi.fn(),
+ mcpDiscoverCalendars: vi.fn(),
+ mcpSyncAccount: vi.fn()
+}));
+
+vi.mock('../services/dailyReview.js', () => ({
+ getDailyReview: vi.fn(),
+ getDailyReviewHistory: vi.fn(),
+ confirmEvent: vi.fn()
+}));
+
+vi.mock('../services/googleAuth.js', () => ({
+ getAuthStatus: vi.fn(),
+ saveCredentials: vi.fn(),
+ getAuthUrl: vi.fn(),
+ handleCallback: vi.fn(),
+ clearAuth: vi.fn()
+}));
+
+vi.mock('../services/calendarGoogleApiSync.js', () => ({
+ apiSyncAccount: vi.fn(),
+ apiDiscoverCalendars: vi.fn()
+}));
+
+vi.mock('../services/googleOAuthAutoConfig.js', () => ({
+ startAutoConfig: vi.fn(),
+ captureCredentials: vi.fn(),
+ runAutomatedSetup: vi.fn()
+}));
+
+vi.mock('../services/messageTokenExtractor.js', () => ({
+ getToken: vi.fn(),
+ getTokenStatus: vi.fn(),
+ clearTokenCache: vi.fn()
+}));
+
+import calendarRoutes from './calendar.js';
+import * as calendarSync from '../services/calendarSync.js';
+import * as calendarGoogleSync from '../services/calendarGoogleSync.js';
+import * as calendarGoogleApiSync from '../services/calendarGoogleApiSync.js';
+import * as googleAuth from '../services/googleAuth.js';
+import * as googleOAuthAutoConfig from '../services/googleOAuthAutoConfig.js';
+
+const ACCOUNT_ID = '11111111-1111-1111-1111-111111111111';
+
+describe('Calendar Routes — normalized error handling', () => {
+ let app;
+
+ beforeEach(() => {
+ app = express();
+ app.use(express.json());
+ app.use('/api/calendar', calendarRoutes);
+ // The OAuth callback redirects the BROWSER here — echo the query so tests
+ // can assert what landed (fetch follows redirects by default).
+ app.get('/calendar/config', (req, res) => res.json({ landed: true, oauthError: req.query.oauthError ?? null }));
+ vi.clearAllMocks();
+ });
+
+ describe('thrown ServerErrors map to the standard JSON envelope', () => {
+ it('POST /sync/:accountId surfaces a 409 sync-lock conflict', async () => {
+ calendarSync.syncAccount.mockRejectedValue(new ServerError('Sync already in progress', { status: 409 }));
+
+ const response = await request(app).post(`/api/calendar/sync/${ACCOUNT_ID}`);
+
+ expect(response.status).toBe(409);
+ expect(response.body.error).toBe('Sync already in progress');
+ expect(response.body.code).toBe('CONFLICT');
+ });
+
+ it('POST /sync/:accountId/google surfaces a 404 unknown account', async () => {
+ calendarGoogleSync.mcpSyncAccount.mockRejectedValue(new ServerError('Account not found', { status: 404 }));
+
+ const response = await request(app).post(`/api/calendar/sync/${ACCOUNT_ID}/google`);
+
+ expect(response.status).toBe(404);
+ expect(response.body.error).toBe('Account not found');
+ expect(response.body.code).toBe('NOT_FOUND');
+ });
+
+ it('POST /sync/:accountId/api surfaces a 401 missing-OAuth error', async () => {
+ calendarGoogleApiSync.apiSyncAccount.mockRejectedValue(
+ new ServerError('Google OAuth not configured. Set up credentials in Config tab.', { status: 401 }),
+ );
+
+ const response = await request(app).post(`/api/calendar/sync/${ACCOUNT_ID}/api`);
+
+ expect(response.status).toBe(401);
+ expect(response.body.error).toMatch(/Google OAuth not configured/);
+ });
+
+ it('GET /google/auth/url surfaces a 400 when no credentials are configured', async () => {
+ googleAuth.getAuthUrl.mockRejectedValue(new ServerError('No Google OAuth credentials configured', { status: 400 }));
+
+ const response = await request(app).get('/api/calendar/google/auth/url');
+
+ expect(response.status).toBe(400);
+ expect(response.body.error).toBe('No Google OAuth credentials configured');
+ });
+
+ it('POST /google/auto-configure/capture surfaces a 404 with the partial clientId in context', async () => {
+ googleOAuthAutoConfig.captureCredentials.mockRejectedValue(
+ new ServerError('Found Client ID but not secret. Click "Information and summary" on the client detail page first.', {
+ status: 404,
+ context: { clientId: 'abc.apps.googleusercontent.com' },
+ }),
+ );
+
+ const response = await request(app).post('/api/calendar/google/auto-configure/capture');
+
+ expect(response.status).toBe(404);
+ expect(response.body.error).toMatch(/Found Client ID but not secret/);
+ expect(response.body.context).toEqual({ clientId: 'abc.apps.googleusercontent.com' });
+ });
+ });
+
+ describe('success passthrough', () => {
+ it('POST /sync/:accountId returns the sync result as-is', async () => {
+ calendarSync.syncAccount.mockResolvedValue({ newEvents: 3, pruned: 1, total: 42, status: 'success' });
+
+ const response = await request(app).post(`/api/calendar/sync/${ACCOUNT_ID}`);
+
+ expect(response.status).toBe(200);
+ expect(response.body).toEqual({ newEvents: 3, pruned: 1, total: 42, status: 'success' });
+ });
+
+ it('GET /google/auth/url returns the url', async () => {
+ googleAuth.getAuthUrl.mockResolvedValue({ url: 'https://accounts.google.com/o/oauth2/auth?x=1' });
+
+ const response = await request(app).get('/api/calendar/google/auth/url');
+
+ expect(response.status).toBe(200);
+ expect(response.body.url).toMatch(/^https:\/\/accounts\.google\.com/);
+ });
+ });
+
+ describe('GET /google/oauth/callback stays browser-friendly (redirects, never JSON errors)', () => {
+ it('redirects to the config page on success', async () => {
+ googleAuth.handleCallback.mockResolvedValue({ success: true });
+
+ const response = await request(app).get('/api/calendar/google/oauth/callback?code=ok');
+
+ expect(response.body).toEqual({ landed: true, oauthError: null });
+ expect(googleAuth.handleCallback).toHaveBeenCalledWith('ok');
+ });
+
+ it('redirects with oauthError when the code is missing', async () => {
+ const response = await request(app).get('/api/calendar/google/oauth/callback');
+
+ expect(response.body.landed).toBe(true);
+ expect(response.body.oauthError).toBe('Missing authorization code');
+ expect(googleAuth.handleCallback).not.toHaveBeenCalled();
+ });
+
+ it('redirects with oauthError when the token exchange fails', async () => {
+ googleAuth.handleCallback.mockRejectedValue(new ServerError('invalid_grant', { status: 400 }));
+
+ const response = await request(app).get('/api/calendar/google/oauth/callback?code=bad');
+
+ expect(response.body.landed).toBe(true);
+ expect(response.body.oauthError).toBe('invalid_grant');
+ });
+ });
+});
diff --git a/server/services/calendarGoogleApiSync.js b/server/services/calendarGoogleApiSync.js
index 31938ba045..11d7f19ae8 100644
--- a/server/services/calendarGoogleApiSync.js
+++ b/server/services/calendarGoogleApiSync.js
@@ -1,18 +1,19 @@
import { calendar } from '@googleapis/calendar';
+import { ServerError } from '../lib/errorHandler.js';
import { getAuthenticatedClient } from './googleAuth.js';
import { getAccount, updateSubcalendars, mergeDiscoveredSubcalendars } from './calendarAccounts.js';
import { pushSyncEvents, getSyncDateRange } from './calendarGoogleSync.js';
export async function apiSyncAccount(accountId, io) {
const account = await getAccount(accountId);
- if (!account) return { error: 'Account not found', status: 404 };
- if (account.type !== 'google-calendar') return { error: 'Not a Google Calendar account', status: 400 };
+ if (!account) throw new ServerError('Account not found', { status: 404 });
+ if (account.type !== 'google-calendar') throw new ServerError('Not a Google Calendar account', { status: 400 });
const auth = await getAuthenticatedClient();
- if (!auth) return { error: 'Google OAuth not configured. Set up credentials in Config tab.', status: 401 };
+ if (!auth) throw new ServerError('Google OAuth not configured. Set up credentials in Config tab.', { status: 401 });
const enabledCalendars = (account.subcalendars || []).filter(sc => sc.enabled && !sc.dormant);
- if (enabledCalendars.length === 0) return { error: 'No enabled subcalendars', status: 400 };
+ if (enabledCalendars.length === 0) throw new ServerError('No enabled subcalendars', { status: 400 });
io?.emit('calendar:sync:started', { accountId, method: 'api' });
console.log(`📅 Starting Google API sync for ${account.name} (${enabledCalendars.length} calendars)`);
@@ -71,10 +72,10 @@ export async function apiSyncAccount(accountId, io) {
export async function apiDiscoverCalendars(accountId) {
const account = await getAccount(accountId);
- if (!account) return { error: 'Account not found', status: 404 };
+ if (!account) throw new ServerError('Account not found', { status: 404 });
const auth = await getAuthenticatedClient();
- if (!auth) return { error: 'Google OAuth not configured', status: 401 };
+ if (!auth) throw new ServerError('Google OAuth not configured', { status: 401 });
const cal = calendar({ version: 'v3', auth });
const allCalendars = [];
diff --git a/server/services/calendarGoogleSync.js b/server/services/calendarGoogleSync.js
index d7c3ca3b62..998323b1b5 100644
--- a/server/services/calendarGoogleSync.js
+++ b/server/services/calendarGoogleSync.js
@@ -6,6 +6,7 @@ import { getAllProviders } from './providers.js';
import { getSettings } from './settings.js';
import { pickCliProvider, runCliProviderPrompt } from '../lib/cliProviderRun.js';
import { safeJSONParse } from '../lib/fileUtils.js';
+import { ServerError } from '../lib/errorHandler.js';
// Google Calendar sync is driven through an MCP-capable CLI provider — the
// prompt asks the model to call the `mcp__claude_ai_Google_Calendar__*` tools.
@@ -118,14 +119,14 @@ export async function pushSyncEvents(accountId, calendarId, calendarName, rawEve
const mcpSyncLock = new Map();
export async function mcpSyncAccount(accountId, io) {
- if (mcpSyncLock.has(accountId)) return { error: 'MCP sync already in progress', status: 409 };
+ if (mcpSyncLock.has(accountId)) throw new ServerError('MCP sync already in progress', { status: 409 });
const account = await getAccount(accountId);
- if (!account) return { error: 'Account not found', status: 404 };
- if (account.type !== 'google-calendar') return { error: 'Not a Google Calendar account', status: 400 };
+ if (!account) throw new ServerError('Account not found', { status: 404 });
+ if (account.type !== 'google-calendar') throw new ServerError('Not a Google Calendar account', { status: 400 });
const enabledCalendars = (account.subcalendars || []).filter(sc => sc.enabled && !sc.dormant);
- if (enabledCalendars.length === 0) return { error: 'No enabled subcalendars', status: 400 };
+ if (enabledCalendars.length === 0) throw new ServerError('No enabled subcalendars', { status: 400 });
mcpSyncLock.set(accountId, true);
io?.emit('calendar:sync:started', { accountId, method: 'mcp' });
@@ -148,46 +149,42 @@ After fetching ALL calendars, output ONLY a single JSON object (no markdown fenc
Include the full events arrays as returned by gcal_list_events. Output NOTHING else — just the JSON.`;
- const result = await runConfiguredMcp(prompt, io, accountId);
-
- mcpSyncLock.delete(accountId);
-
- if (result.error) {
- console.error(`❌ MCP sync failed for ${account.name}: ${result.error}`);
- io?.emit('calendar:sync:failed', { accountId, error: result.error, method: 'mcp' });
- await updateSyncStatus(accountId, 'error');
- return { error: result.error, status: 502 };
- }
+ const runSync = async () => {
+ const result = await runConfiguredMcp(prompt, io, accountId);
+
+ // Parse Claude's output and push events
+ const parsed = parseCalendarJson(result.output);
+ if (!parsed) throw new ServerError('Failed to parse calendar data from Claude response', { status: 502 });
+
+ let totalNew = 0;
+ let totalUpdated = 0;
+ let totalPruned = 0;
+ const results = [];
+
+ for (const cal of parsed.calendars) {
+ if (!cal.calendarId || !Array.isArray(cal.events)) continue;
+ const syncResult = await pushSyncEvents(accountId, cal.calendarId, cal.calendarName || cal.calendarId, cal.events, null);
+ totalNew += syncResult.newEvents;
+ totalUpdated += syncResult.updated;
+ totalPruned += syncResult.pruned;
+ results.push({ calendarId: cal.calendarId, calendarName: cal.calendarName, ...syncResult });
+ }
- // Parse Claude's output and push events
- const parsed = parseCalendarJson(result.output);
- if (!parsed) {
- const errMsg = 'Failed to parse calendar data from Claude response';
- io?.emit('calendar:sync:failed', { accountId, error: errMsg, method: 'mcp' });
- await updateSyncStatus(accountId, 'error');
- console.error(`❌ ${errMsg}`);
- return { error: errMsg, status: 502 };
- }
+ await updateSyncStatus(accountId, 'success');
+ io?.emit('calendar:sync:completed', { accountId, newEvents: totalNew, updated: totalUpdated, pruned: totalPruned, status: 'success', method: 'mcp' });
+ console.log(`📅 MCP sync complete for ${account.name}: ${totalNew} new, ${totalUpdated} updated, ${totalPruned} pruned across ${results.length} calendars`);
- let totalNew = 0;
- let totalUpdated = 0;
- let totalPruned = 0;
- const results = [];
-
- for (const cal of parsed.calendars) {
- if (!cal.calendarId || !Array.isArray(cal.events)) continue;
- const syncResult = await pushSyncEvents(accountId, cal.calendarId, cal.calendarName || cal.calendarId, cal.events, null);
- totalNew += syncResult.newEvents;
- totalUpdated += syncResult.updated;
- totalPruned += syncResult.pruned;
- results.push({ calendarId: cal.calendarId, calendarName: cal.calendarName, ...syncResult });
- }
-
- await updateSyncStatus(accountId, 'success');
- io?.emit('calendar:sync:completed', { accountId, newEvents: totalNew, updated: totalUpdated, pruned: totalPruned, status: 'success', method: 'mcp' });
- console.log(`📅 MCP sync complete for ${account.name}: ${totalNew} new, ${totalUpdated} updated, ${totalPruned} pruned across ${results.length} calendars`);
+ return { newEvents: totalNew, updated: totalUpdated, pruned: totalPruned, calendars: results, status: 'success' };
+ };
- return { newEvents: totalNew, updated: totalUpdated, pruned: totalPruned, calendars: results, status: 'success' };
+ return runSync().catch(async (error) => {
+ console.error(`❌ MCP sync failed for ${account.name}: ${error.message}`);
+ io?.emit('calendar:sync:failed', { accountId, error: error.message, method: 'mcp' });
+ await updateSyncStatus(accountId, 'error').catch(() => {});
+ throw error instanceof ServerError ? error : new ServerError(error.message, { status: 502 });
+ }).finally(() => {
+ mcpSyncLock.delete(accountId);
+ });
}
function parseCalendarJson(output) {
@@ -206,8 +203,8 @@ function parseCalendarJson(output) {
export async function mcpDiscoverCalendars(accountId, io) {
const account = await getAccount(accountId);
- if (!account) return { error: 'Account not found', status: 404 };
- if (account.type !== 'google-calendar') return { error: 'Not a Google Calendar account', status: 400 };
+ if (!account) throw new ServerError('Account not found', { status: 404 });
+ if (account.type !== 'google-calendar') throw new ServerError('Not a Google Calendar account', { status: 400 });
console.log(`📅 Discovering Google calendars for ${account.name} via MCP`);
io?.emit('calendar:sync:progress', { accountId, message: 'Discovering calendars via Claude...' });
@@ -226,17 +223,12 @@ Output NOTHING else — just the JSON array.`;
const result = await runConfiguredMcp(prompt, io, accountId);
- if (result.error) {
- console.error(`❌ Calendar discovery failed: ${result.error}`);
- return { error: result.error, status: 502 };
- }
-
// Parse the calendar list from Claude's output
const match = result.output.match(/\[[\s\S]*\]/);
- if (!match) return { error: 'Failed to parse calendar list from Claude response', status: 502 };
+ if (!match) throw new ServerError('Failed to parse calendar list from Claude response', { status: 502 });
const calendars = safeJSONParse(match[0], null);
- if (!Array.isArray(calendars)) return { error: 'Invalid calendar list format', status: 502 };
+ if (!Array.isArray(calendars)) throw new ServerError('Invalid calendar list format', { status: 502 });
// Merge with existing subcalendars (preserve enabled/dormant state)
const merged = mergeDiscoveredSubcalendars(account.subcalendars, calendars);
@@ -255,7 +247,7 @@ async function runConfiguredMcp(prompt, io, accountId) {
const settings = await getSettings().catch(() => ({}));
const picked = pickCliProvider(all?.providers, settings?.calendarSync || {});
if (picked.error) {
- return { error: picked.error };
+ throw new ServerError(picked.error, { status: 502 });
}
// `--allowedTools mcp__…` is Claude-Code-specific argv. Other CLIs grant MCP
@@ -283,7 +275,7 @@ async function runConfiguredMcp(prompt, io, accountId) {
});
if (result.error) {
- return { error: result.error };
+ throw new ServerError(result.error, { status: 502 });
}
return { output: result.text, exitCode: result.exitCode };
}
diff --git a/server/services/calendarSync.js b/server/services/calendarSync.js
index 8e61eebb17..169d081dba 100644
--- a/server/services/calendarSync.js
+++ b/server/services/calendarSync.js
@@ -1,6 +1,7 @@
import { readdir, unlink, writeFile } from 'fs/promises';
import { join } from 'path';
import { ensureDir, filterBySearch as genericFilterBySearch, PATHS, readJSONFile, safeDate, UUID_RE } from '../lib/fileUtils.js';
+import { ServerError } from '../lib/errorHandler.js';
import { getAccount, updateSyncStatus } from './calendarAccounts.js';
export const CACHE_DIR = join(PATHS.calendar, 'cache');
@@ -143,11 +144,11 @@ export async function deleteCache(accountId) {
}
export async function syncAccount(accountId, io, options = {}) {
- if (syncLocks.has(accountId)) return { error: 'Sync already in progress', status: 409 };
+ if (syncLocks.has(accountId)) throw new ServerError('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 };
+ if (!account) throw new ServerError('Account not found', { status: 404 });
+ if (!account.enabled) throw new ServerError('Account is disabled', { status: 400 });
syncLocks.set(accountId, true);
io?.emit('calendar:sync:started', { accountId });
@@ -220,7 +221,7 @@ export async function syncAccount(accountId, io, options = {}) {
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 };
+ throw new ServerError(error.message, { status: 502 });
}).finally(() => {
syncLocks.delete(accountId);
});
diff --git a/server/services/googleAuth.js b/server/services/googleAuth.js
index 7c2fd16a6f..9c0897a3b8 100644
--- a/server/services/googleAuth.js
+++ b/server/services/googleAuth.js
@@ -2,6 +2,7 @@ import { OAuth2Client } from 'google-auth-library';
import { writeFile } from 'fs/promises';
import { join } from 'path';
import { ensureDir, PATHS, tryReadFile } from '../lib/fileUtils.js';
+import { ServerError } from '../lib/errorHandler.js';
const AUTH_DIR = join(PATHS.calendar, 'google-auth');
const CREDENTIALS_FILE = join(AUTH_DIR, 'credentials.json');
@@ -64,7 +65,7 @@ function createOAuth2Client(credentials) {
export async function getAuthUrl() {
const credentials = await getCredentials();
- if (!credentials) return { error: 'No Google OAuth credentials configured' };
+ if (!credentials) throw new ServerError('No Google OAuth credentials configured', { status: 400 });
const client = createOAuth2Client(credentials);
const url = client.generateAuthUrl({
@@ -77,7 +78,7 @@ export async function getAuthUrl() {
export async function handleCallback(code) {
const credentials = await getCredentials();
- if (!credentials) return { error: 'No credentials configured' };
+ if (!credentials) throw new ServerError('No credentials configured', { status: 400 });
const client = createOAuth2Client(credentials);
const { tokens } = await client.getToken(code);
diff --git a/server/services/googleOAuthAutoConfig.js b/server/services/googleOAuthAutoConfig.js
index 0541d42335..ed91490738 100644
--- a/server/services/googleOAuthAutoConfig.js
+++ b/server/services/googleOAuthAutoConfig.js
@@ -19,6 +19,7 @@ import { findOrOpenPage, evaluateOnPage, getPages } from './messagePlaywrightSyn
import { navigateToUrl } from './browserService.js';
import { saveCredentials, getAuthUrl, OAUTH_REDIRECT_URI } from './googleAuth.js';
import { sleep } from '../lib/fileUtils.js';
+import { ServerError } from '../lib/errorHandler.js';
async function getGcpPage() {
const pages = await getPages();
@@ -113,7 +114,7 @@ export async function startAutoConfig(io) {
const page = await findOrOpenPage('https://console.cloud.google.com');
if (!page) {
- return { error: 'Failed to open browser. Ensure portos-browser is running.', status: 503 };
+ throw new ServerError('Failed to open browser. Ensure portos-browser is running.', { status: 503 });
}
io?.emit('calendar:google:autoconfig', { step: 'login', message: 'Google Cloud Console opened. Log in and select a project, then click Continue.' });
@@ -129,7 +130,7 @@ export async function runAutomatedSetup(userEmail, io) {
};
let page = await getGcpPage();
- if (!page) return { error: 'Google Cloud Console not open. Click "Setup with Browser" first.', status: 400 };
+ if (!page) throw new ServerError('Google Cloud Console not open. Click "Setup with Browser" first.', { status: 400 });
// Detect the project from the current URL
const projectMatch = page.url?.match(/project=([^&]+)/);
@@ -444,11 +445,12 @@ export async function runAutomatedSetup(userEmail, io) {
if (!credentials?.clientId || !credentials?.clientSecret) {
emit('error', 'Could not capture credentials automatically');
- return {
- status: 'partial',
- error: 'Automation completed but could not extract the client secret. Use "Download JSON" from the Google Cloud Console client page and paste the credentials manually.',
- clientId: credentials?.clientId || null
- };
+ // The route's old { error } mapping returned HTTP 500 and dropped the
+ // partial clientId; keep it available to operators via error context.
+ throw new ServerError(
+ 'Automation completed but could not extract the client secret. Use "Download JSON" from the Google Cloud Console client page and paste the credentials manually.',
+ { status: 500, context: { clientId: credentials?.clientId || null } },
+ );
}
// Save credentials
@@ -492,7 +494,7 @@ async function extractFromDialog(page) {
export async function captureCredentials(io) {
const page = await getGcpPage();
- if (!page) return { error: 'Google Cloud Console not open in browser', status: 404 };
+ if (!page) throw new ServerError('Google Cloud Console not open in browser', { status: 404 });
io?.emit('calendar:google:autoconfig', { step: 'capturing', message: 'Scanning for credentials...' });
@@ -523,10 +525,13 @@ export async function captureCredentials(io) {
`);
if (!credentials?.clientId) {
- return { error: 'Could not find credentials on the page.', status: 404 };
+ throw new ServerError('Could not find credentials on the page.', { status: 404 });
}
if (!credentials.clientSecret) {
- return { error: 'Found Client ID but not secret. Click "Information and summary" on the client detail page first.', clientId: credentials.clientId, status: 404 };
+ throw new ServerError('Found Client ID but not secret. Click "Information and summary" on the client detail page first.', {
+ status: 404,
+ context: { clientId: credentials.clientId },
+ });
}
await saveCredentials(credentials);