Skip to content

Voice-to-text dictation app with local (Nvidia Parakeet/Whisper) and cloud models (BYOK). Privacy-first and available cross-platform.

fix(gcal): fetch all pages during sync when Google Calendar API returns nextPageToken (#1572)

Henry Suefcc741e4146
diff --git a/src/helpers/googleCalendarManager.js b/src/helpers/googleCalendarManager.js
index f4c0d8e48..7bcc2deb8 100644
--- a/src/helpers/googleCalendarManager.js
+++ b/src/helpers/googleCalendarManager.js
@@ -156,50 +156,62 @@ class GoogleCalendarManager {
async _syncCalendar(calendar) {
const accountEmail = calendar.account_email;
- const params = new URLSearchParams({
- singleEvents: "true",
- orderBy: "startTime",
- timeMin: new Date().toISOString(),
- timeMax: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000).toISOString(),
- });
- if (calendar.sync_token) {
- params.delete("timeMin");
- params.delete("timeMax");
- params.delete("orderBy");
- params.set("syncToken", calendar.sync_token);
- }
+ const buildFullParams = () =>
+ new URLSearchParams({
+ singleEvents: "true",
+ orderBy: "startTime",
+ timeMin: new Date().toISOString(),
+ timeMax: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000).toISOString(),
+ });
let isFullSync = !calendar.sync_token;
- let data;
- try {
- data = await this._apiGet(
- `/calendars/${encodeURIComponent(calendar.id)}/events?${params.toString()}`,
- accountEmail
- );
- } catch (err) {
- // 410 Gone means syncToken is invalid; fall back to full sync
- if (err.statusCode === 410) {
- isFullSync = true;
- const fullParams = new URLSearchParams({
+ let baseParams = isFullSync
+ ? buildFullParams()
+ : new URLSearchParams({
singleEvents: "true",
- orderBy: "startTime",
- timeMin: new Date().toISOString(),
- timeMax: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000).toISOString(),
+ syncToken: calendar.sync_token,
});
+ let pageToken = null;
+ let nextSyncToken = null;
+ const allItems = [];
+
+ while (true) {
+ const params = new URLSearchParams(baseParams);
+ if (pageToken) params.set("pageToken", pageToken);
+
+ let data;
+ try {
data = await this._apiGet(
- `/calendars/${encodeURIComponent(calendar.id)}/events?${fullParams.toString()}`,
+ `/calendars/${encodeURIComponent(calendar.id)}/events?${params.toString()}`,
accountEmail
);
- } else {
+ } catch (err) {
+ // 410 Gone means syncToken is invalid; fall back to full sync
+ if (err.statusCode === 410 && !pageToken && !isFullSync) {
+ isFullSync = true;
+ baseParams = buildFullParams();
+ continue;
+ }
throw err;
}
+
+ if (data.items) {
+ allItems.push(...data.items);
+ }
+ pageToken = data.nextPageToken || null;
+ if (data.nextSyncToken) {
+ nextSyncToken = data.nextSyncToken;
+ }
+
+ if (!pageToken) break;
}
const toUpsert = [];
const toRemove = [];
+ const contactsToUpsert = [];
- for (const item of data.items || []) {
+ for (const item of allItems) {
if (item.status === "cancelled") {
toRemove.push(item.id);
continue;
@@ -230,6 +242,13 @@ class GoogleCalendarManager {
)
: null,
});
+
+ if (item.attendees) {
+ for (const a of item.attendees) {
+ if (a.email)
+ contactsToUpsert.push({ email: a.email, displayName: a.displayName || null });
+ }
+ }
}
// A full sync has no incremental baseline, so deletions that happened
@@ -244,18 +263,7 @@ class GoogleCalendarManager {
}
if (toUpsert.length > 0) this.databaseManager.upsertCalendarEvents(toUpsert);
if (toRemove.length > 0) this.databaseManager.removeCalendarEvents(toRemove);
- if (data.nextSyncToken)
- this.databaseManager.updateCalendarSyncToken(calendar.id, data.nextSyncToken);
-
- const contactsToUpsert = [];
- for (const item of data.items || []) {
- if (item.attendees) {
- for (const a of item.attendees) {
- if (a.email)
- contactsToUpsert.push({ email: a.email, displayName: a.displayName || null });
- }
- }
- }
+ if (nextSyncToken) this.databaseManager.updateCalendarSyncToken(calendar.id, nextSyncToken);
if (contactsToUpsert.length > 0) this.databaseManager.upsertContacts(contactsToUpsert);
}
diff --git a/test/helpers/googleCalendarManager.test.js b/test/helpers/googleCalendarManager.test.js
new file mode 100644
index 000000000..b8ab735c0
--- /dev/null
+++ b/test/helpers/googleCalendarManager.test.js
@@ -0,0 +1,138 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+const Module = require("node:module");
+
+const managerModulePath = require.resolve("../../src/helpers/googleCalendarManager.js");
+const originalLoad = Module._load;
+
+function loadManagerModule() {
+ delete require.cache[managerModulePath];
+ Module._load = function loadWithElectronMock(request, parent, isMain) {
+ if (request === "electron") {
+ return { net: {}, BrowserWindow: { getAllWindows: () => [] } };
+ }
+ return originalLoad.call(this, request, parent, isMain);
+ };
+ try {
+ return require(managerModulePath);
+ } finally {
+ Module._load = originalLoad;
+ }
+}
+
+test("_syncCalendar fetches all pages when nextPageToken is returned", async () => {
+ const GoogleCalendarManager = loadManagerModule();
+
+ const upsertedEvents = [];
+ let savedSyncToken = null;
+ const prunedEventsMap = [];
+
+ const databaseManager = {
+ getGoogleAccounts: () => [],
+ removeStaleCalendarEvents: (provider, calendarId, keptIds) => {
+ prunedEventsMap.push({ provider, calendarId, keptIds });
+ },
+ upsertCalendarEvents: (events) => {
+ upsertedEvents.push(...events);
+ },
+ removeCalendarEvents: () => {},
+ updateCalendarSyncToken: (calendarId, syncToken) => {
+ savedSyncToken = syncToken;
+ },
+ upsertContacts: () => {},
+ };
+
+ const reminderScheduler = {
+ scheduleNextMeeting: () => {},
+ reset: () => {},
+ };
+
+ const manager = new GoogleCalendarManager(databaseManager, null, reminderScheduler);
+
+ const apiCalls = [];
+ manager._apiGet = async (path, email) => {
+ apiCalls.push({ path, email });
+ if (!path.includes("pageToken=")) {
+ return {
+ items: [
+ { id: "event-1", summary: "Event Page 1", start: { dateTime: "2026-08-12T10:00:00Z" } },
+ ],
+ nextPageToken: "token-page-2",
+ };
+ }
+ if (path.includes("pageToken=token-page-2")) {
+ return {
+ items: [
+ { id: "event-2", summary: "Event Page 2", start: { dateTime: "2026-08-12T11:00:00Z" } },
+ ],
+ nextSyncToken: "sync-token-final",
+ };
+ }
+ throw new Error(`Unexpected path: ${path}`);
+ };
+
+ const calendar = { id: "cal-1", account_email: "[email protected]" };
+ await manager._syncCalendar(calendar);
+
+ assert.equal(apiCalls.length, 2, "should make 2 API calls for 2 pages");
+ const firstPageParams = new URL(apiCalls[0].path, "https://www.googleapis.com").searchParams;
+ const secondPageParams = new URL(apiCalls[1].path, "https://www.googleapis.com").searchParams;
+ for (const name of ["singleEvents", "orderBy", "timeMin", "timeMax"]) {
+ assert.equal(
+ secondPageParams.get(name),
+ firstPageParams.get(name),
+ `should preserve ${name} across pages`
+ );
+ }
+ assert.equal(secondPageParams.get("pageToken"), "token-page-2");
+ assert.equal(upsertedEvents.length, 2, "should upsert events from both pages");
+ assert.equal(upsertedEvents[0].id, "event-1");
+ assert.equal(upsertedEvents[1].id, "event-2");
+ assert.equal(savedSyncToken, "sync-token-final", "should save nextSyncToken from final page");
+ assert.deepEqual(
+ prunedEventsMap[0].keptIds,
+ ["event-1", "event-2"],
+ "full sync prune should keep events from all pages"
+ );
+});
+
+test("_syncCalendar preserves incremental sync parameters across pages", async () => {
+ const GoogleCalendarManager = loadManagerModule();
+
+ const databaseManager = {
+ getGoogleAccounts: () => [],
+ removeStaleCalendarEvents: () => {},
+ upsertCalendarEvents: () => {},
+ removeCalendarEvents: () => {},
+ updateCalendarSyncToken: () => {},
+ upsertContacts: () => {},
+ };
+ const reminderScheduler = {
+ scheduleNextMeeting: () => {},
+ reset: () => {},
+ };
+ const manager = new GoogleCalendarManager(databaseManager, null, reminderScheduler);
+
+ const apiCalls = [];
+ manager._apiGet = async (path, email) => {
+ apiCalls.push({ path, email });
+ return apiCalls.length === 1
+ ? { items: [], nextPageToken: "token-page-2" }
+ : { items: [], nextSyncToken: "sync-token-final" };
+ };
+
+ await manager._syncCalendar({
+ id: "cal-1",
+ account_email: "[email protected]",
+ sync_token: "sync-token-previous",
+ });
+
+ assert.equal(apiCalls.length, 2);
+ const firstPageParams = new URL(apiCalls[0].path, "https://www.googleapis.com").searchParams;
+ const secondPageParams = new URL(apiCalls[1].path, "https://www.googleapis.com").searchParams;
+ assert.equal(firstPageParams.get("singleEvents"), "true");
+ assert.equal(firstPageParams.get("syncToken"), "sync-token-previous");
+ assert.equal(secondPageParams.get("singleEvents"), "true");
+ assert.equal(secondPageParams.get("syncToken"), "sync-token-previous");
+ assert.equal(secondPageParams.get("pageToken"), "token-page-2");
+});
diff --git a/test/utils/formatAmount.test.js b/test/utils/formatAmount.test.js
index 0ed38521a..98d93f7c1 100644
--- a/test/utils/formatAmount.test.js
+++ b/test/utils/formatAmount.test.js
@@ -1,7 +1,10 @@
const test = require("node:test");
const assert = require("node:assert/strict");
-const load = () => import("../../src/utils/formatAmount.ts");
+const load = async () => {
+ const m = await import("../../src/utils/formatAmount.ts");
+ return m.default || m;
+};
// Reference formatting through the same Intl path, so expectations
// track the host locale instead of hardcoding "$1.00".
diff --git a/test/utils/formatDuration.test.js b/test/utils/formatDuration.test.js
index 5335e154b..f6ebe83b2 100644
--- a/test/utils/formatDuration.test.js
+++ b/test/utils/formatDuration.test.js
@@ -1,7 +1,10 @@
const test = require("node:test");
const assert = require("node:assert/strict");
-const load = () => import("../../src/utils/formatDuration.ts");
+const load = async () => {
+ const m = await import("../../src/utils/formatDuration.ts");
+ return m.default || m;
+};
test("formatMmSs formats valid positive seconds", async () => {
const { formatMmSs } = await load();
diff --git a/test/utils/participants.test.js b/test/utils/participants.test.js
index ceb17f11a..63a258900 100644
--- a/test/utils/participants.test.js
+++ b/test/utils/participants.test.js
@@ -1,7 +1,10 @@
const test = require("node:test");
const assert = require("node:assert/strict");
-const load = () => import("../../src/utils/participants.ts");
+const load = async () => {
+ const m = await import("../../src/utils/participants.ts");
+ return m.default || m;
+};
test("returns positive integer expected_speaker_count verbatim", async () => {
const { resolveExpectedSpeakerCount } = await load();