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: report Calendar and Messages sync outcomes and release busy controls (#7101)

[._.]/ Adam Eivy8defc4fe673a
diff --git a/client/src/components/calendar/SyncTab.jsx b/client/src/components/calendar/SyncTab.jsx
index 460bb6c1e4..e55081c7f0 100644
--- a/client/src/components/calendar/SyncTab.jsx
+++ b/client/src/components/calendar/SyncTab.jsx
@@ -4,9 +4,9 @@ import toast from '../ui/Toast';
import { formatDateTime } from '../../utils/formatters';
import * as api from '../../services/api';
import socket from '../../services/socket';
+import { useAccountSyncStatus } from '../../hooks/useAccountSyncStatus';
export default function SyncTab({ accounts, onRefresh }) {
- const [syncing, setSyncing] = useState({});
const [tokenStatus, setTokenStatus] = useState(null);
const [tokenLoading, setTokenLoading] = useState(true);
const [mcpProgress, setMcpProgress] = useState({});
@@ -17,66 +17,37 @@ export default function SyncTab({ accounts, onRefresh }) {
setTokenLoading(false);
}, []);
- useEffect(() => {
- fetchTokenStatus();
+ const clearProgress = useCallback((accountId) => {
+ setMcpProgress(prev => { const next = { ...prev }; delete next[accountId]; return next; });
+ }, []);
- const onSyncStarted = ({ accountId }) => {
- setSyncing(prev => ({ ...prev, [accountId]: 'syncing' }));
- };
- 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();
- };
- const onSyncFailed = ({ accountId, error }) => {
- setSyncing(prev => ({ ...prev, [accountId]: null }));
- toast.error(`Calendar sync failed: ${error ?? 'unknown error'}`);
- };
+ const { syncing, sync } = useAccountSyncStatus({
+ eventPrefix: 'calendar',
+ label: 'Calendar sync',
+ successText: ({ newEvents }) => `Calendar sync complete: ${newEvents ?? 0} events`,
+ onRefresh,
+ onStart: clearProgress,
+ onTerminal: clearProgress,
+ });
+
+ useEffect(() => { fetchTokenStatus(); }, [fetchTokenStatus]);
+ useEffect(() => {
const onSyncProgress = ({ accountId, message }) => {
setMcpProgress(prev => ({ ...prev, [accountId]: message }));
};
-
- socket.on('calendar:sync:started', onSyncStarted);
- socket.on('calendar:sync:completed', onSyncCompleted);
- socket.on('calendar:sync:failed', onSyncFailed);
socket.on('calendar:sync:progress', onSyncProgress);
+ return () => socket.off('calendar:sync:progress', onSyncProgress);
+ }, []);
- return () => {
- socket.off('calendar:sync:started', onSyncStarted);
- socket.off('calendar:sync:completed', onSyncCompleted);
- socket.off('calendar:sync:failed', onSyncFailed);
- socket.off('calendar:sync:progress', onSyncProgress);
- };
- }, [fetchTokenStatus, onRefresh]);
-
- const handleSync = async (accountId) => {
- setSyncing(prev => ({ ...prev, [accountId]: 'syncing' }));
- await api.syncCalendarAccount(accountId).catch(() => {
- setSyncing(prev => ({ ...prev, [accountId]: null }));
- });
- };
+ const handleSync = (accountId) => sync(accountId, () => api.syncCalendarAccount(accountId, { silent: true }));
- const handleGoogleSync = async (account) => {
- setSyncing(prev => ({ ...prev, [account.id]: 'syncing' }));
+ const handleGoogleSync = (account) => sync(account.id, () => {
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(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')) {
- toast.error('Claude CLI not found. Ensure Claude Code is installed and in your PATH.');
- } else if (result?.error?.includes('OAuth')) {
- toast.error('Google OAuth not configured. Set up in Config tab.');
- }
- }
- };
+ return account.syncMethod === 'google-api'
+ ? api.apiSyncGoogleCalendar(account.id, { silent: true })
+ : api.mcpSyncGoogleCalendar(account.id, { silent: true });
+ });
const handleTestToken = async (provider) => {
const result = await api.testCalendarToken(provider).catch(() => null);
diff --git a/client/src/components/calendar/SyncTab.test.jsx b/client/src/components/calendar/SyncTab.test.jsx
new file mode 100644
index 0000000000..b2463441ff
--- /dev/null
+++ b/client/src/components/calendar/SyncTab.test.jsx
@@ -0,0 +1,109 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { act, fireEvent, render, screen, waitFor } from '@testing-library/react';
+import SyncTab from './SyncTab';
+
+const api = vi.hoisted(() => ({
+ getCalendarTokenStatus: vi.fn(),
+ syncCalendarAccount: vi.fn(),
+ apiSyncGoogleCalendar: vi.fn(),
+ mcpSyncGoogleCalendar: vi.fn(),
+}));
+const toast = vi.hoisted(() => ({ success: vi.fn(), error: vi.fn(), warning: vi.fn() }));
+const listeners = vi.hoisted(() => new Map());
+vi.mock('../../services/api', () => api);
+vi.mock('../ui/Toast', () => ({ default: toast }));
+vi.mock('../../services/socket', () => ({ default: {
+ on: (event, handler) => listeners.set(event, handler),
+ off: (event, handler) => { if (listeners.get(event) === handler) listeners.delete(event); },
+} }));
+
+const account = { id: 'calendar-1', name: 'Calendar', enabled: true, type: 'outlook-calendar' };
+const emit = (event, payload = {}) => act(() => listeners.get(`calendar:sync:${event}`)?.({ accountId: account.id, ...payload }));
+const syncButton = () => screen.getByRole('button', { name: 'Sync' });
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ listeners.clear();
+ api.getCalendarTokenStatus.mockResolvedValue({ providers: [] });
+});
+
+describe('Calendar sync lifecycle', () => {
+ it('releases failed and partial syncs without claiming success, then accepts a new legacy success', async () => {
+ const onRefresh = vi.fn();
+ render(<SyncTab accounts={[account]} onRefresh={onRefresh} />);
+ emit('started');
+ expect(screen.queryByRole('button', { name: 'Sync' })).toBeNull();
+ emit('completed', { status: 'api-error' });
+ expect(syncButton()).toBeEnabled();
+ expect(toast.error).toHaveBeenCalledWith(expect.stringContaining('provider API'));
+ expect(toast.success).not.toHaveBeenCalled();
+
+ emit('started');
+ emit('completed', { status: 'partial', reason: 'One calendar was unavailable', newEvents: 2 });
+ expect(syncButton()).toBeEnabled();
+ expect(toast.warning).toHaveBeenCalledWith('Calendar sync incomplete: One calendar was unavailable');
+ expect(toast.success).not.toHaveBeenCalled();
+ expect(onRefresh).toHaveBeenCalledTimes(1);
+
+ emit('started');
+ emit('completed', { newEvents: 3 });
+ expect(toast.success).toHaveBeenCalledWith('Calendar sync complete: 3 events');
+ expect(onRefresh).toHaveBeenCalledTimes(2);
+ await waitFor(() => expect(api.getCalendarTokenStatus).toHaveBeenCalled());
+ });
+
+ it('explains an HTTP-only skipped sync and deduplicates HTTP-first completion', async () => {
+ api.syncCalendarAccount.mockResolvedValue({ status: 'skipped' });
+ render(<SyncTab accounts={[account]} onRefresh={vi.fn()} />);
+ fireEvent.click(syncButton());
+ await waitFor(() => expect(syncButton()).toBeEnabled());
+ expect(toast.warning).toHaveBeenCalledWith(expect.stringContaining('no usable token'));
+ expect(api.syncCalendarAccount).toHaveBeenCalledWith(account.id, { silent: true });
+
+ api.syncCalendarAccount.mockResolvedValue({ status: 'success', newEvents: 4 });
+ fireEvent.click(syncButton());
+ emit('started');
+ await waitFor(() => expect(toast.success).toHaveBeenCalledTimes(1));
+ emit('completed', { status: 'success', newEvents: 4 });
+ expect(toast.success).toHaveBeenCalledTimes(1);
+ });
+
+ it('ignores an older HTTP result after a newer socket cycle starts', async () => {
+ let resolve;
+ api.syncCalendarAccount.mockImplementation(() => new Promise(done => { resolve = done; }));
+ render(<SyncTab accounts={[account]} onRefresh={vi.fn()} />);
+ fireEvent.click(syncButton());
+ emit('started');
+ emit('completed', { status: 'success', newEvents: 1 });
+ emit('started');
+ await act(async () => resolve({ status: 'success', newEvents: 1 }));
+ expect(screen.queryByRole('button', { name: 'Sync' })).toBeNull();
+ expect(toast.success).toHaveBeenCalledTimes(1);
+ emit('completed', { status: 'push-only' });
+ expect(syncButton()).toBeEnabled();
+ expect(toast.warning).toHaveBeenCalledWith(expect.stringContaining('pushed updates'));
+ });
+
+ it('clears Google progress on HTTP failure and removes listeners before a late response', async () => {
+ const onRefresh = vi.fn();
+ api.apiSyncGoogleCalendar.mockRejectedValue(new Error('Google OAuth not configured'));
+ let resolve;
+ api.mcpSyncGoogleCalendar.mockImplementation(() => new Promise(done => { resolve = done; }));
+ const { rerender, unmount } = render(<SyncTab accounts={[{ ...account, type: 'google-calendar', syncMethod: 'google-api' }]} onRefresh={onRefresh} />);
+ fireEvent.click(screen.getByRole('button', { name: 'Sync (API)' }));
+ await waitFor(() => expect(toast.error).toHaveBeenCalledWith(expect.stringContaining('Google OAuth not configured')));
+ expect(screen.getByRole('button', { name: 'Sync (API)' })).toBeEnabled();
+ expect(screen.queryByText('Starting Google Calendar sync...')).toBeNull();
+
+ rerender(<SyncTab accounts={[{ ...account, type: 'google-calendar' }]} onRefresh={onRefresh} />);
+ fireEvent.click(screen.getByRole('button', { name: 'Sync (Claude)' }));
+ emit('started');
+ emit('progress', { message: 'Fetching calendars' });
+ expect(screen.getByText('Fetching calendars')).toBeTruthy();
+ unmount();
+ expect(listeners.size).toBe(0);
+ await act(async () => resolve({ status: 'success', newEvents: 9 }));
+ expect(toast.success).not.toHaveBeenCalled();
+ expect(onRefresh).not.toHaveBeenCalled();
+ });
+});
diff --git a/client/src/components/messages/SyncTab.jsx b/client/src/components/messages/SyncTab.jsx
index 434cc14f74..2f75bf2bee 100644
--- a/client/src/components/messages/SyncTab.jsx
+++ b/client/src/components/messages/SyncTab.jsx
@@ -6,7 +6,7 @@ import QueueInvestigationButton from '../ui/QueueInvestigationButton';
import { formatDateTime } from '../../utils/formatters';
import { buildSelectorTestFailureTask } from '../../lib/selectorTestFailureTask';
import * as api from '../../services/api';
-import socket from '../../services/socket';
+import { useAccountSyncStatus } from '../../hooks/useAccountSyncStatus';
// Human-facing summary per `testSelectors()` status — kept out of JSX so the
// failure-task builder and the toast can share the same wording.
@@ -26,7 +26,6 @@ const DEFAULT_SELECTORS = {
};
export default function SyncTab({ accounts, onRefresh }) {
- const [syncing, setSyncing] = useState({});
const [rawSelectors, setRawSelectors] = useState({});
const [editingSelector, setEditingSelector] = useState(null);
const [selectorForm, setSelectorForm] = useState({});
@@ -45,51 +44,22 @@ export default function SyncTab({ accounts, onRefresh }) {
setRawSelectors(data || {});
}, []);
- useEffect(() => {
- fetchSelectors();
-
- const onSyncStarted = ({ accountId }) => {
- setSyncing(prev => ({ ...prev, [accountId]: 'syncing' }));
- };
- const onSyncCompleted = ({ accountId, newMessages, status }) => {
- if (status && status !== 'success') return; // non-success handled by specific event (e.g. sync:auth-required)
- setSyncing(prev => ({ ...prev, [accountId]: null }));
- toast.success(`Sync complete: ${newMessages} new messages`);
- onRefresh();
- };
- const onAuthRequired = ({ accountId }) => {
- setSyncing(prev => ({ ...prev, [accountId]: 'auth-required' }));
- toast('Login required -- open Browser page to authenticate', { icon: '\uD83D\uDD10' });
- };
- const onSyncFailed = ({ accountId, error }) => {
- setSyncing(prev => ({ ...prev, [accountId]: null }));
- toast.error(`Sync failed: ${error ?? 'unknown error'}`);
- };
+ const { syncing, sync } = useAccountSyncStatus({
+ eventPrefix: 'messages',
+ label: 'Sync',
+ successText: ({ newMessages }) => `Sync complete: ${newMessages ?? 0} new messages`,
+ onRefresh,
+ });
- socket.on('messages:sync:started', onSyncStarted);
- socket.on('messages:sync:completed', onSyncCompleted);
- socket.on('messages:sync:auth-required', onAuthRequired);
- socket.on('messages:sync:failed', onSyncFailed);
-
- return () => {
- socket.off('messages:sync:started', onSyncStarted);
- socket.off('messages:sync:completed', onSyncCompleted);
- socket.off('messages:sync:auth-required', onAuthRequired);
- socket.off('messages:sync:failed', onSyncFailed);
- };
- }, [fetchSelectors, onRefresh]);
+ useEffect(() => { fetchSelectors(); }, [fetchSelectors]);
const handleLaunch = async (accountId) => {
const result = await api.launchMessageBrowser(accountId).catch(() => null);
if (result?.success) toast.success('Browser tab opened — log in if needed, then sync');
};
- const handleSync = async (accountId, mode = 'unread') => {
- setSyncing(prev => ({ ...prev, [accountId]: 'syncing' }));
- await api.syncMessageAccount(accountId, mode).catch(() => {
- setSyncing(prev => ({ ...prev, [accountId]: null }));
- });
- };
+ const handleSync = (accountId, mode = 'unread') =>
+ sync(accountId, () => api.syncMessageAccount(accountId, mode, { silent: true }));
const handleSaveSelectors = async (provider) => {
const result = await api.updateMessageSelectors(provider, selectorForm).catch(() => null);
diff --git a/client/src/components/messages/SyncTab.test.jsx b/client/src/components/messages/SyncTab.test.jsx
index ec1f2bfd60..2c6836d162 100644
--- a/client/src/components/messages/SyncTab.test.jsx
+++ b/client/src/components/messages/SyncTab.test.jsx
@@ -1,14 +1,16 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
-import { fireEvent, render, screen, waitFor } from '@testing-library/react';
+import { act, fireEvent, render, screen, waitFor } from '@testing-library/react';
const api = vi.hoisted(() => ({
getMessageSelectors: vi.fn(),
+ syncMessageAccount: vi.fn(),
testMessageSelectors: vi.fn(),
addCosTask: vi.fn(),
}));
const toast = vi.hoisted(() => Object.assign(vi.fn(), {
error: vi.fn(),
success: vi.fn(),
+ warning: vi.fn(),
}));
const socket = vi.hoisted(() => ({ on: vi.fn(), off: vi.fn(), emit: vi.fn() }));
@@ -81,3 +83,54 @@ describe('SyncTab DOM selector test', () => {
await waitFor(() => expect(screen.getByRole('button', { name: /agent queued/i })).toBeTruthy());
});
});
+
+
+describe('Messages sync lifecycle', () => {
+ const account = { id: 'message-1', name: 'Inbox', enabled: true, provider: 'playwright' };
+ const emit = (event, payload = {}) => act(() => {
+ const handler = socket.on.mock.calls.find(([name]) => name === `messages:sync:${event}`)?.[1];
+ handler?.({ accountId: account.id, ...payload });
+ });
+
+ it('releases provider failures without a dedicated event and preserves login guidance', async () => {
+ render(<SyncTab accounts={[account]} onRefresh={vi.fn()} />);
+ for (const status of ['no-browser', 'extraction-failed', 'unexpected-status']) {
+ emit('started');
+ expect(screen.queryByRole('button', { name: 'Sync Unread' })).toBeNull();
+ emit('completed', { status });
+ expect(screen.getByRole('button', { name: 'Sync Unread' })).toBeEnabled();
+ }
+ expect(toast.error).toHaveBeenCalledTimes(3);
+ expect(toast.success).not.toHaveBeenCalled();
+ emit('started');
+ emit('auth-required');
+ emit('completed', { status: 'auth-required' });
+ expect(screen.getByText('Auth required')).toBeTruthy();
+ expect(screen.getByRole('button', { name: 'Launch' })).toBeEnabled();
+ expect(screen.getByRole('button', { name: 'Sync Unread' })).toBeEnabled();
+ expect(toast.warning).toHaveBeenCalledTimes(1);
+ expect(toast.warning).toHaveBeenCalledWith(expect.stringContaining('open Browser page'));
+ await waitFor(() => expect(api.getMessageSelectors).toHaveBeenCalled());
+ });
+
+ it('reports a socket-first success once and a later manual rejection once', async () => {
+ let resolve;
+ api.syncMessageAccount.mockImplementation(() => new Promise(done => { resolve = done; }));
+ const onRefresh = vi.fn();
+ render(<SyncTab accounts={[account]} onRefresh={onRefresh} />);
+ fireEvent.click(screen.getByRole('button', { name: 'Full Sync' }));
+ expect(api.syncMessageAccount).toHaveBeenCalledWith(account.id, 'full', { silent: true });
+ emit('started');
+ emit('completed', { status: 'success', newMessages: 5 });
+ await act(async () => resolve({ status: 'success', newMessages: 5 }));
+ expect(toast.success).toHaveBeenCalledExactlyOnceWith('Sync complete: 5 new messages');
+ expect(onRefresh).toHaveBeenCalledTimes(1);
+
+ api.syncMessageAccount.mockRejectedValue(new Error('Connection lost'));
+ fireEvent.click(screen.getByRole('button', { name: 'Sync Unread' }));
+ emit('started');
+ emit('failed', { error: 'Connection lost' });
+ await waitFor(() => expect(screen.getByRole('button', { name: 'Sync Unread' })).toBeEnabled());
+ expect(toast.error).toHaveBeenCalledExactlyOnceWith('Sync failed: Connection lost');
+ });
+});
diff --git a/client/src/hooks/README.md b/client/src/hooks/README.md
index e888c6be88..129a40da3e 100644
--- a/client/src/hooks/README.md
+++ b/client/src/hooks/README.md
@@ -80,6 +80,7 @@ grep -i "what you want to do" client/src/hooks/README.md
| Hook | Purpose | Use when |
|---|---|---|
| `useCosTaskUpdates` | Shared five-event CoS task lifecycle subscription; re-subscribes on socket reconnect and forwards normalized task updates to the current callback. | A CoS task surface with its own task-status reducer. |
+| `useAccountSyncStatus` | Per-account busy/auth state and deduplicated HTTP/socket sync outcomes. | Calendar and Messages sync controls. |
| `useSocket` | Shared socket instance + connection status. | You need to subscribe to a socket event. |
| `useShellSession` | All Socket.IO `shell:*` session/terminal state + lifecycle for the Shell page: owns the xterm instance, the attach/detach/generation-guard contract (`pendingAttachRef {target,generation}`, `claim`, `userIdleRef`, `mountedRef`), URL sync, and every session action. Returns `{ terminalRef, connected, sessions, activeSessionId, activeSession, interactiveCount, liveRunCount, isLiveRun, emitShellInput, sendImage, sendCommand, sendCd, sendCtrlB, sendCtrlC, sendNavKey, restartSession, stopSession, startNewSession, switchToSession, killOtherSession }` so the route stays presentational. `sendCd(path)` sends a FOLDER over `shell:cd` rather than composing a `cd` line — the server renders it for the session's actual shell (`server/lib/shellCd.js`), which is the only form that works on a Windows cmd.exe session. `sendCommand(cmd)` submits with CR, never `\n` (see `SUBMIT_KEY` in `server/lib/tuiHandshake.js`). `sendImage(file, message)` is the one operation that leaves the socket — it POSTs to `/api/shell/sessions/:id/image` so a running agent TUI gets the photo's path pasted into its prompt. | The Shell page (`pages/Shell.jsx`) — don't re-roll the single-subscriber PTY attach lifecycle. |
| `useUpdateChecker` | Update-available + install-out-of-sync advisories as *state* (`{ update, outOfSync, ignoreUpdate, dismissUpdate, clearOutOfSync, dismissOutOfSync }`), never toasts — a non-transient advisory must not occlude the screen's primary action (#3786). Out-of-sync dismissals persist per on-disk commit in `safeStorage`, so a later `git pull` re-raises; `clearOutOfSync` is the session-only clear used when the user acts on it. | Never call it directly — `components/UpdateBanners` owns the single instance and Layout renders that once at the app root. A second caller means a second status fetch and socket subscription. |
diff --git a/client/src/hooks/index.js b/client/src/hooks/index.js
index 7421fc2050..4e8a23814d 100644
--- a/client/src/hooks/index.js
+++ b/client/src/hooks/index.js
@@ -220,3 +220,4 @@ export * from './useVideoGenValidation.js';
export * from './useVoiceUiSync.js';
export { default as useEidoverseFrame } from './useEidoverseFrame.js';
export * from './useGalleryPage.js';
+export * from './useAccountSyncStatus.js';
diff --git a/client/src/hooks/useAccountSyncStatus.js b/client/src/hooks/useAccountSyncStatus.js
new file mode 100644
index 0000000000..543dd63c9f
--- /dev/null
+++ b/client/src/hooks/useAccountSyncStatus.js
@@ -0,0 +1,91 @@
+import { useCallback, useEffect, useRef, useState } from 'react';
+import socket from '../services/socket';
+import toast from '../components/ui/Toast';
+import useMounted from './useMounted';
+
+const STATUS_TEXT = {
+ 'api-error': 'The provider API could not complete the sync',
+ 'no-browser': 'No browser tab available — open the Browser page and try again',
+ 'extraction-failed': 'Could not extract messages from the browser page',
+ skipped: 'Sync skipped — no usable token is available; authenticate and try again',
+ 'push-only': 'This account receives pushed updates; use its provider sync control',
+};
+
+// HTTP and socket results share one terminal decision, including older frames
+// with no status. An error body must never be mistaken for legacy success.
+function outcome(result, label, successText) {
+ const status = result?.status ?? (result?.error ? 'error' : 'success');
+ const reason = result?.reason || result?.error || STATUS_TEXT[status] || status;
+ if (status === 'success') return { type: 'success', text: successText(result ?? {}), refresh: true };
+ if (status === 'auth-required') return {
+ type: 'warning', auth: true, text: 'Login required — open Browser page to authenticate',
+ };
+ if (status === 'partial') return { type: 'warning', text: `${label} incomplete: ${reason}`, refresh: true };
+ if (status === 'skipped' || status === 'push-only') return { type: 'warning', text: reason };
+ return { type: 'error', text: `${label} failed: ${reason}` };
+}
+
+/** One per-account cycle joins manual HTTP and socket terminal notifications. */
+export function useAccountSyncStatus({ eventPrefix, label, successText, onRefresh, onStart, onTerminal }) {
+ const [syncing, setSyncing] = useState({});
+ const mounted = useMounted();
+ const cycles = useRef(new Map());
+ const callbacks = useRef({});
+ callbacks.current = { label, successText, onRefresh, onStart, onTerminal };
+
+ const begin = useCallback((accountId, manual = false) => {
+ const cycle = { awaitingStart: manual, settled: false };
+ cycles.current.set(accountId, cycle);
+ setSyncing(prev => ({ ...prev, [accountId]: 'syncing' }));
+ callbacks.current.onStart?.(accountId);
+ return cycle;
+ }, []);
+
+ const finish = useCallback((accountId, result, expectedCycle) => {
+ if (!mounted.current) return;
+ let cycle = cycles.current.get(accountId);
+ if (expectedCycle && cycle !== expectedCycle) return;
+ if (cycle?.settled) return;
+ if (!cycle) {
+ cycle = {};
+ cycles.current.set(accountId, cycle);
+ }
+ cycle.settled = true;
+ const current = callbacks.current;
+ const terminal = outcome(result, current.label, current.successText);
+ setSyncing(prev => ({ ...prev, [accountId]: terminal.auth ? 'auth-required' : null }));
+ current.onTerminal?.(accountId);
+ toast[terminal.type](terminal.text);
+ if (terminal.refresh) current.onRefresh?.();
+ }, [mounted]);
+
+ useEffect(() => {
+ const started = ({ accountId }) => {
+ const cycle = cycles.current.get(accountId);
+ // A server start acknowledges the manual cycle; it must not orphan its
+ // pending HTTP response. Later starts open a fresh notification cycle.
+ if (cycle?.awaitingStart && !cycle.settled) cycle.awaitingStart = false;
+ else begin(accountId);
+ };
+ const completed = ({ accountId, ...result }) => finish(accountId, result);
+ const failed = ({ accountId, error }) => finish(accountId, { status: 'error', error: error ?? 'unknown error' });
+ const authRequired = ({ accountId }) => finish(accountId, { status: 'auth-required' });
+ const handlers = { started, completed, failed, 'auth-required': authRequired };
+ for (const [event, handler] of Object.entries(handlers)) socket.on(`${eventPrefix}:sync:${event}`, handler);
+ return () => {
+ for (const [event, handler] of Object.entries(handlers)) socket.off(`${eventPrefix}:sync:${event}`, handler);
+ cycles.current.clear();
+ };
+ }, [eventPrefix, begin, finish]);
+
+ const sync = useCallback(async (accountId, request) => {
+ const cycle = begin(accountId, true);
+ // Callers use silent API requests: this hook owns the single outcome toast.
+ const result = await request().catch(error => ({
+ status: 'error', error: error?.message || 'Sync request failed',
+ }));
+ finish(accountId, result, cycle);
+ }, [begin, finish]);
+
+ return { syncing, sync };
+}
diff --git a/client/src/services/apiCalendar.js b/client/src/services/apiCalendar.js
index ecf9c2e0a5..84ee3371ff 100644
--- a/client/src/services/apiCalendar.js
+++ b/client/src/services/apiCalendar.js
@@ -5,7 +5,7 @@ export const getCalendarAccounts = () => request('/calendar/accounts');
export const createCalendarAccount = (data, options = {}) => request('/calendar/accounts', { method: 'POST', body: JSON.stringify(data), ...options });
export const updateCalendarAccount = (id, data, options = {}) => request(`/calendar/accounts/${id}`, { method: 'PUT', body: JSON.stringify(data), ...options });
export const deleteCalendarAccount = (id) => request(`/calendar/accounts/${id}`, { method: 'DELETE' });
-export const syncCalendarAccount = (accountId) => request(`/calendar/sync/${accountId}`, { method: 'POST' });
+export const syncCalendarAccount = (accountId, options = {}) => request(`/calendar/sync/${accountId}`, { method: 'POST', ...options });
export const getCalendarEvents = (params = {}) => {
const str = new URLSearchParams(Object.entries(params).filter(([, v]) => v != null)).toString();
return request(`/calendar/events${str ? `?${str}` : ''}`);
@@ -15,7 +15,7 @@ export const getCalendarTokenStatus = () => request('/calendar/debug/token-statu
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 }) });
export const updateSubcalendars = (accountId, data, options = {}) => request(`/calendar/accounts/${accountId}/subcalendars`, { method: 'PUT', body: JSON.stringify(data), ...options });
-export const mcpSyncGoogleCalendar = (accountId) => request(`/calendar/sync/${accountId}/google`, { method: 'POST' });
+export const mcpSyncGoogleCalendar = (accountId, options = {}) => request(`/calendar/sync/${accountId}/google`, { method: 'POST', ...options });
export const mcpDiscoverCalendars = (accountId) => request(`/calendar/sync/${accountId}/discover`, { method: 'POST' });
export const getGoogleAuthStatus = () => request('/calendar/google/auth/status');
export const saveGoogleAuthCredentials = (data, options = {}) => request('/calendar/google/auth/credentials', { method: 'POST', body: JSON.stringify(data), ...options });
@@ -24,7 +24,7 @@ export const getGoogleAuthUrl = ({ returnTo, ...options } = {}) => {
return request(`/calendar/google/auth/url${query}`, options);
};
export const clearGoogleAuth = () => request('/calendar/google/auth/clear', { method: 'POST' });
-export const apiSyncGoogleCalendar = (accountId) => request(`/calendar/sync/${accountId}/api`, { method: 'POST' });
+export const apiSyncGoogleCalendar = (accountId, options = {}) => request(`/calendar/sync/${accountId}/api`, { method: 'POST', ...options });
export const apiDiscoverCalendars = (accountId) => request(`/calendar/sync/${accountId}/discover-api`, { method: 'POST' });
export const startGoogleAutoConfig = (options = {}) => request('/calendar/google/auto-configure/start', { method: 'POST', ...options });
export const runGoogleAutoConfig = (email, options = {}) => request('/calendar/google/auto-configure/run', { method: 'POST', body: JSON.stringify({ email }), ...options });
diff --git a/server/services/messageSync.test.js b/server/services/messageSync.test.js
index c743126bcf..e2bdccc2c4 100644
--- a/server/services/messageSync.test.js
+++ b/server/services/messageSync.test.js
@@ -47,6 +47,17 @@ vi.mock('./messagePlaywrightSync.js', () => ({
refreshMessageDetail: vi.fn()
}));
+// Keep provider fallback and secondary activity writes inside the fixture;
+// these sync tests must never reach browser credentials or a persistent store.
+vi.mock('./messageApiSync.js', () => ({
+ syncOutlookApi: vi.fn(async () => null),
+}));
+vi.mock('./humanActivity.js', async (importOriginal) => ({
+ ...await importOriginal(),
+ recordEvents: vi.fn(async () => ({ recorded: 0, skipped: 0 })),
+ stripParticipantsForAccount: vi.fn(async () => 0),
+}));
+
// tribe.js is loaded dynamically by logMessageTouchpoints; mock it so the
// producer test asserts the candidates without a live Postgres.
vi.mock('./tribe.js', () => ({