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: deduplicate calendar batches and heal cached duplicates (#8635)

[._.]/ Adam Eivy35c0628b14e0
diff --git a/server/services/calendarGoogleSync.js b/server/services/calendarGoogleSync.js
index 6e43ff7a81..5935be7483 100644
--- a/server/services/calendarGoogleSync.js
+++ b/server/services/calendarGoogleSync.js
@@ -95,12 +95,14 @@ export async function pushSyncEvents(accountId, calendarId, calendarName, rawEve
const cache = await loadCache(accountId);
const normalized = rawEvents.map(e => normalizeGoogleEvent(e, calendarId, calendarName));
- // Build map of existing events for this subcalendar
- const existingMap = new Map(
- cache.events
- .filter(e => e.externalId && e.subcalendarId === calendarId)
- .map(e => [e.externalId, e])
- );
+ // Heal legacy duplicates in this subcalendar, retaining the first local id.
+ const existingMap = new Map();
+ cache.events = cache.events.filter(event => {
+ if (!event.externalId || event.subcalendarId !== calendarId) return true;
+ if (existingMap.has(event.externalId)) return false;
+ existingMap.set(event.externalId, event);
+ return true;
+ });
let newCount = 0;
let updatedCount = 0;
@@ -135,7 +137,9 @@ export async function pushSyncEvents(accountId, calendarId, calendarName, rawEve
} else {
// A newly cached event always carries the key, so `meetingUrl` is absent
// from the cache only for records written before this shipped.
- cache.events.push({ ...event, meetingUrl: event.meetingUrl ?? null });
+ const retained = { ...event, meetingUrl: event.meetingUrl ?? null };
+ cache.events.push(retained);
+ existingMap.set(event.externalId, retained);
newCount++;
}
}
diff --git a/server/services/calendarGoogleSync.test.js b/server/services/calendarGoogleSync.test.js
index f9aa898ef6..b66079cd85 100644
--- a/server/services/calendarGoogleSync.test.js
+++ b/server/services/calendarGoogleSync.test.js
@@ -402,3 +402,36 @@ describe('meetingUrl projection (#6289)', () => {
expect(event.meetingUrl).toBeNull();
});
});
+
+describe('Google batch identity reconciliation (#8635)', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ getAccount.mockResolvedValue(account());
+ loadCache.mockResolvedValue({ events: [] });
+ });
+
+ it('adds one row for duplicate deliveries and retains the last mutable fields', async () => {
+ const result = await pushSyncEvents(ACCOUNT_ID, CAL_ID, 'Work', [
+ rawEvent('a', 'Earlier'), rawEvent('a', 'Latest'),
+ ]);
+ expect(result).toMatchObject({ newEvents: 1, total: 1 });
+ expect(savedCache().events).toEqual([expect.objectContaining({ title: 'Latest' })]);
+ });
+
+ it('heals old duplicates with a stable id while preserving other calendars and partial omissions', async () => {
+ await pushSyncEvents(ACCOUNT_ID, CAL_ID, 'Work', [rawEvent('a', 'Earlier')]);
+ const retained = savedCache().events[0];
+ const otherCalendar = { ...retained, id: 'other-calendar', subcalendarId: '[email protected]' };
+ const omitted = { ...retained, id: 'omitted', externalId: 'omitted' };
+ loadCache.mockResolvedValue({ events: [
+ retained, { ...retained, id: 'old-duplicate' }, otherCalendar, omitted,
+ ] });
+ const result = await pushSyncEvents(ACCOUNT_ID, CAL_ID, 'Work', [
+ rawEvent('a', 'Current'),
+ ], null, { prune: false });
+ expect(result).toMatchObject({ newEvents: 0, total: 3, pruned: 0 });
+ expect(savedCache().events).toEqual([
+ expect.objectContaining({ id: retained.id, title: 'Current' }), otherCalendar, omitted,
+ ]);
+ });
+});
diff --git a/server/services/calendarSync.js b/server/services/calendarSync.js
index fc357cf490..ad8df64ccc 100644
--- a/server/services/calendarSync.js
+++ b/server/services/calendarSync.js
@@ -181,11 +181,18 @@ export async function syncAccount(accountId, io, options = {}) {
const providerStatus = Array.isArray(providerResult) ? 'success' : providerResult?.status ?? 'success';
// Deduplicate by externalId; update fields on existing events
- const existingMap = new Map(cache.events.filter(e => e.externalId).map(e => [e.externalId, e]));
+ const existingMap = new Map();
+ cache.events = cache.events.filter(event => {
+ if (!event.externalId) return true;
+ if (existingMap.has(event.externalId)) return false;
+ existingMap.set(event.externalId, event);
+ return true;
+ });
const uniqueNew = [];
for (const event of newEvents) {
if (!event.externalId || !existingMap.has(event.externalId)) {
uniqueNew.push(event);
+ if (event.externalId) existingMap.set(event.externalId, event);
} else {
const existing = existingMap.get(event.externalId);
// Update mutable fields
diff --git a/server/services/calendarSync.test.js b/server/services/calendarSync.test.js
index d6ff1d173c..8072040b75 100644
--- a/server/services/calendarSync.test.js
+++ b/server/services/calendarSync.test.js
@@ -22,6 +22,21 @@ vi.mock('./tribe.js', () => ({
autoLogTouchpoints: vi.fn().mockResolvedValue({ created: 0, matched: 0 }),
}));
+vi.mock('../lib/fileUtils.js', async importOriginal => ({
+ ...await importOriginal(),
+ ensureDir: vi.fn(),
+ readJSONFile: vi.fn(),
+ atomicWrite: vi.fn(),
+}));
+vi.mock('./calendarApiSync.js', () => ({ syncOutlookCalendarApi: vi.fn() }));
+vi.mock('./humanActivity.js', () => ({
+ calendarActivityCandidates: vi.fn(() => []),
+ recordEvents: vi.fn(),
+}));
+vi.mock('./userTimezone.js', () => ({ getUserTimezone: vi.fn(async () => 'UTC') }));
+
+import { readJSONFile, atomicWrite } from '../lib/fileUtils.js';
+import { syncOutlookCalendarApi } from './calendarApiSync.js';
import { syncAccount, logCalendarTouchpoints } from './calendarSync.js';
import { autoLogTouchpoints } from './tribe.js';
import { mcpSyncAccount, mcpDiscoverCalendars } from './calendarGoogleSync.js';
@@ -131,3 +146,45 @@ describe('logCalendarTouchpoints — candidate building (#2033)', () => {
expect(autoLogTouchpoints).not.toHaveBeenCalled();
});
});
+
+
+describe('Outlook batch identity reconciliation (#8635)', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ getAccount.mockResolvedValue({
+ id: ACCOUNT_ID, name: 'Example Account', enabled: true, type: 'outlook-calendar',
+ });
+ readJSONFile.mockResolvedValue({ events: [] });
+ });
+
+ it('counts overlapping page events once and retains the last mutable fields', async () => {
+ syncOutlookCalendarApi.mockResolvedValue([
+ { id: 'first', externalId: 'a', title: 'Earlier' },
+ { id: 'second', externalId: 'a', title: 'Latest' },
+ ]);
+ expect(await syncAccount(ACCOUNT_ID)).toMatchObject({ newEvents: 1, total: 1 });
+ expect(atomicWrite.mock.calls.at(-1)[1].events).toEqual([
+ { id: 'first', externalId: 'a', title: 'Latest' },
+ ]);
+ });
+
+ it.each(['success', 'partial'])('heals old duplicates with a stable id during %s sync', async status => {
+ const omitted = { id: 'omitted', externalId: 'b' };
+ readJSONFile.mockResolvedValue({ events: [
+ { id: 'retained', externalId: 'a', title: 'Old' },
+ { id: 'duplicate', externalId: 'a', title: 'Stale' },
+ omitted,
+ ] });
+ syncOutlookCalendarApi.mockResolvedValue({
+ status, events: [{ id: 'incoming', externalId: 'a', title: 'Current' }],
+ });
+ expect(await syncAccount(ACCOUNT_ID)).toMatchObject({
+ newEvents: 0, total: status === 'partial' ? 2 : 1,
+ pruned: status === 'partial' ? 0 : 1,
+ });
+ expect(atomicWrite.mock.calls.at(-1)[1].events).toEqual([
+ { id: 'retained', externalId: 'a', title: 'Current' },
+ ...(status === 'partial' ? [omitted] : []),
+ ]);
+ });
+});