diff --git a/src/seqta/utils/calendarSync/lessonSyncShared.test.ts b/src/seqta/utils/calendarSync/lessonSyncShared.test.ts index 39518169..82039058 100644 --- a/src/seqta/utils/calendarSync/lessonSyncShared.test.ts +++ b/src/seqta/utils/calendarSync/lessonSyncShared.test.ts @@ -177,6 +177,44 @@ describe("mergeRemoteEventsIntoMap", () => { ); expect(eventMap[key]).toMatchObject({ id: "remote-1", fingerprint: "local-fp" }); }); + + it("returns extra remote events for the same lesson as duplicates", () => { + const key = `${origin}::${origin}:cal:1`; + const eventMap = { + [key]: { id: "tracked", date: "2026-07-13", fingerprint: "fp" }, + }; + const remote = (id: string) => ({ + seqtaKey: `${origin}:cal:1`, + id, + date: "2026-07-13", + fingerprint: "fp", + }); + const duplicates = mergeRemoteEventsIntoMap( + eventMap, + origin, + [remote("copy-a"), remote("tracked"), remote("copy-b")], + mapKey, + ); + + expect(eventMap[key]).toMatchObject({ id: "tracked" }); + expect(duplicates.sort()).toEqual(["copy-a", "copy-b"]); + }); + + it("keeps the first remote event when none is tracked", () => { + const eventMap: Record = {}; + const duplicates = mergeRemoteEventsIntoMap( + eventMap, + origin, + [ + { seqtaKey: `${origin}:cal:1`, id: "first", date: "2026-07-13", fingerprint: "fp" }, + { seqtaKey: `${origin}:cal:1`, id: "second", date: "2026-07-13", fingerprint: "fp" }, + ], + mapKey, + ); + + expect(eventMap[`${origin}::${origin}:cal:1`]).toMatchObject({ id: "first" }); + expect(duplicates).toEqual(["second"]); + }); }); describe("collectOriginDeleteEntries", () => { diff --git a/src/seqta/utils/calendarSync/lessonSyncShared.ts b/src/seqta/utils/calendarSync/lessonSyncShared.ts index b2a15d63..1f28ad73 100644 --- a/src/seqta/utils/calendarSync/lessonSyncShared.ts +++ b/src/seqta/utils/calendarSync/lessonSyncShared.ts @@ -122,18 +122,33 @@ export function mergeRemoteEventsIntoMap( origin: string, remoteEvents: RemoteSyncedEvent[], mapKey: (origin: string, seqtaKey: string) => string, -): void { +): string[] { + const byKey = new Map(); for (const remote of remoteEvents) { if (!remote.seqtaKey.startsWith(origin)) continue; const key = mapKey(origin, remote.seqtaKey); + const group = byKey.get(key); + if (group) group.push(remote); + else byKey.set(key, [remote]); + } + + // Overlapping syncs can create several remote events for one lesson. Keep the tracked one + // (or the first seen) and return the rest so the caller can delete them. + const duplicateIds: string[] = []; + for (const [key, group] of byKey) { const existing = normalizeEventMapEntry(eventMap[key]); + const kept = group.find((remote) => remote.id === existing?.id) ?? group[0]; + for (const remote of group) { + if (remote.id !== kept.id) duplicateIds.push(remote.id); + } eventMap[key] = { - id: remote.id, - date: remote.date || existing?.date || lessonDateFromSeqtaKey(remote.seqtaKey) || "", + id: kept.id, + date: kept.date || existing?.date || lessonDateFromSeqtaKey(kept.seqtaKey) || "", // Prefer last-written local fingerprint so skip stays stable across API format quirks. - fingerprint: existing?.fingerprint ?? remote.fingerprint, + fingerprint: existing?.fingerprint ?? kept.fingerprint, }; } + return duplicateIds; } /** diff --git a/src/seqta/utils/calendarSync/settings.ts b/src/seqta/utils/calendarSync/settings.ts index 5253621d..884692ec 100644 --- a/src/seqta/utils/calendarSync/settings.ts +++ b/src/seqta/utils/calendarSync/settings.ts @@ -108,13 +108,28 @@ export async function markWeeklySyncPending(): Promise { await writeSharedCalendarSyncSettings({ pendingWeeklySync: true }); } -type PendingCalendarSync = { +export type PendingCalendarSync = { provider: "google" | "outlook"; mode: "full" | "incremental"; origin: string; startedAt: number; + /** Refreshed while a sync is running; a recent value means another tab is still syncing. */ + heartbeatAt?: number; }; +export const CALENDAR_SYNC_HEARTBEAT_MS = 10_000; +const CALENDAR_SYNC_HEARTBEAT_STALE_MS = 45_000; + +/** True when another tab's sync marker has a recent heartbeat. */ +export async function isCalendarSyncRunningElsewhere(): Promise { + const got = await browser.storage.local.get(BSPLUS_CALENDAR_SYNC_IN_PROGRESS_KEY); + const raw = got[BSPLUS_CALENDAR_SYNC_IN_PROGRESS_KEY]; + if (!raw || typeof raw !== "object" || Array.isArray(raw)) return false; + const pending = raw as PendingCalendarSync; + const lastBeat = pending.heartbeatAt ?? pending.startedAt; + return typeof lastBeat === "number" && Date.now() - lastBeat < CALENDAR_SYNC_HEARTBEAT_STALE_MS; +} + /** Returns a pending sync worth resuming, or clears and returns null. */ export async function readResumableCalendarSync(): Promise { const got = await browser.storage.local.get(BSPLUS_CALENDAR_SYNC_IN_PROGRESS_KEY); diff --git a/src/seqta/utils/calendarSync/syncEngine.ts b/src/seqta/utils/calendarSync/syncEngine.ts index a617c0dc..3eb3f801 100644 --- a/src/seqta/utils/calendarSync/syncEngine.ts +++ b/src/seqta/utils/calendarSync/syncEngine.ts @@ -65,6 +65,8 @@ type CalendarStoredState = { eventMap?: EventMapRecord; }; +const DUPLICATE_EVENT_MAP_KEY_PREFIX = "__duplicate__::"; + export type CalendarLessonSyncProvider = { label: string; isConfigured: () => boolean; @@ -204,13 +206,14 @@ export async function syncLessonsToCalendar( events.map((event) => eventMapKey(request.origin, event.seqtaKey)), ); + let duplicateIds: string[] = []; try { const remoteEvents = await provider.listSyncedEvents( accessToken, reconcileRange, refreshAccessToken, ); - mergeRemoteEventsIntoMap(eventMap, request.origin, remoteEvents, eventMapKey); + duplicateIds = mergeRemoteEventsIntoMap(eventMap, request.origin, remoteEvents, eventMapKey); const remoteIds = new Set(remoteEvents.map((event) => event.id)); for (const key of currentMapKeys) { const entry = normalizeEventMapEntry(eventMap[key]); @@ -238,6 +241,10 @@ export async function syncLessonsToCalendar( if (entry) staleEntries.push([mapKey, entry.id]); } } + // Untracked map key so deleting a duplicate never drops the kept event's map entry. + for (const id of duplicateIds) { + staleEntries.push([`${DUPLICATE_EVENT_MAP_KEY_PREFIX}${id}`, id]); + } const totalSteps = Math.max(staleEntries.length + events.length, 1); const lastSyncAt = Date.now(); diff --git a/src/seqta/utils/calendarSync/syncRunner.ts b/src/seqta/utils/calendarSync/syncRunner.ts index 0229af58..26f99e80 100644 --- a/src/seqta/utils/calendarSync/syncRunner.ts +++ b/src/seqta/utils/calendarSync/syncRunner.ts @@ -19,9 +19,12 @@ import { } from "@/seqta/utils/calendarSync/providerStorage"; import { BSPLUS_CALENDAR_SYNC_IN_PROGRESS_KEY, + CALENDAR_SYNC_HEARTBEAT_MS, getSyncAssessmentDueDates, getSyncWeeksAhead, + isCalendarSyncRunningElsewhere, readResumableCalendarSync, + type PendingCalendarSync, } from "@/seqta/utils/calendarSync/settings"; import type { GoogleCalendarStatus, @@ -105,21 +108,49 @@ const OUTLOOK_SYNC_RUNNER: CalendarSyncRunnerConfig = { lessonSyncProvider: outlookLessonSyncProvider, }; -export async function runCalendarSync( +/** In-flight syncs for this tab; overlapping syncs each create every event, duplicating them. */ +const activeSyncs = new Map>(); + +export function runCalendarSync( config: CalendarSyncRunnerConfig, params: RunCalendarSyncParams = {}, ): Promise { + const active = activeSyncs.get(config.provider); + if (active) return active; + const run = runExclusiveCalendarSync(config, params).finally(() => { + activeSyncs.delete(config.provider); + }); + activeSyncs.set(config.provider, run); + return run; +} + +async function runExclusiveCalendarSync( + config: CalendarSyncRunnerConfig, + params: RunCalendarSyncParams, +): Promise { + if (await isCalendarSyncRunningElsewhere()) { + return { + success: false, + error: "A calendar sync is already running in another SEQTA tab. Try again in a minute.", + }; + } + const mode = params.mode ?? "full"; const weeksAhead = await getSyncWeeksAhead(); - await browser.storage.local.set({ - [BSPLUS_CALENDAR_SYNC_IN_PROGRESS_KEY]: { - provider: config.provider, - mode, - origin: location.origin, - startedAt: Date.now(), - }, - }); + const marker: PendingCalendarSync = { + provider: config.provider, + mode, + origin: location.origin, + startedAt: Date.now(), + heartbeatAt: Date.now(), + }; + await browser.storage.local.set({ [BSPLUS_CALENDAR_SYNC_IN_PROGRESS_KEY]: marker }); + const heartbeat = setInterval(() => { + void browser.storage.local.set({ + [BSPLUS_CALENDAR_SYNC_IN_PROGRESS_KEY]: { ...marker, heartbeatAt: Date.now() }, + }); + }, CALENDAR_SYNC_HEARTBEAT_MS); try { reportSyncProgress(params.onProgress, { @@ -157,6 +188,7 @@ export async function runCalendarSync( { onProgress: params.onProgress }, ); } finally { + clearInterval(heartbeat); await browser.storage.local.remove(BSPLUS_CALENDAR_SYNC_IN_PROGRESS_KEY); } } @@ -166,6 +198,8 @@ export async function resumeInterruptedCalendarSync( ): Promise { const pending = await readResumableCalendarSync(); if (!pending) return null; + // Another tab is still mid-sync — leave its marker alone; a later page load resumes if it dies. + if (await isCalendarSyncRunningElsewhere()) return null; const state = pending.provider === "google"