Voice-to-text dictation app with local (Nvidia Parakeet/Whisper) and cloud models (BYOK). Privacy-first and available cross-platform.
JavaScript aianthropiccross-platformgeminigroqlinuxmacosnvidiaopen-sourceopenaiparakeetspeech-to-texttranscribewhisperwindows
feat(notes): link a calendar event from the note header (#2822)
Joshua8abe082a18e3
diff --git a/CLAUDE.md b/CLAUDE.mdindex ef570ad47..b1b16ef43 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -158,11 +158,13 @@ OpenWhispr is an Electron-based desktop dictation application that uses whisper.- `calendarView/delta` incremental sync over a 38-day window; delta token discarded after 7 days (Graph delta links never roll their window forward)- Delta can return recurring-series occurrences as bare stubs (no subject/attendees/meeting link); they're backfilled from their series master, one `GET /me/calendars/{calendarId}/events/{id}` per series (calendar-scoped: `/me/events/{id}` 404s for shared calendars). A failed backfill shortens the delta token TTL to 10 min so an early full sync retries instead of leaving untitled blocks- Full re-sync (410 or expired token) prunes stale events like Google-- **appleCalendarManager.js**: Apple Calendar (EventKit) via the `macos-calendar-listener` Swift helper — macOS only, snapshot-push over stdout, no tokens ("connected" = `apple_calendars` has rows)+- **appleCalendarManager.js**: Apple Calendar (EventKit) via the `macos-calendar-listener` Swift helper — macOS only, snapshot-push over stdout, no tokens ("connected" = `apple_calendars` has rows). The helper takes `--lookback-seconds` (an old binary ignores it and keeps a ~2-hour lookback; rebuild with `npm run compile:calendar-listener`)+- **calendarCacheWindow.js**: `CALENDAR_LOOKBACK_DAYS` (3) — every provider keeps this much past history (Google `timeMin`, Microsoft `startDateTime`, the Apple helper flag) so notes can link recent meetings offline. Widening it needs a `user_version` token reset in `database.js` (v5 did it for 3 days)- **calendarReminderScheduler.js**: Provider-agnostic meeting reminder scheduling over the shared `calendar_events` table (provider-scoped reset keys, so one provider's disconnect doesn't re-fire another's reminders)- **calendarSyncInterval.js**: Shared interval runner for the REST providers — exponential backoff (2min → 4min → 8min → cap 30min on consecutive failures, reset on success) and 30s focus-sync throttle- **oauthLoopbackFlow.js**: Shared PKCE auth-code flow over an ephemeral 127.0.0.1 server, used by both calendar OAuth helpers-- Events from all providers land in the shared `calendar_events` table with a `provider` column; queries suppress the Apple copy of a meeting when a REST row occupies the same time slot + title (Calendar.app mirrors the same accounts)+- Events from all providers land in the shared `calendar_events` table with a `provider` column; queries suppress the Apple copy of a meeting when a REST row occupies the same time slot + title (Calendar.app mirrors the same accounts); all-day rows pair by local start and end days + title, since REST stores plain dates and the Apple helper local instants+- The note header's date/attendees dropdown (`NoteParticipants.tsx` + `NoteEventPicker.tsx`) links a note to a stored event (`getLinkableCalendarEvents`, local only): linking merges the event's guests into `participants` in the same write, leaving out rooms and declined guests and leaving attendees already on the note as they are, and tags the ones it adds `addedByEvent: <event id>` (meeting detection tags the attendees it copies onto new notes the same way, via `eventAttendees.js`); the user's own `self` row (every calendar sync stores `self` as the user, Google's shared calendars included) is kept whatever they answered and never tagged, since they recorded the note whichever event it links. Removing or switching the event drops exactly the tagged ones, and speaker counts skip `resource` attendees; Join only opens the link; `web_link` (Google `htmlLink`, Outlook `webLink`, none for Apple) backs "Open in calendar". An unlink is stored as `calendar_event_id = ""`, never NULL (`updateNote` converts an explicit NULL on a linked note), because the cloud and `upsertNoteFromCloud` COALESCE a NULL as "unchanged"- **menuManager.js**: Application menu management- **toneAppCategories.js**: Tone & Style's app classifier (pure, `test/helpers/toneAppCategories.test.js`): an app identity, window title and page host map to `personal`, `work`, `email` or `other` (see Tone & Style)- **tray.js**: System tray icon and menudiff --git a/preload.js b/preload.jsindex 2371be9c2..b1e87c587 100644--- a/preload.js+++ b/preload.js@@ -1346,6 +1346,7 @@ contextBridge.exposeInMainWorld("electronAPI", {},calendarGetAvailability: (request) => ipcRenderer.invoke("calendar-get-availability", request),gcalGetEvent: (eventId) => ipcRenderer.invoke("gcal-get-event", eventId),+ calendarGetLinkableEvents: () => ipcRenderer.invoke("calendar-get-linkable-events"),// Microsoft CalendarmcalStartOAuth: () => ipcRenderer.invoke("mcal-start-oauth"),diff --git a/resources/macos-calendar-listener.swift b/resources/macos-calendar-listener.swiftindex 9b25565d0..9e2535016 100644--- a/resources/macos-calendar-listener.swift+++ b/resources/macos-calendar-listener.swift@@ -6,7 +6,8 @@* calendars+events snapshot whenever the store changes, "sync" arrives on* stdin, or a 5-minute timer rolls the availability cache window forward.*- * Pass --request to prompt for calendar access when it is not determined.+ * Pass --request to prompt for calendar access when it is not determined, and+ * --lookback-seconds <n> to keep that much history in each snapshot.* macOS reads the usage strings from the TCC "responsible process": the* OpenWhispr app bundle in packaged builds, or this binary's embedded* __info_plist in dev, where the manager spawns it via macos-disclaim-exec@@ -29,6 +30,15 @@ let REFRESH_INTERVAL_SECONDS = 300.0// Keep events that may still block availability after the maximum two-hour// buffer, plus one snapshot interval of safety.let AVAILABILITY_LOOKBACK_SECONDS = (120.0 * 60) + REFRESH_INTERVAL_SECONDS+// The app passes --lookback-seconds <n> (calendarCacheWindow.js) so recent past+// events stay linkable to notes; never look back less than availability needs.+let CACHE_LOOKBACK_SECONDS: Double = {+ let args = CommandLine.arguments+ guard let flag = args.firstIndex(of: "--lookback-seconds"), flag + 1 < args.count,+ let seconds = Double(args[flag + 1]), seconds.isFinite+ else { return AVAILABILITY_LOOKBACK_SECONDS }+ return max(seconds, AVAILABILITY_LOOKBACK_SECONDS)+}()let isoFormatter: ISO8601DateFormatter = {let formatter = ISO8601DateFormatter()@@ -249,7 +259,7 @@ func emitSnapshot() {}let now = Date()- let start = now.addingTimeInterval(-AVAILABILITY_LOOKBACK_SECONDS)+ let start = now.addingTimeInterval(-CACHE_LOOKBACK_SECONDS)let end = now.addingTimeInterval(CACHE_LOOKAHEAD_DAYS * 24 * 60 * 60)let predicate = eventStore.predicateForEvents(withStart: start, end: end, calendars: calendars)let eventsOut = eventStore.events(matching: predicate).compactMap(mapEvent)diff --git a/src/components/UpcomingMeetings.tsx b/src/components/UpcomingMeetings.tsxindex 68001d610..287fb255e 100644--- a/src/components/UpcomingMeetings.tsx+++ b/src/components/UpcomingMeetings.tsx@@ -17,7 +17,7 @@ import { canManageSystemAudioInApp } from "../utils/systemAudioAccess";import { getMeetingJoinUrl } from "../helpers/meetingJoinUrl";import TouchGrass from "./TouchGrass";import { createGrassRustle, type GrassRustle } from "../utils/grassRustle";-import { parseEventDate } from "../utils/dateFormatting";+import { formatTimeRange, parseEventDate } from "../utils/dateFormatting";interface UpcomingMeetingsProps {events: CalendarEvent[];@@ -34,12 +34,6 @@ const openJoinUrl = (url: string) => {}};-function formatTimeRange(locale: string, startTime: string, endTime: string): string {- const format = (value: string) =>- new Date(value).toLocaleTimeString(locale, { hour: "numeric", minute: "2-digit" });- return `${format(startTime)} – ${format(endTime)}`;-}-// Today plus the next days that have events, capped at a working week.const MAX_DAY_CARDS = 5;// Avatars shown before the "+N" overflow pill.diff --git a/src/components/notes/NoteEditor.tsx b/src/components/notes/NoteEditor.tsxindex e962723ee..8ee64accb 100644--- a/src/components/notes/NoteEditor.tsx+++ b/src/components/notes/NoteEditor.tsx@@ -7,7 +7,6 @@ import {Sparkles,AlignLeft,MessageSquareText,- LinkIcon,Link2,Lock,FolderOpen,@@ -62,6 +61,7 @@ import {SPLIT_BUTTON_GROUP_CLASS,SPLIT_BUTTON_SEGMENT_CLASS,} from "../ui/splitButton";+import type { CalendarEvent } from "../../types/calendar";import type { NoteItem, FolderItem, ActionItem, ActionKind } from "../../types/electron";import type { ActionProcessingState } from "../../hooks/useActionProcessing";import type { NoteActionProgress } from "../../stores/actionProcessingStore";@@ -227,7 +227,8 @@ interface NoteEditorProps {onSetSessionDiarizationEnabled?: (enabled: boolean) => void;onSetSessionExpectedCount?: (count: number) => void;folderName?: string | null;- calendarEventName?: string | null;+ /** The linked event's stored row; undefined while it is being looked up. */+ linkedEvent?: CalendarEvent | null;folders?: FolderItem[];onMoveToFolder?: (noteId: number, folderId: number) => void;onCreateFolderAndMove?: (noteId: number, folderName: string) => void;@@ -264,7 +265,7 @@ export default function NoteEditor({onSetSessionDiarizationEnabled,onSetSessionExpectedCount,folderName,- calendarEventName,+ linkedEvent,folders,onMoveToFolder,onCreateFolderAndMove,@@ -1034,13 +1035,12 @@ export default function NoteEditor({participants={parsedParticipants}dateLabel={shortDate || undefined}dateTitle={noteDate}+ noteCreatedAt={note.created_at}+ linkedEventId={note.calendar_event_id || null}+ linkedEvent={linkedEvent}+ canEdit={canEditNote}+ ownedByUser={ownedByUser}/>- {calendarEventName && (- <span className={cn(NOTE_META_CHIP_CLASS, "cursor-default")}>- <LinkIcon size={14} className="shrink-0 text-foreground/60" />- <span className="max-w-40 truncate">{calendarEventName}</span>- </span>- )}{isTeamNote && space && (<><buttondiff --git a/src/components/notes/NoteEventPicker.tsx b/src/components/notes/NoteEventPicker.tsxnew file mode 100644index 000000000..aeb189caa--- /dev/null+++ b/src/components/notes/NoteEventPicker.tsx@@ -0,0 +1,176 @@+import { useMemo, useRef, useState, type KeyboardEvent } from "react";+import { useTranslation } from "react-i18next";+import { Check, ChevronLeft, Loader2, Unlink } from "../icons";+import { CALENDAR_LOOKBACK_DAYS } from "../../helpers/calendarCacheWindow";+import { useUiLocale } from "../../hooks/useUiLocale";+import { formatEventWhen } from "../../utils/dateFormatting";+import {+ eventsOnDay,+ startsBeforeStoredWindow,+ searchLinkableEvents,+} from "../../utils/noteEventPicker";+import type { LinkableCalendarEvent } from "../../types/calendar";++interface NoteEventPickerProps {+ /** null while loading */+ events: LinkableCalendarEvent[] | null;+ loadFailed: boolean;+ calendarConnected: boolean;+ noteDay: Date;+ linkedEventId: string | null;+ onSelect: (event: LinkableCalendarEvent) => void;+ onRemove: () => void;+ onBack: () => void;+}++const ROW_CLASS =+ "flex items-center gap-2 w-full px-2 py-1.5 rounded-md text-start text-xs text-foreground/70 hover:bg-foreground/5 transition-colors cursor-pointer";++export function EventDot({ color }: { color: string | null }) {+ return (+ <span+ aria-hidden="true"+ className={+ color+ ? "size-2.5 shrink-0 rounded-[3px]"+ : "size-2.5 shrink-0 rounded-[3px] bg-foreground/30"+ }+ style={color ? { backgroundColor: color } : undefined}+ />+ );+}++export default function NoteEventPicker({+ events,+ loadFailed,+ calendarConnected,+ noteDay,+ linkedEventId,+ onSelect,+ onRemove,+ onBack,+}: NoteEventPickerProps) {+ const { t } = useTranslation();+ const locale = useUiLocale();+ const [query, setQuery] = useState("");+ const pickerRef = useRef<HTMLDivElement>(null);+ const searching = query.trim().length > 0;++ const rows = useMemo(() => {+ if (!events) return [];+ return searching ? searchLinkableEvents(events, query, noteDay) : eventsOnDay(events, noteDay);+ }, [events, noteDay, query, searching]);++ let emptyState: { message: string; hint?: string } | null = null;+ if (!calendarConnected) {+ emptyState = { message: t("notes.eventLink.noCalendar") };+ } else if (loadFailed) {+ emptyState = { message: t("notes.eventLink.loadFailed") };+ } else if (events && rows.length === 0) {+ if (searching) {+ emptyState = { message: t("notes.eventLink.noResults") };+ } else {+ emptyState = {+ message: startsBeforeStoredWindow(noteDay)+ ? t("notes.eventLink.outsideWindow", { days: CALENDAR_LOOKBACK_DAYS })+ : t("notes.eventLink.noEventsOnDay"),+ hint: t("notes.eventLink.searchOtherDays"),+ };+ }+ }+ const loading = calendarConnected && !loadFailed && events === null;++ // Arrow keys walk the search box and the rows; Enter in a search picks the first match.+ const handleKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {+ if (event.nativeEvent.isComposing) return;+ if (event.key === "Enter" && event.target instanceof HTMLInputElement) {+ if (!searching || rows.length === 0) return;+ event.preventDefault();+ onSelect(rows[0]);+ return;+ }+ if (event.key !== "ArrowDown" && event.key !== "ArrowUp") return;+ const items = Array.from(+ pickerRef.current?.querySelectorAll<HTMLElement>("input, [data-event-row]") ?? []+ );+ const index = items.indexOf(document.activeElement as HTMLElement);+ if (index === -1) return;+ event.preventDefault();+ const next = event.key === "ArrowDown" ? index + 1 : index - 1;+ items[Math.max(0, Math.min(items.length - 1, next))].focus();+ };++ return (+ <div ref={pickerRef} onKeyDown={handleKeyDown}>+ <div className="flex items-center gap-1 p-2 border-b border-border/70">+ <button+ type="button"+ onClick={onBack}+ aria-label={t("notes.eventLink.back")}+ className="shrink-0 p-1 rounded-md text-foreground/50 hover:bg-foreground/5 hover:text-foreground/70 transition-colors cursor-pointer"+ >+ <ChevronLeft size={14} className="rtl:rotate-180" />+ </button>+ <input+ dir="auto"+ value={query}+ onChange={(e) => setQuery(e.target.value)}+ placeholder={t("notes.eventLink.searchPlaceholder")}+ aria-label={t("notes.eventLink.searchPlaceholder")}+ className="w-full px-1 py-1.5 rounded-md bg-transparent text-xs text-foreground placeholder:text-foreground/45 outline-none border-none appearance-none"+ autoFocus+ />+ </div>++ <div className="max-h-64 overflow-y-auto p-1">+ {linkedEventId && (+ <button type="button" onClick={onRemove} data-event-row className={ROW_CLASS}>+ <Unlink size={14} className="shrink-0 text-foreground/50" />+ <span>{t("notes.eventLink.removeEvent")}</span>+ </button>+ )}++ {rows.map((event) => (+ <button+ key={event.id}+ type="button"+ onClick={() => onSelect(event)}+ aria-current={event.id === linkedEventId || undefined}+ data-event-row+ className={ROW_CLASS}+ >+ <EventDot color={event.calendar_color} />+ <span className="flex-1 min-w-0">+ <span dir="auto" className="block truncate text-foreground/80">+ {event.summary || t("upcoming.untitledEvent")}+ </span>+ <span className="block truncate text-[11px] text-foreground/45">+ {formatEventWhen(event, locale, t("notes.eventLink.allDay"))}+ </span>+ </span>+ {event.id === linkedEventId && (+ <Check size={14} className="shrink-0 text-primary" aria-hidden="true" />+ )}+ </button>+ ))}++ {loading && (+ <div+ role="status"+ className="flex items-center justify-center gap-1.5 px-3 py-4 text-[11px] text-foreground/45"+ >+ <Loader2 size={12} className="animate-spin" aria-hidden="true" />+ {t("common.loading")}+ </div>+ )}++ {emptyState && (+ <div className="px-3 py-4 text-center text-[11px] text-foreground/45">+ <p>{emptyState.message}</p>+ {emptyState.hint && <p className="mt-1">{emptyState.hint}</p>}+ </div>+ )}+ </div>+ </div>+ );+}diff --git a/src/components/notes/NoteParticipants.tsx b/src/components/notes/NoteParticipants.tsxindex 51013ff51..4f08503a1 100644--- a/src/components/notes/NoteParticipants.tsx+++ b/src/components/notes/NoteParticipants.tsx@@ -1,12 +1,23 @@-import { useState, useEffect, useCallback, useMemo } from "react";+import { useState, useEffect, useCallback, useMemo, useRef, type ReactNode } from "react";import { useTranslation } from "react-i18next";-import { Calendar, ChevronDown, Users, X } from "../icons";+import { Calendar, ChevronDown, ExternalLink, Users, Video, X } from "../icons";import { cn } from "../lib/utils";import { NOTE_META_CHIP_CLASS } from "./shared";+import NoteEventPicker, { EventDot } from "./NoteEventPicker";import { Popover, PopoverTrigger, PopoverContent } from "../ui/popover";import PersonAvatar from "../ui/PersonAvatar";-import type { CalendarAttendee } from "../../types/calendar";+import type { CalendarAttendee, CalendarEvent, LinkableCalendarEvent } from "../../types/calendar";+import { getMeetingJoinUrl } from "../../helpers/meetingJoinUrl";+import { useUiLocale } from "../../hooks/useUiLocale";import { syncSessionExpectedCountFromParticipants } from "../../stores/meetingRecordingStore";+import { useSettingsStore } from "../../stores/settingsStore";+import { parseAttendees } from "../../utils/calendarAttendees";+import { formatEventWhen, normalizeDbDate } from "../../utils/dateFormatting";+import {+ attendeesForUser,+ mergeEventAttendees,+ removeEventAttendees,+} from "../../utils/noteAttendees";const MAX_STACKED_AVATARS = 2;@@ -16,26 +27,85 @@ interface NoteParticipantsProps {/** When present the capsule leads with the note's date, so date and people read as one fact. */dateLabel?: string;dateTitle?: string;+ noteCreatedAt: string;+ /** The note's calendar_event_id; "" or null when no event is linked. */+ linkedEventId: string | null;+ /**+ * The linked event's stored row: null when this device doesn't have it,+ * undefined while the lookup is still running.+ */+ linkedEvent: CalendarEvent | null | undefined;+ /** Viewers see the linked event and can join it, but not change it. */+ canEdit: boolean;+ /** Whether the note is the user's own, so their calendar's `self` flag may mark them on it. */+ ownedByUser: boolean;}+const EVENT_ACTION_CLASS =+ "flex flex-1 items-center justify-center gap-1.5 px-2 py-1.5 rounded-full border border-border/70 text-xs text-foreground/70 hover:bg-foreground/5 transition-colors cursor-pointer";+export default function NoteParticipants({noteId,participants,dateLabel,dateTitle,+ noteCreatedAt,+ linkedEventId,+ linkedEvent,+ canEdit,+ ownedByUser,}: NoteParticipantsProps) {const { t } = useTranslation();+ const locale = useUiLocale();+ const calendarConnected = useSettingsStore(+ (s) => s.gcalConnected || s.mcalConnected || s.appleCalendarConnected+ );const [localParticipants, setLocalParticipants] = useState(participants);const [search, setSearch] = useState("");const [suggestions, setSuggestions] = useState<Array<{ email: string; display_name: string | null }>>([]);const [open, setOpen] = useState(false);+ const [view, setView] = useState<"people" | "events">("people");+ // Read by the popover's Escape handler, which can run with a stale closure.+ const viewRef = useRef(view);+ const [events, setEvents] = useState<LinkableCalendarEvent[] | null>(null);+ const [eventsFailed, setEventsFailed] = useState(false);+ const [localLinkedId, setLocalLinkedId] = useState(linkedEventId || null);useEffect(() => {setLocalParticipants(participants);}, [participants]);+ useEffect(() => {+ setLocalLinkedId(linkedEventId || null);+ }, [linkedEventId]);++ useEffect(() => {+ viewRef.current = view;+ }, [view]);++ const noteDay = useMemo(() => normalizeDbDate(noteCreatedAt), [noteCreatedAt]);++ // Edit rights can resolve after the dropdown opened (a shared note's role+ // loads from the network); a viewer never keeps the event list.+ useEffect(() => {+ if (!canEdit) setView("people");+ }, [canEdit]);++ useEffect(() => {+ if (!open || !canEdit) return;+ let cancelled = false;+ window.electronAPI.calendarGetLinkableEvents?.().then((result) => {+ if (cancelled) return;+ setEvents(result?.success ? result.events : []);+ setEventsFailed(!result?.success);+ });+ return () => {+ cancelled = true;+ };+ }, [open, canEdit]);+useEffect(() => {if (!open) return;const query = search.trim();@@ -48,15 +118,63 @@ export default function NoteParticipants({}, [search, open, localParticipants]);const saveParticipants = useCallback(- (updated: CalendarAttendee[]) => {+ (updated: CalendarAttendee[], extra: { calendar_event_id?: string } = {}) => {syncSessionExpectedCountFromParticipants(noteId, updated);window.electronAPI.updateNote(noteId, {participants: JSON.stringify(updated),+ ...extra,});},[noteId]);+ const linkEvent = useCallback(+ (event: LinkableCalendarEvent) => {+ setView("people");+ // Re-picking the linked event must not re-add guests the user removed.+ if (event.id === localLinkedId) return;+ // Switching events swaps the previous event's guests for this one's.+ const kept = localLinkedId+ ? removeEventAttendees(localParticipants, localLinkedId)+ : localParticipants;+ // The guests come from this user's copy of the event, whose `self` is+ // them; on someone else's note `self` stays with whoever recorded it.+ const guests = attendeesForUser(parseAttendees(event), ownedByUser);+ const merged = mergeEventAttendees(kept, guests, event.id);+ setLocalParticipants(merged);+ setLocalLinkedId(event.id);+ saveParticipants(merged, { calendar_event_id: event.id });+ },+ [localLinkedId, localParticipants, ownedByUser, saveParticipants]+ );++ const unlinkEvent = useCallback(() => {+ setView("people");+ const kept = localLinkedId+ ? removeEventAttendees(localParticipants, localLinkedId)+ : localParticipants;+ setLocalParticipants(kept);+ setLocalLinkedId(null);+ // "" (not NULL) so the unlink syncs: the cloud keeps a NULL as "unchanged".+ saveParticipants(kept, { calendar_event_id: "" });+ }, [localLinkedId, localParticipants, saveParticipants]);++ const resolvedEvent: (CalendarEvent & { calendar_color?: string | null }) | null = localLinkedId+ ? (events?.find((event) => event.id === localLinkedId) ??+ (linkedEvent?.id === localLinkedId ? linkedEvent : null))+ : null;+ const joinUrl = getMeetingJoinUrl(resolvedEvent);+ const calendarUrl =+ resolvedEvent?.web_link?.startsWith("https://") &&+ (resolvedEvent.provider === "google" || resolvedEvent.provider === "microsoft")+ ? resolvedEvent.web_link+ : null;+ const linkLookupDone = linkedEvent !== undefined && (!canEdit || events !== null);+ const openInCalendarLabel =+ resolvedEvent?.provider === "microsoft"+ ? t("notes.eventLink.openInOutlook")+ : t("notes.eventLink.openInGoogle");+const addParticipant = useCallback((email: string, displayName?: string | null) => {const normalized = email.toLowerCase().trim();@@ -112,7 +230,10 @@ export default function NoteParticipants({open={open}onOpenChange={(o) => {setOpen(o);- if (!o) setSearch("");+ if (!o) {+ setSearch("");+ setView("people");+ }}}><PopoverTrigger asChild>@@ -155,82 +276,204 @@ export default function NoteParticipants({<ChevronDown size={14} className="shrink-0 text-foreground/50" /></button></PopoverTrigger>- <PopoverContent className="w-72 p-0">- <div className="p-2 border-b border-border/70">- <input- dir="auto"- value={search}- onChange={(e) => setSearch(e.target.value)}- onKeyDown={handleKeyDown}- placeholder={t("notes.participants.addPlaceholder", "Add attendees...")}- className="w-full px-2 py-1.5 rounded-md bg-transparent text-xs text-foreground placeholder:text-foreground/45 outline-none border-none appearance-none"- autoFocus+ <PopoverContent+ className="w-72 p-0"+ // The popover takes Escape on document capture, before the list's own+ // input sees it, so step back from the event list here instead.+ onEscapeKeyDown={(event) => {+ if (viewRef.current !== "events") return;+ event.preventDefault();+ setView("people");+ }}+ >+ {view === "events" && canEdit ? (+ <NoteEventPicker+ events={events}+ loadFailed={eventsFailed}+ calendarConnected={calendarConnected}+ noteDay={noteDay}+ linkedEventId={localLinkedId}+ onSelect={linkEvent}+ onRemove={unlinkEvent}+ onBack={() => setView("people")}/>- </div>-- <div className="max-h-64 overflow-y-auto">- {search && suggestions.length > 0 && (- <div className="p-1 border-b border-border/70">- {suggestions.slice(0, 5).map((contact) => (- <button- key={contact.email}- onClick={() => addParticipant(contact.email, contact.display_name)}- className="flex items-center gap-2 w-full px-2 py-1.5 rounded-md text-xs text-foreground/70 hover:bg-foreground/5 transition-colors cursor-pointer"- >- <PersonAvatar email={contact.email} displayName={contact.display_name} />- <span dir="auto" className="truncate">- {contact.display_name || contact.email}- </span>- </button>- ))}- </div>- )}+ ) : (+ <>+ {(canEdit || localLinkedId) && (+ <div className="p-1 border-b border-border/70">+ <EventHeaderRow canEdit={canEdit} onOpenEvents={() => setView("events")}>+ {resolvedEvent ? (+ <>+ <EventDot color={resolvedEvent.calendar_color ?? null} />+ <span className="flex-1 min-w-0">+ <span dir="auto" className="block truncate text-foreground/80">+ {resolvedEvent.summary || t("upcoming.untitledEvent")}+ </span>+ <span className="block truncate text-[11px] text-foreground/45">+ {formatEventWhen(resolvedEvent, locale, t("notes.eventLink.allDay"))}+ </span>+ </span>+ </>+ ) : localLinkedId ? (+ <span className="flex-1 min-w-0">+ <span className="block truncate text-foreground/70">+ {t("notes.eventLink.linkedEvent")}+ </span>+ {linkLookupDone && (+ <span className="block text-[11px] text-foreground/45">+ {t("notes.eventLink.unavailable")}+ </span>+ )}+ </span>+ ) : (+ <span className="flex-1 min-w-0">+ <span className="block truncate text-foreground/80">+ {t("notes.eventLink.selectEvent")}+ </span>+ {dateTitle && (+ <span className="block truncate text-[11px] text-foreground/45">+ {dateTitle}+ </span>+ )}+ </span>+ )}+ </EventHeaderRow>+ {(joinUrl || calendarUrl) && (+ <div className="flex gap-2 px-2 pt-1 pb-1.5">+ {joinUrl && (+ <button+ type="button"+ onClick={() => window.electronAPI.openExternal(joinUrl)}+ className={EVENT_ACTION_CLASS}+ >+ <Video size={14} className="shrink-0" />+ {t("notes.eventLink.join")}+ </button>+ )}+ {calendarUrl && (+ <button+ type="button"+ onClick={() => window.electronAPI.openExternal(calendarUrl)}+ // The short label keeps its own accessible name; the+ // tooltip says where it opens.+ title={joinUrl ? openInCalendarLabel : undefined}+ className={EVENT_ACTION_CLASS}+ >+ <ExternalLink size={14} className="shrink-0" />+ {joinUrl ? t("notes.eventLink.calendar") : openInCalendarLabel}+ </button>+ )}+ </div>+ )}+ </div>+ )}- {search && !search.includes("@") && suggestions.length === 0 && (- <div className="px-3 py-2 text-[11px] text-foreground/45">- {t("notes.participants.typeEmail", "Type an email to add...")}+ <div className="p-2 border-b border-border/70">+ <input+ dir="auto"+ value={search}+ onChange={(e) => setSearch(e.target.value)}+ onKeyDown={handleKeyDown}+ placeholder={t("notes.participants.addPlaceholder", "Add attendees...")}+ className="w-full px-2 py-1.5 rounded-md bg-transparent text-xs text-foreground placeholder:text-foreground/45 outline-none border-none appearance-none"+ autoFocus+ /></div>- )}- {grouped.map(([domain, members]) => (- <div key={domain} className="p-1">- <div dir="ltr" className="px-2 py-1 text-[11px] font-medium text-muted-foreground">- {domain}- </div>- {members.map((p) => (- <div- key={p.email}- className="group flex items-center gap-2 px-2 py-1.5 rounded-md hover:bg-foreground/5 transition-colors"- >- <PersonAvatar email={p.email} displayName={p.displayName} />-- <span dir="auto" className="flex-1 min-w-0 truncate text-xs text-foreground/70">- {p.displayName || p.email.split("@")[0]}- {p.self && (- <span className="ms-1 text-foreground/45">- {t("notes.participants.me", "(me)")}+ <div className="max-h-64 overflow-y-auto">+ {search && suggestions.length > 0 && (+ <div className="p-1 border-b border-border/70">+ {suggestions.slice(0, 5).map((contact) => (+ <button+ key={contact.email}+ onClick={() => addParticipant(contact.email, contact.display_name)}+ className="flex items-center gap-2 w-full px-2 py-1.5 rounded-md text-xs text-foreground/70 hover:bg-foreground/5 transition-colors cursor-pointer"+ >+ <PersonAvatar email={contact.email} displayName={contact.display_name} />+ <span dir="auto" className="truncate">+ {contact.display_name || contact.email}</span>- )}- </span>+ </button>+ ))}+ </div>+ )}++ {search && !search.includes("@") && suggestions.length === 0 && (+ <div className="px-3 py-2 text-[11px] text-foreground/45">+ {t("notes.participants.typeEmail", "Type an email to add...")}+ </div>+ )}- <button- onClick={() => removeParticipant(p.email)}- className="shrink-0 opacity-0 group-hover:opacity-100 p-0.5 rounded text-foreground/45 hover:text-foreground/60 transition-opacity cursor-pointer"+ {grouped.map(([domain, members]) => (+ <div key={domain} className="p-1">+ <div+ dir="ltr"+ className="px-2 py-1 text-[11px] font-medium text-muted-foreground">- <X size={12} />- </button>+ {domain}+ </div>+ {members.map((p) => (+ <div+ key={p.email}+ className="group flex items-center gap-2 px-2 py-1.5 rounded-md hover:bg-foreground/5 transition-colors"+ >+ <PersonAvatar email={p.email} displayName={p.displayName} />++ <span+ dir="auto"+ className="flex-1 min-w-0 truncate text-xs text-foreground/70"+ >+ {p.displayName || p.email.split("@")[0]}+ {p.self && (+ <span className="ms-1 text-foreground/45">+ {t("notes.participants.me", "(me)")}+ </span>+ )}+ </span>++ <button+ onClick={() => removeParticipant(p.email)}+ className="shrink-0 opacity-0 group-hover:opacity-100 p-0.5 rounded text-foreground/45 hover:text-foreground/60 transition-opacity cursor-pointer"+ >+ <X size={12} />+ </button>+ </div>+ ))}</div>))}- </div>- ))}- {localParticipants.length === 0 && !search && (- <div className="px-3 py-4 text-center text-[11px] text-foreground/45">- {t("notes.participants.typeEmail", "Type an email to add...")}+ {localParticipants.length === 0 && !search && (+ <div className="px-3 py-4 text-center text-[11px] text-foreground/45">+ {t("notes.participants.typeEmail", "Type an email to add...")}+ </div>+ )}</div>- )}- </div>+ </>+ )}</PopoverContent></Popover>);}++function EventHeaderRow({+ canEdit,+ onOpenEvents,+ children,+}: {+ canEdit: boolean;+ onOpenEvents: () => void;+ children: ReactNode;+}) {+ const className = "flex items-center gap-2 w-full px-2 py-1.5 rounded-md text-start text-xs";+ if (!canEdit) return <div className={className}>{children}</div>;+ return (+ <button+ type="button"+ onClick={onOpenEvents}+ className={cn(className, "hover:bg-foreground/5 transition-colors cursor-pointer")}+ >+ {children}+ <ChevronDown size={14} className="shrink-0 text-foreground/50" />+ </button>+ );+}diff --git a/src/components/notes/PersonalNotesView.tsx b/src/components/notes/PersonalNotesView.tsxindex 9959148c3..765caeb39 100644--- a/src/components/notes/PersonalNotesView.tsx+++ b/src/components/notes/PersonalNotesView.tsx@@ -32,7 +32,7 @@ import {type MeetingIdentity,} from "../../utils/llmTranscript";import type { MentionPerson } from "../../utils/mentionMarkdown";-import type { CalendarAttendee } from "../../types/calendar";+import type { CalendarAttendee, CalendarEvent } from "../../types/calendar";import {useNotes,useSpaces,@@ -386,16 +386,31 @@ export default function PersonalNotesView({[activeNote, folders]);- const [calendarEventName, setCalendarEventName] = useState<string | null>(null);+ // The linked event's stored row, tagged with the id it was looked up for so a+ // stale lookup never shows against another link.+ const [linkedEventLookup, setLinkedEventLookup] = useState<{+ id: string;+ event: CalendarEvent | null;+ } | null>(null);+ const linkedEventId = activeNote?.calendar_event_id || null;useEffect(() => {- if (!activeNote?.calendar_event_id) {- setCalendarEventName(null);- return;- }- window.electronAPI.gcalGetEvent?.(activeNote.calendar_event_id).then((result) => {- setCalendarEventName(result?.success && result.event?.summary ? result.event.summary : null);+ if (!linkedEventId) return;+ let cancelled = false;+ window.electronAPI.gcalGetEvent?.(linkedEventId).then((result) => {+ if (!cancelled) {+ setLinkedEventLookup({ id: linkedEventId, event: result?.success ? result.event : null });+ }});- }, [activeNote?.calendar_event_id]);+ return () => {+ cancelled = true;+ };+ }, [linkedEventId]);+ const linkedEvent = !linkedEventId+ ? null+ : linkedEventLookup?.id === linkedEventId+ ? linkedEventLookup.event+ : undefined;+ const calendarEventName = linkedEvent?.summary ?? null;const startRecording = useCallback(() => startRecordingForNote(activeNote ?? null), [activeNote]);@@ -889,7 +904,7 @@ export default function PersonalNotesView({onSetSessionDiarizationEnabled={setSessionDiarizationEnabled}onSetSessionExpectedCount={setSessionExpectedCount}folderName={activeFolderName}- calendarEventName={calendarEventName}+ linkedEvent={linkedEvent}folders={editorFolders}onMoveToFolder={handleMoveToFolder}onCreateFolderAndMove={handleCreateFolderAndMove}diff --git a/src/helpers/appleCalendarManager.js b/src/helpers/appleCalendarManager.jsindex 70882c96b..32359b79a 100644--- a/src/helpers/appleCalendarManager.js+++ b/src/helpers/appleCalendarManager.js@@ -3,6 +3,7 @@ const { app } = require("electron");const debugLogger = require("./debugLogger");const { resolveBundledBinary } = require("./binaryResolver");const { extractMeetingUrl } = require("./meetingJoinUrl");+const { CALENDAR_LOOKBACK_MS } = require("./calendarCacheWindow");const { broadcastToWindows } = require("./windowBroadcast");const { FOCUS_SYNC_THROTTLE_MS } = require("./calendarSyncInterval");@@ -106,6 +107,14 @@ class AppleCalendarManager {}}+ _helperArgs(requestAccess) {+ return [+ "--lookback-seconds",+ String(CALENDAR_LOOKBACK_MS / 1000),+ ...(requestAccess ? ["--request"] : []),+ ];+ }+_spawnHelper(requestAccess) {if (this._restartTimer) {clearTimeout(this._restartTimer);@@ -120,7 +129,7 @@ class AppleCalendarManager {}let command = binaryPath;- let args = requestAccess ? ["--request"] : [];+ let args = this._helperArgs(requestAccess);if (!app.isPackaged) {// A terminal-launched dev app makes the terminal the helper's TCC// "responsible process", and its missing calendar usage strings abortdiff --git a/src/helpers/calendarCacheWindow.js b/src/helpers/calendarCacheWindow.jsnew file mode 100644index 000000000..9cbdc73bc--- /dev/null+++ b/src/helpers/calendarCacheWindow.js@@ -0,0 +1,7 @@+// ESM like calendarAvailability.js: shared with the renderer, where Vite only+// handles ESM source files; main-process CJS callers load it via Node's+// require(esm) with module-syntax detection.+// Every provider keeps this much history so a note can be linked to a recent+// past meeting from the local cache, offline and without a live API call.+export const CALENDAR_LOOKBACK_DAYS = 3;+export const CALENDAR_LOOKBACK_MS = CALENDAR_LOOKBACK_DAYS * 24 * 60 * 60 * 1000;diff --git a/src/helpers/database.js b/src/helpers/database.jsindex 32f9e3439..661d9941e 100644--- a/src/helpers/database.js+++ b/src/helpers/database.js@@ -191,12 +191,21 @@ const FOLDER_NAME_TAKEN_FILTER = `(deleted_at IS NULL OR EXISTS (// duplicate UI rows; suppress the Apple copy when a REST row occupies the same// time slot + title (REST rows have richer conference data). datetime()// normalizes the providers' timestamp formats (Google stores offset-form-// RFC3339, Apple/Microsoft store UTC "Z" form). REST rows are never collapsed-// — Google and Microsoft are never mirrors of each other.+// RFC3339, Apple/Microsoft store UTC "Z" form). All-day rows pair by local+// days instead: REST providers store plain dates (the end exclusive) while the+// Apple helper writes local instants, ending at either the next midnight or+// the last second of the final day — one second later is the exclusive end+// day in both cases. REST rows are never collapsed — Google and Microsoft are+// never mirrors of each other.+const MIRROR_SLOT = `CASE WHEN is_all_day THEN 'day:' || CASE WHEN length(start_time) = 10+ THEN start_time || '|' || end_time+ ELSE date(start_time, 'localtime') || '|' || date(end_time, '+1 second', 'localtime') END+ ELSE datetime(start_time) || '|' || datetime(end_time) END`;+function dedupedEventsQuery(where) {return `SELECT * FROM (SELECT *, MAX(provider != 'apple') OVER (- PARTITION BY datetime(start_time), datetime(end_time), COALESCE(summary, '')+ PARTITION BY ${MIRROR_SLOT}, COALESCE(summary, '')) AS has_syncedFROM calendar_eventsWHERE ${where}@@ -978,6 +987,18 @@ class DatabaseManager {this.db.pragma("user_version = 4");}+ // One-time reset (user_version 5): the stored lookback widened to+ // CALENDAR_LOOKBACK_DAYS so notes can link recent past events, and REST+ // sync tokens pin the window they were created with. The full sync also+ // fills calendar_events.web_link.+ if (this.db.pragma("user_version", { simple: true }) < 5) {+ this.db.exec(`+ UPDATE google_calendars SET sync_token = NULL, sync_token_expires_at = NULL;+ UPDATE microsoft_calendars SET sync_token = NULL, sync_token_expires_at = NULL;+ `);+ this.db.pragma("user_version = 5");+ }+this.db.exec(`CREATE TABLE IF NOT EXISTS apple_calendars (id TEXT PRIMARY KEY,@@ -1004,6 +1025,13 @@ class DatabaseManager {} catch (err) {if (!err.message.includes("duplicate column")) throw err;}+ // The event's page in Google Calendar or Outlook on the web; Apple has+ // none. The user_version 5 full sync fills it for rows in the sync window.+ try {+ this.db.exec("ALTER TABLE calendar_events ADD COLUMN web_link TEXT");+ } catch (err) {+ if (!err.message.includes("duplicate column")) throw err;+ }try {this.db.exec("ALTER TABLE notes ADD COLUMN participants TEXT");} catch (err) {@@ -3382,6 +3410,10 @@ class DatabaseManager {const previous = this.getNote(id);if (!previous) return { success: false, error: "Note not found" };updates = { ...updates };+ // An unlink is stored as "" so it syncs: the cloud keeps a NULL as "unchanged".+ if (updates.calendar_event_id === null && previous.calendar_event_id != null) {+ updates.calendar_event_id = "";+ }const clears = updates.clear_fields ?? [];if (!Array.isArray(clears) || clears.some((field) => !NOTE_TEXT_FIELDS.includes(field))) {return { success: false, error: "Invalid note clear fields" };@@ -5002,7 +5034,7 @@ class DatabaseManager {if (!this.db) throw new Error("Database not initialized");const transaction = this.db.transaction((eventList) => {const stmt = this.db.prepare(- "INSERT OR REPLACE INTO calendar_events (id, calendar_id, provider, summary, start_time, end_time, is_all_day, status, availability_status, self_response_status, hangout_link, conference_data, organizer_email, attendees_count, attendees, synced_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP)"+ "INSERT OR REPLACE INTO calendar_events (id, calendar_id, provider, summary, start_time, end_time, is_all_day, status, availability_status, self_response_status, hangout_link, conference_data, organizer_email, attendees_count, attendees, web_link, synced_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP)");for (const e of eventList) {stmt.run(@@ -5020,7 +5052,8 @@ class DatabaseManager {e.conference_data || null,e.organizer_email || null,e.attendees_count || 0,- e.attendees || null+ e.attendees || null,+ e.web_link || null);}});@@ -5147,6 +5180,52 @@ class DatabaseManager {}}+ // The stored events on the user's selected calendars that a note can link+ // to (not cancelled or declined), with its calendar's colour for the picker.+ // `endsAfter` (ISO) leaves out old rows kept only because a note links them,+ // which would otherwise grow with every linked note.+ getLinkableCalendarEvents({ endsAfter = null } = {}) {+ try {+ if (!this.db) throw new Error("Database not initialized");+ const colors = new Map(+ this.db+ .prepare(+ `SELECT 'google' AS provider, id, background_color AS color FROM google_calendars+ UNION ALL+ SELECT 'microsoft', id, background_color FROM microsoft_calendars+ UNION ALL+ SELECT 'apple', id, color FROM apple_calendars`+ )+ .all()+ .map((row) => [`${row.provider}:${row.id}`, row.color])+ );+ return this.db+ .prepare(+ dedupedEventsQuery(+ `status IN ('confirmed', 'tentative') AND ${SELECTED_CALENDAR_EVENT_FILTER}+ AND (? IS NULL OR datetime(end_time) > datetime(?))`+ )+ )+ .all(endsAfter, endsAfter)+ .filter((event) => event.self_response_status !== "declined")+ .map((row) => {+ const event = stripDedupeColumn(row);+ const color = colors.get(`${event.provider}:${event.calendar_id}`);+ return {+ ...event,+ calendar_color: /^#[0-9a-f]{6}$/i.test(color ?? "") ? color : null,+ };+ });+ } catch (error) {+ debugLogger.error(+ "Error getting linkable calendar events",+ { error: error.message },+ "calendar"+ );+ throw error;+ }+ }+getCalendarEventById(eventId) {try {if (!this.db) throw new Error("Database not initialized");@@ -5253,7 +5332,7 @@ class DatabaseManager {}// What find_contact searches. calendar_events only holds a sync window- // (about two days back to a month ahead), so the meetings nearest to now go+ // (about three days back to a month ahead), so the meetings nearest to now go// first, and the contacts table (every synced attendee until its last// source is disconnected) covers older ones, most recently seen first. Only// the user's own meetings count: not cancelled or declined ones, not a@@ -5340,6 +5419,8 @@ class DatabaseManager {// match, or both apps record into one note. Ownership follows ownsNote() in// spacePermissions.ts, plus Personal rows synced before owners were recorded.getOwnNoteByCalendarEventId(eventId, { throwOnError = false } = {}) {+ // An unlinked note stores "", which must never match.+ if (!eventId) return null;try {if (!this.db) throw new Error("Database not initialized");const accountScope = this._accountScopeCondition("notes");@@ -5820,15 +5901,15 @@ class DatabaseManager {}}- // Snapshots cover the full current/future window, so missing unreferenced- // events can be removed while note-linked history is retained.+ // Snapshots cover the full cache window, so missing unreferenced events can+ // be removed while note-linked history is retained.replaceAppleCalendarEvents(events) {try {if (!this.db) throw new Error("Database not initialized");const transaction = this.db.transaction((list) => {- // The helper snapshot only contains current/future events. Keep past or- // rescheduled rows that are still referenced by meeting notes so those- // notes retain their calendar metadata.+ // The helper snapshot only covers the lookback window and the future.+ // Keep older or rescheduled rows that are still referenced by meeting+ // notes so those notes retain their calendar metadata.this.db.prepare(`DELETE FROM calendar_events@@ -6495,7 +6576,9 @@ class DatabaseManager {localFolderId,spaceId,cloudNote.participants || null,- cloudNote.calendar_event_id || null,+ // "" is the cloud's record of a deliberate unlink; NULL means the API+ // omitted the field, which the COALESCE above treats as "keep local".+ cloudNote.calendar_event_id ?? null,cloudNote.diarization_enabled ?? null,normalizeStoredSpeakerCount(cloudNote.expected_speaker_count),cloudNote.updated_by_user_id || null,diff --git a/src/helpers/eventAttendees.js b/src/helpers/eventAttendees.jsnew file mode 100644index 000000000..e7ba63bb8--- /dev/null+++ b/src/helpers/eventAttendees.js@@ -0,0 +1,40 @@+// ESM like calendarCacheWindow.js: shared with the renderer, where Vite only+// handles ESM source files; main-process CJS callers load it via Node's+// require(esm) with module-syntax detection.++/**+ * Whether an event's attendee belongs on a note made from it: rooms and other+ * resources are booked rather than invited, and a guest who declined isn't+ * coming. The user (`self`) stays whatever they answered, since they are the+ * one recording. Notes created before this rule may still hold rooms, so+ * speaker counts skip `resource` attendees on their own.+ */+export function isEventGuest(attendee) {+ return (+ attendee.resource !== true && (attendee.self === true || attendee.responseStatus !== "declined")+ );+}++/**+ * An event's attendees JSON for the note it creates. Each guest is tagged with+ * the event (`addedByEvent`) so removing the event later takes them off again,+ * except the user (`self`), who recorded the note whichever event it links.+ */+export function tagEventAttendeesJson(attendeesJson, eventId) {+ if (!attendeesJson || !eventId) return attendeesJson || null;+ try {+ const attendees = JSON.parse(attendeesJson);+ if (!Array.isArray(attendees)) return attendeesJson;+ return JSON.stringify(+ attendees+ .filter((attendee) => !attendee || typeof attendee !== "object" || isEventGuest(attendee))+ .map((attendee) =>+ attendee && typeof attendee === "object" && attendee.self !== true+ ? { ...attendee, addedByEvent: eventId }+ : attendee+ )+ );+ } catch {+ return attendeesJson;+ }+}diff --git a/src/helpers/googleCalendarManager.js b/src/helpers/googleCalendarManager.jsindex 51a5f2df9..1bf112c51 100644--- a/src/helpers/googleCalendarManager.js+++ b/src/helpers/googleCalendarManager.js@@ -2,12 +2,11 @@ const { net } = require("electron");const debugLogger = require("./debugLogger");const GoogleCalendarOAuth = require("./googleCalendarOAuth");const CalendarSyncInterval = require("./calendarSyncInterval");-const { MAX_BUFFER_MINUTES } = require("./calendarAvailability");+const { CALENDAR_LOOKBACK_MS } = require("./calendarCacheWindow");const { extractMeetingUrl } = require("./meetingJoinUrl");const { broadcastToWindows } = require("./windowBroadcast");const CALENDAR_API_BASE = "https://www.googleapis.com/calendar/v3";-const BUFFER_COVERAGE_MS = MAX_BUFFER_MINUTES * 60 * 1000;const ALL_DAY_TIMEZONE_PADDING_MS = 48 * 60 * 60 * 1000;// Sync tokens pin the full sync's timeMin/timeMax window, so discard them@@ -16,6 +15,20 @@ const SYNC_LOOKAHEAD_MS = 33 * 24 * 60 * 60 * 1000;const SYNC_TOKEN_TTL_MS = 24 * 60 * 60 * 1000;const GOOGLE_RESPONSE_STATUSES = new Set(["accepted", "declined", "tentative", "needsAction"]);+// The browser opens an event link under its default Google account, so with+// several signed in it finds no such event; authuser picks the calendar's own.+function eventWebLink(htmlLink, accountEmail) {+ if (!htmlLink) return null;+ if (!accountEmail) return htmlLink;+ try {+ const url = new URL(htmlLink);+ url.searchParams.set("authuser", accountEmail);+ return url.toString();+ } catch {+ return htmlLink;+ }+}+class GoogleCalendarManager {constructor(databaseManager, windowManager, reminderScheduler) {this.databaseManager = databaseManager;@@ -171,9 +184,7 @@ class GoogleCalendarManager {new URLSearchParams({singleEvents: "true",orderBy: "startTime",- timeMin: new Date(- Date.now() - BUFFER_COVERAGE_MS - ALL_DAY_TIMEZONE_PADDING_MS- ).toISOString(),+ timeMin: new Date(Date.now() - CALENDAR_LOOKBACK_MS).toISOString(),timeMax: new Date(Date.now() + SYNC_LOOKAHEAD_MS + ALL_DAY_TIMEZONE_PADDING_MS).toISOString(),@@ -263,6 +274,7 @@ class GoogleCalendarManager {hangout_link: item.hangoutLink || extractMeetingUrl([item.location, item.description]),conference_data: item.conferenceData ? JSON.stringify(item.conferenceData) : null,organizer_email: item.organizer?.email || null,+ web_link: eventWebLink(item.htmlLink, accountEmail),attendees_count: item.attendees?.length || 0,attendees: item.attendees? JSON.stringify(@@ -270,7 +282,9 @@ class GoogleCalendarManager {email: a.email,displayName: a.displayName || null,responseStatus: a.responseStatus || null,- self: a.self || false,+ // Stored self means the user, as on Microsoft and Apple; on a+ // shared calendar Google's flag marks the calendar's owner.+ self: selfIsUser ? a.self === true : a.email?.toLowerCase() === ownEmail,...(a.resource ? { resource: true } : {}),})))diff --git a/src/helpers/ipcHandlers.js b/src/helpers/ipcHandlers.jsindex 61efd1e59..719fe8cce 100644--- a/src/helpers/ipcHandlers.js+++ b/src/helpers/ipcHandlers.js@@ -207,6 +207,7 @@ const {isSignInRefusal,} = require("./realtimeTokenProviders");const { getCalendarAvailability } = require("./calendarAvailabilityService");+const { CALENDAR_LOOKBACK_MS } = require("./calendarCacheWindow");// Meeting capture runs at 24 kHz (see meetingRecordingStore AudioContext); cloud// streaming providers must be told the true PCM rate or they misread the audio.@@ -1150,8 +1151,13 @@ class IPCHandlers {const googleEmails = new Set(this.databaseManager.getGoogleAccounts().map((a) => a.email.toLowerCase()));+ // Rooms aren't speakers; notes linked before rooms were left out may hold them.return participants.filter(- (p) => p && p.self !== true && !googleEmails.has((p.email || "").toLowerCase())+ (p) =>+ p &&+ p.self !== true &&+ p.resource !== true &&+ !googleEmails.has((p.email || "").toLowerCase()));}@@ -12227,6 +12233,23 @@ class IPCHandlers {}});+ ipcMain.handle("calendar-get-linkable-events", async () => {+ try {+ // A day past the synced history: an all-day row's plain-date end reads+ // as UTC midnight, up to 14 hours off the user's local end.+ const endsAfter = new Date(+ Date.now() - CALENDAR_LOOKBACK_MS - 24 * 60 * 60 * 1000+ ).toISOString();+ return {+ success: true,+ events: this.databaseManager.getLinkableCalendarEvents({ endsAfter }),+ };+ } catch (error) {+ debugLogger.debug("Linkable calendar events failed", { error: error.message }, "calendar");+ return { success: false, events: [] };+ }+ });+// Microsoft CalendaripcMain.handle("mcal-start-oauth", async () => {try {diff --git a/src/helpers/meetingDetectionEngine.js b/src/helpers/meetingDetectionEngine.jsindex 3509f5ab8..33ba8cfe5 100644--- a/src/helpers/meetingDetectionEngine.js+++ b/src/helpers/meetingDetectionEngine.js@@ -8,6 +8,7 @@ const {} = require("./meetingNotificationDestination");const { openExternalUrl } = require("./externalUrlOpener");const { getMeetingJoinUrl } = require("./meetingJoinUrl");+const { tagEventAttendeesJson } = require("./eventAttendees");const createMeetingAutoEndController = require("./meetingAutoEndController");const { createMeetingAudioActivityMonitor } = require("./meetingAudioActivityMonitor");const { broadcastToWindows } = require("./windowBroadcast");@@ -506,7 +507,7 @@ class MeetingDetectionEngine {folderId: folder.id,spaceId: folder.space_id,eventId,- participants: calendarEvent?.attendees,+ participants: tagEventAttendeesJson(calendarEvent?.attendees, eventId),});note = result.note;owner.committedNoteId = note.id;@@ -633,7 +634,7 @@ class MeetingDetectionEngine {const updates = { calendar_event_id: calEvent.id };if (calEvent.attendees) {- updates.participants = calEvent.attendees;+ updates.participants = tagEventAttendeesJson(calEvent.attendees, calEvent.id);}const updateResult = this.databaseManager.updateNote(noteResult.note.id, updates);diff --git a/src/helpers/microsoftCalendarManager.js b/src/helpers/microsoftCalendarManager.jsindex a6852fb20..729e40faf 100644--- a/src/helpers/microsoftCalendarManager.js+++ b/src/helpers/microsoftCalendarManager.js@@ -2,25 +2,26 @@ const { net } = require("electron");const debugLogger = require("./debugLogger");const MicrosoftCalendarOAuth = require("./microsoftCalendarOAuth");const CalendarSyncInterval = require("./calendarSyncInterval");-const { MAX_BUFFER_MINUTES } = require("./calendarAvailability");+const { CALENDAR_LOOKBACK_MS } = require("./calendarCacheWindow");const { extractMeetingUrl } = require("./meetingJoinUrl");const { broadcastToWindows } = require("./windowBroadcast");const GRAPH_API_BASE = "https://graph.microsoft.com/v1.0";+// webLink is the series' page: a stripped occurrence has none of its own, and+// the series is the nearest page to open without a request per occurrence.const SERIES_MASTER_FIELDS =- "subject,isAllDay,isCancelled,showAs,responseStatus,onlineMeeting,onlineMeetingUrl,location,bodyPreview,organizer,attendees";+ "subject,isAllDay,isCancelled,showAs,responseStatus,onlineMeeting,onlineMeetingUrl,location,bodyPreview,organizer,attendees,webLink";// Graph's deltaLink permanently encodes the calendarView window it was created-// with — it never rolls forward. Sync a 38-day window and discard the token-// after 7 days so coverage never drops below the app's 31-day lookahead.+// with — it never rolls forward. Sync from CALENDAR_LOOKBACK_MS back to 38 days+// ahead and discard the token after 7 days so coverage never drops below the+// app's 31-day lookahead.const DELTA_WINDOW_MS = 38 * 24 * 60 * 60 * 1000;const DELTA_TOKEN_TTL_MS = 7 * 24 * 60 * 60 * 1000;// A failed series-master backfill can't be retried via delta (unchanged// occurrences are never re-delivered); a short TTL forces an early full sync.const BACKFILL_RETRY_TTL_MS = 10 * 60 * 1000;-const BUFFER_COVERAGE_MS = MAX_BUFFER_MINUTES * 60 * 1000;-const LOOKBACK_SAFETY_MS = 24 * 60 * 60 * 1000;const AVAILABILITY_STATUS_BY_GRAPH = {free: "free",@@ -352,6 +353,7 @@ class MicrosoftCalendarManager {extractMeetingUrl([item.location?.displayName, item.bodyPreview]),conference_data: null,organizer_email: item.organizer?.emailAddress?.address || null,+ web_link: item.webLink || null,attendees_count: attendees.length,attendees: attendees.length? JSON.stringify(@@ -430,7 +432,7 @@ class MicrosoftCalendarManager {// deltaLink for incremental syncs (stored in microsoft_calendars.sync_token)._deltaUrl(calendarId) {const params = new URLSearchParams({- startDateTime: new Date(Date.now() - LOOKBACK_SAFETY_MS - BUFFER_COVERAGE_MS).toISOString(),+ startDateTime: new Date(Date.now() - CALENDAR_LOOKBACK_MS).toISOString(),endDateTime: new Date(Date.now() + DELTA_WINDOW_MS).toISOString(),});return `/me/calendars/${encodeURIComponent(calendarId)}/calendarView/delta?${params.toString()}`;diff --git a/src/locales/ar/translation.json b/src/locales/ar/translation.jsonindex 6abcd7e16..761c1e4f8 100644--- a/src/locales/ar/translation.json+++ b/src/locales/ar/translation.json@@ -2196,6 +2196,25 @@"typeEmail": "اكتب بريدًا إلكترونيًا لإضافته...","me": "(أنا)"},+ "eventLink": {+ "selectEvent": "اختيار حدث من التقويم",+ "searchPlaceholder": "البحث عن حدث…",+ "back": "رجوع",+ "removeEvent": "إزالة حدث التقويم",+ "allDay": "طوال اليوم",+ "noEventsOnDay": "لا توجد أحداث في هذا اليوم",+ "searchOtherDays": "ابحث للعثور على أحداث من أيام أخرى",+ "outsideWindow": "يمكن ربط أحداث آخر {{days}} أيام فقط",+ "noResults": "لا توجد أحداث مطابقة",+ "noCalendar": "اربط تقويمًا من «التكاملات» لربط الأحداث",+ "loadFailed": "تعذّر تحميل أحداث التقويم",+ "join": "انضمام",+ "calendar": "التقويم",+ "openInGoogle": "فتح في Google Calendar",+ "openInOutlook": "فتح في Outlook",+ "linkedEvent": "حدث التقويم",+ "unavailable": "هذا الحدث غير موجود في تقاويمك على هذا الجهاز"+ },"upload": {"title": "رفع ملف صوتي","using": "باستخدام {{model}}",diff --git a/src/locales/de/translation.json b/src/locales/de/translation.jsonindex ff787ed2c..9b00cf5aa 100644--- a/src/locales/de/translation.json+++ b/src/locales/de/translation.json@@ -3452,6 +3452,25 @@"typeEmail": "E-Mail eingeben zum Hinzufügen...","me": "(ich)"},+ "eventLink": {+ "selectEvent": "Kalenderereignis auswählen",+ "searchPlaceholder": "Ereignis suchen…",+ "back": "Zurück",+ "removeEvent": "Kalenderereignis entfernen",+ "allDay": "Ganztägig",+ "noEventsOnDay": "Keine Ereignisse an diesem Tag",+ "searchOtherDays": "Suchen, um Ereignisse an anderen Tagen zu finden",+ "outsideWindow": "Nur Ereignisse der letzten {{days}} Tage können verknüpft werden",+ "noResults": "Keine passenden Ereignisse",+ "noCalendar": "Verbinde unter Integrationen einen Kalender, um Ereignisse zu verknüpfen",+ "loadFailed": "Kalenderereignisse konnten nicht geladen werden",+ "join": "Beitreten",+ "calendar": "Kalender",+ "openInGoogle": "In Google Calendar öffnen",+ "openInOutlook": "In Outlook öffnen",+ "linkedEvent": "Kalenderereignis",+ "unavailable": "Dieses Ereignis ist auf diesem Gerät in keinem deiner Kalender"+ },"upload": {"title": "Audio hochladen","using": "Verwendet {{model}}",diff --git a/src/locales/en/translation.json b/src/locales/en/translation.jsonindex fb4a5bc10..58a743646 100644--- a/src/locales/en/translation.json+++ b/src/locales/en/translation.json@@ -3452,6 +3452,25 @@"typeEmail": "Type an email to add...","me": "(me)"},+ "eventLink": {+ "selectEvent": "Select calendar event",+ "searchPlaceholder": "Search event…",+ "back": "Back",+ "removeEvent": "Remove calendar event",+ "allDay": "All day",+ "noEventsOnDay": "No events on this day",+ "searchOtherDays": "Search to find events from other days",+ "outsideWindow": "Only events from the last {{days}} days can be linked",+ "noResults": "No matching events",+ "noCalendar": "Connect a calendar in Integrations to link events",+ "loadFailed": "Couldn't load calendar events",+ "join": "Join",+ "calendar": "Calendar",+ "openInGoogle": "Open in Google Calendar",+ "openInOutlook": "Open in Outlook",+ "linkedEvent": "Calendar event",+ "unavailable": "This event isn't in your calendars on this device"+ },"upload": {"title": "Upload Audio","using": "Using {{model}}",diff --git a/src/locales/es/translation.json b/src/locales/es/translation.jsonindex 57d4eeb03..aa30d4030 100644--- a/src/locales/es/translation.json+++ b/src/locales/es/translation.json@@ -3153,6 +3153,25 @@"typeEmail": "Escribe un correo para agregar...","me": "(yo)"},+ "eventLink": {+ "selectEvent": "Seleccionar evento del calendario",+ "searchPlaceholder": "Buscar evento…",+ "back": "Atrás",+ "removeEvent": "Quitar evento del calendario",+ "allDay": "Todo el día",+ "noEventsOnDay": "No hay eventos este día",+ "searchOtherDays": "Busca para encontrar eventos de otros días",+ "outsideWindow": "Solo se pueden vincular eventos de los últimos {{days}} días",+ "noResults": "No hay eventos que coincidan",+ "noCalendar": "Conecta un calendario en Integraciones para vincular eventos",+ "loadFailed": "No se pudieron cargar los eventos del calendario",+ "join": "Unirse",+ "calendar": "Calendario",+ "openInGoogle": "Abrir en Google Calendar",+ "openInOutlook": "Abrir en Outlook",+ "linkedEvent": "Evento del calendario",+ "unavailable": "Este evento no está en tus calendarios en este dispositivo"+ },"upload": {"title": "Subir audio","using": "Usando {{model}}",diff --git a/src/locales/fr/translation.json b/src/locales/fr/translation.jsonindex 4bc5fb5c9..689ffe954 100644--- a/src/locales/fr/translation.json+++ b/src/locales/fr/translation.json@@ -3452,6 +3452,25 @@"typeEmail": "Saisissez un e-mail pour ajouter...","me": "(moi)"},+ "eventLink": {+ "selectEvent": "Sélectionner un événement",+ "searchPlaceholder": "Rechercher un événement…",+ "back": "Retour",+ "removeEvent": "Retirer l'événement",+ "allDay": "Toute la journée",+ "noEventsOnDay": "Aucun événement ce jour-là",+ "searchOtherDays": "Recherchez pour trouver des événements d'autres jours",+ "outsideWindow": "Seuls les événements des {{days}} derniers jours peuvent être liés",+ "noResults": "Aucun événement correspondant",+ "noCalendar": "Connectez un calendrier dans Intégrations pour lier des événements",+ "loadFailed": "Impossible de charger les événements du calendrier",+ "join": "Rejoindre",+ "calendar": "Calendrier",+ "openInGoogle": "Ouvrir dans Google Calendar",+ "openInOutlook": "Ouvrir dans Outlook",+ "linkedEvent": "Événement du calendrier",+ "unavailable": "Cet événement ne figure dans aucun de vos calendriers sur cet appareil"+ },"upload": {"title": "Téléverser un fichier audio","using": "Utilisation de {{model}}",diff --git a/src/locales/it/translation.json b/src/locales/it/translation.jsonindex ef579d889..6abedc6bd 100644--- a/src/locales/it/translation.json+++ b/src/locales/it/translation.json@@ -3101,6 +3101,25 @@"typeEmail": "Digita un'email per aggiungere...","me": "(io)"},+ "eventLink": {+ "selectEvent": "Seleziona evento del calendario",+ "searchPlaceholder": "Cerca evento…",+ "back": "Indietro",+ "removeEvent": "Rimuovi evento del calendario",+ "allDay": "Tutto il giorno",+ "noEventsOnDay": "Nessun evento in questo giorno",+ "searchOtherDays": "Cerca per trovare eventi di altri giorni",+ "outsideWindow": "Si possono collegare solo eventi degli ultimi {{days}} giorni",+ "noResults": "Nessun evento corrispondente",+ "noCalendar": "Collega un calendario in Integrazioni per collegare eventi",+ "loadFailed": "Impossibile caricare gli eventi del calendario",+ "join": "Partecipa",+ "calendar": "Calendario",+ "openInGoogle": "Apri in Google Calendar",+ "openInOutlook": "Apri in Outlook",+ "linkedEvent": "Evento del calendario",+ "unavailable": "Questo evento non è nei tuoi calendari su questo dispositivo"+ },"upload": {"title": "Carica audio","using": "Utilizzando {{model}}",diff --git a/src/locales/ja/translation.json b/src/locales/ja/translation.jsonindex 50b8d89b7..4385bda59 100644--- a/src/locales/ja/translation.json+++ b/src/locales/ja/translation.json@@ -2996,6 +2996,25 @@"typeEmail": "メールアドレスを入力して追加...","me": "(自分)"},+ "eventLink": {+ "selectEvent": "カレンダーの予定を選択",+ "searchPlaceholder": "予定を検索…",+ "back": "戻る",+ "removeEvent": "カレンダーの予定を解除",+ "allDay": "終日",+ "noEventsOnDay": "この日に予定はありません",+ "searchOtherDays": "検索すると他の日の予定も見つかります",+ "outsideWindow": "リンクできるのは過去{{days}}日間の予定のみです",+ "noResults": "一致する予定はありません",+ "noCalendar": "予定をリンクするには「連携」でカレンダーを接続してください",+ "loadFailed": "カレンダーの予定を読み込めませんでした",+ "join": "参加",+ "calendar": "カレンダー",+ "openInGoogle": "Google Calendar で開く",+ "openInOutlook": "Outlook で開く",+ "linkedEvent": "カレンダーの予定",+ "unavailable": "この予定はこのデバイスのカレンダーにありません"+ },"context": {"moveToFolder": "フォルダに移動","delete": "削除",diff --git a/src/locales/pt/translation.json b/src/locales/pt/translation.jsonindex e7f0f6659..017e07cc7 100644--- a/src/locales/pt/translation.json+++ b/src/locales/pt/translation.json@@ -3101,6 +3101,25 @@"typeEmail": "Digite um e-mail para adicionar...","me": "(eu)"},+ "eventLink": {+ "selectEvent": "Selecionar evento do calendário",+ "searchPlaceholder": "Pesquisar evento…",+ "back": "Voltar",+ "removeEvent": "Remover evento do calendário",+ "allDay": "Dia inteiro",+ "noEventsOnDay": "Nenhum evento neste dia",+ "searchOtherDays": "Pesquise para encontrar eventos de outros dias",+ "outsideWindow": "Só é possível vincular eventos dos últimos {{days}} dias",+ "noResults": "Nenhum evento correspondente",+ "noCalendar": "Conecte um calendário em Integrações para vincular eventos",+ "loadFailed": "Não foi possível carregar os eventos do calendário",+ "join": "Entrar",+ "calendar": "Calendário",+ "openInGoogle": "Abrir no Google Calendar",+ "openInOutlook": "Abrir no Outlook",+ "linkedEvent": "Evento do calendário",+ "unavailable": "Este evento não está nos seus calendários neste dispositivo"+ },"upload": {"title": "Enviar áudio","using": "Usando {{model}}",diff --git a/src/locales/ru/translation.json b/src/locales/ru/translation.jsonindex 3530211cc..a389d6665 100644--- a/src/locales/ru/translation.json+++ b/src/locales/ru/translation.json@@ -3121,6 +3121,25 @@"typeEmail": "Введите email для добавления...","me": "(я)"},+ "eventLink": {+ "selectEvent": "Выбрать событие календаря",+ "searchPlaceholder": "Найти событие…",+ "back": "Назад",+ "removeEvent": "Убрать событие календаря",+ "allDay": "Весь день",+ "noEventsOnDay": "В этот день нет событий",+ "searchOtherDays": "Воспользуйтесь поиском, чтобы найти события за другие дни",+ "outsideWindow": "Можно связать только события за последние {{days}} дн.",+ "noResults": "Нет подходящих событий",+ "noCalendar": "Подключите календарь в разделе «Интеграции», чтобы связывать события",+ "loadFailed": "Не удалось загрузить события календаря",+ "join": "Присоединиться",+ "calendar": "Календарь",+ "openInGoogle": "Открыть в Google Calendar",+ "openInOutlook": "Открыть в Outlook",+ "linkedEvent": "Событие календаря",+ "unavailable": "Этого события нет в ваших календарях на этом устройстве"+ },"upload": {"title": "Загрузить аудио","using": "Используется {{model}}",diff --git a/src/locales/zh-CN/translation.json b/src/locales/zh-CN/translation.jsonindex 051f97cf1..8d0a89c7d 100644--- a/src/locales/zh-CN/translation.json+++ b/src/locales/zh-CN/translation.json@@ -3101,6 +3101,25 @@"typeEmail": "输入邮箱以添加...","me": "(我)"},+ "eventLink": {+ "selectEvent": "选择日历事件",+ "searchPlaceholder": "搜索事件…",+ "back": "返回",+ "removeEvent": "移除日历事件",+ "allDay": "全天",+ "noEventsOnDay": "这一天没有事件",+ "searchOtherDays": "搜索以查找其他日期的事件",+ "outsideWindow": "只能关联最近 {{days}} 天内的事件",+ "noResults": "没有匹配的事件",+ "noCalendar": "请在“集成”中连接日历以关联事件",+ "loadFailed": "无法加载日历事件",+ "join": "加入",+ "calendar": "日历",+ "openInGoogle": "在 Google Calendar 中打开",+ "openInOutlook": "在 Outlook 中打开",+ "linkedEvent": "日历事件",+ "unavailable": "此设备上的日历中没有这个事件"+ },"upload": {"title": "上传音频","using": "使用 {{model}}",diff --git a/src/locales/zh-TW/translation.json b/src/locales/zh-TW/translation.jsonindex 51ffb3fb6..34039f8d7 100644--- a/src/locales/zh-TW/translation.json+++ b/src/locales/zh-TW/translation.json@@ -3101,6 +3101,25 @@"typeEmail": "輸入電子郵件以新增...","me": "(我)"},+ "eventLink": {+ "selectEvent": "選擇行事曆活動",+ "searchPlaceholder": "搜尋活動…",+ "back": "返回",+ "removeEvent": "移除行事曆活動",+ "allDay": "整天",+ "noEventsOnDay": "這一天沒有活動",+ "searchOtherDays": "搜尋以尋找其他日期的活動",+ "outsideWindow": "只能連結最近 {{days}} 天內的活動",+ "noResults": "沒有相符的活動",+ "noCalendar": "請在「整合」中連結行事曆以連結活動",+ "loadFailed": "無法載入行事曆活動",+ "join": "加入",+ "calendar": "行事曆",+ "openInGoogle": "在 Google Calendar 中開啟",+ "openInOutlook": "在 Outlook 中開啟",+ "linkedEvent": "行事曆活動",+ "unavailable": "此裝置上的行事曆中沒有這個活動"+ },"upload": {"title": "上傳音訊","using": "使用 {{model}}",diff --git a/src/types/calendar.ts b/src/types/calendar.tsindex efa708514..660fa49fa 100644--- a/src/types/calendar.ts+++ b/src/types/calendar.ts@@ -24,10 +24,14 @@ export interface CalendarEvent {organizer_email: string | null;attendees_count: number;attendees: string | null;+ /** The event's page in Google Calendar or Outlook on the web; null for Apple. */+ web_link: string | null;availability_status: CalendarAvailabilityStatus;self_response_status: CalendarResponseStatus | "unknown";}+export type LinkableCalendarEvent = CalendarEvent & { calendar_color: string | null };+export type CalendarAvailabilityStatus = "free" | "tentative" | "busy" | "unavailable" | "unknown";export interface CalendarAvailabilityRequest {@@ -79,6 +83,8 @@ export interface CalendarAttendee {responseStatus: CalendarResponseStatus | null;self: boolean;resource?: boolean;+ /** The calendar event that put this attendee on a note; removing that event removes them. */+ addedByEvent?: string;}export interface Contact {diff --git a/src/types/electron.ts b/src/types/electron.tsindex 277611f55..20eb50657 100644--- a/src/types/electron.ts+++ b/src/types/electron.ts@@ -15,6 +15,8 @@ import type {import type {CalendarAvailabilityRequest,CalendarAvailabilityResult,+ CalendarEvent,+ LinkableCalendarEvent,MicrosoftCalendarAccount,} from "./calendar";import type {@@ -3249,14 +3251,11 @@ declare global {>;gcalGetEvent?: (eventId: string) => Promise<{success: boolean;- event: {- id: string;- summary: string | null;- start_time: string;- end_time: string;- attendees_count: number;- attendees: string | null;- } | null;+ event: CalendarEvent | null;+ }>;+ calendarGetLinkableEvents?: () => Promise<{+ success: boolean;+ events: LinkableCalendarEvent[];}>;// Contactsdiff --git a/src/utils/dateFormatting.ts b/src/utils/dateFormatting.tsindex 3dbcdbff5..4786ccea2 100644--- a/src/utils/dateFormatting.ts+++ b/src/utils/dateFormatting.ts@@ -11,6 +11,28 @@ export function parseEventDate(value: string): Date | null {return Number.isNaN(parsed.getTime()) ? null : parsed;}+export function formatTimeRange(locale: string, startTime: string, endTime: string): string {+ const format = (value: string) =>+ new Date(value).toLocaleTimeString(locale, { hour: "numeric", minute: "2-digit" });+ return `${format(startTime)} – ${format(endTime)}`;+}++/** "Tue, Oct 20 · 14:15 – 15:15", or "Tue, Oct 20 · All day". */+export function formatEventWhen(+ event: { start_time: string; end_time: string; is_all_day: number | boolean },+ locale: string,+ allDayLabel: string+): string {+ const start = parseEventDate(event.start_time);+ const day = start+ ? start.toLocaleDateString(locale, { weekday: "short", month: "short", day: "numeric" })+ : "";+ const time = event.is_all_day+ ? allDayLabel+ : formatTimeRange(locale, event.start_time, event.end_time);+ return day ? `${day} · ${time}` : time;+}+export function normalizeDbDate(dateStr: string): Date {if (typeof dateStr !== "string" || !dateStr.trim()) return new Date(NaN);const trimmed = dateStr.trim();diff --git a/src/utils/noteAttendees.ts b/src/utils/noteAttendees.tsindex b15fc4167..e5fec11aa 100644--- a/src/utils/noteAttendees.ts+++ b/src/utils/noteAttendees.ts@@ -1,3 +1,4 @@+import { isEventGuest } from "../helpers/eventAttendees";import type { CalendarAttendee } from "../types/calendar";import type { NoteAttendee } from "../types/connectors";@@ -20,6 +21,47 @@ export function parseNoteParticipants(raw: string | null | undefined): CalendarA}}+/**+ * The note's attendees plus a linked event's guests: existing people stay+ * first and as they are, guests are matched by email, and rooms and declined+ * guests are left out. Guests this adds are tagged with the event, so removing+ * it takes exactly them off again; the user (`self`, only ever passed on their+ * own note) is not, since they recorded the note whichever event it links.+ */+export function mergeEventAttendees(+ current: CalendarAttendee[],+ incoming: CalendarAttendee[],+ eventId: string+): CalendarAttendee[] {+ const merged = [...current];+ const byEmail = new Map(+ merged.map((attendee) => [attendee.email.toLowerCase().trim(), attendee])+ );+ for (const guest of incoming) {+ if (!isAttendee(guest) || !isEventGuest(guest)) continue;+ const email = guest.email.toLowerCase().trim();+ if (!email || byEmail.has(email)) continue;+ const added: CalendarAttendee = {+ email,+ displayName: guest.displayName || null,+ responseStatus: guest.responseStatus ?? null,+ self: Boolean(guest.self),+ ...(guest.self ? {} : { addedByEvent: eventId }),+ };+ merged.push(added);+ byEmail.set(email, added);+ }+ return merged;+}++/** The attendees left when the event is removed: everyone it didn't add. */+export function removeEventAttendees(+ attendees: CalendarAttendee[],+ eventId: string+): CalendarAttendee[] {+ return attendees.filter((attendee) => attendee.addedByEvent !== eventId);+}+/*** The attendees as the signed-in user sees them. A participant's `self` flag* marks whoever recorded the meeting, so it means "the user" only on thediff --git a/src/utils/noteEventPicker.ts b/src/utils/noteEventPicker.tsnew file mode 100644index 000000000..2d9209b5b--- /dev/null+++ b/src/utils/noteEventPicker.ts@@ -0,0 +1,59 @@+import { CALENDAR_LOOKBACK_MS } from "../helpers/calendarCacheWindow";+import type { CalendarEvent } from "../types/calendar";+import { parseAttendees } from "./calendarAttendees";+import { parseEventDate } from "./dateFormatting";++const MAX_SEARCH_RESULTS = 50;++function startOfLocalDay(day: Date): Date {+ return new Date(day.getFullYear(), day.getMonth(), day.getDate());+}++function nextLocalMidnight(day: Date): Date {+ return new Date(day.getFullYear(), day.getMonth(), day.getDate() + 1);+}++/** Events that overlap the note's local calendar day: all-day ones first, then in their given order. */+export function eventsOnDay<T extends CalendarEvent>(events: T[], day: Date): T[] {+ const dayStart = startOfLocalDay(day).getTime();+ const dayEnd = nextLocalMidnight(day).getTime();+ return events+ .filter((event) => {+ const start = parseEventDate(event.start_time)?.getTime();+ const end = parseEventDate(event.end_time)?.getTime();+ if (start === undefined || end === undefined) return false;+ return start < dayEnd && Math.max(end, start + 1) > dayStart;+ })+ .sort((a, b) => Number(Boolean(b.is_all_day)) - Number(Boolean(a.is_all_day)));+}++/** Title or guest matches across every stored event, nearest to the note first. */+export function searchLinkableEvents<T extends CalendarEvent>(+ events: T[],+ query: string,+ anchor: Date,+ limit = MAX_SEARCH_RESULTS+): T[] {+ const needle = query.trim().toLowerCase();+ if (!needle) return [];+ const anchorMs = anchor.getTime();+ const distance = (event: T) =>+ Math.abs((parseEventDate(event.start_time)?.getTime() ?? Infinity) - anchorMs);+ return events+ .filter(+ (event) =>+ (event.summary ?? "").toLowerCase().includes(needle) ||+ parseAttendees(event).some(+ (guest) =>+ (guest.displayName ?? "").toLowerCase().includes(needle) ||+ (guest.email ?? "").toLowerCase().includes(needle)+ )+ )+ .sort((a, b) => distance(a) - distance(b))+ .slice(0, limit);+}++/** True when the local day starts before the stored history, so some or all of its events aren't stored. */+export function startsBeforeStoredWindow(day: Date, now = Date.now()): boolean {+ return startOfLocalDay(day).getTime() < now - CALENDAR_LOOKBACK_MS;+}diff --git a/src/utils/participants.ts b/src/utils/participants.tsindex 2c02ddfea..1ea24e1a8 100644--- a/src/utils/participants.ts+++ b/src/utils/participants.ts@@ -11,7 +11,10 @@ interface ParticipantSpeakerCountSyncInput {export const resolveParticipantExpectedSpeakerCount = (participants: readonly CalendarAttendee[]): number | null => {- const others = participants.filter((attendee) => attendee?.self !== true).length;+ // Rooms aren't speakers; notes linked before rooms were left out may hold them.+ const others = participants.filter(+ (attendee) => attendee?.self !== true && attendee?.resource !== true+ ).length;return others > 0 ? others + 1 : null;};diff --git a/test/components/fieldDirectionPolicy.test.js b/test/components/fieldDirectionPolicy.test.jsindex 34004e389..b03c92388 100644--- a/test/components/fieldDirectionPolicy.test.js+++ b/test/components/fieldDirectionPolicy.test.js@@ -100,6 +100,7 @@ const EXPECTED_NATIVE_FIELD_DIRECTIONS = {"src/components/notes/AddNotesToFolderDialog.tsx": ["auto"],"src/components/notes/MeetingTranscriptChat.tsx": ["ltr", "auto"],"src/components/notes/NoteEditor.tsx": ["auto", "auto"],+ "src/components/notes/NoteEventPicker.tsx": ["auto"],"src/components/notes/NoteParticipants.tsx": ["auto"],"src/components/notes/NotesOnboarding.tsx": ["auto", "auto", "auto"],"src/components/notes/ShareNoteDialog.tsx": ["auto"],diff --git a/test/components/noteEditorSummaryDeletion.test.js b/test/components/noteEditorSummaryDeletion.test.jsindex f6a12b980..5dbef9d88 100644--- a/test/components/noteEditorSummaryDeletion.test.js+++ b/test/components/noteEditorSummaryDeletion.test.js@@ -867,3 +867,40 @@ for (const failing of ["flush", "base"]) {await unmount();});}++// The note header's date and attendees dropdown in the tree the component returned.+function findElementOfType(tree, type) {+ let found = null;+ walk(tree, (node) => {+ if (!found && node.type === type) found = node;+ });+ return found;+}++test("the note header hands its event link to the dropdown, changeable only by editors", async (t) => {+ const { render, latest, unmount, vite } = await loadNoteEditor(t, "viewer");+ const { default: NoteParticipants } = await vite.ssrLoadModule(+ "/components/notes/NoteParticipants.tsx"+ );+ try {+ const linkedEvent = { id: "evt-1", summary: "Standup" };+ await render(undefined, {+ note: { ...NOTE, cloud_id: "shared-note", calendar_event_id: "evt-1" },+ linkedEvent,+ });+ const viewer = findElementOfType(latest(), NoteParticipants).props;+ assert.equal(viewer.canEdit, false, "a viewer of a shared note can't change the link");+ assert.equal(viewer.ownedByUser, false, "someone else's note");+ assert.equal(viewer.linkedEventId, "evt-1");+ assert.equal(viewer.linkedEvent, linkedEvent);+ assert.equal(viewer.noteCreatedAt, NOTE.created_at);++ await render(undefined, { note: { ...NOTE, calendar_event_id: "" } });+ const owner = findElementOfType(latest(), NoteParticipants).props;+ assert.equal(owner.canEdit, true, "the user's own note is editable");+ assert.equal(owner.ownedByUser, true);+ assert.equal(owner.linkedEventId, null, "an unlinked note's blank id reaches it as no link");+ } finally {+ await unmount();+ }+});diff --git a/test/components/noteEventPicker.test.js b/test/components/noteEventPicker.test.jsnew file mode 100644index 000000000..0d16edc88--- /dev/null+++ b/test/components/noteEventPicker.test.js@@ -0,0 +1,241 @@+const test = require("node:test");+const assert = require("node:assert/strict");+const { createRendererServer } = require("../lib/rendererTestHarness");++// Mounts the real event list in happy-dom. Without an i18next instance, t()+// returns the key, so rows read as notes.eventLink.*.++const DOM_GLOBALS = [+ "document",+ "navigator",+ "Node",+ "Element",+ "HTMLElement",+ "MutationObserver",+ "getComputedStyle",+ "Event",+ "CustomEvent",+ "MouseEvent",+ "PointerEvent",+ "FocusEvent",+ "KeyboardEvent",+ "HTMLInputElement",+];++let happyWindow;++test.before(async () => {+ const { Window } = await import("happy-dom");+ happyWindow = new Window();+ const define = (name, value) =>+ Object.defineProperty(globalThis, name, { value, configurable: true, writable: true });+ define("window", happyWindow);+ for (const name of DOM_GLOBALS) define(name, happyWindow[name]);+ for (const name of ["requestAnimationFrame", "cancelAnimationFrame"]) {+ define(name, happyWindow[name].bind(happyWindow));+ }+});++test.after(async () => {+ await happyWindow.happyDOM.close();+});++async function mount(t, props) {+ globalThis.IS_REACT_ACT_ENVIRONMENT = true;+ const React = require("react");+ const { createRoot } = require("react-dom/client");+ const vite = await createRendererServer(t);+ const mod = await vite.ssrLoadModule("/components/notes/NoteEventPicker.tsx");+ const host = happyWindow.document.createElement("div");+ happyWindow.document.body.appendChild(host);+ const root = createRoot(host);+ t.after(async () => {+ await React.act(async () => root.unmount());+ host.remove();+ });+ const act = (callback) =>+ React.act(async () => {+ await callback();+ await new Promise((resolve) => setTimeout(resolve, 10));+ });+ const calls = { select: [], remove: 0, back: 0 };+ await act(() =>+ root.render(+ React.createElement(mod.default, {+ events: [],+ loadFailed: false,+ calendarConnected: true,+ noteDay: new Date(2026, 9, 20, 13, 45),+ linkedEventId: null,+ onSelect: (event) => calls.select.push(event),+ onRemove: () => {+ calls.remove += 1;+ },+ onBack: () => {+ calls.back += 1;+ },+ ...props,+ })+ )+ );+ return { act, host, calls };+}++const iso = (...parts) => new Date(...parts).toISOString();+const event = (id, summary, start, end) => ({+ id,+ calendar_id: "cal",+ provider: "google",+ summary,+ start_time: start,+ end_time: end,+ is_all_day: 0,+ status: "confirmed",+ attendees: null,+ calendar_color: "#1A73E8",+});+const EVENTS = [+ event("focus", "Focus", iso(2026, 9, 20, 10), iso(2026, 9, 20, 13)),+ event("standup", "Team Standup", iso(2026, 9, 20, 14, 15), iso(2026, 9, 20, 15, 15)),+ event("old", "Planning", iso(2026, 9, 18, 9), iso(2026, 9, 18, 10)),+];++// Booleans and strings only: printing a happy-dom element in a failed assert+// runs the test process out of memory.+const rowTexts = (host) => [...host.querySelectorAll("button")].map((b) => b.textContent.trim());+const rowWith = (host, text) =>+ [...host.querySelectorAll("button")].find((b) => b.textContent.includes(text));+const searchInput = (host) =>+ host.querySelector('input[placeholder="notes.eventLink.searchPlaceholder"]');+const type = (host, text) => {+ const input = searchInput(host);+ Object.getOwnPropertyDescriptor(happyWindow.HTMLInputElement.prototype, "value").set.call(+ input,+ text+ );+ input.dispatchEvent(new happyWindow.Event("input", { bubbles: true }));+};++test("opens on the note's day and filters by search", async (t) => {+ const { act, host } = await mount(t, { events: EVENTS });++ assert.equal(!!rowWith(host, "Focus"), true);+ assert.equal(!!rowWith(host, "Team Standup"), true);+ assert.equal(!!rowWith(host, "Planning"), false);++ await act(() => type(host, "stand"));+ assert.equal(!!rowWith(host, "Focus"), false);+ assert.match(rowWith(host, "Team Standup").textContent, / · /);++ await act(() => type(host, "plan"));+ assert.equal(!!rowWith(host, "Planning"), true, "search reaches other stored days");+});++test("marks the linked event and offers removal first", async (t) => {+ const { act, host, calls } = await mount(t, { events: EVENTS, linkedEventId: "standup" });++ const rows = rowTexts(host).filter((text) => text !== "");+ assert.equal(rows[0], "notes.eventLink.removeEvent");+ assert.equal(rowWith(host, "Team Standup").getAttribute("aria-current"), "true");+ assert.equal(rowWith(host, "Focus").hasAttribute("aria-current"), false);+ assert.equal(!!rowWith(host, "Team Standup").querySelector("svg[aria-hidden='true']"), true);+ assert.equal(rowWith(host, "Focus").querySelectorAll("svg").length, 0);++ await act(() => rowWith(host, "notes.eventLink.removeEvent").click());+ assert.equal(calls.remove, 1);+});++test("selecting an event hands it back", async (t) => {+ const { act, host, calls } = await mount(t, { events: EVENTS });++ await act(() => rowWith(host, "Focus").click());++ assert.deepEqual(+ calls.select.map((selected) => selected.id),+ ["focus"]+ );+});++test("shows the right empty state", async (t) => {+ const message = (host) => host.querySelector("p")?.textContent ?? null;+ const cases = [+ [{ calendarConnected: false }, "notes.eventLink.noCalendar"],+ [{ loadFailed: true }, "notes.eventLink.loadFailed"],+ [{ noteDay: new Date(Date.now() - 10 * 86_400_000) }, "notes.eventLink.outsideWindow"],+ [{ noteDay: new Date() }, "notes.eventLink.noEventsOnDay"],+ ];+ for (const [props, expected] of cases) {+ const { host } = await mount(t, props);+ assert.equal(message(host), expected);+ host.remove();+ }++ const { act, host } = await mount(t, { events: EVENTS });+ await act(() => type(host, "zzz"));+ assert.equal(message(host), "notes.eventLink.noResults");+});++test("shows a loading state until the events arrive", async (t) => {+ const { host } = await mount(t, { events: null });++ assert.equal(host.querySelector("[role='status']")?.textContent.trim(), "common.loading");+ assert.equal(host.querySelector("p"), null, "no empty-state message while loading");++ for (const props of [{ loadFailed: true }, { calendarConnected: false }]) {+ const other = await mount(t, { events: null, ...props });+ assert.equal(other.host.querySelector("[role='status']"), null);+ other.host.remove();+ }+});++test("the search box has an accessible name", async (t) => {+ const { host } = await mount(t, { events: EVENTS });++ assert.equal(searchInput(host).getAttribute("aria-label"), "notes.eventLink.searchPlaceholder");+});++const press = (target, key) =>+ target.dispatchEvent(new happyWindow.KeyboardEvent("keydown", { key, bubbles: true }));++test("Enter in a search picks the first match, and does nothing without one", async (t) => {+ const { act, host, calls } = await mount(t, { events: EVENTS });++ await act(() => press(searchInput(host), "Enter"));+ assert.deepEqual(calls.select, [], "an empty search box never links the day's first event");++ await act(() => type(host, "zzz"));+ await act(() => press(searchInput(host), "Enter"));+ assert.deepEqual(calls.select, []);++ await act(() => type(host, "stand"));+ await act(() => press(searchInput(host), "Enter"));+ assert.deepEqual(+ calls.select.map((selected) => selected.id),+ ["standup"]+ );+});++test("arrow keys move between the search box and the rows", async (t) => {+ const { act, host } = await mount(t, { events: EVENTS, linkedEventId: "standup" });+ const focused = () => happyWindow.document.activeElement?.textContent?.trim() ?? "";+ searchInput(host).focus();++ await act(() => press(happyWindow.document.activeElement, "ArrowDown"));+ assert.equal(focused(), "notes.eventLink.removeEvent");+ await act(() => press(happyWindow.document.activeElement, "ArrowDown"));+ assert.match(focused(), /^Focus/);+ await act(() => press(happyWindow.document.activeElement, "ArrowDown"));+ await act(() => press(happyWindow.document.activeElement, "ArrowDown"));+ assert.match(focused(), /^Team Standup/, "stops at the last row");++ for (let i = 0; i < 4; i += 1) {+ await act(() => press(happyWindow.document.activeElement, "ArrowUp"));+ }+ assert.equal(happyWindow.document.activeElement === searchInput(host), true, "stops at the box");+});++test("titles keep their own direction", async (t) => {+ const { host } = await mount(t, { events: EVENTS });++ assert.equal(rowWith(host, "Focus").querySelector("span[dir]")?.getAttribute("dir"), "auto");+});diff --git a/test/components/noteParticipantsEventLink.test.js b/test/components/noteParticipantsEventLink.test.jsnew file mode 100644index 000000000..b26a6ce02--- /dev/null+++ b/test/components/noteParticipantsEventLink.test.js@@ -0,0 +1,451 @@+const test = require("node:test");+const assert = require("node:assert/strict");+const { createRendererServer } = require("../lib/rendererTestHarness");++// Opens the real note-header dropdown in happy-dom. Without an i18next+// instance, t() returns the key, so rows read as notes.eventLink.*.++const DOM_GLOBALS = [+ "document",+ "navigator",+ "Node",+ "Element",+ "HTMLElement",+ "MutationObserver",+ "getComputedStyle",+ "Event",+ "CustomEvent",+ "MouseEvent",+ "PointerEvent",+ "FocusEvent",+ "KeyboardEvent",+ "HTMLInputElement",+ "ResizeObserver",+ "DOMRect",+];++const MOCKS = {+ "/stores/settingsStore": `+ export function useSettingsStore(selector) {+ return selector({ gcalConnected: true, mcalConnected: false, appleCalendarConnected: false });+ }+ `,+ "/stores/meetingRecordingStore": `+ export function syncSessionExpectedCountFromParticipants() {}+ `,+};++let happyWindow;++test.before(async () => {+ const { Window } = await import("happy-dom");+ happyWindow = new Window();+ const define = (name, value) =>+ Object.defineProperty(globalThis, name, { value, configurable: true, writable: true });+ define("window", happyWindow);+ for (const name of DOM_GLOBALS) define(name, happyWindow[name]);+ for (const name of ["requestAnimationFrame", "cancelAnimationFrame"]) {+ define(name, happyWindow[name].bind(happyWindow));+ }+});++test.after(async () => {+ await happyWindow.happyDOM.close();+});++const dana = { email: "[email protected]", displayName: "Dana", responseStatus: null, self: false };+const frank = { email: "[email protected]", displayName: "Frank", responseStatus: null, self: false };+const eve = { email: "[email protected]", displayName: "Eve", responseStatus: "accepted", self: false };+// The note's created_at in the SQLite UTC form, for 13:45 local time on the+// Standup's day, so the note's day matches in every time zone.+const NOTE_CREATED_AT = new Date(2026, 9, 20, 13, 45).toISOString().replace("T", " ").slice(0, 19);+const STANDUP = {+ id: "evt-standup",+ calendar_id: "cal",+ provider: "google",+ summary: "Team Standup",+ start_time: new Date(2026, 9, 20, 14, 15).toISOString(),+ end_time: new Date(2026, 9, 20, 15, 15).toISOString(),+ is_all_day: 0,+ status: "confirmed",+ hangout_link: "https://meet.google.com/abc-defg-hij",+ conference_data: null,+ attendees: JSON.stringify([dana, eve]),+ calendar_color: "#1A73E8",+};++async function mount(t, props, { events = [STANDUP] } = {}) {+ globalThis.IS_REACT_ACT_ENVIRONMENT = true;+ const calls = { updateNote: [], openExternal: [], joinCalendarMeeting: 0 };+ happyWindow.electronAPI = {+ searchContacts: async () => ({ success: true, contacts: [] }),+ upsertContact: () => {},+ updateNote: (...args) => calls.updateNote.push(args),+ openExternal: (url) => calls.openExternal.push(url),+ joinCalendarMeeting: () => {+ calls.joinCalendarMeeting += 1;+ },+ calendarGetLinkableEvents: async () => ({ success: true, events }),+ };+ const React = require("react");+ const { createRoot } = require("react-dom/client");+ const vite = await createRendererServer(t, { mockModules: MOCKS });+ const mod = await vite.ssrLoadModule("/components/notes/NoteParticipants.tsx");+ const host = happyWindow.document.createElement("div");+ happyWindow.document.body.appendChild(host);+ const root = createRoot(host);+ t.after(async () => {+ await React.act(async () => root.unmount());+ host.remove();+ });+ const act = (callback) =>+ React.act(async () => {+ await callback();+ await new Promise((resolve) => setTimeout(resolve, 30));+ });+ const render = (overrides) =>+ act(() =>+ root.render(+ React.createElement(mod.default, {+ noteId: 7,+ participants: [dana],+ dateLabel: "Oct 20",+ dateTitle: "Oct 20, 2026 · 1:45 PM",+ noteCreatedAt: NOTE_CREATED_AT,+ linkedEventId: null,+ linkedEvent: null,+ canEdit: true,+ ownedByUser: true,+ ...props,+ ...overrides,+ })+ )+ );+ await render();+ const trigger = host.querySelector("button");+ await act(() => trigger.click());+ return { act, trigger, calls, render };+}++const savedParticipants = (call) => JSON.parse(call[1].participants);++// Strings and booleans only: printing a happy-dom element in a failed assert+// runs the test process out of memory.+const buttonWith = (text) =>+ [...happyWindow.document.querySelectorAll("button")].find((b) => b.textContent.includes(text));+const bodyText = () => happyWindow.document.body.textContent;+// This string has an inline fallback, which t() returns without an instance.+const attendeeInput = () =>+ !!happyWindow.document.querySelector('input[placeholder="Add attendees..."]');++test("an editor links an event and its guests merge in one write", async (t) => {+ const { act, calls } = await mount(t, { participants: [dana, frank] });++ await act(() => buttonWith("notes.eventLink.selectEvent").click());+ await act(() => buttonWith("Team Standup").click());++ assert.equal(calls.updateNote.length, 1);+ assert.equal(calls.updateNote[0][0], 7);+ assert.equal(calls.updateNote[0][1].calendar_event_id, "evt-standup");+ assert.deepEqual(+ savedParticipants(calls.updateNote[0]),+ [dana, frank, { ...eve, addedByEvent: "evt-standup" }],+ "existing attendees stay, in order, and only new guests are added, tagged with the event"+ );+ assert.equal(attendeeInput(), true, "back on the attendees view");+ assert.equal(bodyText().includes("Team Standup"), true);+});++// This user's copy of the event marks them `self`.+const me = { email: "[email protected]", displayName: "Me", responseStatus: "accepted", self: true };+const owner = { email: "[email protected]", displayName: "Owner", responseStatus: null, self: true };+const STANDUP_WITH_ME = { ...STANDUP, attendees: JSON.stringify([owner, me, dana]) };++test("linking on the user's own note marks them from their calendar", async (t) => {+ const { act, calls } = await mount(t, { participants: [] }, { events: [STANDUP_WITH_ME] });++ await act(() => buttonWith("notes.eventLink.selectEvent").click());+ await act(() => buttonWith("Team Standup").click());++ assert.equal(savedParticipants(calls.updateNote[0]).find((p) => p.email === me.email).self, true);+});++test("linking on a teammate's note never marks the user as the one who recorded it", async (t) => {+ const { act, calls } = await mount(+ t,+ { participants: [owner, { ...me, self: false }], ownedByUser: false },+ { events: [{ ...STANDUP_WITH_ME, attendees: JSON.stringify([me, dana]) }] }+ );++ await act(() => buttonWith("notes.eventLink.selectEvent").click());+ await act(() => buttonWith("Team Standup").click());++ assert.deepEqual(+ savedParticipants(calls.updateNote[0]),+ [owner, { ...me, self: false }, { ...dana, addedByEvent: "evt-standup" }],+ "the owner stays the only self, whether this user was on the note already or not"+ );+});++test("on a teammate's note a newly added user is an ordinary attendee", async (t) => {+ const { act, calls } = await mount(+ t,+ { participants: [owner], ownedByUser: false },+ { events: [{ ...STANDUP_WITH_ME, attendees: JSON.stringify([me]) }] }+ );++ await act(() => buttonWith("notes.eventLink.selectEvent").click());+ await act(() => buttonWith("Team Standup").click());++ assert.deepEqual(savedParticipants(calls.updateNote[0]), [+ owner,+ { ...me, self: false, addedByEvent: "evt-standup" },+ ]);+});++test("on the user's own note, linking and removing leaves earlier rows as they were and keeps the user", async (t) => {+ const namelessDana = { ...dana, displayName: null };+ const room = {+ email: "[email protected]",+ displayName: "Room 4",+ responseStatus: null,+ self: false,+ resource: true,+ };+ const { act, calls } = await mount(+ t,+ { participants: [namelessDana] },+ { events: [{ ...STANDUP, attendees: JSON.stringify([me, dana, room]) }] }+ );++ await act(() => buttonWith("notes.eventLink.selectEvent").click());+ await act(() => buttonWith("Team Standup").click());+ await act(() => buttonWith("Team Standup").click());+ await act(() => buttonWith("notes.eventLink.removeEvent").click());++ assert.deepEqual(+ savedParticipants(calls.updateNote[0]),+ [namelessDana, me],+ "the room stays out and Dana's row isn't filled in from the event"+ );+ assert.deepEqual(+ savedParticipants(calls.updateNote[1]),+ [namelessDana, me],+ "removing the event takes off nothing it didn't add, and the user recorded the note"+ );+});++test("removing an event you just linked takes off its guests and keeps everyone else", async (t) => {+ const { act, calls } = await mount(t, { participants: [frank] });++ await act(() => buttonWith("notes.eventLink.selectEvent").click());+ await act(() => buttonWith("Team Standup").click());+ await act(() => buttonWith("Team Standup").click());+ await act(() => buttonWith("notes.eventLink.removeEvent").click());++ assert.equal(calls.updateNote.length, 2);+ assert.deepEqual(calls.updateNote[1][1], {+ participants: JSON.stringify([frank]),+ calendar_event_id: "",+ });+ assert.equal(/\bEve\b/.test(bodyText()), false, "the guest the event added is gone");+ assert.equal(bodyText().includes("Frank"), true);+});++test("switching to another event swaps the first event's guests for the new one's", async (t) => {+ const gail = { email: "[email protected]", displayName: "Gail", responseStatus: null, self: false };+ const focus = {+ ...STANDUP,+ id: "evt-focus",+ summary: "Focus",+ hangout_link: null,+ attendees: JSON.stringify([gail]),+ };+ const { act, calls } = await mount(+ t,+ {+ participants: [frank, { ...gail, addedByEvent: "evt-focus" }],+ linkedEventId: "evt-focus",+ linkedEvent: focus,+ },+ { events: [focus, STANDUP] }+ );++ await act(() => buttonWith("Focus").click());+ await act(() => buttonWith("Team Standup").click());++ assert.equal(calls.updateNote.length, 1);+ assert.equal(calls.updateNote[0][1].calendar_event_id, "evt-standup");+ assert.deepEqual(savedParticipants(calls.updateNote[0]), [+ frank,+ { ...dana, addedByEvent: "evt-standup" },+ { ...eve, addedByEvent: "evt-standup" },+ ]);+});++test("picking the already-linked event changes nothing", async (t) => {+ const { act, calls } = await mount(t, {+ participants: [frank],+ linkedEventId: "evt-standup",+ linkedEvent: STANDUP,+ });++ await act(() => buttonWith("Team Standup").click());+ await act(() => buttonWith("Team Standup").click());++ assert.deepEqual(calls.updateNote, [], "guests the user removed don't come back");+ assert.equal(attendeeInput(), true);+});++test("the event list closes when edit rights turn out to be view-only", async (t) => {+ const { act, render, calls } = await mount(t);+ await act(() => buttonWith("notes.eventLink.selectEvent").click());+ assert.equal(attendeeInput(), false, "the event list is open");++ await render({ canEdit: false });++ assert.equal(attendeeInput(), true, "back on the attendees view");+ assert.equal(!!buttonWith("Team Standup"), false);+ assert.deepEqual(calls.updateNote, []);+});++test("Join opens the meeting link and never starts a recording", async (t) => {+ const { act, calls } = await mount(t, { linkedEventId: "evt-standup", linkedEvent: STANDUP });++ await act(() => buttonWith("notes.eventLink.join").click());++ assert.deepEqual(calls.openExternal, ["https://meet.google.com/abc-defg-hij"]);+ assert.equal(calls.joinCalendarMeeting, 0);+});++test("no Join without a meeting link", async (t) => {+ const plain = { ...STANDUP, hangout_link: null };+ await mount(t, { linkedEventId: "evt-standup", linkedEvent: plain }, { events: [plain] });++ assert.equal(bodyText().includes("Team Standup"), true);+ assert.equal(!!buttonWith("notes.eventLink.join"), false);+});++test("removing the event writes a blank link and keeps attendees it didn't add", async (t) => {+ const { act, calls } = await mount(t, {+ participants: [dana, frank, { ...eve, addedByEvent: "evt-standup" }],+ linkedEventId: "evt-standup",+ linkedEvent: STANDUP,+ });++ await act(() => buttonWith("Team Standup").click());+ await act(() => buttonWith("notes.eventLink.removeEvent").click());++ assert.deepEqual(calls.updateNote, [+ [7, { participants: JSON.stringify([dana, frank]), calendar_event_id: "" }],+ ]);+ assert.equal(bodyText().includes("notes.eventLink.selectEvent"), true);+ assert.equal(bodyText().includes("Dana"), true, "a guest who was on the note before stays");+ assert.equal(/\bEve\b/.test(bodyText()), false, "the guest the event added is gone");+});++test("a viewer sees the linked event but cannot change it", async (t) => {+ const { act, calls } = await mount(t, {+ canEdit: false,+ linkedEventId: "evt-standup",+ linkedEvent: STANDUP,+ });++ assert.equal(bodyText().includes("Team Standup"), true);+ assert.equal(!!buttonWith("Team Standup"), false, "the event row is not a button");+ await act(() => buttonWith("notes.eventLink.join").click());+ assert.deepEqual(calls.openExternal, ["https://meet.google.com/abc-defg-hij"]);+});++test("a viewer of an unlinked note sees no event row", async (t) => {+ await mount(t, { canEdit: false });++ assert.equal(bodyText().includes("notes.eventLink.selectEvent"), false);+});++test("an unresolved link shows the fallback, not a title", async (t) => {+ const { trigger } = await mount(t, {+ linkedEventId: '{"eventId":"e1"}',+ linkedEvent: null,+ });++ assert.equal(trigger.textContent.includes("Oct 20"), true);+ assert.equal(bodyText().includes("notes.eventLink.unavailable"), true);+ assert.equal(!!buttonWith("notes.eventLink.join"), false);+});++test("the capsule keeps the date while linked", async (t) => {+ const { trigger } = await mount(t, { linkedEventId: "evt-standup", linkedEvent: STANDUP });++ assert.equal(trigger.textContent.includes("Oct 20"), true);+ assert.equal(trigger.textContent.includes("Team Standup"), false);+});++test("a Google event opens in Google Calendar, beside Join", async (t) => {+ const linked = { ...STANDUP, web_link: "https://www.google.com/calendar/event?eid=abc" };+ const { act, calls } = await mount(+ t,+ { linkedEventId: linked.id, linkedEvent: linked },+ { events: [linked] }+ );++ const button = buttonWith("notes.eventLink.calendar");+ assert.equal(button.getAttribute("aria-label"), null, "the visible label is its name");+ assert.equal(button.getAttribute("title"), "notes.eventLink.openInGoogle");+ await act(() => button.click());+ assert.deepEqual(calls.openExternal, ["https://www.google.com/calendar/event?eid=abc"]);+});++test("an Outlook event without a meeting link offers Open in Outlook", async (t) => {+ const linked = {+ ...STANDUP,+ provider: "microsoft",+ hangout_link: null,+ web_link: "https://outlook.office365.com/owa/?itemid=abc",+ };+ await mount(t, { linkedEventId: linked.id, linkedEvent: linked }, { events: [linked] });++ assert.equal(!!buttonWith("notes.eventLink.openInOutlook"), true);+ assert.equal(!!buttonWith("notes.eventLink.join"), false);+});++test("an Apple event has no calendar button", async (t) => {+ const linked = { ...STANDUP, provider: "apple", web_link: "https://example.com/x" };+ await mount(t, { linkedEventId: linked.id, linkedEvent: linked }, { events: [linked] });++ assert.equal(!!buttonWith("notes.eventLink.calendar"), false);+ assert.equal(!!buttonWith("notes.eventLink.openInGoogle"), false);+});++test("Escape in the event list goes back to the attendees without closing the dropdown", async (t) => {+ const { act } = await mount(t);+ await act(() => buttonWith("notes.eventLink.selectEvent").click());+ const search = happyWindow.document.querySelector(+ 'input[placeholder="notes.eventLink.searchPlaceholder"]'+ );+ assert.equal(!!search, true);++ await act(() =>+ search.dispatchEvent(+ new happyWindow.KeyboardEvent("keydown", { key: "Escape", bubbles: true, cancelable: true })+ )+ );++ assert.equal(attendeeInput(), true, "the dropdown stays open on the attendees view");+ assert.equal(bodyText().includes("notes.eventLink.selectEvent"), true);+});++test("Escape on the attendees view still closes the dropdown", async (t) => {+ const { act } = await mount(t);+ assert.equal(attendeeInput(), true);++ await act(() =>+ happyWindow.document+ .querySelector('input[placeholder="Add attendees..."]')+ .dispatchEvent(+ new happyWindow.KeyboardEvent("keydown", { key: "Escape", bubbles: true, cancelable: true })+ )+ );++ assert.equal(attendeeInput(), false);+});diff --git a/test/helpers/appleCalendarManager.test.js b/test/helpers/appleCalendarManager.test.jsindex d5847e357..d9b97b4f8 100644--- a/test/helpers/appleCalendarManager.test.js+++ b/test/helpers/appleCalendarManager.test.js@@ -5,9 +5,10 @@ const Module = require("node:module");const managerModulePath = require.resolve("../../src/helpers/appleCalendarManager.js");const originalLoad = Module._load;-function loadManager() {+function loadManager(mocks = {}) {delete require.cache[managerModulePath];Module._load = function loadWithElectronMock(request, parent, isMain) {+ if (request in mocks) return mocks[request];if (request === "electron") {return { BrowserWindow: { getAllWindows: () => [] } };}@@ -194,3 +195,35 @@ test("Apple RSVP ignores another attendee's decline and follows current-user chaassert.equal(mapped.self_response_status, response);}});++test("the helper is launched with the stored lookback", () => {+ const { EventEmitter } = require("node:events");+ const launches = [];+ const AppleCalendarManager = loadManager({+ electron: { app: { isPackaged: true }, BrowserWindow: { getAllWindows: () => [] } },+ child_process: {+ spawn: (command, args) => {+ launches.push({ command, args });+ const child = new EventEmitter();+ child.stdout = new EventEmitter();+ child.stderr = new EventEmitter();+ child.stdin = { write() {} };+ child.kill = () => {};+ return child;+ },+ },+ "./binaryResolver": { resolveBundledBinary: () => "/bundle/macos-calendar-listener" },+ });+ const manager = new AppleCalendarManager({}, {});++ assert.equal(manager._spawnHelper(false), true);+ assert.equal(manager._spawnHelper(true), true);++ assert.deepEqual(launches, [+ { command: "/bundle/macos-calendar-listener", args: ["--lookback-seconds", "259200"] },+ {+ command: "/bundle/macos-calendar-listener",+ args: ["--lookback-seconds", "259200", "--request"],+ },+ ]);+});diff --git a/test/helpers/calendarCacheWindow.test.js b/test/helpers/calendarCacheWindow.test.jsnew file mode 100644index 000000000..6071d93b2--- /dev/null+++ b/test/helpers/calendarCacheWindow.test.js@@ -0,0 +1,14 @@+const test = require("node:test");+const assert = require("node:assert/strict");++const {+ CALENDAR_LOOKBACK_DAYS,+ CALENDAR_LOOKBACK_MS,+} = require("../../src/helpers/calendarCacheWindow.js");+const { MAX_BUFFER_MINUTES } = require("../../src/helpers/calendarAvailability.js");++test("the stored lookback never shrinks availability coverage", () => {+ assert.equal(CALENDAR_LOOKBACK_DAYS, 3);+ // The widest lookback before this window: Google's buffer plus all-day padding.+ assert.ok(CALENDAR_LOOKBACK_MS >= MAX_BUFFER_MINUTES * 60_000 + 48 * 3_600_000);+});diff --git a/test/helpers/calendarDatabase.test.js b/test/helpers/calendarDatabase.test.jsindex 8e1190927..b4bec8392 100644--- a/test/helpers/calendarDatabase.test.js+++ b/test/helpers/calendarDatabase.test.js@@ -249,7 +249,7 @@ test("reopening a pre-v2 database clears microsoft sync tokens once", (t) => {assert.equal(calendar.sync_token, null);assert.equal(calendar.sync_token_expires_at, null);// Reopening runs every later migration too.- assert.equal(reopened.db.pragma("user_version", { simple: true }), 4);+ assert.equal(reopened.db.pragma("user_version", { simple: true }), 5);reopened.db.close();});@@ -304,16 +304,16 @@ test("Google shared RSVP repair is scoped, preserves notes, and runs once", (t)for (const id of ["primary", "[email protected]", "ms-event", "apple-event"]) {assert.equal(repaired.getCalendarEventById(id).self_response_status, "declined");}- assert.equal(repaired.db.pragma("user_version", { simple: true }), 4);+ // Reopening also runs the v5 lookback reset, which clears every REST token.+ assert.equal(repaired.db.pragma("user_version", { simple: true }), 5);const calendars = repaired.getGoogleCalendars();assert.equal(calendars.find((c) => c.id === "shared").sync_token, null);assert.equal(calendars.find((c) => c.id === "shared").sync_token_expires_at, null);- assert.equal(calendars.find((c) => c.id === "primary").sync_token, "old-google");- assert.equal(calendars.find((c) => c.id === "[email protected]").sync_token, "old-google");+ assert.equal(calendars.find((c) => c.id === "primary").sync_token, null);assert.equal(repaired.db.prepare("SELECT sync_token FROM microsoft_calendars WHERE id='ms'").get().sync_token,- "old-ms"+ null);assert.equal(repaired.db.prepare("SELECT calendar_event_id FROM notes WHERE id=?").get(note.id)@@ -389,3 +389,332 @@ test("declined REST suppresses its stale Apple mirror", (t) => {assert.deepEqual(db.getUpcomingEvents(120), []);assert.deepEqual(db.getActiveEvents(), []);});++test("reopening a pre-v5 database clears REST sync tokens once", (t) => {+ const db = createDb(t);+ if (!db) return;+ insertCalendar(db, "google", "google-calendar");+ insertCalendar(db, "microsoft", "ms-calendar");+ const seedTokens = (target) => {+ target.updateCalendarSyncToken("google-calendar", "sync-token", Date.now() + 1000000);+ target.updateMicrosoftCalendarSyncToken("ms-calendar", "delta-link", Date.now() + 1000000);+ };+ const tokens = (target) => [+ target.db.prepare("SELECT sync_token FROM google_calendars").get().sync_token,+ target.db.prepare("SELECT sync_token FROM microsoft_calendars").get().sync_token,+ ];+ seedTokens(db);+ db.db.pragma("user_version = 4");+ db.db.close();++ const reopened = new DatabaseManager();+ assert.deepEqual(tokens(reopened), [null, null]);+ seedTokens(reopened);+ reopened.db.close();++ const again = new DatabaseManager();+ assert.deepEqual(tokens(again), ["sync-token", "delta-link"]);+ again.db.close();+});++test("events from two and three days ago never surface as active, upcoming or available", (t) => {+ const db = createDb(t);+ if (!db) return;+ insertCalendar(db, "google", "google-calendar");+ const now = Date.now();+ const twoDaysAgo = new Date(now - 2 * 86_400_000);+ const localDate = (date) =>+ `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")}`;+ db.upsertCalendarEvents([+ restEvent("google", "google-calendar", "past-timed", {+ start_time: new Date(now - 50 * 3_600_000).toISOString(),+ end_time: new Date(now - 49 * 3_600_000).toISOString(),+ }),+ restEvent("google", "google-calendar", "past-all-day", {+ start_time: localDate(twoDaysAgo),+ end_time: localDate(new Date(twoDaysAgo.getTime() + 86_400_000)),+ is_all_day: true,+ }),+ ]);+ const pastIds = new Set(["past-timed", "past-all-day"]);+ const ids = (events) => events.map((event) => event.id).filter((id) => pastIds.has(id));++ assert.deepEqual(ids(db.getActiveEvents()), []);+ assert.deepEqual(ids(db.getUpcomingEvents(1440)), []);+ assert.deepEqual(+ ids(+ db.getCalendarEventsInRange(+ new Date(now).toISOString(),+ new Date(now + 86_400_000).toISOString(),+ ["google"]+ )+ ),+ []+ );+ db.db.close();+});++function insertAppleCalendar(db, id, color = null) {+ db.db+ .prepare("INSERT INTO apple_calendars (id, title, color) VALUES (?, ?, ?)")+ .run(id, id, color);+}++test("linkable events cover selected calendars and skip cancelled and declined ones", (t) => {+ const db = createDb(t);+ if (!db) return;+ insertCalendar(db, "google", "google-calendar");+ insertCalendar(db, "google", "hidden-google", 0);+ insertCalendar(db, "microsoft", "ms-calendar");+ db.upsertCalendarEvents([+ restEvent("google", "google-calendar", "tentative", {+ start_time: "2026-07-22T12:00:00Z",+ end_time: "2026-07-22T13:00:00Z",+ status: "tentative",+ }),+ restEvent("google", "google-calendar", "confirmed"),+ restEvent("microsoft", "ms-calendar", "cancelled", { status: "cancelled" }),+ restEvent("google", "google-calendar", "declined", { self_response_status: "declined" }),+ restEvent("google", "hidden-google", "hidden"),+ ]);++ assert.deepEqual(+ db.getLinkableCalendarEvents().map((event) => event.id),+ ["confirmed", "tentative"]+ );+ db.db.close();+});++test("a declined REST event keeps its Apple mirror out of the linkable list", (t) => {+ const db = createDb(t);+ if (!db) return;+ insertCalendar(db, "google", "google-calendar");+ insertAppleCalendar(db, "apple-calendar");+ db.upsertCalendarEvents([+ restEvent("google", "google-calendar", "declined", {+ summary: "Standup",+ self_response_status: "declined",+ }),+ appleEvent("mirror", {+ summary: "Standup",+ start_time: "2026-07-22T10:00:00Z",+ end_time: "2026-07-22T11:00:00Z",+ }),+ ]);++ assert.deepEqual(db.getLinkableCalendarEvents(), []);+ db.db.close();+});++test("linkable events carry their calendar's colour only when it is a hex colour", (t) => {+ const db = createDb(t);+ if (!db) return;+ insertCalendar(db, "google", "google-calendar");+ insertCalendar(db, "microsoft", "ms-calendar");+ insertAppleCalendar(db, "apple-calendar", "#FF0000");+ db.db.prepare("UPDATE google_calendars SET background_color = '#1A73E8'").run();+ db.db.prepare("UPDATE microsoft_calendars SET background_color = 'auto'").run();+ db.upsertCalendarEvents([+ restEvent("google", "google-calendar", "google-event"),+ restEvent("microsoft", "ms-calendar", "ms-event", { summary: "Other" }),+ appleEvent("apple-event"),+ ]);++ const colors = Object.fromEntries(+ db.getLinkableCalendarEvents().map((event) => [event.id, event.calendar_color])+ );+ assert.deepEqual(colors, {+ "apple-event": "#FF0000",+ "google-event": "#1A73E8",+ "ms-event": null,+ });+ db.db.close();+});++test("linkable events include all-day rows and recent past events", (t) => {+ const db = createDb(t);+ if (!db) return;+ insertCalendar(db, "google", "google-calendar");+ const twoDaysAgo = Date.now() - 2 * 86_400_000;+ db.upsertCalendarEvents([+ restEvent("google", "google-calendar", "all-day", {+ start_time: "2026-07-22",+ end_time: "2026-07-23",+ is_all_day: true,+ }),+ restEvent("google", "google-calendar", "two-days-ago", {+ start_time: new Date(twoDaysAgo).toISOString(),+ end_time: new Date(twoDaysAgo + 3_600_000).toISOString(),+ }),+ ]);++ assert.deepEqual(+ db+ .getLinkableCalendarEvents()+ .map((event) => event.id)+ .sort(),+ ["all-day", "two-days-ago"]+ );+ db.db.close();+});++test("linkable events leave out old rows kept only for the notes that link them", (t) => {+ const db = createDb(t);+ if (!db) return;+ insertCalendar(db, "google", "google-calendar");+ const at = (daysAgo) => new Date(Date.now() - daysAgo * 86_400_000).toISOString();+ db.upsertCalendarEvents([+ restEvent("google", "google-calendar", "recent", { start_time: at(2), end_time: at(1.9) }),+ restEvent("google", "google-calendar", "old-linked", {+ start_time: at(30),+ end_time: at(29.9),+ }),+ ]);+ const note = db.saveNote("Old meeting", "", "meeting").note;+ db.updateNote(note.id, { calendar_event_id: "old-linked" });++ assert.deepEqual(+ db.getLinkableCalendarEvents({ endsAfter: at(4) }).map((event) => event.id),+ ["recent"]+ );+ assert.equal(db.getCalendarEventById("old-linked")?.id, "old-linked", "the row itself stays");+ db.db.close();+});++test("web_link round-trips through upsertCalendarEvents", (t) => {+ const db = createDb(t);+ if (!db) return;+ db.upsertCalendarEvents([+ restEvent("google", "google-calendar", "linked", { web_link: "https://calendar.google.com/x" }),+ appleEvent("apple"),+ ]);++ assert.equal(db.getCalendarEventById("linked").web_link, "https://calendar.google.com/x");+ assert.equal(db.getCalendarEventById("apple").web_link, null);+ db.db.close();+});++// SQLite reads local dates through libc, which follows process.env.TZ, so a+// non-UTC zone exercises what CI (TZ=UTC) would otherwise hide.+function useTimeZone(t, zone) {+ const original = process.env.TZ;+ process.env.TZ = zone;+ t.after(() => {+ if (original === undefined) delete process.env.TZ;+ else process.env.TZ = original;+ });+}++// The Apple helper writes an all-day start as local midnight in UTC form.+const appleAllDayInstant = (year, month, day) =>+ new Date(year, month, day).toISOString().replace(".000Z", "Z");++test("an all-day event and its Calendar.app copy collapse outside UTC", (t) => {+ useTimeZone(t, "America/Los_Angeles");+ const db = createDb(t);+ if (!db) return;+ insertCalendar(db, "google", "google-calendar");+ insertAppleCalendar(db, "apple-calendar");+ db.upsertCalendarEvents([+ restEvent("google", "google-calendar", "google-offsite", {+ summary: "Offsite",+ start_time: "2026-10-20",+ end_time: "2026-10-21",+ is_all_day: true,+ }),+ appleEvent("apple-offsite", {+ summary: "Offsite",+ start_time: appleAllDayInstant(2026, 9, 20),+ end_time: appleAllDayInstant(2026, 9, 21),+ is_all_day: true,+ }),+ appleEvent("apple-holiday", {+ summary: "Holiday",+ start_time: appleAllDayInstant(2026, 9, 20),+ end_time: appleAllDayInstant(2026, 9, 21),+ is_all_day: true,+ }),+ ]);++ assert.deepEqual(+ db+ .getLinkableCalendarEvents()+ .map((event) => event.id)+ .sort(),+ ["apple-holiday", "google-offsite"]+ );+ db.db.close();+});++test("a declined all-day event keeps its Calendar.app copy out outside UTC", (t) => {+ useTimeZone(t, "Asia/Kolkata");+ const db = createDb(t);+ if (!db) return;+ insertCalendar(db, "google", "google-calendar");+ insertAppleCalendar(db, "apple-calendar");+ db.upsertCalendarEvents([+ restEvent("google", "google-calendar", "google-offsite", {+ summary: "Offsite",+ start_time: "2026-10-20",+ end_time: "2026-10-21",+ is_all_day: true,+ self_response_status: "declined",+ }),+ appleEvent("apple-offsite", {+ summary: "Offsite",+ start_time: appleAllDayInstant(2026, 9, 20),+ end_time: appleAllDayInstant(2026, 9, 21),+ is_all_day: true,+ }),+ ]);++ assert.deepEqual(db.getLinkableCalendarEvents(), []);+ db.db.close();+});++test("all-day mirrors pair whichever end EventKit reports, and a longer namesake stays", (t) => {+ useTimeZone(t, "America/Los_Angeles");+ const db = createDb(t);+ if (!db) return;+ insertCalendar(db, "google", "google-calendar");+ insertAppleCalendar(db, "apple-calendar");+ const lastSecond = (year, month, day) =>+ new Date(year, month, day, 23, 59, 59).toISOString().replace(".000Z", "Z");+ db.upsertCalendarEvents([+ restEvent("google", "google-calendar", "google-offsite", {+ summary: "Offsite",+ start_time: "2026-10-20",+ end_time: "2026-10-21",+ is_all_day: true,+ }),+ // The mirror ends on the event's last second rather than the next midnight.+ appleEvent("apple-offsite", {+ summary: "Offsite",+ start_time: appleAllDayInstant(2026, 9, 20),+ end_time: lastSecond(2026, 9, 20),+ is_all_day: true,+ }),+ restEvent("google", "google-calendar", "google-vacation", {+ summary: "Vacation",+ start_time: "2026-10-20",+ end_time: "2026-10-21",+ is_all_day: true,+ }),+ // A separate, longer event on the user's own calendar, not a mirror.+ appleEvent("apple-vacation-4d", {+ summary: "Vacation",+ start_time: appleAllDayInstant(2026, 9, 20),+ end_time: appleAllDayInstant(2026, 9, 24),+ is_all_day: true,+ }),+ ]);++ assert.deepEqual(+ db+ .getLinkableCalendarEvents()+ .map((event) => event.id)+ .sort(),+ ["apple-vacation-4d", "google-offsite", "google-vacation"]+ );+ db.db.close();+});diff --git a/test/helpers/connectorActionsDatabase.test.js b/test/helpers/connectorActionsDatabase.test.jsindex d2010d742..df8dc2f52 100644--- a/test/helpers/connectorActionsDatabase.test.js+++ b/test/helpers/connectorActionsDatabase.test.js@@ -657,6 +657,6 @@ test("upgrading to user_version 3 forces a full calendar re-sync", (t) => {.all();assert.deepEqual(tokens, [{ sync_token: null }, { sync_token: null }]);// Reopening also applies subsequent migrations.- assert.equal(reopened.db.pragma("user_version", { simple: true }), 4);+ assert.equal(reopened.db.pragma("user_version", { simple: true }), 5);reopened.db.close();});diff --git a/test/helpers/eventAttendees.test.js b/test/helpers/eventAttendees.test.jsnew file mode 100644index 000000000..fe980fe60--- /dev/null+++ b/test/helpers/eventAttendees.test.js@@ -0,0 +1,45 @@+const test = require("node:test");+const assert = require("node:assert/strict");++const { tagEventAttendeesJson } = require("../../src/helpers/eventAttendees.js");++test("tagEventAttendeesJson tags every guest with the event that added them, but not the user", () => {+ const attendees = [+ { email: "[email protected]", displayName: "Dana", responseStatus: "accepted", self: false },+ { email: "[email protected]", displayName: "Me", responseStatus: "accepted", self: true },+ ];++ assert.deepEqual(+ JSON.parse(tagEventAttendeesJson(JSON.stringify(attendees), "evt-1")),+ [{ ...attendees[0], addedByEvent: "evt-1" }, attendees[1]],+ "the user recorded the note, so removing the event keeps their own row"+ );+});++test("tagEventAttendeesJson leaves rooms and declined guests off the note, never the user", () => {+ const dana = { email: "[email protected]", displayName: "Dana", responseStatus: null, self: false };+ const attendees = [+ dana,+ {+ email: "[email protected]",+ displayName: "Room 4",+ self: false,+ resource: true,+ },+ { email: "[email protected]", displayName: "Kim", responseStatus: "declined", self: false },+ // The user records the note even when their RSVP says no.+ { email: "[email protected]", displayName: "Me", responseStatus: "declined", self: true },+ ];++ assert.deepEqual(JSON.parse(tagEventAttendeesJson(JSON.stringify(attendees), "evt-1")), [+ { ...dana, addedByEvent: "evt-1" },+ attendees[3],+ ]);+});++test("tagEventAttendeesJson leaves missing or unreadable attendees as they are", () => {+ assert.equal(tagEventAttendeesJson(null, "evt-1"), null);+ assert.equal(tagEventAttendeesJson("[]", null), "[]");+ assert.equal(tagEventAttendeesJson("not json", "evt-1"), "not json");+ assert.equal(tagEventAttendeesJson('{"email":"[email protected]"}', "evt-1"), '{"email":"[email protected]"}');+});diff --git a/test/helpers/googleCalendarManager.test.js b/test/helpers/googleCalendarManager.test.jsindex 06f4663bd..39a9ac9af 100644--- a/test/helpers/googleCalendarManager.test.js+++ b/test/helpers/googleCalendarManager.test.js@@ -58,6 +58,7 @@ test("_syncCalendar fetches all pages when nextPageToken is returned", async (){id: "event-1",summary: "Event Page 1",+ htmlLink: "https://www.google.com/calendar/event?eid=abc",start: { dateTime: "2026-08-12T10:00:00Z" },transparency: "transparent",attendees: [{ self: true, responseStatus: "declined" }],@@ -95,6 +96,12 @@ test("_syncCalendar fetches all pages when nextPageToken is returned", async ()assert.equal(upsertedEvents[0].id, "event-1");assert.equal(upsertedEvents[0].availability_status, "free");assert.equal(upsertedEvents[0].self_response_status, "declined");+ assert.equal(+ upsertedEvents[0].web_link,+ "https://www.google.com/calendar/event?eid=abc&authuser=test%40example.com",+ "the link opens under the calendar's own account, not the browser's default one"+ );+ assert.equal(upsertedEvents[1].web_link, null);assert.equal(upsertedEvents[1].id, "event-2");assert.equal(savedSyncToken, "sync-token-final", "should save nextSyncToken from final page");assert.deepEqual(@@ -378,7 +385,7 @@ test("_syncCalendar trusts self as the user only on the account's primary calend);});-async function syncGoogleResponse(calendar, attendees) {+async function syncGoogleRow(calendar, attendees) {const rows = [];const GoogleCalendarManager = loadManagerModule();const manager = new GoogleCalendarManager(@@ -405,7 +412,11 @@ async function syncGoogleResponse(calendar, attendees) {],});await manager._syncCalendar(calendar);- return rows[0].self_response_status;+ return rows[0];+}++async function syncGoogleResponse(calendar, attendees) {+ return (await syncGoogleRow(calendar, attendees)).self_response_status;}test("Google RSVP on a shared calendar uses the connected account's attendee", async () => {@@ -427,3 +438,56 @@ test("Google RSVP on a shared calendar uses the connected account's attendee", a"unknown");});++test("a stored attendee is self only when it is the user, on shared calendars too", async () => {+ const shared = { id: "[email protected]", account_email: "[email protected]" };+ const colleague = { email: "[email protected]", self: true };+ const flags = async (calendar, attendees) =>+ JSON.parse((await syncGoogleRow(calendar, attendees)).attendees).map((a) => [a.email, a.self]);++ assert.deepEqual(await flags(shared, [colleague, { email: "[email protected]" }]), [+ ["[email protected]", false],+ ["[email protected]", true],+ ]);+ assert.deepEqual(+ await flags({ id: "[email protected]", account_email: "[email protected]" }, [+ { email: "[email protected]", self: true },+ { email: "[email protected]" },+ ]),+ [+ ["[email protected]", true],+ ["[email protected]", false],+ ],+ "on the user's own calendar Google's flag still marks them, under an alias too"+ );+});++test("_syncCalendar full sync looks back CALENDAR_LOOKBACK_DAYS", async () => {+ const GoogleCalendarManager = loadManagerModule();+ const { CALENDAR_LOOKBACK_MS } = require("../../src/helpers/calendarCacheWindow.js");+ const databaseManager = {+ getGoogleAccounts: () => [],+ removeStaleCalendarEvents: () => {},+ upsertCalendarEvents: () => {},+ removeCalendarEvents: () => {},+ updateCalendarSyncToken: () => {},+ syncCalendarContacts: () => {},+ };+ const manager = new GoogleCalendarManager(databaseManager, null, {+ scheduleNextMeeting: () => {},+ reset: () => {},+ });+ const paths = [];+ manager._apiGet = async (path) => {+ paths.push(path);+ return { items: [], nextSyncToken: "token" };+ };++ await manager._syncCalendar({ id: "cal-1", account_email: "[email protected]", is_primary: 1 });++ const params = new URL(paths[0], "https://www.googleapis.com").searchParams;+ const now = Date.now();+ assert.ok(Math.abs(Date.parse(params.get("timeMin")) - (now - CALENDAR_LOOKBACK_MS)) < 5_000);+ const lookaheadMs = (33 * 24 + 48) * 3_600_000;+ assert.ok(Math.abs(Date.parse(params.get("timeMax")) - (now + lookaheadMs)) < 5_000);+});diff --git a/test/helpers/meetingDetectionEngine.test.js b/test/helpers/meetingDetectionEngine.test.jsindex 854de2656..ea5553301 100644--- a/test/helpers/meetingDetectionEngine.test.js+++ b/test/helpers/meetingDetectionEngine.test.js@@ -200,6 +200,37 @@ test("joining a calendar meeting resumes the user's own note for the event", asyassert.equal(meetingNavigations[0].folderId, 3);});+test("a joined meeting's new note tags the event's guests, keeps the user and skips rooms and declines", async () => {+ const { engine } = createEngine();+ const db = createJoinDatabase(null);+ const updates = [];+ const me = { email: "[email protected]", displayName: "Me", self: true };+ db.databaseManager.getCalendarEventById = (id) => ({+ id,+ summary: "Weekly sync",+ attendees: JSON.stringify([+ { email: "[email protected]", displayName: "Dana", self: false },+ me,+ { email: "[email protected]", displayName: "Room 4", self: false, resource: true },+ { email: "[email protected]", displayName: "Kim", responseStatus: "declined", self: false },+ ]),+ });+ db.databaseManager.updateNote = (id, update) => {+ updates.push(update);+ return { note: { id, ...update } };+ };+ engine.databaseManager = db.databaseManager;++ await engine.joinCalendarMeeting("event-1");++ assert.equal(updates.length, 1);+ assert.equal(updates[0].calendar_event_id, "event-1");+ assert.deepEqual(JSON.parse(updates[0].participants), [+ { email: "[email protected]", displayName: "Dana", self: false, addedByEvent: "event-1" },+ me,+ ]);+});+test("joining a calendar meeting with no note of the user's own creates one", async () => {const { engine, meetingNavigations } = createEngine();const db = createJoinDatabase(null);@@ -377,6 +408,37 @@ test("notification Start saves directly in selected folder and duplicate clicksassert.equal(c.db.getNotes().length, 1);});+test("notification Start's new note tags the event's attendees", async (t) => {+ const c = ownedNotification(t);+ if (!c) return;+ const dana = { email: "[email protected]", displayName: "Dana", self: false };+ const me = { email: "[email protected]", displayName: "Me", self: true };+ const room = { email: "[email protected]", displayName: "Room 4", self: false, resource: true };+ c.db.upsertCalendarEvents([+ {+ id: "event",+ calendar_id: "test-calendar",+ provider: "google",+ summary: "Weekly",+ start_time: "2026-07-22T10:00:00Z",+ end_time: "2026-07-22T11:00:00Z",+ is_all_day: false,+ status: "confirmed",+ attendees: JSON.stringify([dana, me, room]),+ },+ ]);++ assert.equal((await c.respond()).success, true);++ const note = c.db.getNote(c.meetingNavigations[0].noteId);+ assert.equal(note.calendar_event_id, "event");+ assert.deepEqual(+ JSON.parse(note.participants),+ [{ ...dana, addedByEvent: "event" }, me],+ "the user's own row survives removing the event, and the room never joins"+ );+});+test("a linked root note requires current acknowledgment and is never moved or copied", async (t) => {const c = ownedNotification(t);if (!c) return;diff --git a/test/helpers/meetingSpeakerReconcile.test.js b/test/helpers/meetingSpeakerReconcile.test.jsindex 442b9fc79..f179f7155 100644--- a/test/helpers/meetingSpeakerReconcile.test.js+++ b/test/helpers/meetingSpeakerReconcile.test.js@@ -162,6 +162,14 @@ test("roster changes refresh an auto-derived speaker config", () => {assert.deepEqual(broadcasts[0].payload, { enabled: true, expectedCount: 4 });});+test("a room on the note doesn't raise the speaker config", () => {+ const { fakeThis } = refreshConfig(false, {+ attendees: [...THREE_ATTENDEES, { email: "[email protected]", resource: true }],+ });++ assert.equal(fakeThis.activeMeetingSpeakerConfig.expectedCount, 4);+});+test("an explicit stepper count is never overridden by roster changes", () => {const { fakeThis, broadcasts } = refreshConfig(true);diff --git a/test/helpers/microsoftCalendarManager.test.js b/test/helpers/microsoftCalendarManager.test.jsindex 25b8f4983..d8cae59f1 100644--- a/test/helpers/microsoftCalendarManager.test.js+++ b/test/helpers/microsoftCalendarManager.test.js@@ -79,6 +79,7 @@ test("_mapEvent maps a Graph event to the shared calendar_events shape", () => {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" },@@ -98,6 +99,7 @@ test("_mapEvent maps a Graph event to the shared calendar_events shape", () => {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);@@ -198,6 +200,7 @@ test("_syncCalendar backfills stripped recurring occurrences from their series mid: "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: [@@ -213,12 +216,20 @@ test("_syncCalendar backfills stripped recurring occurrences from their series massert.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");@@ -478,3 +489,17 @@ test("a stripped occurrence keeps details but applies explicit RSVP after masterawait 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);+});diff --git a/test/helpers/noteCloudUpsertGuard.test.js b/test/helpers/noteCloudUpsertGuard.test.jsindex 42bbcdb05..9a1e1e13f 100644--- a/test/helpers/noteCloudUpsertGuard.test.js+++ b/test/helpers/noteCloudUpsertGuard.test.js@@ -245,3 +245,66 @@ test("upsertNoteFromCloud: a cloud copy from an API without template ids keeps t"a cloud copy that carries a template id brings its own");});++test("upsertNoteFromCloud: a cloud blank calendar_event_id clears the local link", (t) => {+ const db = createDb(t);+ if (!db) return;+ const before = seedEditedMeetingNote(db);+ db.updateNote(before.id, { calendar_event_id: "cal-ev-1" });++ db.upsertNoteFromCloud({ ...emptyCloudShell(before), calendar_event_id: "" }, null);++ assert.equal(db.getNote(before.id).calendar_event_id, "");+});++test("upsertNoteFromCloud: a cloud null calendar_event_id keeps the local link", (t) => {+ const db = createDb(t);+ if (!db) return;+ const before = seedEditedMeetingNote(db);+ db.updateNote(before.id, { calendar_event_id: "cal-ev-1" });++ db.upsertNoteFromCloud({ ...emptyCloudShell(before), calendar_event_id: null }, null);++ assert.equal(db.getNote(before.id).calendar_event_id, "cal-ev-1");+});++test("linking or unlinking an event retires an outstanding assistant Undo", (t) => {+ const db = createDb(t);+ if (!db) return;+ for (const [initial, next] of [+ [null, "evt-1"],+ ["evt-1", ""],+ ]) {+ const note = db.saveNote("Meeting", "", "meeting").note;+ if (initial) db.updateNote(note.id, { calendar_event_id: initial });+ db.updateNote(+ note.id,+ { title: "Assistant title" },+ { undoable: true, expected: db.getNote(note.id) }+ );+ assert.equal(db.getNoteUndos().length, 1);++ db.updateNote(note.id, { calendar_event_id: next });++ assert.equal(db.getNoteUndos().length, 0);+ }+});++test("clearing a linked note's event with null stores the synced blank", (t) => {+ const db = createDb(t);+ if (!db) return;+ const linked = db.saveNote("Meeting", "", "meeting").note;+ db.updateNote(linked.id, { calendar_event_id: "evt-1" });+ const unlinked = db.saveNote("Notes", "", "personal").note;++ // The local API and other non-UI callers may unlink with null.+ db.updateNote(linked.id, { calendar_event_id: null });+ db.updateNote(unlinked.id, { calendar_event_id: null });++ assert.equal(db.getNote(linked.id).calendar_event_id, "");+ assert.equal(db.getNote(unlinked.id).calendar_event_id, null, "a never-linked note stays NULL");++ // A null arriving while that unlink still waits to sync keeps it.+ db.updateNote(linked.id, { calendar_event_id: null });+ assert.equal(db.getNote(linked.id).calendar_event_id, "");+});diff --git a/test/helpers/notesOwnerDatabase.test.js b/test/helpers/notesOwnerDatabase.test.jsindex a9b1a0eec..a416f30b6 100644--- a/test/helpers/notesOwnerDatabase.test.js+++ b/test/helpers/notesOwnerDatabase.test.js@@ -250,6 +250,20 @@ test("getOwnNoteByCalendarEventId never resumes a teammate's note for the same edb.db.close();});+test("getOwnNoteByCalendarEventId never matches a note whose event link was removed", (t) => {+ const db = createDb(t);+ if (!db) return;+ const note = db.saveNote("Weekly sync", "", "meeting").note;+ db.updateNote(note.id, { calendar_event_id: "event-1" });+ db.updateNote(note.id, { calendar_event_id: "" });++ assert.equal(db.getNote(note.id).calendar_event_id, "");+ assert.equal(db.getOwnNoteByCalendarEventId(""), null);+ assert.equal(db.getOwnNoteByCalendarEventId(null), null);++ db.db.close();+});+test("getOwnNoteByCalendarEventId resumes notes the user owns, newest first", (t) => {const db = createDb(t);if (!db) return;diff --git a/test/helpers/participants.test.js b/test/helpers/participants.test.jsindex f3087b687..d23631e8c 100644--- a/test/helpers/participants.test.js+++ b/test/helpers/participants.test.js@@ -30,6 +30,22 @@ test("participant rosters derive total speakers from non-self attendees plus theassert.equal(resolveParticipantExpectedSpeakerCount([]), null);});+test("a room on the note is never counted as a speaker", async () => {+ const { resolveParticipantExpectedSpeakerCount, resolveExpectedSpeakerCount } = await load();+ const room = { email: "[email protected]", self: false, resource: true };+ const participants = [+ { email: "[email protected]", self: true },+ { email: "[email protected]" },+ ];++ assert.equal(resolveParticipantExpectedSpeakerCount([...participants, room]), 2);+ assert.equal(resolveParticipantExpectedSpeakerCount([room]), null);+ assert.equal(+ resolveExpectedSpeakerCount({ participants: JSON.stringify([...participants, room]) }),+ 2+ );+});+test("active participant changes synchronize the session count before a manual override", async () => {const { resolveParticipantSpeakerCountSync } = await load();diff --git a/test/helpers/syncServiceNotes.test.js b/test/helpers/syncServiceNotes.test.jsindex 879ba3dda..02152c447 100644--- a/test/helpers/syncServiceNotes.test.js+++ b/test/helpers/syncServiceNotes.test.js@@ -717,3 +717,37 @@ test("an AUTH_EXPIRED envelope surfaces as a 401 CloudApiError and nothing is maassert.equal(cloud.note(cloudRow.id).deleted_at, null);assertNoContentRegression(before, snapshotNotes(db), cloud.notes());});++test("an unlinked calendar event reaches the cloud as a blank and clears a stale copy on pull", async (t) => {+ const ctx = await setup(t);+ if (!ctx) return;+ const { db, cloud, service } = ctx;++ const note = db.saveNote("Weekly sync", "", "meeting").note;+ db.updateNote(note.id, { calendar_event_id: "evt-1" });+ await service.syncAll(true);+ const cloudId = db.getNote(note.id).cloud_id;+ assert.equal(cloud.note(cloudId).calendar_event_id, "evt-1");++ db.updateNote(note.id, { calendar_event_id: "" });+ await service.syncAll(true);+ assert.equal(cloud.note(cloudId).calendar_event_id, "");++ // Model a second device that still holds the link, then a newer edit from+ // elsewhere that does not mention the event.+ updateNote(db, note.id, {+ calendar_event_id: "evt-1",+ sync_status: "synced",+ updated_at: LOCAL_EARLY,+ });+ await cloud.request({+ method: "PATCH",+ path: "/api/notes/update",+ body: { id: cloudId, title: "Renamed elsewhere" },+ });+ await service.syncAll(true);++ const local = db.getNote(note.id);+ assert.equal(local.title, "Renamed elsewhere");+ assert.equal(local.calendar_event_id, "");+});diff --git a/test/services/noteAttendees.test.js b/test/services/noteAttendees.test.jsindex 09bbf4573..5a102a7a5 100644--- a/test/services/noteAttendees.test.js+++ b/test/services/noteAttendees.test.js@@ -88,3 +88,102 @@ test("other context loses the attendee fence's tag name, whatever brackets surro);assert.equal(withoutAttendeesFence("Kickoff"), "Kickoff");});++test("mergeEventAttendees appends new guests after the existing ones, tagged with the event", async () => {+ const { mergeEventAttendees } = await load();+ const dana = { email: "[email protected]", displayName: "Dana", responseStatus: null, self: false };+ const eve = { email: "[email protected]", displayName: "Eve", responseStatus: "accepted", self: false };++ assert.deepEqual(+ mergeEventAttendees([dana], [eve, { ...dana, email: "[email protected]" }], "evt-1"),+ [+ dana,+ {+ email: "[email protected]",+ displayName: "Eve",+ responseStatus: "accepted",+ self: false,+ addedByEvent: "evt-1",+ },+ ],+ "only the guest the event added carries its tag"+ );+});++test("mergeEventAttendees leaves an attendee already on the note as it was", async () => {+ const { mergeEventAttendees, removeEventAttendees } = await load();+ const existing = { email: "[email protected]", displayName: null, responseStatus: null, self: false };++ const linked = mergeEventAttendees(+ [existing],+ [{ email: "[email protected] ", displayName: "Me", responseStatus: "accepted", self: true }],+ "evt-1"+ );++ assert.deepEqual(linked, [existing], "nothing the event knows is written onto the row");+ assert.deepEqual(+ removeEventAttendees(linked, "evt-1"),+ [existing],+ "so removing the event leaves the row exactly as it was before linking"+ );+});++test("mergeEventAttendees leaves rooms and declined guests out", async () => {+ const { mergeEventAttendees } = await load();+ const eve = { email: "[email protected]", displayName: "Eve", responseStatus: "accepted", self: false };++ assert.deepEqual(+ mergeEventAttendees(+ [],+ [+ eve,+ {+ email: "[email protected]",+ displayName: "Room 4",+ responseStatus: null,+ self: false,+ resource: true,+ },+ { email: "[email protected]", displayName: "Kim", responseStatus: "declined", self: false },+ ],+ "evt-1"+ ),+ [{ ...eve, addedByEvent: "evt-1" }]+ );+});++test("the user added by linking on their own note stays when the event is removed", async () => {+ const { mergeEventAttendees, removeEventAttendees } = await load();+ const me = { email: "[email protected]", displayName: "Me", responseStatus: "accepted", self: true };+ const eve = { email: "[email protected]", displayName: "Eve", responseStatus: "accepted", self: false };++ const linked = mergeEventAttendees([], [me, eve], "evt-1");++ assert.deepEqual(linked, [me, { ...eve, addedByEvent: "evt-1" }]);+ assert.deepEqual(removeEventAttendees(linked, "evt-1"), [me]);+});++test("mergeEventAttendees ignores guests without an email", async () => {+ const { mergeEventAttendees } = await load();++ assert.deepEqual(mergeEventAttendees([], [{ email: null, displayName: "Room" }], "evt-1"), []);+});++test("mergeEventAttendees leaves the attendees alone for an event without guests", async () => {+ const { mergeEventAttendees } = await load();+ const current = [{ email: "[email protected]", displayName: "Dana", responseStatus: null, self: false }];++ assert.deepEqual(mergeEventAttendees(current, [], "evt-1"), current);+});++test("removeEventAttendees takes off only the attendees that event added", async () => {+ const { removeEventAttendees } = await load();+ const manual = { email: "[email protected]", displayName: "Dana", responseStatus: null, self: false };+ const fromEvent = { ...manual, email: "[email protected]", addedByEvent: "evt-1" };+ const fromOtherEvent = { ...manual, email: "[email protected]", addedByEvent: "evt-2" };++ assert.deepEqual(removeEventAttendees([manual, fromEvent, fromOtherEvent], "evt-1"), [+ manual,+ fromOtherEvent,+ ]);+});diff --git a/test/utils/dateFormatting.test.js b/test/utils/dateFormatting.test.jsindex 7fe15543c..b94c8bd47 100644--- a/test/utils/dateFormatting.test.js+++ b/test/utils/dateFormatting.test.js@@ -13,3 +13,22 @@ test("future timestamps use a calendar date instead of the now label", async (t)formatShortDate(futureTimestamp));});++test("formatEventWhen labels all-day events and shows a time range otherwise", async () => {+ const { formatEventWhen, formatTimeRange } = await load();+ assert.equal(+ formatEventWhen(+ { start_time: "2026-10-20", end_time: "2026-10-21", is_all_day: 1 },+ "en-US",+ "All day"+ ),+ "Tue, Oct 20 · All day"+ );++ const start = new Date(2026, 9, 20, 14, 15).toISOString();+ const end = new Date(2026, 9, 20, 15, 15).toISOString();+ assert.equal(+ formatEventWhen({ start_time: start, end_time: end, is_all_day: 0 }, "en-US", "All day"),+ `Tue, Oct 20 · ${formatTimeRange("en-US", start, end)}`+ );+});diff --git a/test/utils/noteEventPicker.test.js b/test/utils/noteEventPicker.test.jsnew file mode 100644index 000000000..241f387f1--- /dev/null+++ b/test/utils/noteEventPicker.test.js@@ -0,0 +1,116 @@+const test = require("node:test");+const assert = require("node:assert/strict");++// A zone with daylight saving, so local-day boundaries differ from UTC ones+// even on CI (TZ=UTC). Each test file runs in its own process.+process.env.TZ = "America/Los_Angeles";++const load = () => import("../../src/utils/noteEventPicker.ts");++const iso = (...parts) => new Date(...parts).toISOString();++function event(id, start, end, overrides = {}) {+ return {+ id,+ calendar_id: "cal",+ provider: "google",+ summary: id,+ start_time: start,+ end_time: end,+ is_all_day: 0,+ status: "confirmed",+ attendees: null,+ ...overrides,+ };+}++test("eventsOnDay keeps every event that overlaps the local day, all-day ones first", async () => {+ const { eventsOnDay } = await load();+ const events = [+ event("overnight-in", iso(2026, 9, 19, 23), iso(2026, 9, 20, 1)),+ event("morning", iso(2026, 9, 20, 10), iso(2026, 9, 20, 13)),+ event("late", iso(2026, 9, 20, 23, 30), iso(2026, 9, 21, 0, 30)),+ event("all-day", "2026-10-20", "2026-10-21", { is_all_day: 1 }),+ event("conference", "2026-10-19", "2026-10-22", { is_all_day: 1 }),+ event("yesterday-all-day", "2026-10-19", "2026-10-20", { is_all_day: 1 }),+ event("next-all-day", "2026-10-21", "2026-10-22", { is_all_day: 1 }),+ event("yesterday", iso(2026, 9, 19, 8), iso(2026, 9, 19, 9)),+ event("ends-at-midnight", iso(2026, 9, 19, 22), iso(2026, 9, 20, 0)),+ ];++ assert.deepEqual(+ eventsOnDay(events, new Date(2026, 9, 20, 13, 45)).map((e) => e.id),+ ["all-day", "conference", "overnight-in", "morning", "late"]+ );+});++test("eventsOnDay uses calendar midnights on a 25-hour daylight-saving day", async () => {+ const { eventsOnDay } = await load();+ // US daylight saving ends on Sunday Nov 1, 2026: that local day lasts 25 hours.+ const lateEvening = event("late-evening", iso(2026, 10, 1, 23, 30), iso(2026, 10, 1, 23, 45));++ assert.deepEqual(+ eventsOnDay([lateEvening], new Date(2026, 10, 1, 9)).map((e) => e.id),+ ["late-evening"]+ );+ assert.deepEqual(eventsOnDay([lateEvening], new Date(2026, 10, 2, 9)), []);+});++test("searchLinkableEvents matches titles and guests, nearest to the note first", async () => {+ const { searchLinkableEvents } = await load();+ const anchor = new Date(2026, 9, 20, 12);+ const events = [+ event("standup-later", iso(2026, 9, 23, 9), iso(2026, 9, 23, 10), { summary: "Team Standup" }),+ event("standup-yesterday", iso(2026, 9, 19, 9), iso(2026, 9, 19, 10), {+ summary: "Team Standup",+ }),+ event("one-on-one", iso(2026, 9, 19, 9), iso(2026, 9, 19, 10), {+ summary: "1:1",+ attendees: JSON.stringify([{ email: "[email protected]", displayName: "Evelyn" }]),+ }),+ ];++ assert.deepEqual(+ searchLinkableEvents(events, " team ", anchor).map((e) => e.id),+ ["standup-yesterday", "standup-later"]+ );+ assert.deepEqual(+ searchLinkableEvents(events, "EVELYN", anchor).map((e) => e.id),+ ["one-on-one"],+ "guest display names are searched"+ );+ assert.deepEqual(+ searchLinkableEvents(events, "e.v@x", anchor).map((e) => e.id),+ ["one-on-one"],+ "guest emails are searched"+ );+ assert.deepEqual(searchLinkableEvents(events, " ", anchor), []);+});++test("searchLinkableEvents returns the 50 events nearest the note", async () => {+ const { searchLinkableEvents } = await load();+ const anchor = new Date(2026, 9, 20, 12);+ // Input order is oldest first, so a cap applied before sorting would return+ // the 50 furthest from the note.+ const events = Array.from({ length: 80 }, (_, i) =>+ event(`e${i}`, iso(2026, 9, 20, 12 - 80 + i), iso(2026, 9, 20, 13 - 80 + i), {+ summary: "Sync",+ })+ );++ const results = searchLinkableEvents(events, "sync", anchor);+ assert.equal(results.length, 50);+ assert.deepEqual(results.map((e) => e.id).slice(0, 2), ["e79", "e78"]);+ assert.equal(results.at(-1).id, "e30");+});++test("startsBeforeStoredWindow flags any day the stored history doesn't fully cover", async () => {+ const { startsBeforeStoredWindow } = await load();+ // The stored history reaches back to Oct 17 12:00.+ const now = new Date(2026, 9, 20, 12).getTime();++ assert.equal(startsBeforeStoredWindow(new Date(2026, 9, 16, 9), now), true);+ assert.equal(startsBeforeStoredWindow(new Date(2026, 9, 17, 18), now), true);+ assert.equal(startsBeforeStoredWindow(new Date(2026, 9, 18, 9), now), false);+ assert.equal(startsBeforeStoredWindow(new Date(2026, 9, 20, 9), now), false);+});