From 84922f27d20955d40e397e421c6eedefb7dde4e6 Mon Sep 17 00:00:00 2001 From: maxwakelin8-a11y <297909343+maxwakelin8-a11y@users.noreply.github.com> Date: Wed, 4 Nov 2026 09:49:23 +1030 Subject: [PATCH 1/4] fix: stop overlapping calendar syncs from duplicating lesson events Co-Authored-By: Claude Opus 5.5 --- .../calendarSync/lessonSyncShared.test.ts | 38 ++++++++++++++ .../utils/calendarSync/lessonSyncShared.ts | 23 ++++++-- src/seqta/utils/calendarSync/settings.ts | 17 +++++- src/seqta/utils/calendarSync/syncEngine.ts | 9 +++- src/seqta/utils/calendarSync/syncRunner.ts | 52 +++++++++++++++---- 5 files changed, 124 insertions(+), 15 deletions(-) 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" From 4509632774dc90372b4c2904f70e787052a55166 Mon Sep 17 00:00:00 2001 From: Aden Lindsay Date: Wed, 4 Nov 2026 12:50:32 +1030 Subject: [PATCH 2/4] Harden calendar sync locks and cover review follow-ups for PR #502. Per-provider in-progress keys, compare-and-set lock acquire, duplicate cleanup on full removal, tests, and manual QA checklist. Co-authored-by: Cursor --- docs/calendar-sync-manual-qa.md | 33 +++++ .../calendarSync/calendarSyncSettings.test.ts | 117 +++++++++++++++ src/seqta/utils/calendarSync/settings.ts | 134 ++++++++++++++++-- src/seqta/utils/calendarSync/syncEngine.ts | 9 +- .../utils/calendarSync/syncRunner.test.ts | 73 ++++++++++ src/seqta/utils/calendarSync/syncRunner.ts | 37 ++--- .../utils/cloudSettingsSync.legacy.test.ts | 6 +- src/seqta/utils/cloudSettingsSync.ts | 6 +- 8 files changed, 380 insertions(+), 35 deletions(-) create mode 100644 docs/calendar-sync-manual-qa.md create mode 100644 src/seqta/utils/calendarSync/calendarSyncSettings.test.ts create mode 100644 src/seqta/utils/calendarSync/syncRunner.test.ts diff --git a/docs/calendar-sync-manual-qa.md b/docs/calendar-sync-manual-qa.md new file mode 100644 index 00000000..9ee389a1 --- /dev/null +++ b/docs/calendar-sync-manual-qa.md @@ -0,0 +1,33 @@ +# Calendar sync manual QA + +Run these checks before merging calendar sync changes. Use a school SEQTA account with Google Calendar and/or Outlook connected in BetterSEQTA+ settings. + +## Dual-tab overlap (duplicate prevention) + +1. Open SEQTA in **Tab A** and wait for an automatic calendar sync to start (or trigger **Sync now** from settings). +2. Open the **same school** SEQTA origin in **Tab B** while Tab A is still syncing. +3. In Tab B, click **Sync now** for the same provider. +4. **Expected:** Tab B shows an error that sync is already running in another tab (no new duplicate events). +5. After Tab A finishes, sync from Tab B should succeed. + +## Same-tab overlap + +1. With one tab open, click **Sync now** twice quickly (or trigger sync while page-load sync is still running). +2. **Expected:** Only one sync runs; no duplicate calendar events for the same lessons. + +## Google and Outlook together + +1. Connect **both** Google and Outlook if available. +2. Start sync for Google, then immediately start sync for Outlook (same or different tabs). +3. **Expected:** Both providers can sync concurrently; neither blocks the other. + +## Resume after interrupted sync + +1. Start a full sync, then close the tab mid-sync (or kill the tab process). +2. Wait longer than the heartbeat stale window (~45s) without another tab syncing. +3. Reload SEQTA. +4. **Expected:** Sync resumes or can be started cleanly without duplicate events piling up. + +## Duplicate cleanup (optional) + +If duplicates already exist from an older build, run a full sync once and confirm extra remote events for the same lesson are removed from the calendar. diff --git a/src/seqta/utils/calendarSync/calendarSyncSettings.test.ts b/src/seqta/utils/calendarSync/calendarSyncSettings.test.ts new file mode 100644 index 00000000..a1aa40c2 --- /dev/null +++ b/src/seqta/utils/calendarSync/calendarSyncSettings.test.ts @@ -0,0 +1,117 @@ +import { beforeEach, describe, expect, it, jest } from "@jest/globals"; +import browser from "@/lib/browser"; +import { + BSPLUS_CALENDAR_SYNC_IN_PROGRESS_KEY, + CALENDAR_SYNC_HEARTBEAT_MS, + calendarSyncInProgressStorageKey, + isCalendarSyncRunningElsewhere, + readResumableCalendarSync, + tryAcquireCalendarSyncLock, +} from "./settings"; + +const origin = "https://school.seqta.com.au"; + +describe("calendar sync cross-tab lock", () => { + beforeEach(() => { + Object.defineProperty(globalThis, "location", { + value: { origin }, + configurable: true, + }); + }); + + it("reports no sync elsewhere when marker is missing", async () => { + expect(await isCalendarSyncRunningElsewhere("google")).toBe(false); + expect(await isCalendarSyncRunningElsewhere("outlook")).toBe(false); + }); + + it("uses separate in-progress keys per provider", async () => { + const now = Date.now(); + await browser.storage.local.set({ + [calendarSyncInProgressStorageKey("google")]: { + provider: "google", + mode: "full", + origin, + startedAt: now, + heartbeatAt: now, + lockId: "google-lock", + }, + [calendarSyncInProgressStorageKey("outlook")]: { + provider: "outlook", + mode: "full", + origin, + startedAt: now, + heartbeatAt: now, + lockId: "outlook-lock", + }, + }); + + expect(await isCalendarSyncRunningElsewhere("google")).toBe(true); + expect(await isCalendarSyncRunningElsewhere("outlook")).toBe(true); + }); + + it("treats stale heartbeats as not running elsewhere", async () => { + const stale = Date.now() - 60_000; + await browser.storage.local.set({ + [calendarSyncInProgressStorageKey("google")]: { + provider: "google", + mode: "full", + origin, + startedAt: stale, + heartbeatAt: stale, + }, + }); + + expect(await isCalendarSyncRunningElsewhere("google")).toBe(false); + expect(await readResumableCalendarSync()).toMatchObject({ provider: "google" }); + }); + + it("acquires lock and rejects when another tab holds a live marker", async () => { + const first = await tryAcquireCalendarSyncLock("google", "full"); + expect(first.acquired).toBe(true); + + const second = await tryAcquireCalendarSyncLock("google", "full"); + expect(second.acquired).toBe(false); + }); + + it("loses acquire when storage contains another tab's lockId after write", async () => { + const key = calendarSyncInProgressStorageKey("google"); + const originalSet = browser.storage.local.set.getMockImplementation(); + browser.storage.local.set.mockImplementation(async (items: Record) => { + if (key in items) { + await originalSet?.({ + [key]: { + ...(items[key] as object), + lockId: "other-tab", + }, + }); + return; + } + await originalSet?.(items); + }); + + const result = await tryAcquireCalendarSyncLock("google", "incremental"); + expect(result.acquired).toBe(false); + }); + + it("migrates legacy in-progress key to per-provider storage", async () => { + const now = Date.now(); + await browser.storage.local.set({ + [BSPLUS_CALENDAR_SYNC_IN_PROGRESS_KEY]: { + provider: "outlook", + mode: "incremental", + origin, + startedAt: now, + heartbeatAt: now, + }, + }); + + expect(await isCalendarSyncRunningElsewhere("outlook")).toBe(true); + expect(await browser.storage.local.get(BSPLUS_CALENDAR_SYNC_IN_PROGRESS_KEY)).toEqual({}); + }); +}); + +describe("calendar sync heartbeat constant", () => { + it("refreshes at most every ten seconds", () => { + expect(CALENDAR_SYNC_HEARTBEAT_MS).toBe(10_000); + }); +}); diff --git a/src/seqta/utils/calendarSync/settings.ts b/src/seqta/utils/calendarSync/settings.ts index 884692ec..e1a1471b 100644 --- a/src/seqta/utils/calendarSync/settings.ts +++ b/src/seqta/utils/calendarSync/settings.ts @@ -10,8 +10,22 @@ import { } from "@/seqta/utils/calendarSync/providerStorage"; export const BSPLUS_CALENDAR_SYNC_SETTINGS_KEY = "bsplus_calendar_sync_settings"; -/** Device-local interrupted sync marker — never cloud-synced. */ +/** @deprecated Legacy single marker; migrated to per-provider keys on read. */ export const BSPLUS_CALENDAR_SYNC_IN_PROGRESS_KEY = "bsplus_calendar_sync_in_progress"; + +export type CalendarSyncProvider = "google" | "outlook"; + +export const CALENDAR_SYNC_PROVIDERS: readonly CalendarSyncProvider[] = ["google", "outlook"]; + +/** Device-local interrupted sync marker per provider — never cloud-synced. */ +export function calendarSyncInProgressStorageKey(provider: CalendarSyncProvider): string { + return `bsplus_calendar_sync_in_progress_${provider}`; +} + +export const BSPLUS_CALENDAR_SYNC_IN_PROGRESS_KEYS = [ + BSPLUS_CALENDAR_SYNC_IN_PROGRESS_KEY, + ...CALENDAR_SYNC_PROVIDERS.map(calendarSyncInProgressStorageKey), +] as const; export const CALENDAR_WEEKLY_ALARM = "bsplus_calendar_weekly"; export const WEEKLY_SYNC_INTERVAL_MS = 7 * 24 * 60 * 60 * 1000; @@ -109,42 +123,138 @@ export async function markWeeklySyncPending(): Promise { } export type PendingCalendarSync = { - provider: "google" | "outlook"; + provider: CalendarSyncProvider; mode: "full" | "incremental"; origin: string; startedAt: number; /** Refreshed while a sync is running; a recent value means another tab is still syncing. */ heartbeatAt?: number; + /** Set when this tab owns the in-progress marker; used to detect cross-tab lock races. */ + lockId?: string; }; 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 { +async function migrateLegacyCalendarSyncInProgressKey(): 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; + if (!raw || typeof raw !== "object" || Array.isArray(raw)) return; + const pending = raw as PendingCalendarSync; + if (pending.provider !== "google" && pending.provider !== "outlook") { + await browser.storage.local.remove(BSPLUS_CALENDAR_SYNC_IN_PROGRESS_KEY); + return; + } + + const key = calendarSyncInProgressStorageKey(pending.provider); + const existing = await browser.storage.local.get(key); + if (!existing[key]) { + await browser.storage.local.set({ [key]: pending }); + } + await browser.storage.local.remove(BSPLUS_CALENDAR_SYNC_IN_PROGRESS_KEY); +} + +function isPendingHeartbeatLive(pending: PendingCalendarSync): boolean { 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); - const raw = got[BSPLUS_CALENDAR_SYNC_IN_PROGRESS_KEY]; +/** True when another tab holds a live in-progress marker for this provider. */ +export async function isCalendarSyncRunningElsewhere( + provider: CalendarSyncProvider, +): Promise { + await migrateLegacyCalendarSyncInProgressKey(); + const key = calendarSyncInProgressStorageKey(provider); + const got = await browser.storage.local.get(key); + const raw = got[key]; + if (!raw || typeof raw !== "object" || Array.isArray(raw)) return false; + return isPendingHeartbeatLive(raw as PendingCalendarSync); +} + +export async function clearCalendarSyncInProgressMarker( + provider: CalendarSyncProvider, +): Promise { + await browser.storage.local.remove(calendarSyncInProgressStorageKey(provider)); +} + +/** + * Claim the cross-tab sync lock for a provider. Re-reads storage after write so only one tab wins + * a simultaneous acquire (avoids check-then-set races). + */ +export async function tryAcquireCalendarSyncLock( + provider: CalendarSyncProvider, + mode: "full" | "incremental", +): Promise<{ acquired: true; lockId: string; marker: PendingCalendarSync } | { acquired: false }> { + await migrateLegacyCalendarSyncInProgressKey(); + if (await isCalendarSyncRunningElsewhere(provider)) { + return { acquired: false }; + } + + const lockId = crypto.randomUUID(); + const marker: PendingCalendarSync = { + provider, + mode, + origin: location.origin, + startedAt: Date.now(), + heartbeatAt: Date.now(), + lockId, + }; + const key = calendarSyncInProgressStorageKey(provider); + await browser.storage.local.set({ [key]: marker }); + const got = await browser.storage.local.get(key); + const raw = got[key]; + if (!raw || typeof raw !== "object" || Array.isArray(raw)) { + return { acquired: false }; + } + const stored = raw as PendingCalendarSync; + if (stored.lockId !== lockId) { + return { acquired: false }; + } + return { acquired: true, lockId, marker }; +} + +/** Release the in-progress marker only when this tab still owns it. */ +export async function releaseCalendarSyncLock( + provider: CalendarSyncProvider, + lockId: string, +): Promise { + const key = calendarSyncInProgressStorageKey(provider); + const got = await browser.storage.local.get(key); + const raw = got[key]; + if (!raw || typeof raw !== "object" || Array.isArray(raw)) return; + const stored = raw as PendingCalendarSync; + if (stored.lockId === lockId) { + await browser.storage.local.remove(key); + } +} + +async function readResumableCalendarSyncForProvider( + provider: CalendarSyncProvider, +): Promise { + const key = calendarSyncInProgressStorageKey(provider); + const got = await browser.storage.local.get(key); + const raw = got[key]; if (!raw || typeof raw !== "object" || Array.isArray(raw)) return null; const pending = raw as PendingCalendarSync; - const validProvider = pending.provider === "google" || pending.provider === "outlook"; const validMode = pending.mode === "full" || pending.mode === "incremental"; const fresh = Date.now() - pending.startedAt < 24 * 60 * 60 * 1000; - if (!validProvider || !validMode || pending.origin !== location.origin || !fresh) { - await browser.storage.local.remove(BSPLUS_CALENDAR_SYNC_IN_PROGRESS_KEY); + if (pending.provider !== provider || !validMode || pending.origin !== location.origin || !fresh) { + await browser.storage.local.remove(key); return null; } return pending; } + +/** Returns a pending sync worth resuming, or clears stale markers and returns null. */ +export async function readResumableCalendarSync(): Promise { + await migrateLegacyCalendarSyncInProgressKey(); + for (const provider of CALENDAR_SYNC_PROVIDERS) { + const pending = await readResumableCalendarSyncForProvider(provider); + if (pending) return pending; + } + return null; +} diff --git a/src/seqta/utils/calendarSync/syncEngine.ts b/src/seqta/utils/calendarSync/syncEngine.ts index 3eb3f801..286c4763 100644 --- a/src/seqta/utils/calendarSync/syncEngine.ts +++ b/src/seqta/utils/calendarSync/syncEngine.ts @@ -361,6 +361,7 @@ export async function deleteSyncedEventsFromCalendar( }; let remoteEvents: RemoteSyncedEvent[] = []; + let duplicateIds: string[] = []; try { remoteEvents = await provider.listSyncedEvents( accessToken, @@ -368,12 +369,18 @@ export async function deleteSyncedEventsFromCalendar( refreshAccessToken, { includeUnkeyed: true }, ); - mergeRemoteEventsIntoMap(eventMap, origin, remoteEvents, eventMapKey); + duplicateIds = mergeRemoteEventsIntoMap(eventMap, origin, remoteEvents, eventMapKey); } catch (err) { verboseLog(`[BetterSEQTA+] ${provider.label} cleanup list failed:`, err); } const entries = collectOriginDeleteEntries(eventMap, origin, remoteEvents, eventMapKey); + const deleteIds = new Set(entries.map(([, id]) => id)); + for (const id of duplicateIds) { + if (deleteIds.has(id)) continue; + entries.push([`${DUPLICATE_EVENT_MAP_KEY_PREFIX}${id}`, id]); + deleteIds.add(id); + } if (entries.length === 0) { clearOriginEventMapEntries(eventMap, origin); await provider.writeState({ eventMap }); diff --git a/src/seqta/utils/calendarSync/syncRunner.test.ts b/src/seqta/utils/calendarSync/syncRunner.test.ts new file mode 100644 index 00000000..dd761ecd --- /dev/null +++ b/src/seqta/utils/calendarSync/syncRunner.test.ts @@ -0,0 +1,73 @@ +import { beforeEach, describe, expect, it, jest } from "@jest/globals"; + +jest.mock("@/seqta/utils/googleCalendar/fetchTimetable", () => ({ + fetchAssessmentsForCalendarSync: jest.fn(async () => []), + fetchTimetableForSync: jest.fn(async () => []), + fetchTimetableLessons: jest.fn(async () => []), +})); + +jest.mock("@/seqta/utils/calendarSync/syncEngine", () => ({ + googleLessonSyncProvider: {}, + outlookLessonSyncProvider: {}, + syncLessonsToCalendar: jest.fn(), +})); + +jest.mock("@/seqta/utils/calendarSync/settings", () => ({ + CALENDAR_SYNC_HEARTBEAT_MS: 10_000, + calendarSyncInProgressStorageKey: (provider: string) => + `bsplus_calendar_sync_in_progress_${provider}`, + clearCalendarSyncInProgressMarker: jest.fn(async () => undefined), + getSyncAssessmentDueDates: jest.fn(async () => false), + getSyncWeeksAhead: jest.fn(async () => 12), + isCalendarSyncRunningElsewhere: jest.fn(async () => false), + readResumableCalendarSync: jest.fn(async () => null), + releaseCalendarSyncLock: jest.fn(async () => undefined), + tryAcquireCalendarSyncLock: jest.fn(async () => ({ + acquired: true as const, + lockId: "test-lock", + marker: { + provider: "google" as const, + mode: "full" as const, + origin: "https://school.seqta.com.au", + startedAt: Date.now(), + heartbeatAt: Date.now(), + lockId: "test-lock", + }, + })), +})); + +import { syncLessonsToCalendar } from "@/seqta/utils/calendarSync/syncEngine"; +import { + __resetActiveCalendarSyncsForTests, + runGoogleCalendarSync, +} from "@/seqta/utils/calendarSync/syncRunner"; + +describe("runCalendarSync coalescing", () => { + beforeEach(() => { + Object.defineProperty(globalThis, "location", { + value: { origin: "https://school.seqta.com.au" }, + configurable: true, + }); + __resetActiveCalendarSyncsForTests(); + jest.mocked(syncLessonsToCalendar).mockReset(); + }); + + it("returns the same in-flight promise for overlapping syncs in one tab", async () => { + let resolveSync!: (value: { success: true }) => void; + const syncPromise = new Promise<{ success: true }>((resolve) => { + resolveSync = resolve; + }); + jest.mocked(syncLessonsToCalendar).mockReturnValue(syncPromise); + + const first = runGoogleCalendarSync(); + const second = runGoogleCalendarSync(); + + expect(second).toBe(first); + + await new Promise((resolve) => setImmediate(resolve)); + expect(syncLessonsToCalendar).toHaveBeenCalledTimes(1); + + resolveSync({ success: true }); + await first; + }); +}); diff --git a/src/seqta/utils/calendarSync/syncRunner.ts b/src/seqta/utils/calendarSync/syncRunner.ts index 26f99e80..56d11d61 100644 --- a/src/seqta/utils/calendarSync/syncRunner.ts +++ b/src/seqta/utils/calendarSync/syncRunner.ts @@ -18,13 +18,16 @@ import { readOutlookCalendarState, } from "@/seqta/utils/calendarSync/providerStorage"; import { - BSPLUS_CALENDAR_SYNC_IN_PROGRESS_KEY, CALENDAR_SYNC_HEARTBEAT_MS, + calendarSyncInProgressStorageKey, + clearCalendarSyncInProgressMarker, getSyncAssessmentDueDates, getSyncWeeksAhead, isCalendarSyncRunningElsewhere, readResumableCalendarSync, - type PendingCalendarSync, + releaseCalendarSyncLock, + tryAcquireCalendarSyncLock, + type CalendarSyncProvider, } from "@/seqta/utils/calendarSync/settings"; import type { GoogleCalendarStatus, @@ -32,7 +35,7 @@ import type { GoogleCalendarSyncResult, } from "@/seqta/utils/googleCalendar/types"; -export type CalendarProvider = "google" | "outlook"; +export type { CalendarSyncProvider as CalendarProvider }; const MSG = { accessToken: { google: "googleCalendarGetAccessToken", outlook: "outlookCalendarGetAccessToken" }, @@ -128,27 +131,22 @@ async function runExclusiveCalendarSync( config: CalendarSyncRunnerConfig, params: RunCalendarSyncParams, ): Promise { - if (await isCalendarSyncRunningElsewhere()) { + const mode = params.mode ?? "full"; + const lock = await tryAcquireCalendarSyncLock(config.provider, mode); + if (!lock.acquired) { 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 { lockId, marker } = lock; + const storageKey = calendarSyncInProgressStorageKey(config.provider); const weeksAhead = await getSyncWeeksAhead(); - 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() }, + [storageKey]: { ...marker, heartbeatAt: Date.now(), lockId }, }); }, CALENDAR_SYNC_HEARTBEAT_MS); @@ -189,7 +187,7 @@ async function runExclusiveCalendarSync( ); } finally { clearInterval(heartbeat); - await browser.storage.local.remove(BSPLUS_CALENDAR_SYNC_IN_PROGRESS_KEY); + await releaseCalendarSyncLock(config.provider, lockId); } } @@ -199,14 +197,14 @@ export async function resumeInterruptedCalendarSync( 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; + if (await isCalendarSyncRunningElsewhere(pending.provider)) return null; const state = pending.provider === "google" ? await readGoogleCalendarState() : await readOutlookCalendarState(); if (!state.refreshToken && !state.accessToken) { - await browser.storage.local.remove(BSPLUS_CALENDAR_SYNC_IN_PROGRESS_KEY); + await clearCalendarSyncInProgressMarker(pending.provider); return null; } @@ -219,3 +217,8 @@ export const runGoogleCalendarSync = (params?: RunCalendarSyncParams) => export const runOutlookCalendarSync = (params?: RunCalendarSyncParams) => runCalendarSync(OUTLOOK_SYNC_RUNNER, params); + +/** @internal Test hook for in-tab sync coalescing. */ +export function __resetActiveCalendarSyncsForTests(): void { + activeSyncs.clear(); +} diff --git a/src/seqta/utils/cloudSettingsSync.legacy.test.ts b/src/seqta/utils/cloudSettingsSync.legacy.test.ts index e3eeb1c8..b39d4766 100644 --- a/src/seqta/utils/cloudSettingsSync.legacy.test.ts +++ b/src/seqta/utils/cloudSettingsSync.legacy.test.ts @@ -4,7 +4,7 @@ import { normalizeThemeIdForSync, resolveThemeIdForPostSyncDownload, } from "./cloudSettingsSync"; -import { BSPLUS_CALENDAR_SYNC_IN_PROGRESS_KEY } from "@/seqta/utils/calendarSync/settings"; +import { BSPLUS_CALENDAR_SYNC_IN_PROGRESS_KEYS } from "@/seqta/utils/calendarSync/settings"; describe("migrateLegacyToPluginSettings", () => { it("maps animatedbk without overwriting existing plugin fields", () => { @@ -31,7 +31,9 @@ describe("isKeyIncludedInCloudUploadPayload", () => { it("excludes auth and device cache prefixes", () => { expect(isKeyIncludedInCloudUploadPayload("bsplus_token")).toBe(false); expect(isKeyIncludedInCloudUploadPayload("bsplus_install_id")).toBe(false); - expect(isKeyIncludedInCloudUploadPayload(BSPLUS_CALENDAR_SYNC_IN_PROGRESS_KEY)).toBe(false); + for (const key of BSPLUS_CALENDAR_SYNC_IN_PROGRESS_KEYS) { + expect(isKeyIncludedInCloudUploadPayload(key)).toBe(false); + } expect(isKeyIncludedInCloudUploadPayload("plugin.global-search.storage.index")).toBe(false); expect(isKeyIncludedInCloudUploadPayload("bsplus.analytics.v2.school.1")).toBe(false); }); diff --git a/src/seqta/utils/cloudSettingsSync.ts b/src/seqta/utils/cloudSettingsSync.ts index 386ed8f0..fdb684e1 100644 --- a/src/seqta/utils/cloudSettingsSync.ts +++ b/src/seqta/utils/cloudSettingsSync.ts @@ -1,6 +1,6 @@ import browser from "@/lib/browser"; import isEqual from "@/seqta/utils/isEqual"; -import { BSPLUS_CALENDAR_SYNC_IN_PROGRESS_KEY } from "@/seqta/utils/calendarSync/settings"; +import { BSPLUS_CALENDAR_SYNC_IN_PROGRESS_KEYS } from "@/seqta/utils/calendarSync/settings"; /** Matches the contract in docs/CLOUD_SETTINGS_SYNC_SERVER.md */ export const CLOUD_SETTINGS_SYNC_SCHEMA_VERSION = 1; @@ -45,7 +45,7 @@ export const KEYS_OMITTED_FROM_CLOUD_UPLOAD = [ /** Pending feedback ids awaiting a reply notification — device-local. */ "bsplus_pending_feedback_ids", "bsplus_remote_status", - BSPLUS_CALENDAR_SYNC_IN_PROGRESS_KEY, + ...BSPLUS_CALENDAR_SYNC_IN_PROGRESS_KEYS, ] as const; /** @@ -68,7 +68,7 @@ const CLIENT_ONLY_CLOUD_KEYS_EXACT = [ BSPLUS_CLOUD_LAST_UPLOADED_SNAPSHOT_KEY, "bsplus_lastCloudPoll", BSPLUS_PENDING_THEME_ENSURE_AFTER_CLOUD_KEY, - BSPLUS_CALENDAR_SYNC_IN_PROGRESS_KEY, + ...BSPLUS_CALENDAR_SYNC_IN_PROGRESS_KEYS, ] as const; /** After restoring from cloud, keep local session so the user stays signed in. */ From 032dbab5f5bec7876c6a210f9b52e5afda67fe93 Mon Sep 17 00:00:00 2001 From: Aden Lindsay Date: Wed, 4 Nov 2026 12:51:46 +1030 Subject: [PATCH 3/4] fix: remove unused jest import in calendar sync settings test Co-authored-by: Cursor --- src/seqta/utils/calendarSync/calendarSyncSettings.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/seqta/utils/calendarSync/calendarSyncSettings.test.ts b/src/seqta/utils/calendarSync/calendarSyncSettings.test.ts index a1aa40c2..fdc381ea 100644 --- a/src/seqta/utils/calendarSync/calendarSyncSettings.test.ts +++ b/src/seqta/utils/calendarSync/calendarSyncSettings.test.ts @@ -1,4 +1,4 @@ -import { beforeEach, describe, expect, it, jest } from "@jest/globals"; +import { beforeEach, describe, expect, it } from "@jest/globals"; import browser from "@/lib/browser"; import { BSPLUS_CALENDAR_SYNC_IN_PROGRESS_KEY, From ec0503018d742fcf7b4609dbfa3a80a629989103 Mon Sep 17 00:00:00 2001 From: Aden Lindsay Date: Wed, 4 Nov 2026 12:54:01 +1030 Subject: [PATCH 4/4] fix: resolve CalendarProvider type and jest mock typing in calendar sync tests Co-authored-by: Cursor --- src/seqta/utils/calendarSync/calendarSyncSettings.test.ts | 7 ++++--- src/seqta/utils/calendarSync/syncRunner.ts | 2 +- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/src/seqta/utils/calendarSync/calendarSyncSettings.test.ts b/src/seqta/utils/calendarSync/calendarSyncSettings.test.ts index fdc381ea..5ad6ba91 100644 --- a/src/seqta/utils/calendarSync/calendarSyncSettings.test.ts +++ b/src/seqta/utils/calendarSync/calendarSyncSettings.test.ts @@ -1,4 +1,4 @@ -import { beforeEach, describe, expect, it } from "@jest/globals"; +import { beforeEach, describe, expect, it, jest } from "@jest/globals"; import browser from "@/lib/browser"; import { BSPLUS_CALENDAR_SYNC_IN_PROGRESS_KEY, @@ -75,8 +75,9 @@ describe("calendar sync cross-tab lock", () => { it("loses acquire when storage contains another tab's lockId after write", async () => { const key = calendarSyncInProgressStorageKey("google"); - const originalSet = browser.storage.local.set.getMockImplementation(); - browser.storage.local.set.mockImplementation(async (items: Record) => { + const setMock = jest.mocked(browser.storage.local.set); + const originalSet = setMock.getMockImplementation(); + setMock.mockImplementation(async (items: Record) => { if (key in items) { await originalSet?.({ [key]: { diff --git a/src/seqta/utils/calendarSync/syncRunner.ts b/src/seqta/utils/calendarSync/syncRunner.ts index 56d11d61..81b7965a 100644 --- a/src/seqta/utils/calendarSync/syncRunner.ts +++ b/src/seqta/utils/calendarSync/syncRunner.ts @@ -35,7 +35,7 @@ import type { GoogleCalendarSyncResult, } from "@/seqta/utils/googleCalendar/types"; -export type { CalendarSyncProvider as CalendarProvider }; +export type CalendarProvider = CalendarSyncProvider; const MSG = { accessToken: { google: "googleCalendarGetAccessToken", outlook: "outlookCalendarGetAccessToken" },