Skip to content

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

17.6 KB
Raw Blame
const test = require("node:test");
const assert = require("node:assert/strict");
const Module = require("node:module");

const managerModulePath = require.resolve("../../src/helpers/microsoftCalendarManager.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("normalizeGraphDateTime converts Graph timestamps to SQLite-parseable UTC", () => {
  const { normalizeGraphDateTime } = loadManagerModule();

  assert.equal(
    normalizeGraphDateTime({ dateTime: "2026-07-20T17:00:00.0000000" }),
    "2026-07-20T17:00:00Z"
  );
  assert.equal(normalizeGraphDateTime({ dateTime: "2026-07-20T17:00:00" }), "2026-07-20T17:00:00Z");
});

test("normalizeGraphDateTime keeps only the date for all-day events", () => {
  const { normalizeGraphDateTime } = loadManagerModule();

  assert.equal(
    normalizeGraphDateTime({ dateTime: "2026-07-22T00:00:00.0000000" }, true),
    "2026-07-22"
  );
});

test("_mapEvent stores all-day events as date-only local calendar days", () => {
  const MicrosoftCalendarManager = loadManagerModule();
  const manager = new MicrosoftCalendarManager({}, {});

  const mapped = manager._mapEvent(
    {
      id: "evt-ooo",
      subject: "Out of office",
      start: { dateTime: "2026-07-22T00:00:00.0000000" },
      end: { dateTime: "2026-07-23T00:00:00.0000000" },
      isAllDay: true,
      isCancelled: false,
      showAs: "oof",
    },
    { id: "cal-1", account_email: "[email protected]" }
  );

  assert.equal(mapped.start_time, "2026-07-22");
  assert.equal(mapped.end_time, "2026-07-23");
  assert.equal(mapped.is_all_day, true);
  assert.equal(mapped.availability_status, "unavailable");
});

test("_mapEvent maps a Graph event to the shared calendar_events shape", () => {
  const MicrosoftCalendarManager = loadManagerModule();
  const manager = new MicrosoftCalendarManager({}, {});
  const calendar = { id: "cal-1", account_email: "[email protected]" };

  const mapped = manager._mapEvent(
    {
      id: "evt-1",
      subject: "Standup",
      start: { dateTime: "2026-07-20T17:00:00.0000000" },
      end: { dateTime: "2026-07-20T17:30:00.0000000" },
      isAllDay: false,
      isCancelled: false,
      showAs: "workingElsewhere",
      responseStatus: { response: "declined" },
      onlineMeeting: { joinUrl: "https://teams.microsoft.com/l/meetup-join/abc" },
      organizer: { emailAddress: { address: "[email protected]" } },
      webLink: "https://outlook.office365.com/owa/?itemid=abc",
      attendees: [
        {
          emailAddress: { address: "[email protected]", name: "Me" },
          status: { response: "tentativelyAccepted" },
        },
        { emailAddress: { address: "[email protected]" }, status: { response: "notResponded" } },
      ],
    },
    calendar
  );

  assert.equal(mapped.provider, "microsoft");
  assert.equal(mapped.summary, "Standup");
  assert.equal(mapped.start_time, "2026-07-20T17:00:00Z");
  assert.equal(mapped.status, "confirmed");
  assert.equal(mapped.availability_status, "free");
  assert.equal(mapped.self_response_status, "declined");
  assert.equal(mapped.hangout_link, "https://teams.microsoft.com/l/meetup-join/abc");
  assert.equal(mapped.organizer_email, "[email protected]");
  assert.equal(mapped.web_link, "https://outlook.office365.com/owa/?itemid=abc");
  assert.equal(mapped.attendees_count, 2);

  const attendees = JSON.parse(mapped.attendees);
  assert.deepEqual(attendees[0], {
    email: "[email protected]",
    displayName: "Me",
    responseStatus: "tentative",
    self: true,
  });
  assert.deepEqual(attendees[1], {
    email: "[email protected]",
    displayName: null,
    responseStatus: "needsAction",
    self: false,
  });
});

test("_mapEvent falls back to a meeting link found in location or body text", () => {
  const MicrosoftCalendarManager = loadManagerModule();
  const manager = new MicrosoftCalendarManager({}, {});

  const mapped = manager._mapEvent(
    {
      id: "evt-2",
      subject: "External call",
      start: { dateTime: "2026-07-21T09:00:00.0000000" },
      end: { dateTime: "2026-07-21T10:00:00.0000000" },
      isAllDay: false,
      isCancelled: true,
      bodyPreview: "Join here: https://example.zoom.us/j/123456789.",
    },
    { id: "cal-1", account_email: "[email protected]" }
  );

  assert.equal(mapped.status, "cancelled");
  assert.equal(mapped.hangout_link, "https://example.zoom.us/j/123456789");
  assert.equal(mapped.attendees, null);
});

function createManager(MicrosoftCalendarManager, upserted, contacts = [], overrides = {}) {
  return new MicrosoftCalendarManager(
    {
      removeStaleCalendarEvents: () => {},
      upsertCalendarEvents: (events) => upserted.push(...events),
      removeCalendarEvents: () => {},
      updateMicrosoftCalendarSyncToken: () => {},
      syncCalendarContacts: (_provider, _accountEmail, rows) => contacts.push(...rows),
      getCalendarEventById: () => null,
      getMicrosoftOwnAddresses: () => [],
      ...overrides,
    },
    {}
  );
}

const STRIPPED_OCCURRENCE = {
  id: "occ-1",
  type: "occurrence",
  seriesMasterId: "master-1",
  start: { dateTime: "2026-07-20T09:25:00.0000000" },
  end: { dateTime: "2026-07-20T09:30:00.0000000" },
};

test("_syncCalendar backfills stripped recurring occurrences from their series master", async () => {
  const MicrosoftCalendarManager = loadManagerModule();
  const upserted = [];
  const contacts = [];
  const tokenWrites = [];
  const manager = createManager(MicrosoftCalendarManager, upserted, contacts, {
    updateMicrosoftCalendarSyncToken: (id, token, expiresAt) =>
      tokenWrites.push({ id, token, expiresAt }),
  });

  const masterFetches = [];
  manager._apiGet = async (url) => {
    if (url.includes("/calendarView/delta")) {
      return {
        "@odata.deltaLink": "delta-link",
        value: [
          STRIPPED_OCCURRENCE,
          {
            ...STRIPPED_OCCURRENCE,
            id: "occ-2",
            start: { dateTime: "2026-07-21T09:25:00.0000000" },
            end: { dateTime: "2026-07-21T09:30:00.0000000" },
          },
          {
            id: "evt-1",
            subject: "One-off",
            start: { dateTime: "2026-07-20T17:00:00.0000000" },
            end: { dateTime: "2026-07-20T17:30:00.0000000" },
          },
        ],
      };
    }
    masterFetches.push(url);
    return {
      id: "master-1",
      subject: "Standup",
      isAllDay: false,
      webLink: "https://outlook.office365.com/owa/?itemid=master-1",
      onlineMeeting: { joinUrl: "https://teams.microsoft.com/l/meetup-join/abc" },
      organizer: { emailAddress: { address: "[email protected]" } },
      attendees: [
        {
          emailAddress: { address: "[email protected]", name: "Teammate" },
          status: { response: "accepted" },
        },
      ],
    };
  };

  await manager._syncCalendar({ id: "cal-1", account_email: "[email protected]" });

  assert.equal(masterFetches.length, 1);
  assert.match(masterFetches[0], /^\/me\/calendars\/cal-1\/events\/master-1\?\$select=/);
  assert.ok(
    new URL(masterFetches[0], "https://graph.microsoft.com").searchParams
      .get("$select")
      .split(",")
      .includes("webLink"),
    "the master fetch asks for its web link"
  );

  const occurrence = upserted.find((event) => event.id === "occ-1");
  assert.equal(occurrence.summary, "Standup");
  assert.equal(occurrence.start_time, "2026-07-20T09:25:00Z");
  assert.equal(occurrence.hangout_link, "https://teams.microsoft.com/l/meetup-join/abc");
  assert.equal(occurrence.organizer_email, "[email protected]");
  assert.equal(occurrence.web_link, "https://outlook.office365.com/owa/?itemid=master-1");
  assert.equal(occurrence.attendees_count, 1);
  assert.equal(upserted.find((event) => event.id === "occ-2").summary, "Standup");
  assert.equal(upserted.find((event) => event.id === "evt-1").summary, "One-off");
  assert.ok(contacts.some((contact) => contact.email === "[email protected]"));
  assert.ok(tokenWrites[0].expiresAt > Date.now() + 6 * 24 * 60 * 60 * 1000);
});

test("_syncCalendar inserts a never-seen stripped occurrence bare when the series master fetch fails", async () => {
  const MicrosoftCalendarManager = loadManagerModule();
  const upserted = [];
  const manager = createManager(MicrosoftCalendarManager, upserted);

  manager._apiGet = async (url) => {
    if (url.includes("/calendarView/delta")) {
      return { "@odata.deltaLink": "delta-link", value: [STRIPPED_OCCURRENCE] };
    }
    throw new Error("master gone");
  };

  await manager._syncCalendar({ id: "cal-1", account_email: "[email protected]" });

  assert.equal(upserted.length, 1);
  assert.equal(upserted[0].id, "occ-1");
  assert.equal(upserted[0].summary, null);
  assert.equal(upserted[0].start_time, "2026-07-20T09:25:00Z");
});

test("_syncCalendar shortens the delta token TTL when a master fetch fails", async () => {
  const MicrosoftCalendarManager = loadManagerModule();
  const upserted = [];
  const tokenWrites = [];
  const manager = createManager(MicrosoftCalendarManager, upserted, [], {
    updateMicrosoftCalendarSyncToken: (id, token, expiresAt) =>
      tokenWrites.push({ id, token, expiresAt }),
  });

  manager._apiGet = async (url) => {
    if (url.includes("/calendarView/delta")) {
      return { "@odata.deltaLink": "delta-link", value: [STRIPPED_OCCURRENCE] };
    }
    throw new Error("master gone");
  };

  await manager._syncCalendar({ id: "cal-1", account_email: "[email protected]" });

  assert.equal(tokenWrites.length, 1);
  assert.ok(
    tokenWrites[0].expiresAt <= Date.now() + 10 * 60 * 1000,
    `expected a shortened TTL, got expiry ${tokenWrites[0].expiresAt - Date.now()}ms out`
  );
});

// A bare stub has attendees_count 0 and no join link, which the reminder
// scheduler treats as a time block — it must not overwrite a full row.
test("_syncCalendar keeps the stored row when a stripped occurrence's master fetch fails", async () => {
  const MicrosoftCalendarManager = loadManagerModule();
  const upserted = [];
  const staleKeepLists = [];
  const manager = createManager(MicrosoftCalendarManager, upserted, [], {
    getCalendarEventById: (id) => (id === "occ-1" ? { id, summary: "Standup" } : null),
    removeStaleCalendarEvents: (_provider, _calendarId, keepIds) => staleKeepLists.push(keepIds),
  });

  manager._apiGet = async (url) => {
    if (url.includes("/calendarView/delta")) {
      return {
        "@odata.deltaLink": "delta-link",
        value: [
          STRIPPED_OCCURRENCE,
          {
            id: "evt-1",
            subject: "One-off",
            start: { dateTime: "2026-07-20T17:00:00.0000000" },
            end: { dateTime: "2026-07-20T17:30:00.0000000" },
          },
        ],
      };
    }
    throw new Error("master gone");
  };

  // No sync_token → full sync, so the stale prune runs and must spare occ-1.
  await manager._syncCalendar({ id: "cal-1", account_email: "[email protected]" });

  assert.deepEqual(
    upserted.map((event) => event.id),
    ["evt-1"]
  );
  assert.deepEqual(staleKeepLists, [["occ-1", "evt-1"]]);
});

test("_syncCalendar flags rooms and resources and keeps them and the user out of contacts", async () => {
  const MicrosoftCalendarManager = loadManagerModule();
  const upserted = [];
  const synced = [];
  const manager = createManager(MicrosoftCalendarManager, upserted, [], {
    syncCalendarContacts: (...args) => synced.push(args),
  });
  manager._apiGet = async () => ({
    "@odata.deltaLink": "delta-link",
    value: [
      {
        id: "evt-room",
        subject: "Planning",
        start: { dateTime: "2026-07-20T17:00:00.0000000" },
        end: { dateTime: "2026-07-20T17:30:00.0000000" },
        attendees: [
          {
            type: "required",
            emailAddress: { address: "[email protected]", name: "Ana" },
            status: { response: "accepted" },
          },
          {
            type: "resource",
            emailAddress: { address: "[email protected]", name: "Boardroom" },
            status: { response: "accepted" },
          },
          {
            type: "required",
            emailAddress: { address: "[email protected]", name: "Me" },
            status: { response: "organizer" },
          },
        ],
      },
    ],
  });

  await manager._syncCalendar({ id: "cal-1", account_email: "[email protected]" });

  const attendees = JSON.parse(upserted[0].attendees);
  assert.equal(attendees[0].resource, undefined);
  assert.equal(attendees[1].resource, true);
  // Rows older builds stored for the room and the user are purged.
  assert.deepEqual(synced, [
    [
      "microsoft",
      "[email protected]",
      [{ email: "[email protected]", displayName: "Ana" }],
      ["[email protected]", "[email protected]"],
    ],
  ]);
});

test("_syncCalendar keeps the user's other Microsoft addresses out of contacts", async () => {
  const MicrosoftCalendarManager = loadManagerModule();
  const synced = [];
  const manager = createManager(MicrosoftCalendarManager, [], [], {
    getMicrosoftOwnAddresses: (email) =>
      email === "[email protected]" ? ["[email protected]"] : [],
    syncCalendarContacts: (...args) => synced.push(args),
  });
  manager._apiGet = async () => ({
    "@odata.deltaLink": "delta-link",
    value: [
      {
        id: "evt-1",
        subject: "Planning",
        start: { dateTime: "2026-07-20T17:00:00.0000000" },
        end: { dateTime: "2026-07-20T17:30:00.0000000" },
        attendees: [
          { type: "required", emailAddress: { address: "[email protected]", name: "Ana" } },
          { type: "required", emailAddress: { address: "[email protected]", name: "Chad" } },
        ],
      },
    ],
  });

  await manager._syncCalendar({ id: "cal-1", account_email: "[email protected]" });

  assert.deepEqual(synced[0].slice(2), [
    [{ email: "[email protected]", displayName: "Ana" }],
    ["[email protected]"],
  ]);
});

test("fetchCalendars stores the account's mail, sign-in name and SMTP aliases", async () => {
  const MicrosoftCalendarManager = loadManagerModule();
  const saved = [];
  const manager = new MicrosoftCalendarManager(
    {
      saveMicrosoftCalendars: () => {},
      saveMicrosoftOwnAddresses: (email, addresses) => saved.push([email, addresses]),
      applyMicrosoftPrimaryOnlyToSelection: () => {},
      removeEventsFromDeselectedCalendars: () => {},
    },
    {}
  );
  const paths = [];
  manager._apiGet = async (path) => {
    paths.push(path);
    if (path.startsWith("/me/calendars")) return { value: [] };
    return {
      mail: "[email protected]",
      userPrincipalName: "[email protected]",
      proxyAddresses: ["SMTP:[email protected]", "smtp:[email protected]", "SIP:[email protected]"],
    };
  };

  await manager.fetchCalendars("[email protected]");

  assert.deepEqual(saved, [
    ["[email protected]", ["[email protected]", "[email protected]", "[email protected]"]],
  ]);
  assert.ok(paths.includes("/me?$select=mail,userPrincipalName,proxyAddresses"));
});

test("fetchCalendars still saves the calendars when the address lookup fails", async () => {
  const MicrosoftCalendarManager = loadManagerModule();
  const savedCalendars = [];
  const manager = new MicrosoftCalendarManager(
    {
      saveMicrosoftCalendars: (calendars) => savedCalendars.push(...calendars),
      saveMicrosoftOwnAddresses: () => assert.fail("nothing to save"),
      applyMicrosoftPrimaryOnlyToSelection: () => {},
      removeEventsFromDeselectedCalendars: () => {},
    },
    {}
  );
  manager._apiGet = async (path) => {
    if (path.startsWith("/me?")) throw new Error("API error 400");
    return { value: [{ id: "cal-1", name: "Calendar", isDefaultCalendar: true }] };
  };

  const calendars = await manager.fetchCalendars("[email protected]");

  assert.equal(calendars.length, 1);
  assert.equal(savedCalendars.length, 1);
});

test("a stripped occurrence keeps details but applies explicit RSVP after master failure", async () => {
  const MicrosoftCalendarManager = loadManagerModule();
  const original = {
    id: "occ-1",
    calendar_id: "cal-1",
    provider: "microsoft",
    summary: "Standup",
    start_time: "2026-10-01T10:00:00Z",
    end_time: "2026-10-01T11:00:00Z",
    is_all_day: 0,
    status: "confirmed",
    availability_status: "busy",
    self_response_status: "accepted",
    hangout_link: "https://teams.live.com/meet/123",
    attendees_count: 1,
    attendees: '[{"email":"[email protected]"}]',
  };
  const upserted = [];
  const manager = createManager(MicrosoftCalendarManager, upserted, [], {
    getCalendarEventById: () => original,
  });
  manager._apiGet = async (url) => {
    if (!url.includes("/calendarView/delta")) throw new Error("master unavailable");
    return {
      value: [{ ...STRIPPED_OCCURRENCE, responseStatus: { response: "declined" } }],
    };
  };
  await manager._syncCalendar({ id: "cal-1", account_email: "[email protected]" });
  assert.deepEqual(upserted, [{ ...original, self_response_status: "declined" }]);
});

test("_deltaUrl starts CALENDAR_LOOKBACK_DAYS back", () => {
  const MicrosoftCalendarManager = loadManagerModule();
  const { CALENDAR_LOOKBACK_MS } = require("../../src/helpers/calendarCacheWindow.js");
  const manager = new MicrosoftCalendarManager({}, {});

  const params = new URL(manager._deltaUrl("cal-1"), "https://graph.microsoft.com").searchParams;

  const now = Date.now();
  assert.ok(
    Math.abs(Date.parse(params.get("startDateTime")) - (now - CALENDAR_LOOKBACK_MS)) < 5_000
  );
  assert.ok(Math.abs(Date.parse(params.get("endDateTime")) - (now + 38 * 86_400_000)) < 5_000);
});