Skip to content

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

feat: choose a meeting folder from the notification (#2511)

Joshua6478f1cb47ee
diff --git a/preload.js b/preload.js
index 186b95edc..b2dfc7f79 100644
--- a/preload.js
+++ b/preload.js
@@ -1379,10 +1379,32 @@ contextBridge.exposeInMainWorld("electronAPI", {
"meeting-auto-end-requested",
(callback) => (_event, data) => callback(data)
),
+ getMeetingNotificationDestination: () =>
+ ipcRenderer.invoke("get-meeting-notification-destination"),
+ selectMeetingNotificationFolder: (folder) =>
+ ipcRenderer.invoke("select-meeting-notification-folder", folder),
+ createMeetingNotificationFolder: (request) =>
+ ipcRenderer.invoke("create-meeting-notification-folder", request),
+ onMeetingNotificationFolderCreated: registerListener(
+ "meeting-notification-folder-created",
+ (callback) => (_event, data) => callback(data)
+ ),
+ setMeetingNotificationSurface: (state) =>
+ ipcRenderer.invoke("set-meeting-notification-surface", state),
+ onMeetingNotificationSurfaceClosed: registerListener(
+ "meeting-notification-surface-closed",
+ (callback) => (_event, data) => callback(data)
+ ),
+ onMeetingNotificationSurfaceResized: registerListener(
+ "meeting-notification-surface-resized",
+ (callback) => (_event, data) => callback(data)
+ ),
getMeetingNotificationData: () => ipcRenderer.invoke("get-meeting-notification-data"),
meetingNotificationReady: () => ipcRenderer.invoke("meeting-notification-ready"),
- meetingNotificationRespond: (detectionId, action) =>
- ipcRenderer.invoke("meeting-notification-respond", detectionId, action),
+ meetingNotificationRespond: (detectionId, action, options) =>
+ ipcRenderer.invoke("meeting-notification-respond", detectionId, action, options),
+ confirmMeetingNoteNavigation: (navigationId, status) =>
+ ipcRenderer.invoke("confirm-meeting-note-navigation", navigationId, status),
joinCalendarMeeting: (eventId) => ipcRenderer.invoke("join-calendar-meeting", eventId),
startManualMeeting: () => ipcRenderer.invoke("start-manual-meeting"),
getPendingMeetingNoteNavigation: () => ipcRenderer.invoke("get-pending-meeting-note-navigation"),
diff --git a/src/components/ControlPanel.tsx b/src/components/ControlPanel.tsx
index 197c72460..35453ca7c 100644
--- a/src/components/ControlPanel.tsx
+++ b/src/components/ControlPanel.tsx
@@ -57,6 +57,7 @@ import {
DEFAULT_INTEGRATIONS_SECTION,
type IntegrationsSection,
} from "./integrations/integrationsSections";
+import { navigateMeetingNotification } from "./meetingNotificationNavigation";
import MeetingRecordingMount from "./MeetingRecordingMount";
import MeetingRecordingPill from "./notes/MeetingRecordingPill";
import NewNoteMenu from "./notes/NewNoteMenu";
@@ -64,7 +65,7 @@ import NewNoteMenu from "./notes/NewNoteMenu";
import { getCachedPlatform } from "../utils/platform";
import { isAccessibilitySkipped } from "../utils/permissions";
import { useGpuBannerAvailability } from "../hooks/useGpuBannerAvailability";
-import { useCreateNote } from "../hooks/useCreateNote";
+import { startRecordingForNote, useCreateNote } from "../hooks/useCreateNote";
import { useSignInCloudNudge } from "../hooks/useSignInCloudNudge";
import {
setActiveNoteId,
@@ -72,6 +73,7 @@ import {
navigateToContainer,
useActiveNoteId,
initializeNotes,
+ subscribeMeetingNotificationFolders,
} from "../stores/noteStore";
import { fetchProviders as fetchStreamingProviders } from "../stores/streamingProvidersStore";
import {
@@ -116,6 +118,7 @@ interface ControlPanelProps {
export default function ControlPanel({ initialSettingsSection }: ControlPanelProps = {}) {
const { t } = useTranslation();
+ useEffect(subscribeMeetingNotificationFolders, []);
const history = useTranscriptions();
const [isLoading, setIsLoading] = useState(true);
const [showSettings, setShowSettings] = useState(!!initialSettingsSection);
@@ -164,7 +167,7 @@ export default function ControlPanel({ initialSettingsSection }: ControlPanelPro
const recordingFolderId = useMeetingRecordingStore((s) => s.recordingFolderId);
const [meetingRecordingRequest, setMeetingRecordingRequest] = useState<{
noteId: number;
- folderId: number;
+ folderId: number | null;
event: any;
} | null>(null);
const [gpuBannerDismissed, setGpuBannerDismissed] = useState(
@@ -390,10 +393,41 @@ export default function ControlPanel({ initialSettingsSection }: ControlPanelPro
}
}, [authLoaded, isSignedIn]);
+ // A ref, not a per-run flag: StrictMode's remount must not cancel the first drain.
+ const meetingNavigationMounted = useRef(false);
useEffect(() => {
+ meetingNavigationMounted.current = true;
+ const isCurrent = () => meetingNavigationMounted.current;
const drain = async () => {
const data = await window.electronAPI?.getPendingMeetingNoteNavigation?.();
if (!data) return;
+ if (data.navigationId) {
+ if (!isCurrent() || data.spaceId == null) {
+ await window.electronAPI.confirmMeetingNoteNavigation(data.navigationId, "cancel");
+ return;
+ }
+ setActiveView("personal-notes");
+ await navigateMeetingNotification(
+ { ...data, navigationId: data.navigationId, spaceId: data.spaceId },
+ isCurrent,
+ () => import("./notes/PersonalNotesView"),
+ (note) => {
+ void startRecordingForNote(note)
+ .then((accepted) => {
+ if (!accepted) void window.electronAPI?.restoreFromMeetingMode?.();
+ })
+ .catch((error) =>
+ logger.warn(
+ "Failed to start notification recording",
+ { error: String(error) },
+ "meeting"
+ )
+ );
+ }
+ );
+ return;
+ }
+ if (!isCurrent()) return;
setActiveFolderId(data.folderId);
setActiveNoteId(data.noteId);
setActiveView("personal-notes");
@@ -402,7 +436,7 @@ export default function ControlPanel({ initialSettingsSection }: ControlPanelPro
folderId: data.folderId,
event: data.event,
});
- initializeNotes(null, 50, data.folderId);
+ void initializeNotes(null, 50, data.folderId);
if (
data.trigger === "hotkey" &&
useSettingsStore.getState().meetingHotkeyLayoutMode === "side-panel"
@@ -410,9 +444,17 @@ export default function ControlPanel({ initialSettingsSection }: ControlPanelPro
window.electronAPI?.snapToMeetingMode?.();
}
};
- drain();
- const cleanup = window.electronAPI?.onMeetingNoteNavigationPending?.(drain);
- return () => cleanup?.();
+ const safeDrain = () => {
+ void drain().catch((error) =>
+ logger.warn("Failed to open meeting note", { error: String(error) }, "meeting")
+ );
+ };
+ safeDrain();
+ const cleanup = window.electronAPI?.onMeetingNoteNavigationPending?.(safeDrain);
+ return () => {
+ meetingNavigationMounted.current = false;
+ cleanup?.();
+ };
}, []);
useEffect(() => {
diff --git a/src/components/MeetingNotificationCard.tsx b/src/components/MeetingNotificationCard.tsx
index 778715097..c881571f1 100644
--- a/src/components/MeetingNotificationCard.tsx
+++ b/src/components/MeetingNotificationCard.tsx
@@ -1,3 +1,4 @@
+import type { ReactNode } from "react";
import { X } from "./icons";
import { cn } from "./lib/utils";
import { BRAND_GLASS_SURFACE } from "./ui/gradientCircle";
@@ -7,6 +8,9 @@ interface MeetingNotificationCardProps {
body: string;
startLabel: string;
onStart?: () => void;
+ picker?: ReactNode;
+ busy?: boolean;
+ dismissLabel?: string;
onDismiss?: () => void;
/** Controls the close button's hover fade. Ignored when `onDismiss` is absent. */
closeVisible?: boolean;
@@ -26,6 +30,9 @@ export function MeetingNotificationCard({
body,
startLabel,
onStart,
+ picker,
+ busy = false,
+ dismissLabel,
onDismiss,
closeVisible = true,
className = "",
@@ -39,6 +46,7 @@ export function MeetingNotificationCard({
"bg-card/95 dark:bg-surface-2/95 backdrop-blur-xl",
"border border-border/70 dark:border-border-subtle/60",
"rounded-xl shadow-lg p-2.5",
+ picker ? "min-h-[60px] flex flex-col justify-center" : "",
className,
].join(" ")}
onMouseEnter={onMouseEnter}
@@ -46,7 +54,10 @@ export function MeetingNotificationCard({
>
{onDismiss && (
<button
+ data-meeting-region="dismiss"
onClick={onDismiss}
+ disabled={busy}
+ aria-label={dismissLabel}
className={[
"absolute -left-2.5 -top-2.5 z-10 size-6 rounded-full",
"flex items-center justify-center",
@@ -80,15 +91,21 @@ export function MeetingNotificationCard({
</p>
</div>
- <button
- onClick={onStart}
+ <div
className={cn(
BRAND_GLASS_SURFACE,
- "shrink-0 whitespace-nowrap rounded-full px-2.5 py-1 text-[11px] font-medium transition-[filter] hover:brightness-110 active:brightness-95"
+ "meeting-folder-compound shrink-0 inline-flex items-stretch rounded-full"
)}
>
- {startLabel}
- </button>
+ <button
+ onClick={onStart}
+ disabled={busy}
+ className="whitespace-nowrap rounded-full px-2.5 py-1 text-[11px] font-medium hover:brightness-110 active:brightness-95 disabled:opacity-60"
+ >
+ {startLabel}
+ </button>
+ {picker}
+ </div>
</div>
</div>
);
diff --git a/src/components/MeetingNotificationFolderPicker.tsx b/src/components/MeetingNotificationFolderPicker.tsx
new file mode 100644
index 000000000..679b1f009
--- /dev/null
+++ b/src/components/MeetingNotificationFolderPicker.tsx
@@ -0,0 +1,382 @@
+import { useEffect, useMemo, useRef, useState, type KeyboardEvent } from "react";
+import { useTranslation } from "react-i18next";
+import { Check, ChevronDown, Folder, Plus, Search, Users, X } from "./icons";
+import { defaultFolderDisplayName, folderMatchesQuery } from "./notes/shared";
+import type { MeetingDestinationContext, MeetingError, MeetingFolderRef } from "../types/electron";
+
+const key = (name: string) => `meetingNotification.folders.${name}`;
+import { meetingFolderLabel, meetingLocationLabel } from "./meetingFolderLabel";
+import {
+ DropdownMenu,
+ DropdownMenuTrigger,
+ DropdownMenuContent,
+ DropdownMenuItem,
+} from "./ui/dropdown-menu";
+
+interface Props {
+ context: MeetingDestinationContext | null;
+ mode: "list" | "form";
+ busy: boolean;
+ focusReady: boolean;
+ error: MeetingError | null;
+ onMode: (mode: "closed" | "list" | "form") => void;
+ onSelect: (folder: MeetingFolderRef) => void;
+ onCreate: (request: { requestId: string; name: string; spaceId: number }) => void;
+ onRetry: () => void;
+}
+
+export function MeetingNotificationFolderPicker({
+ context,
+ mode,
+ busy,
+ focusReady,
+ error,
+ onMode,
+ onSelect,
+ onCreate,
+ onRetry,
+}: Props) {
+ const { t } = useTranslation();
+ const [query, setQuery] = useState("");
+ const [draft, setDraft] = useState("");
+ const [spaceId, setSpaceId] = useState<number | null>(null);
+ const [locationOpen, setLocationOpen] = useState(false);
+ const [active, setActive] = useState(0);
+ const dialogRef = useRef<HTMLDivElement>(null);
+ const searchRef = useRef<HTMLInputElement>(null);
+ const nameRef = useRef<HTMLInputElement>(null);
+ const composing = useRef(false);
+ const commitKey = useRef(false);
+ const createRequest = useRef<{ key: string; id: string } | null>(null);
+ const priorMode = useRef(mode);
+ const folders = useMemo(() => context?.folders ?? [], [context]);
+ const selected = context?.selectedDestination ?? context?.defaultDestination;
+ const matchingFolders = useMemo(
+ () =>
+ folders.filter(
+ (folder) =>
+ folderMatchesQuery(folder, t, query.trim()) ||
+ (context &&
+ meetingFolderLabel(context, folder, t)
+ .toLowerCase()
+ .includes(query.trim().toLowerCase()))
+ ),
+ [context, folders, query, t]
+ );
+ const groups = useMemo(() => {
+ if (query.trim()) return [{ label: t(key("folders")), items: matchingFolders }];
+ const recent = (context?.recentDestinations ?? []).flatMap((ref) =>
+ folders.filter((f) => f.id === ref.folderId && f.space_id === ref.spaceId)
+ );
+ const fallback = folders
+ .filter((f) => !recent.some((r) => r.id === f.id))
+ .slice(0, Math.max(0, 5 - recent.length));
+ const pinned = folders.filter(
+ (f) =>
+ f.id === selected?.folderId &&
+ f.space_id === selected.spaceId &&
+ !recent.some((r) => r.id === f.id) &&
+ !fallback.some((r) => r.id === f.id)
+ );
+ return [
+ { label: t(key("current")), items: pinned },
+ { label: t(key("recent")), items: recent },
+ { label: t(key("folders")), items: fallback },
+ ].filter((g) => g.items.length);
+ }, [context, folders, query, matchingFolders, selected, t]);
+ const visible = groups.flatMap((g) => g.items);
+ useEffect(() => {
+ setActive(0);
+ }, [query]);
+ useEffect(() => {
+ if (mode === "form" && priorMode.current !== "form") {
+ setDraft(matchingFolders.length ? "" : query.trim());
+ setSpaceId(context?.spaces.find((s) => s.kind === "private")?.id ?? null);
+ setLocationOpen(false);
+ createRequest.current = null;
+ }
+ priorMode.current = mode;
+ if (focusReady && !busy) {
+ (context?.existingNote ? dialogRef : mode === "form" ? nameRef : searchRef).current?.focus();
+ }
+ }, [mode, focusReady, busy, context?.spaces, context?.existingNote, matchingFolders, query]);
+ useEffect(() => {
+ document
+ .getElementById(`meeting-folder-option-${active}`)
+ ?.scrollIntoView?.({ block: "nearest" });
+ }, [active]);
+
+ const ignoreComposition = (event: KeyboardEvent) => {
+ if (
+ composing.current ||
+ event.nativeEvent.isComposing ||
+ event.nativeEvent.keyCode === 229 ||
+ commitKey.current
+ )
+ return true;
+ return false;
+ };
+ const onKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {
+ if (ignoreComposition(event)) {
+ if (
+ !composing.current &&
+ !event.nativeEvent.isComposing &&
+ commitKey.current &&
+ event.key === "Enter"
+ )
+ event.preventDefault();
+ return;
+ }
+ if (event.key === "Escape") {
+ event.preventDefault();
+ event.stopPropagation();
+ if (locationOpen) setLocationOpen(false);
+ else onMode(mode === "form" ? "list" : "closed");
+ } else if (mode === "list" && !context?.existingNote && event.target === searchRef.current) {
+ if (event.key === "ArrowDown" || event.key === "ArrowUp") {
+ event.preventDefault();
+ setActive((i) =>
+ Math.max(0, Math.min(visible.length - 1, i + (event.key === "ArrowDown" ? 1 : -1)))
+ );
+ } else if (event.key === "Enter" && visible[active] && !busy) {
+ event.preventDefault();
+ onSelect({ folderId: visible[active].id, spaceId: visible[active].space_id });
+ }
+ }
+ };
+ const submit = () => {
+ if (busy || composing.current || commitKey.current || spaceId === null) return;
+ const inputKey = JSON.stringify([draft.trim(), spaceId]);
+ if (createRequest.current?.key !== inputKey)
+ createRequest.current = { key: inputKey, id: crypto.randomUUID() };
+ onCreate({ requestId: createRequest.current.id, name: draft, spaceId });
+ };
+ const locationSpace = context?.spaces.find((s) => s.id === spaceId);
+ const linked = context?.existingNote;
+ const linkedFolder = folders.find((f) => f.id === linked?.folderId);
+ const linkedLocation = linked
+ ? meetingLocationLabel(
+ linked.shared,
+ linked.spaceName,
+ linked.folderName &&
+ (linkedFolder ? defaultFolderDisplayName(linkedFolder, t) : linked.folderName),
+ t
+ )
+ : "";
+ const errorView = error && (
+ <p role="alert" className="meeting-folder-error">
+ {t(key(`errors.${error}`))}
+ </p>
+ );
+ return (
+ <div
+ ref={dialogRef}
+ tabIndex={-1}
+ data-meeting-region="picker"
+ className="meeting-folder-picker"
+ role="dialog"
+ aria-label={t(key("choose"))}
+ onKeyDown={onKeyDown}
+ onKeyUp={() => {
+ commitKey.current = false;
+ }}
+ onCompositionStart={() => {
+ composing.current = true;
+ }}
+ onCompositionEnd={() => {
+ composing.current = false;
+ commitKey.current = true;
+ }}
+ >
+ {linked ? (
+ <div className="p-2 text-xs leading-relaxed">
+ <p className="font-medium">{linkedLocation}</p>
+ <p className="mt-2 text-muted-foreground">
+ {t(key("linked"), { destination: linkedLocation })}
+ </p>
+ {errorView}
+ </div>
+ ) : mode === "form" ? (
+ <form
+ className="meeting-folder-form"
+ onSubmit={(event) => {
+ event.preventDefault();
+ submit();
+ }}
+ >
+ <h3>{t(key("new"))}</h3>
+ <label className="meeting-folder-field">
+ <span>{t(key("name"))}</span>
+ <input
+ className="input-inline"
+ dir="auto"
+ ref={nameRef}
+ aria-label={t(key("name"))}
+ autoComplete="off"
+ value={draft}
+ disabled={busy}
+ onInput={(event) => setDraft(event.currentTarget.value)}
+ aria-invalid={Boolean(error)}
+ />
+ </label>
+ <div className="meeting-folder-field">
+ <span id="meeting-folder-location-label">{t(key("location"))}</span>
+ <div className="meeting-folder-location">
+ <DropdownMenu open={locationOpen} onOpenChange={setLocationOpen} modal={false}>
+ <DropdownMenuTrigger asChild>
+ <button
+ type="button"
+ className="meeting-folder-location-trigger"
+ aria-labelledby="meeting-folder-location-label meeting-folder-location-value"
+ disabled={busy}
+ >
+ <span id="meeting-folder-location-value">
+ {meetingLocationLabel(
+ locationSpace?.kind === "team",
+ locationSpace?.name ?? "",
+ null,
+ t
+ )}
+ </span>
+ <ChevronDown className="size-3" />
+ </button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent
+ container={dialogRef.current}
+ className="meeting-folder-locations"
+ aria-label={t(key("location"))}
+ side="top"
+ align="start"
+ collisionBoundary={dialogRef.current}
+ collisionPadding={6}
+ onEscapeKeyDown={(event) => event.stopPropagation()}
+ >
+ {context?.spaces.map((space) => (
+ <DropdownMenuItem
+ key={space.id}
+ role="menuitemradio"
+ aria-checked={space.id === spaceId}
+ onSelect={() => setSpaceId(space.id)}
+ >
+ {meetingLocationLabel(space.kind === "team", space.name, null, t)}
+ {space.id === spaceId && <Check className="size-3" />}
+ </DropdownMenuItem>
+ ))}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </div>
+ </div>
+ {errorView}
+ <div className="meeting-folder-form-actions">
+ <button type="button" onClick={() => onMode("list")}>
+ {t(key("cancel"))}
+ </button>
+ <button
+ type="submit"
+ disabled={busy || spaceId === null}
+ onClick={(event) => {
+ if (event.detail > 0) commitKey.current = false;
+ }}
+ >
+ {t(key("create"))}
+ </button>
+ </div>
+ </form>
+ ) : (
+ <>
+ <div className="meeting-folder-search">
+ <Search className="size-3.5 shrink-0" />
+ <input
+ className="input-inline"
+ dir="auto"
+ ref={searchRef}
+ role="combobox"
+ aria-label={t(key("search"))}
+ placeholder={t(key("search"))}
+ aria-expanded="true"
+ aria-controls="meeting-folder-results"
+ aria-activedescendant={
+ visible[active] ? `meeting-folder-option-${active}` : undefined
+ }
+ value={query}
+ onInput={(e) => setQuery(e.currentTarget.value)}
+ />
+ {query && (
+ <button aria-label={t(key("clear"))} onClick={() => setQuery("")}>
+ <X className="size-3" />
+ </button>
+ )}
+ </div>
+ {errorView}
+ {!context ? (
+ <div className="p-3 text-xs text-muted-foreground">
+ <p>{t(key(error ? "unavailable" : "loading"))}</p>
+ {error && <button onClick={onRetry}>{t(key("retry"))}</button>}
+ </div>
+ ) : (
+ <>
+ <div
+ className="meeting-folder-results"
+ role="listbox"
+ id="meeting-folder-results"
+ aria-label={t(key("folders"))}
+ >
+ {groups.map((group) => (
+ <div key={group.label}>
+ <p className="meeting-folder-group">{group.label}</p>
+ {group.items.map((folder) => {
+ const index = visible.indexOf(folder);
+ const space = context.spaces.find((s) => s.id === folder.space_id);
+ return (
+ <button
+ key={folder.id}
+ id={`meeting-folder-option-${index}`}
+ className={`meeting-folder-option ${index === active ? "active" : ""}`}
+ role="option"
+ aria-selected={
+ folder.id === selected?.folderId && folder.space_id === selected.spaceId
+ }
+ aria-label={meetingFolderLabel(context, folder, t)}
+ disabled={busy}
+ onClick={() =>
+ onSelect({ folderId: folder.id, spaceId: folder.space_id })
+ }
+ >
+ <Folder className="size-3.5 shrink-0" />
+ <span className="min-w-0 flex-1">
+ <span className="meeting-folder-name">
+ {defaultFolderDisplayName(folder, t)}
+ </span>
+ <span className="meeting-folder-space">
+ {meetingLocationLabel(
+ space?.kind === "team",
+ space?.name ?? "",
+ null,
+ t
+ )}
+ </span>
+ </span>
+ {space?.kind === "team" && <Users className="size-3 shrink-0" />}
+ {folder.id === selected?.folderId && (
+ <Check className="size-3 shrink-0" />
+ )}
+ </button>
+ );
+ })}
+ </div>
+ ))}
+ {!visible.length && (
+ <p className="p-4 text-center text-xs text-muted-foreground">{t(key("empty"))}</p>
+ )}
+ </div>
+ <button className="meeting-folder-new" disabled={busy} onClick={() => onMode("form")}>
+ <Plus className="size-3.5" />
+ {t(key("new"))}
+ </button>
+ </>
+ )}
+ </>
+ )}
+ </div>
+ );
+}
diff --git a/src/components/MeetingNotificationOverlay.tsx b/src/components/MeetingNotificationOverlay.tsx
index e8350a167..b50a766c5 100644
--- a/src/components/MeetingNotificationOverlay.tsx
+++ b/src/components/MeetingNotificationOverlay.tsx
@@ -1,6 +1,7 @@
import {
useCallback,
useEffect,
+ useLayoutEffect,
useRef,
useState,
type CSSProperties,
@@ -8,8 +9,18 @@ import {
type ReactElement,
} from "react";
import { useTranslation } from "react-i18next";
-import type { MeetingNotificationData } from "../types/electron";
+import type {
+ MeetingNotificationData,
+ MeetingDestinationContext,
+ MeetingError,
+ MeetingFolderRef,
+ MeetingSurfaceState,
+} from "../types/electron";
import { MeetingNotificationCard } from "./MeetingNotificationCard";
+import { MeetingNotificationFolderPicker } from "./MeetingNotificationFolderPicker";
+import { meetingFolderLabel } from "./meetingFolderLabel";
+import { Check, ChevronDown } from "./icons";
+import "../styles/meeting-notification.css";
import {
getMeetingNotificationPresentation,
initializeMeetingNotificationOverlay,
@@ -36,29 +47,268 @@ export default function MeetingNotificationOverlay(): ReactElement {
const [exitDirection, setExitDirection] = useState<1 | -1>(1);
const pointerSwipeRef = useRef<PointerSwipe | null>(null);
+ const [context, setContext] = useState<MeetingDestinationContext | null>(null);
+ const [mode, setMode] = useState<MeetingSurfaceState["mode"]>("closed");
+ const [error, setError] = useState<MeetingError | null>(null);
+ const [busy, setBusy] = useState(false);
+ const [focusReady, setFocusReady] = useState(false);
+ const [feedback, setFeedback] = useState<"idle" | "enter" | "hold" | "exit">("idle");
+ const [announcement, setAnnouncement] = useState("");
+ const [maxHeight, setMaxHeight] = useState(512);
+ const surfaceRef = useRef<HTMLDivElement>(null);
+ const dataRef = useRef<MeetingNotificationData | null>(null);
+ const modeRef = useRef<MeetingSurfaceState["mode"]>("closed");
+ const editorGeneration = useRef(0);
+ const loadGeneration = useRef(0);
+ const layoutRevision = useRef(0);
+ const focusGeneration = useRef(0);
+ const focusIntent = useRef<MeetingSurfaceState["focus"]>("keep");
+ const operation = useRef<object | null>(null);
+ const feedbackTimers = useRef<ReturnType<typeof setTimeout>[]>([]);
+
+ const clearFeedback = useCallback(() => {
+ feedbackTimers.current.forEach(clearTimeout);
+ feedbackTimers.current = [];
+ setFeedback("idle");
+ }, []);
+ const changeMode = useCallback((next: MeetingSurfaceState["mode"], requestFocus = true) => {
+ editorGeneration.current++;
+ if (next === "closed") {
+ focusGeneration.current++;
+ focusIntent.current = "release";
+ setFocusReady(false);
+ } else if (modeRef.current === "closed" && requestFocus) {
+ focusGeneration.current++;
+ focusIntent.current = "request";
+ setFocusReady(false);
+ }
+ modeRef.current = next;
+ setMode(next);
+ setError(null);
+ }, []);
+ const loadContext = useCallback(async () => {
+ if (!dataRef.current) return;
+ const generation = ++loadGeneration.current;
+ try {
+ const result = await window.electronAPI.getMeetingNotificationDestination();
+ if (generation !== loadGeneration.current) return;
+ if (result.success === true) {
+ setContext(result.value);
+ setError(null);
+ } else setError(result.code);
+ } catch {
+ if (generation === loadGeneration.current) setError("FOLDERS_UNAVAILABLE");
+ }
+ }, []);
+ useEffect(
+ () =>
+ initializeMeetingNotificationOverlay({
+ subscribe: (callback) => window.electronAPI?.onMeetingNotificationData?.(callback),
+ getPendingData: () =>
+ window.electronAPI?.getMeetingNotificationData?.() ?? Promise.resolve(null),
+ onData: (incoming) => {
+ dataRef.current = incoming;
+ setData(incoming);
+ void loadContext();
+ },
+ onVisible: () => setIsVisible(true),
+ onReady: () => {
+ void window.electronAPI?.meetingNotificationReady?.();
+ },
+ }),
+ [loadContext]
+ );
+ useEffect(() => () => feedbackTimers.current.forEach(clearTimeout), []);
useEffect(() => {
- return initializeMeetingNotificationOverlay({
- subscribe: (callback) => window.electronAPI?.onMeetingNotificationData?.(callback),
- getPendingData: () =>
- window.electronAPI?.getMeetingNotificationData?.() ?? Promise.resolve(null),
- onData: setData,
- onVisible: () => setIsVisible(true),
- onReady: () => {
- void window.electronAPI?.meetingNotificationReady?.();
- },
+ const offClose = window.electronAPI.onMeetingNotificationSurfaceClosed?.((state) => {
+ layoutRevision.current = Math.max(layoutRevision.current, state.revision);
+ changeMode("closed", false);
});
- }, []);
+ const offResize = window.electronAPI.onMeetingNotificationSurfaceResized?.((state) => {
+ layoutRevision.current = Math.max(layoutRevision.current, state.revision);
+ });
+ return () => {
+ offClose?.();
+ offResize?.();
+ };
+ }, [changeMode]);
- const presentation = getMeetingNotificationPresentation(data);
+ useLayoutEffect(() => {
+ if (!data || !surfaceRef.current) return;
+ let active = true;
+ const report = () => {
+ if (!active) return;
+ const elements = [
+ ...surfaceRef.current!.querySelectorAll<HTMLElement>("[data-meeting-region]"),
+ ];
+ const regions = elements
+ .map((element) => {
+ // Layout offsets ignore the entrance/swipe transform, which can put
+ // the entire card outside the window before its first visible frame.
+ let left = 0;
+ let top = 0;
+ let parent: HTMLElement | null = element;
+ while (parent && parent !== surfaceRef.current) {
+ left += parent.offsetLeft;
+ top += parent.offsetTop;
+ parent = parent.offsetParent as HTMLElement | null;
+ }
+ const x = Math.max(0, Math.floor(left - 8));
+ const y = Math.max(0, Math.floor(top - 8));
+ return {
+ x,
+ y,
+ width: Math.max(1, Math.min(416 - x, element.offsetWidth + 16)),
+ height: Math.max(1, element.offsetHeight + 16),
+ };
+ })
+ .filter((r) => r.width > 1 && r.height > 1);
+ if (!regions.length) regions.push({ x: 4, y: 4, width: 408, height: 76 });
+ const height = Math.max(84, ...regions.map((r) => r.y + r.height + 4));
+ const focus = focusIntent.current;
+ focusIntent.current = "keep";
+ const focusEpoch = focusGeneration.current;
+ void window.electronAPI
+ .setMeetingNotificationSurface({
+ revision: ++layoutRevision.current,
+ mode: modeRef.current,
+ contentHeight: height,
+ regions,
+ focus,
+ })
+ .then((result) => {
+ if (result.success !== true) return;
+ if (result.value.maxHeight) setMaxHeight(result.value.maxHeight);
+ if (
+ focus === "request" &&
+ focusGeneration.current === focusEpoch &&
+ modeRef.current !== "closed"
+ )
+ setFocusReady(true);
+ })
+ .catch(() => {});
+ };
+ report();
+ const observer = new ResizeObserver(report);
+ observer.observe(surfaceRef.current);
+ surfaceRef.current
+ .querySelectorAll("[data-meeting-region]")
+ .forEach((element) => observer.observe(element));
+ window.addEventListener("resize", report);
+ return () => {
+ active = false;
+ observer.disconnect();
+ window.removeEventListener("resize", report);
+ };
+ }, [data, mode, context, error]);
+ const confirmSelection = useCallback(
+ (next: MeetingDestinationContext, ref: MeetingFolderRef) => {
+ setContext(next);
+ changeMode("closed");
+ clearFeedback();
+ setFeedback("enter");
+ feedbackTimers.current = [
+ setTimeout(() => setFeedback("hold"), 200),
+ setTimeout(() => setFeedback("exit"), 800),
+ setTimeout(() => setFeedback("idle"), 1200),
+ ];
+ const folder = next.folders.find((f) => f.id === ref.folderId && f.space_id === ref.spaceId);
+ if (folder)
+ setAnnouncement(
+ t("meetingNotification.folders.selected", {
+ destination: meetingFolderLabel(next, folder, t),
+ })
+ );
+ },
+ [changeMode, clearFeedback, t]
+ );
+ const choose = useCallback(
+ async (
+ ref: MeetingFolderRef,
+ createRequest?: { requestId: string; name: string; spaceId: number }
+ ) => {
+ if (!dataRef.current || operation.current) return;
+ const op = {};
+ operation.current = op;
+ setBusy(true);
+ setError(null);
+ loadGeneration.current++;
+ const generation = editorGeneration.current;
+ const isCurrent = () => generation === editorGeneration.current;
+ try {
+ if (createRequest) {
+ const created = await window.electronAPI.createMeetingNotificationFolder(createRequest);
+ if (!isCurrent()) return;
+ if (created.success === false) {
+ if (created.context) setContext(created.context);
+ setError(created.code);
+ return;
+ }
+ ref = created.value.createdFolder;
+ setContext(created.value);
+ }
+ if (!isCurrent()) return;
+ const selected = await window.electronAPI.selectMeetingNotificationFolder(ref);
+ if (!isCurrent()) return;
+ if (selected.success === true) confirmSelection(selected.value, ref);
+ else {
+ if (selected.context) setContext(selected.context);
+ setError(selected.code);
+ }
+ } catch {
+ if (isCurrent()) setError(createRequest ? "CREATE_FAILED" : "FOLDER_UNAVAILABLE");
+ } finally {
+ if (operation.current === op) {
+ operation.current = null;
+ setBusy(false);
+ }
+ }
+ },
+ [confirmSelection]
+ );
+
+ const presentation = getMeetingNotificationPresentation(data);
const respond = useCallback(
async (action: string): Promise<void> => {
- if (!data) return;
- setIsVisible(false);
- await new Promise<void>((resolve) => setTimeout(resolve, 200));
- window.electronAPI?.meetingNotificationRespond?.(data.detectionId, action);
+ const current = dataRef.current;
+ if (!current || operation.current) return;
+ const op = {};
+ operation.current = op;
+ setBusy(true);
+ loadGeneration.current++;
+ try {
+ if (action === "dismiss") {
+ // Main closes the window as soon as it handles a dismiss: slide out first.
+ setIsVisible(false);
+ await new Promise<void>((resolve) => setTimeout(resolve, 200));
+ }
+ const result = await window.electronAPI?.meetingNotificationRespond?.(
+ current.detectionId,
+ action,
+ context?.existingNote ? { existingNote: context.existingNote } : {}
+ );
+ // A dismiss that fails leaves nothing to choose, so it never opens the picker.
+ if (result?.success === true || action === "dismiss") setIsVisible(false);
+ else {
+ if (result?.context) setContext(result.context);
+ changeMode("list");
+ setError(result?.code ?? "START_FAILED");
+ }
+ } catch {
+ if (action === "dismiss") setIsVisible(false);
+ else {
+ changeMode("list");
+ setError("START_FAILED");
+ }
+ } finally {
+ if (operation.current === op) {
+ operation.current = null;
+ setBusy(false);
+ }
+ }
},
- [data]
+ [context, changeMode]
);
const dismiss = useCallback((): void => {
@@ -83,9 +333,11 @@ export default function MeetingNotificationOverlay(): ReactElement {
if (
!presentation.dismissible ||
!isVisible ||
+ modeRef.current !== "closed" ||
+ operation.current !== null ||
!event.isPrimary ||
event.button !== 0 ||
- (event.target instanceof Element && event.target.closest("button"))
+ (event.target instanceof Element && event.target.closest("button,input,form,[role=dialog]"))
) {
return;
}
@@ -157,8 +409,21 @@ export default function MeetingNotificationOverlay(): ReactElement {
return (
<div
- className="meeting-notification-window w-full h-full bg-transparent p-3 select-none"
- style={{ touchAction: presentation.dismissible ? "pan-y" : "auto" }}
+ ref={surfaceRef}
+ className="meeting-notification-window relative w-full bg-transparent p-3 select-none"
+ onMouseMove={(event) => {
+ const interactive =
+ Boolean(pointerSwipeRef.current) ||
+ (event.target instanceof Element &&
+ Boolean(event.target.closest("[data-meeting-region]")));
+ void window.electronAPI?.setNotificationInteractivity?.(interactive);
+ }}
+ style={
+ {
+ touchAction: presentation.dismissible ? "pan-y" : "auto",
+ "--meeting-surface-height": `${maxHeight}px`,
+ } as CSSProperties
+ }
onPointerDown={handlePointerDown}
onPointerMove={handlePointerMove}
onPointerUp={handlePointerUp}
@@ -171,16 +436,57 @@ export default function MeetingNotificationOverlay(): ReactElement {
].join(" ")}
style={motionStyle}
>
- <MeetingNotificationCard
- title={title}
- body={body}
- startLabel={t(presentation.actionKey)}
- onStart={() => respond(presentation.action)}
- onDismiss={presentation.dismissible ? dismiss : undefined}
- closeVisible={isHovered}
- onMouseEnter={handleMouseEnter}
- onMouseLeave={handleMouseLeave}
- />
+ <div data-meeting-region="card">
+ <MeetingNotificationCard
+ title={title}
+ body={body}
+ startLabel={t(presentation.actionKey)}
+ onStart={() => void respond(presentation.action)}
+ busy={busy}
+ dismissLabel={t("meetingNotification.folders.dismiss")}
+ picker={
+ data ? (
+ <button
+ type="button"
+ className={`meeting-folder-trigger feedback-${feedback}`}
+ aria-label={t("meetingNotification.folders.choose")}
+ aria-haspopup="dialog"
+ aria-expanded={mode !== "closed"}
+ disabled={busy}
+ onClick={() => {
+ if (modeRef.current === "closed") {
+ changeMode("list");
+ void loadContext();
+ } else changeMode("closed");
+ }}
+ >
+ <ChevronDown className="meeting-folder-chevron size-3" />
+ <Check className="meeting-folder-confirmation size-3" />
+ </button>
+ ) : undefined
+ }
+ onDismiss={presentation.dismissible ? dismiss : undefined}
+ closeVisible={isHovered}
+ onMouseEnter={handleMouseEnter}
+ onMouseLeave={handleMouseLeave}
+ />
+ </div>
+ {mode !== "closed" && (
+ <MeetingNotificationFolderPicker
+ context={context}
+ mode={mode}
+ busy={busy}
+ focusReady={focusReady}
+ error={error}
+ onMode={changeMode}
+ onSelect={(ref) => void choose(ref)}
+ onCreate={(request) => void choose({ folderId: 0, spaceId: request.spaceId }, request)}
+ onRetry={() => void loadContext()}
+ />
+ )}
+ <span className="sr-only" aria-live="polite">
+ {announcement}
+ </span>
</div>
</div>
);
diff --git a/src/components/meetingFolderLabel.ts b/src/components/meetingFolderLabel.ts
new file mode 100644
index 000000000..a8fd0092f
--- /dev/null
+++ b/src/components/meetingFolderLabel.ts
@@ -0,0 +1,24 @@
+import type { FolderItem, MeetingDestinationContext } from "../types/electron";
+import { defaultFolderDisplayName } from "./notes/shared";
+const key = (name: string) => `meetingNotification.folders.${name}`;
+export function meetingLocationLabel(
+ shared: boolean,
+ spaceName: string,
+ folderName: string | null,
+ t: (key: string) => string
+): string {
+ return `${shared ? spaceName : t(key("private"))}${folderName ? ` / ${folderName}` : ""}${shared ? ` · ${t(key("shared"))}` : ""}`;
+}
+export function meetingFolderLabel(
+ context: MeetingDestinationContext,
+ folder: FolderItem,
+ t: (key: string) => string
+): string {
+ const space = context.spaces.find((s) => s.id === folder.space_id);
+ return meetingLocationLabel(
+ space?.kind === "team",
+ space?.name ?? "",
+ defaultFolderDisplayName(folder, t),
+ t
+ );
+}
diff --git a/src/components/meetingNotificationNavigation.ts b/src/components/meetingNotificationNavigation.ts
new file mode 100644
index 000000000..e9eeeafac
--- /dev/null
+++ b/src/components/meetingNotificationNavigation.ts
@@ -0,0 +1,55 @@
+import type { NoteItem } from "../types/electron";
+import {
+ addNote,
+ ensureContainerLoaded,
+ folderContainerKey,
+ initializeNotesTree,
+ navigateToContainer,
+ setActiveNoteId,
+ spaceContainerKey,
+} from "../stores/noteStore";
+
+interface NotificationNavigation {
+ navigationId: string;
+ noteId: number;
+ spaceId: number;
+ folderId: number | null;
+}
+
+/** Only the main process's final, live row authorizes recording. */
+export async function navigateMeetingNotification(
+ data: NotificationNavigation,
+ isCurrent: () => boolean,
+ prepareEditor: () => Promise<unknown>,
+ requestRecording: (note: NoteItem) => void
+): Promise<void> {
+ const cancel = async () => {
+ await window.electronAPI
+ .confirmMeetingNoteNavigation(data.navigationId, "cancel")
+ .catch(() => {});
+ };
+ try {
+ await prepareEditor();
+ if (!isCurrent()) return await cancel();
+ await initializeNotesTree();
+ if (!isCurrent()) return await cancel();
+ await ensureContainerLoaded(
+ data.folderId == null ? spaceContainerKey(data.spaceId) : folderContainerKey(data.folderId)
+ );
+ if (!isCurrent()) return await cancel();
+ const result = await window.electronAPI.confirmMeetingNoteNavigation(
+ data.navigationId,
+ "ready"
+ );
+ if (!isCurrent()) return await cancel();
+ if (result.success !== true) return;
+ // No awaited loading remains between authorization and the recording request.
+ const note = result.value;
+ addNote(note);
+ navigateToContainer(note.space_id, note.folder_id);
+ setActiveNoteId(note.id);
+ requestRecording(note);
+ } catch {
+ await cancel();
+ }
+}
diff --git a/src/components/notes/PersonalNotesView.tsx b/src/components/notes/PersonalNotesView.tsx
index 98cdacf3f..d825d3ec7 100644
--- a/src/components/notes/PersonalNotesView.tsx
+++ b/src/components/notes/PersonalNotesView.tsx
@@ -119,7 +119,7 @@ interface PersonalNotesViewProps {
onOpenSettings?: (section: string) => void;
meetingRecordingRequest?: {
noteId: number;
- folderId: number;
+ folderId: number | null;
event: any;
} | null;
onMeetingRecordingRequestHandled?: () => void;
@@ -615,7 +615,7 @@ export default function PersonalNotesView({
args: {
noteId: meetingRecordingRequest.noteId,
noteTitle: note?.title ?? null,
- folderId: note?.folder_id ?? meetingRecordingRequest.folderId ?? null,
+ folderId: note ? note.folder_id : (meetingRecordingRequest.folderId ?? null),
seedSegments,
diarizationEnabled:
note?.diarization_enabled == null ? null : note.diarization_enabled === 1,
diff --git a/src/helpers/database.js b/src/helpers/database.js
index 9e5fb0c61..c3ee030a9 100644
--- a/src/helpers/database.js
+++ b/src/helpers/database.js
@@ -5164,7 +5164,7 @@ class DatabaseManager {
// event the same id, so a teammate's synced note for the meeting must never
// match, or both apps record into one note. Ownership follows ownsNote() in
// spacePermissions.ts, plus Personal rows synced before owners were recorded.
- getOwnNoteByCalendarEventId(eventId) {
+ getOwnNoteByCalendarEventId(eventId, { throwOnError = false } = {}) {
try {
if (!this.db) throw new Error("Database not initialized");
const accountScope = this._accountScopeCondition("notes");
@@ -5188,10 +5188,29 @@ class DatabaseManager {
{ error: error.message },
"notes"
);
+ if (throwOnError) throw error;
return null;
}
}
+ createMeetingNoteForNotification({ title, folderId, spaceId, eventId, participants }) {
+ return this.db.transaction(() => {
+ const existing = eventId
+ ? this.getOwnNoteByCalendarEventId(eventId, { throwOnError: true })
+ : null;
+ if (existing) return { created: false, note: existing };
+ const { note } = this.saveNote(title, "", "meeting", null, null, folderId, spaceId);
+ if (!note) throw new Error("Meeting note not saved");
+ if (!eventId) return { created: true, note };
+ const result = this.updateNote(note.id, {
+ calendar_event_id: eventId,
+ ...(participants ? { participants } : {}),
+ });
+ if (!result.success || !result.note) throw new Error("Meeting metadata not saved");
+ return { created: true, note: result.note };
+ })();
+ }
+
// With a source (see contactSource), records that it has seen these
// contacts.
upsertContacts(contacts, source = null) {
diff --git a/src/helpers/ipcHandlers.js b/src/helpers/ipcHandlers.js
index ea54a7164..5e6794f18 100644
--- a/src/helpers/ipcHandlers.js
+++ b/src/helpers/ipcHandlers.js
@@ -612,6 +612,13 @@ async function chunkedCloudTranscribe({
const CLEANUP_TRUNCATED_MESSAGE_KEY = "hooks.audioRecording.errorDescriptions.cleanupTruncated";
const CLEANUP_EMPTY_REPLY_MESSAGE_KEY = "hooks.audioRecording.errorDescriptions.cleanupEmptyReply";
+const {
+ isMeetingFolderRef,
+ resolveMeetingDestination,
+ rememberMeetingDestination,
+ meetingDestinationContext,
+} = require("./meetingNotificationDestination");
+
class IPCHandlers {
constructor(managers) {
this.environmentManager = managers.environmentManager;
@@ -703,7 +710,125 @@ class IPCHandlers {
}
}
+ createFolderWithEffects(name, spaceId) {
+ const result = this.databaseManager.createFolder(name, spaceId);
+ if (result?.success && result?.folder) {
+ setImmediate(() => {
+ broadcastToWindows("folder-created", result.folder);
+ if (this._noteFilesEnabled) {
+ const markdownMirror = require("./markdownMirror");
+ markdownMirror.ensureFolder(result.folder.name);
+ }
+ });
+ }
+ return result;
+ }
+
+ getMeetingNotificationDestination(owner) {
+ if (!this.windowManager.isMeetingNotificationOwner(owner))
+ return { success: false, code: "STALE_NOTIFICATION" };
+ try {
+ const context = meetingDestinationContext(
+ this.databaseManager,
+ owner,
+ this.windowManager.meetingRecentDestinations
+ );
+ this.windowManager.meetingRecentDestinations = context.recentDestinations;
+ return { success: true, value: context };
+ } catch (error) {
+ return {
+ success: false,
+ code: error.code === "NOTE_UNAVAILABLE" ? error.code : "FOLDERS_UNAVAILABLE",
+ };
+ }
+ }
+
+ selectMeetingNotificationFolder(owner, ref) {
+ const result = this.getMeetingNotificationDestination(owner);
+ if (!result.success) return result;
+ if (result.value.existingNote)
+ return { success: false, code: "LINKED_NOTE_CHANGED", context: result.value };
+ if (!isMeetingFolderRef(ref)) return { success: false, code: "INVALID_REQUEST" };
+ const folder = result.value.folders.find(
+ (f) => f.id === ref.folderId && f.space_id === ref.spaceId
+ );
+ if (!folder) return { success: false, code: "FOLDER_UNAVAILABLE" };
+ owner.selectedDestination = { folderId: folder.id, spaceId: folder.space_id };
+ this.windowManager.meetingRecentDestinations = rememberMeetingDestination(
+ this.windowManager.meetingRecentDestinations,
+ owner.selectedDestination
+ );
+ return {
+ success: true,
+ value: {
+ ...result.value,
+ selectedDestination: owner.selectedDestination,
+ recentDestinations: this.windowManager.meetingRecentDestinations,
+ },
+ };
+ }
+
+ createMeetingNotificationFolder(owner, request) {
+ if (!this.windowManager.isMeetingNotificationOwner(owner))
+ return { success: false, code: "STALE_NOTIFICATION" };
+ if (
+ !request ||
+ typeof request.requestId !== "string" ||
+ !request.requestId.trim() ||
+ request.requestId.length > 128 ||
+ typeof request.name !== "string" ||
+ !Number.isSafeInteger(request.spaceId) ||
+ request.spaceId <= 0
+ )
+ return { success: false, code: "INVALID_REQUEST" };
+ const name = request.name.trim();
+ if (!name) return { success: false, code: "FOLDER_NAME_REQUIRED" };
+ const cached = owner.createRequests.get(request.requestId);
+ if (cached && (cached.name !== name || cached.spaceId !== request.spaceId))
+ return { success: false, code: "INVALID_REQUEST" };
+ // Bound per-prompt retry bookkeeping. Successful IDs stay stable for the prompt's lifetime.
+ if (!cached && owner.createRequests.size >= 32)
+ return { success: false, code: "INVALID_REQUEST" };
+ const contextResult = this.getMeetingNotificationDestination(owner);
+ if (!contextResult.success) return contextResult;
+ if (contextResult.value.existingNote)
+ return { success: false, code: "LINKED_NOTE_CHANGED", context: contextResult.value };
+ if (!contextResult.value.spaces.some((space) => space.id === request.spaceId))
+ return { success: false, code: "SPACE_UNAVAILABLE" };
+ try {
+ let ref = cached?.ref;
+ if (ref) {
+ if (!resolveMeetingDestination(this.databaseManager, ref))
+ return { success: false, code: "FOLDER_UNAVAILABLE" };
+ } else {
+ const result = this.createFolderWithEffects(name, request.spaceId);
+ if (!result?.success || !result.folder)
+ return {
+ success: false,
+ code:
+ result?.error === "A folder with that name already exists"
+ ? "FOLDER_NAME_TAKEN"
+ : result?.error === "Space not found"
+ ? "SPACE_UNAVAILABLE"
+ : "CREATE_FAILED",
+ };
+ ref = { folderId: result.folder.id, spaceId: result.folder.space_id };
+ owner.createRequests.set(request.requestId, { name, spaceId: request.spaceId, ref });
+ this.windowManager.sendToControlPanel("meeting-notification-folder-created", {
+ folderId: ref.folderId,
+ });
+ }
+ const refreshed = this.getMeetingNotificationDestination(owner);
+ return refreshed.success
+ ? { success: true, value: { ...refreshed.value, createdFolder: ref } }
+ : refreshed;
+ } catch {
+ return { success: false, code: "CREATE_FAILED" };
+ }
+ }
+
_handleAuthTokenChange({ generation, token }) {
+ this.windowManager.retireMeetingNotificationScope();
this.enterpriseIdentityManager?.clear();
if (!token) {
this.databaseManager.setActiveAccountId(null);
@@ -2192,19 +2317,9 @@ class IPCHandlers {
return this.databaseManager.getFolders(spaceId);
});
- ipcMain.handle("db-create-folder", async (event, name, spaceId) => {
- const result = this.databaseManager.createFolder(name, spaceId);
- if (result?.success && result?.folder) {
- setImmediate(() => {
- broadcastToWindows("folder-created", result.folder);
- if (this._noteFilesEnabled) {
- const markdownMirror = require("./markdownMirror");
- markdownMirror.ensureFolder(result.folder.name);
- }
- });
- }
- return result;
- });
+ ipcMain.handle("db-create-folder", (_event, name, spaceId) =>
+ this.createFolderWithEffects(name, spaceId)
+ );
ipcMain.handle("db-delete-folder", async (event, id) => {
const folderName = this._noteFilesEnabled ? this._getFolderName(id) : null;
@@ -2277,6 +2392,16 @@ class IPCHandlers {
: "Authentication context changed before account scoping",
};
}
+ const previousScope = accountScopeBinding.resolveActiveAccountScope({
+ ...state,
+ binding: accountScopeBinding.read(),
+ });
+ if (
+ this.databaseManager.activeAccountId !== accountId ||
+ (accountId !== null && previousScope?.accountId !== accountId)
+ ) {
+ this.windowManager.retireMeetingNotificationScope();
+ }
this.databaseManager.setActiveAccountId(accountId);
if (accountId !== null) accountScopeBinding.persist(accountId, state.token);
else accountScopeBinding.clear();
@@ -11927,14 +12052,43 @@ class IPCHandlers {
}
});
- ipcMain.handle("meeting-notification-respond", async (_event, detectionId, action) => {
- try {
- await this.meetingDetectionEngine.handleNotificationResponse(detectionId, action);
- return { success: true };
- } catch (error) {
- return { success: false, error: error.message };
- }
+ ipcMain.handle("get-meeting-notification-destination", (event) =>
+ this.getMeetingNotificationDestination(
+ this.windowManager.captureMeetingNotificationOwner(event.sender)
+ )
+ );
+ ipcMain.handle("select-meeting-notification-folder", (event, ref) =>
+ this.selectMeetingNotificationFolder(
+ this.windowManager.captureMeetingNotificationOwner(event.sender),
+ ref
+ )
+ );
+ ipcMain.handle("create-meeting-notification-folder", (event, request) =>
+ this.createMeetingNotificationFolder(
+ this.windowManager.captureMeetingNotificationOwner(event.sender),
+ request
+ )
+ );
+
+ ipcMain.handle("set-meeting-notification-surface", (event, state) => {
+ const owner = this.windowManager.captureMeetingNotificationOwner(event.sender);
+ return this.windowManager.setMeetingNotificationSurface(owner, state);
+ });
+
+ ipcMain.handle("meeting-notification-respond", (event, detectionId, action, options) => {
+ const owner = this.windowManager.captureMeetingNotificationOwner(event.sender);
+ if (!owner || owner.prompt.detectionId !== detectionId)
+ return { success: false, code: "STALE_NOTIFICATION" };
+ return this.meetingDetectionEngine.handleNotificationResponse(
+ detectionId,
+ action,
+ options,
+ owner
+ );
});
+ ipcMain.handle("confirm-meeting-note-navigation", (event, navigationId, status) =>
+ this.windowManager.confirmMeetingNoteNavigation(event.sender, navigationId, status)
+ );
ipcMain.handle("join-calendar-meeting", async (_event, eventId) => {
try {
@@ -11947,12 +12101,13 @@ class IPCHandlers {
ipcMain.handle("start-manual-meeting", () => this.windowManager.startManualMeeting());
- ipcMain.handle("get-meeting-notification-data", async () => {
+ ipcMain.handle("get-meeting-notification-data", async (event) => {
+ if (this.windowManager?.notificationWindow?.webContents !== event.sender) return null;
return this.windowManager?._pendingNotificationData ?? null;
});
- ipcMain.handle("get-pending-meeting-note-navigation", async () => {
- return this.windowManager?.consumePendingMeetingNoteNavigation() ?? null;
+ ipcMain.handle("get-pending-meeting-note-navigation", async (event) => {
+ return this.windowManager?.consumePendingMeetingNoteNavigation(event.sender) ?? null;
});
ipcMain.handle("get-pending-note-navigation", async () => {
diff --git a/src/helpers/meetingDetectionEngine.js b/src/helpers/meetingDetectionEngine.js
index 65c30b06d..2cbb45d0f 100644
--- a/src/helpers/meetingDetectionEngine.js
+++ b/src/helpers/meetingDetectionEngine.js
@@ -1,4 +1,11 @@
const debugLogger = require("./debugLogger");
+const { randomUUID } = require("node:crypto");
+const {
+ meetingDestinationContext,
+ notificationCalendarEventId,
+ resolveMeetingDestination,
+ describeMeetingNote,
+} = require("./meetingNotificationDestination");
const { openExternalUrl } = require("./externalUrlOpener");
const { getMeetingJoinUrl } = require("./meetingJoinUrl");
const createMeetingAutoEndController = require("./meetingAutoEndController");
@@ -429,95 +436,100 @@ class MeetingDetectionEngine {
});
}
- async handleNotificationResponse(detectionId, action) {
- debugLogger.info("Notification response", { detectionId, action }, "meeting");
- try {
- const detection = this.activeDetections.get(detectionId);
-
- if ((action === "start" || action === "join") && detection) {
- if (action === "join") {
- const joinUrl = getMeetingJoinUrl(detection.event);
- if (joinUrl) {
- openExternalUrl(joinUrl).catch((error) =>
- debugLogger.error(
- "Failed to open meeting link",
- { error: error.message, joinUrl },
- "meeting"
- )
- );
- }
- }
-
- const eventSummary = detection.event?.summary || "New note";
-
- const isRealEvent =
- detection.event?.calendar_id &&
- detection.event.calendar_id !== "__detected__" &&
- detection.event.calendar_id !== "__manual__";
-
- if (
- isRealEvent &&
- (await this._resumeExistingEventNote(detection.event, "calendar-join"))
- ) {
- this._meetingModeActive = true;
- this.audioActivityDetector.resetPrompt();
- return;
- }
-
- const noteResult = this.databaseManager.saveNote(eventSummary, "", "meeting");
- const meetingsFolder = this.databaseManager.getMeetingsFolder();
-
- if (!noteResult?.note?.id || !meetingsFolder?.id) {
- debugLogger.error(
- "Meeting note creation failed",
- { noteId: noteResult?.note?.id, folderId: meetingsFolder?.id },
- "meeting"
- );
- return;
- }
-
- this._meetingModeActive = true;
-
- broadcastToWindows("note-added", noteResult.note);
-
- if (isRealEvent) {
- const calEvent = this.databaseManager.getCalendarEventById(detection.event.id);
- const updates = { calendar_event_id: detection.event.id };
- if (calEvent?.attendees) {
- updates.participants = calEvent.attendees;
- }
- const updateResult = this.databaseManager.updateNote(noteResult.note.id, updates);
- if (updateResult?.success && updateResult?.note) {
- broadcastToWindows("note-updated", updateResult.note);
- }
- }
-
- await this.windowManager.queueMeetingNoteNavigation({
- noteId: noteResult.note.id,
- folderId: meetingsFolder.id,
- event: detection.event,
- trigger: "calendar-join",
- });
-
- this.audioActivityDetector.resetPrompt();
- } else if (action === "dismiss") {
- if (detection) {
- this._dismiss();
- }
+ handleNotificationResponse(detectionId, action, options = {}, owner) {
+ if (!["start", "join", "dismiss"].includes(action))
+ return Promise.resolve({ success: false, code: "INVALID_REQUEST" });
+ if (owner.responsePromise) return owner.responsePromise;
+ if (action === "dismiss") {
+ this._dismiss();
+ this.activeDetections.delete(detectionId);
+ this.windowManager.dismissMeetingNotification({ notifyEngine: false });
+ return Promise.resolve({ success: true, value: null });
+ }
+ owner.responseInFlight = true;
+ this.windowManager.updateMeetingNotificationPause(owner);
+ owner.responsePromise = Promise.resolve()
+ .then(() => this._startNotification(owner, action, options))
+ .catch((error) => {
+ debugLogger.error("Meeting notification start failed", { error: error.message }, "meeting");
+ return {
+ success: false,
+ code: error.code === "NOTE_UNAVAILABLE" ? error.code : "START_FAILED",
+ };
+ })
+ .finally(() => {
+ owner.responseInFlight = false;
+ owner.responsePromise = null;
+ this.windowManager.updateMeetingNotificationPause(owner);
+ });
+ return owner.responsePromise;
+ }
+
+ async _startNotification(owner, action, options) {
+ if (action === "join" && !owner.joinDispatched) {
+ owner.joinDispatched = true;
+ const joinUrl = getMeetingJoinUrl(owner.detection.event);
+ if (joinUrl)
+ void openExternalUrl(joinUrl).catch((error) =>
+ debugLogger.error("Failed to open meeting link", { error: error.message }, "meeting")
+ );
+ }
+ const db = this.databaseManager;
+ const context = () =>
+ meetingDestinationContext(db, owner, this.windowManager.meetingRecentDestinations);
+ const eventId = notificationCalendarEventId(owner);
+ let note = owner.committedNoteId
+ ? db.getNote(owner.committedNoteId)
+ : eventId
+ ? db.getOwnNoteByCalendarEventId(eventId, { throwOnError: true })
+ : null;
+ const matches = (ref, row) =>
+ ref &&
+ ref.noteId === row.id &&
+ ref.spaceId === row.space_id &&
+ ref.folderId === row.folder_id;
+ if (note) {
+ if (!describeMeetingNote(db, note)) return { success: false, code: "NOTE_UNAVAILABLE" };
+ if (!matches(options.existingNote, note) && !matches(owner.authorizedNote, note)) {
+ return { success: false, code: "LINKED_NOTE_CHANGED", context: context() };
}
- } catch (error) {
+ } else {
+ if (owner.committedNoteId || options.existingNote || owner.authorizedNote)
+ return { success: false, code: "NOTE_UNAVAILABLE" };
+ const available = context();
+ const ref = owner.selectedDestination ?? available.defaultDestination;
+ const folder = resolveMeetingDestination(db, ref);
+ if (!folder) return { success: false, code: "FOLDER_UNAVAILABLE" };
+ const calendarEvent = eventId ? db.getCalendarEventById(eventId) : null;
+ const result = db.createMeetingNoteForNotification({
+ title: owner.detection.event?.summary || "New note",
+ folderId: folder.id,
+ spaceId: folder.space_id,
+ eventId,
+ participants: calendarEvent?.attendees,
+ });
+ note = result.note;
+ owner.committedNoteId = note.id;
+ if (!result.created)
+ return { success: false, code: "LINKED_NOTE_CHANGED", context: context() };
+ broadcastToWindows("note-added", note);
+ }
+ owner.authorizedNote = { noteId: note.id, spaceId: note.space_id, folderId: note.folder_id };
+ // Entered before navigation so a detection arriving meanwhile cannot
+ // replace this prompt and cancel the Start after its note is saved.
+ this._meetingModeActive = true;
+ const navigation = await this.windowManager.queueMeetingNoteNavigation(
+ { ...owner.authorizedNote, navigationId: randomUUID() },
+ { owner }
+ );
+ if (!navigation.success) {
this._meetingModeActive = false;
- debugLogger.error(
- "Error handling notification response",
- { error: error?.message, detectionId, action },
- "meeting"
- );
- } finally {
- // One overlay at a time — a response settles every pending detection,
- // including any the responded prompt replaced.
- this.activeDetections.clear();
- this.windowManager.dismissMeetingNotification();
+ return navigation;
}
+ this.audioActivityDetector.resetPrompt();
+ this.activeDetections.delete(owner.prompt.detectionId);
+ this.windowManager.dismissMeetingNotification({ notifyEngine: false });
+ return { success: true, value: null };
}
async startManualMeeting() {
@@ -628,9 +640,9 @@ class MeetingDetectionEngine {
}
// A card can vanish without a response — a compositor kill, a load failure,
- // onboarding taking the screen. Only this detection is released, unlike a
- // response or an expiry which settle every pending one: clearing them all
- // would strand _notificationQueue, whose entries the flush below looks up in
+ // onboarding taking the screen. Only this detection is released, unlike an
+ // expiry, which settles every pending one: clearing them all would strand
+ // _notificationQueue, whose entries the flush below looks up in
// activeDetections.
handleDetectionNotificationClosed(detectionId, { flushQueued = true } = {}) {
if (!this.activeDetections.has(detectionId)) return;
@@ -678,15 +690,17 @@ class MeetingDetectionEngine {
"meeting"
);
- const best = this._notificationQueue[0];
+ const [best, ...discarded] = this._notificationQueue;
+ this._notificationQueue = [];
+ // This flush coalesces the batch into one prompt. Entries it discards must
+ // not keep suppressing future microphone detections after that prompt ends.
+ for (const { source, key, data } of discarded) {
+ const id = `${source}:${key}`;
+ if (this.activeDetections.get(id)?.data === data) this.activeDetections.delete(id);
+ }
const detectionId = `${best.source}:${best.key}`;
-
const detection = this.activeDetections.get(detectionId);
- if (detection) {
- this._showPrompt(detectionId, best.source, best.key, best.data);
- }
-
- this._notificationQueue = [];
+ if (detection) this._showPrompt(detectionId, best.source, best.key, best.data);
}
_dismiss() {
diff --git a/src/helpers/meetingNotificationDestination.js b/src/helpers/meetingNotificationDestination.js
new file mode 100644
index 000000000..1ff64eddc
--- /dev/null
+++ b/src/helpers/meetingNotificationDestination.js
@@ -0,0 +1,103 @@
+function isMeetingFolderRef(ref) {
+ return Boolean(
+ ref &&
+ Number.isSafeInteger(ref.folderId) &&
+ ref.folderId > 0 &&
+ Number.isSafeInteger(ref.spaceId) &&
+ ref.spaceId > 0
+ );
+}
+
+function listMeetingDestinations(db) {
+ const spaces = db.getSpaces();
+ const spaceIds = new Set(spaces.map((space) => space.id));
+ const folders = db
+ .getFolders()
+ .filter((folder) => !folder.left_team && spaceIds.has(folder.space_id));
+ const defaultFolder = db.getMeetingsFolder();
+ const eligibleDefault = folders.find((folder) => folder.id === defaultFolder?.id);
+ return {
+ folders,
+ spaces,
+ defaultDestination: eligibleDefault
+ ? { folderId: eligibleDefault.id, spaceId: eligibleDefault.space_id }
+ : null,
+ };
+}
+
+function resolveMeetingDestination(db, ref) {
+ if (!isMeetingFolderRef(ref) || !db.getSpace(ref.spaceId)) return null;
+ return (
+ db.getFolders(ref.spaceId).find((folder) => folder.id === ref.folderId && !folder.left_team) ||
+ null
+ );
+}
+
+function rememberMeetingDestination(recent, ref) {
+ return [
+ { ...ref },
+ ...recent.filter((item) => item.folderId !== ref.folderId || item.spaceId !== ref.spaceId),
+ ].slice(0, 5);
+}
+
+function pruneMeetingDestinations(recent, folders) {
+ return recent.filter((ref) =>
+ folders.some((folder) => folder.id === ref.folderId && folder.space_id === ref.spaceId)
+ );
+}
+
+function notificationCalendarEventId(owner) {
+ const event = owner.detection.event;
+ return event?.calendar_id && !["__detected__", "__manual__"].includes(event.calendar_id)
+ ? event.id
+ : null;
+}
+
+function describeMeetingNote(db, note) {
+ if (!note || note.deleted_at || note.left_team) return null;
+ const space = db.getSpace(note.space_id);
+ if (!space) return null;
+ const folder =
+ note.folder_id == null
+ ? null
+ : resolveMeetingDestination(db, { folderId: note.folder_id, spaceId: note.space_id });
+ if (note.folder_id != null && !folder) return null;
+ return {
+ noteId: note.id,
+ spaceId: space.id,
+ folderId: folder?.id ?? null,
+ spaceName: space.name,
+ folderName: folder?.name ?? null,
+ shared: space.kind === "team",
+ };
+}
+
+function meetingDestinationContext(db, owner, recent) {
+ const context = listMeetingDestinations(db);
+ const eventId = notificationCalendarEventId(owner);
+ const note = owner.committedNoteId
+ ? db.getNote(owner.committedNoteId)
+ : eventId
+ ? db.getOwnNoteByCalendarEventId(eventId, { throwOnError: true })
+ : null;
+ const existingNote = describeMeetingNote(db, note);
+ if ((note || owner.committedNoteId) && !existingNote)
+ throw Object.assign(new Error("Note unavailable"), { code: "NOTE_UNAVAILABLE" });
+ return {
+ ...context,
+ selectedDestination: owner.selectedDestination,
+ recentDestinations: pruneMeetingDestinations(recent, context.folders),
+ existingNote,
+ };
+}
+
+module.exports = {
+ isMeetingFolderRef,
+ listMeetingDestinations,
+ resolveMeetingDestination,
+ rememberMeetingDestination,
+ pruneMeetingDestinations,
+ notificationCalendarEventId,
+ describeMeetingNote,
+ meetingDestinationContext,
+};
diff --git a/src/helpers/windowConfig.js b/src/helpers/windowConfig.js
index 032e88682..7751ce3e4 100644
--- a/src/helpers/windowConfig.js
+++ b/src/helpers/windowConfig.js
@@ -264,8 +264,8 @@ const CONTROL_PANEL_CONFIG = {
};
const NOTIFICATION_WINDOW_CONFIG = {
- width: 392,
- height: 92,
+ width: 416,
+ height: 84,
frame: false,
transparent: true,
alwaysOnTop: true,
@@ -285,6 +285,19 @@ const NOTIFICATION_WINDOW_CONFIG = {
type: OVERLAY_WINDOW_TYPES.notification,
};
+function fitMeetingNotificationWindow(contentHeight, workArea) {
+ const width = Math.max(1, Math.min(NOTIFICATION_WINDOW_CONFIG.width, workArea.width));
+ const height = Math.max(1, Math.min(Math.ceil(contentHeight), 512, workArea.height));
+ const marginX = Math.min(16, Math.max(0, workArea.width - width));
+ const marginY = Math.min(16, Math.max(0, workArea.height - height));
+ return {
+ x: workArea.x + workArea.width - width - marginX,
+ y: workArea.y + marginY,
+ width,
+ height,
+ };
+}
+
class WindowPositionUtil {
static getMainWindowPosition(display, customSize = null, position = "bottom-right") {
const { width, height } = customSize || WINDOW_SIZES.BASE;
@@ -326,18 +339,10 @@ class WindowPositionUtil {
}
static getNotificationPosition(display) {
- const { width, height } = NOTIFICATION_WINDOW_CONFIG;
- const MARGIN = 16;
- const workArea = display.workArea || display.bounds;
- // Same negative-origin trap as getMainWindowPosition: clamp to the display,
- // not to zero, or a monitor above the primary one puts the prompt nowhere.
- const bounds = {
- x: workArea.x + workArea.width - width - MARGIN,
- y: workArea.y + MARGIN,
- width,
- height,
- };
- return { ...WindowPositionUtil.clampToWorkArea(bounds, display), width, height };
+ return fitMeetingNotificationWindow(
+ NOTIFICATION_WINDOW_CONFIG.height,
+ display.workArea || display.bounds
+ );
}
// `level` only applies on macOS; Windows and Linux already use the strongest
@@ -377,6 +382,7 @@ class WindowPositionUtil {
}
module.exports = {
+ fitMeetingNotificationWindow,
MAIN_WINDOW_CONFIG,
CONTROL_PANEL_CONFIG,
ONBOARDING_WINDOW_SIZES,
diff --git a/src/helpers/windowManager.js b/src/helpers/windowManager.js
index e4bc2cca1..954341e4a 100644
--- a/src/helpers/windowManager.js
+++ b/src/helpers/windowManager.js
@@ -1,5 +1,11 @@
const { app, screen, BrowserWindow, dialog, ipcMain, Menu } = require("electron");
const debugLogger = require("./debugLogger");
+const tokenStore = require("./tokenStore");
+const accountScopeBinding = require("./accountScopeBinding");
+const {
+ describeMeetingNote,
+ meetingDestinationContext,
+} = require("./meetingNotificationDestination");
const { createLinuxWindowInputRegion } = require("./linuxWindowInputRegion");
// Aliased: this class has an openExternalUrl method wrapping the helper.
const { openExternalUrl: openUrlInExternalBrowser } = require("./externalUrlOpener");
@@ -35,6 +41,7 @@ const {
CONTROL_PANEL_CONFIG,
ONBOARDING_WINDOW_SIZES,
NOTIFICATION_WINDOW_CONFIG,
+ fitMeetingNotificationWindow,
fitAssistantContentWindowToWorkArea,
fitAssistantWindowToWorkArea,
fitDictationErrorContentWindowToWorkArea,
@@ -44,6 +51,13 @@ const {
WindowPositionUtil,
} = require("./windowConfig");
const AGENT_DICTATION_PILL_SIZE = Object.freeze({ ...WINDOW_SIZES.BASE });
+// The collapsed prompt card, inset 4px inside the notification window.
+const MEETING_NOTIFICATION_CARD_REGION = Object.freeze({
+ x: 4,
+ y: 4,
+ width: NOTIFICATION_WINDOW_CONFIG.width - 8,
+ height: NOTIFICATION_WINDOW_CONFIG.height - 8,
+});
const { centeredBounds, clampedBounds } = require("./onboardingWindowBounds");
const { ONBOARDING_DEMO_KINDS, isOnboardingInputAllowed } = require("./onboardingInputPolicy");
const { createHotkeyRepeatGate } = require("./hotkeyRepeatGate");
@@ -67,6 +81,8 @@ class WindowManager {
// Set by main.js so the tray's listen item rebuilds with dictation state.
this.onDictationStateChanged = null;
this.notificationWindow = null;
+ this._meetingNotificationOwner = null;
+ this.meetingRecentDestinations = [];
this.agentDictationPillWindow = null;
this._agentDictationPillReady = false;
this._agentDictationPillSize = AGENT_DICTATION_PILL_SIZE;
@@ -275,27 +291,151 @@ class WindowManager {
}
}
- // Only the meeting prompt owns this: another overlay reporting its own hover
- // must not pause a countdown it cannot resume — it may be destroyed before
- // its pointer ever leaves.
- setNotificationInteractivity(sender, interactive) {
- const win = this.notificationWindow;
- if (!win || win.isDestroyed() || sender !== win.webContents) {
- return;
+ // Every token or account change retires the prompt first, so only the
+ // current binding has to agree with the database's account.
+ hasMeetingNotificationScope() {
+ const database = this.meetingDetectionEngine?.databaseManager;
+ if (!database) return false;
+ const state = tokenStore.getState();
+ // A token without a valid binding scopes like no token (signed out).
+ const boundAccountId = state.token
+ ? (accountScopeBinding.resolveActiveAccountScope({
+ ...state,
+ binding: accountScopeBinding.read(),
+ })?.accountId ?? null)
+ : null;
+ return boundAccountId === database.activeAccountId;
+ }
+
+ captureMeetingNotificationOwner(sender) {
+ const owner = this._meetingNotificationOwner;
+ return owner && owner.window.webContents === sender && this.isMeetingNotificationOwner(owner)
+ ? owner
+ : null;
+ }
+
+ isMeetingNotificationOwner(owner) {
+ return Boolean(
+ owner &&
+ owner === this._meetingNotificationOwner &&
+ !owner.window.isDestroyed() &&
+ !this._onboardingActive &&
+ owner.detection &&
+ this.meetingDetectionEngine?.activeDetections?.get(owner.prompt.detectionId) ===
+ owner.detection &&
+ this.hasMeetingNotificationScope()
+ );
+ }
+
+ retireMeetingNotificationScope() {
+ this.meetingRecentDestinations = [];
+ this._pendingMeetingNoteNavigation = null;
+ this._cancelMeetingNavigation("STALE_NOTIFICATION");
+ if (this.meetingDetectionEngine) {
+ this.meetingDetectionEngine._notificationQueue = [];
+ this.meetingDetectionEngine.activeDetections.clear();
}
- // Linux ignores the `forward` option, so a card returned to click-through
- // there never sees another mouseenter and Start/Dismiss stay unreachable
- // for the rest of its life (#1456). It is only click-through on macOS to
- // begin with, so on Linux leave the hit-testing alone and move the
- // countdown alone.
- const togglesClickThrough = process.platform !== "linux";
- if (interactive) {
- if (togglesClickThrough) win.setIgnoreMouseEvents(false);
+ this.dismissMeetingNotification({ notifyEngine: false });
+ }
+
+ updateMeetingNotificationPause(owner) {
+ if (owner !== this._meetingNotificationOwner) return;
+ if (owner.pointerInside || owner.mode !== "closed" || owner.responseInFlight) {
this._notificationDismissTimer.pause();
- } else {
- if (togglesClickThrough) win.setIgnoreMouseEvents(true, { forward: true });
- this._notificationDismissTimer.resume();
+ } else this._notificationDismissTimer.resume();
+ }
+
+ setNotificationInteractivity(sender, interactive) {
+ const win = this.notificationWindow;
+ if (!win || win.isDestroyed() || sender !== win.webContents) return;
+ if (process.platform !== "linux") win.setIgnoreMouseEvents(!interactive, { forward: true });
+ const owner = this._meetingNotificationOwner;
+ owner.pointerInside = interactive;
+ this.updateMeetingNotificationPause(owner);
+ }
+
+ setMeetingNotificationSurface(owner, state) {
+ if (!this.isMeetingNotificationOwner(owner))
+ return { success: false, code: "STALE_NOTIFICATION" };
+ if (
+ !state ||
+ !Number.isSafeInteger(state.revision) ||
+ state.revision <= owner.layoutRevision ||
+ !["closed", "list", "form"].includes(state.mode) ||
+ !["request", "release", "keep"].includes(state.focus) ||
+ !Number.isFinite(state.contentHeight) ||
+ state.contentHeight <= 0 ||
+ state.contentHeight > 4096 ||
+ !Array.isArray(state.regions) ||
+ !state.regions.length ||
+ state.regions.length > 16 ||
+ state.regions.some(
+ (r) =>
+ !r ||
+ ![r.x, r.y, r.width, r.height].every(Number.isFinite) ||
+ r.x < 0 ||
+ r.y < 0 ||
+ r.width <= 0 ||
+ r.height <= 0 ||
+ r.x + r.width > NOTIFICATION_WINDOW_CONFIG.width ||
+ r.y + r.height > 4096
+ )
+ ) {
+ return { success: false, code: "INVALID_REQUEST" };
}
+ const win = owner.window;
+ const display = screen.getDisplayMatching(win.getBounds());
+ const bounds = fitMeetingNotificationWindow(
+ state.contentHeight,
+ display.workArea || display.bounds
+ );
+ const regions = state.regions
+ .map((r) => ({
+ x: Math.min(Math.round(r.x), bounds.width),
+ y: Math.min(Math.round(r.y), bounds.height),
+ width: Math.max(0, Math.min(Math.ceil(r.width), bounds.width - Math.round(r.x))),
+ height: Math.max(0, Math.min(Math.ceil(r.height), bounds.height - Math.round(r.y))),
+ }))
+ .filter((r) => r.width > 0 && r.height > 0);
+ if (!regions.length) return { success: false, code: "INVALID_REQUEST" };
+ owner.layoutRevision = state.revision;
+ owner.mode = state.mode;
+ owner.surface = state;
+ const previousBounds = win.getBounds();
+ if (Object.keys(bounds).some((key) => bounds[key] !== previousBounds[key]))
+ win.setBounds(bounds);
+ if (process.platform === "linux") win.setShape(regions);
+ if (state.focus === "request" && state.mode !== "closed") {
+ if (process.platform !== "linux") win.setFocusable(true);
+ // macOS panels need show() to activate after becoming focusable. Only an
+ // explicit chooser action reaches here; measurement never raises them.
+ win.show();
+ win.focus();
+ } else if (state.focus === "release") {
+ // macOS blur orders the window out and back, blinking the whole card.
+ // Match the assistant panel: keep it visible while disabling input focus.
+ if (process.platform !== "darwin") win.blur();
+ if (process.platform !== "linux") win.setFocusable(false);
+ }
+ const cursor = screen.getCursorScreenPoint();
+ owner.pointerInside = regions.some(
+ (r) =>
+ cursor.x >= bounds.x + r.x &&
+ cursor.x < bounds.x + r.x + r.width &&
+ cursor.y >= bounds.y + r.y &&
+ cursor.y < bounds.y + r.y + r.height
+ );
+ if (process.platform !== "linux")
+ win.setIgnoreMouseEvents(!owner.pointerInside, { forward: true });
+ this.updateMeetingNotificationPause(owner);
+ return {
+ success: true,
+ value: {
+ width: bounds.width,
+ height: bounds.height,
+ maxHeight: fitMeetingNotificationWindow(512, display.workArea || display.bounds).height,
+ },
+ };
}
resizeMainWindow(sizeKey) {
@@ -2049,6 +2189,17 @@ class WindowManager {
async showMeetingNotification(promptData, { autoDismiss = true } = {}) {
if (this._onboardingActive) return false;
+ this._cancelMeetingNavigation("STALE_NOTIFICATION");
+ const previousOwner = this._meetingNotificationOwner;
+ if (
+ previousOwner?.detection &&
+ previousOwner.prompt.detectionId !== promptData.detectionId &&
+ this.meetingDetectionEngine?.activeDetections?.get(previousOwner.prompt.detectionId) ===
+ previousOwner.detection
+ ) {
+ this.meetingDetectionEngine.activeDetections.delete(previousOwner.prompt.detectionId);
+ }
+ this._meetingNotificationOwner = null;
if (this.notificationWindow && !this.notificationWindow.isDestroyed()) {
const previousWindow = this.notificationWindow;
this.notificationWindow = null;
@@ -2066,6 +2217,8 @@ class WindowManager {
const win = new BrowserWindow({
...NOTIFICATION_WINDOW_CONFIG,
+ // Linux has no setFocusable, so the picker's typing needs this from creation.
+ ...(process.platform === "linux" && { focusable: true, type: "normal" }),
...position,
});
this.notificationWindow = win;
@@ -2076,6 +2229,7 @@ class WindowManager {
if (this.notificationWindow !== win) return;
const closedDetectionId = this._pendingNotificationData?.detectionId ?? null;
this.notificationWindow = null;
+ this._meetingNotificationOwner = null;
this._pendingNotificationData = null;
this._notificationDismissTimer.cancel();
if (this._notificationReadyFallback) {
@@ -2098,6 +2252,57 @@ class WindowManager {
WindowPositionUtil.setupAlwaysOnTop(win, { level: "screen-saver" });
this._pendingNotificationData = promptData;
+ const owner = {
+ prompt: promptData,
+ window: win,
+ detection: this.meetingDetectionEngine?.activeDetections?.get(promptData.detectionId),
+ selectedDestination: null,
+ createRequests: new Map(),
+ layoutRevision: 0,
+ mode: "closed",
+ pointerInside: false,
+ };
+ this._meetingNotificationOwner = owner;
+ const retireRenderer = () => {
+ if (this._meetingNotificationOwner !== owner) return;
+ this.dismissMeetingNotification();
+ };
+ const notificationContents = win.webContents;
+ notificationContents.once("render-process-gone", retireRenderer);
+ win.on("closed", () => {
+ notificationContents.removeListener("render-process-gone", retireRenderer);
+ });
+ if (process.platform === "linux") win.setShape([MEETING_NOTIFICATION_CARD_REGION]);
+ win.on("blur", () => {
+ if (!this.isMeetingNotificationOwner(owner) || owner.mode === "closed") return;
+ this.setMeetingNotificationSurface(owner, {
+ revision: owner.layoutRevision + 1,
+ mode: "closed",
+ contentHeight: NOTIFICATION_WINDOW_CONFIG.height,
+ regions: [MEETING_NOTIFICATION_CARD_REGION],
+ focus: "release",
+ });
+ win.webContents.send("meeting-notification-surface-closed", {
+ revision: owner.layoutRevision,
+ });
+ });
+ const refit = () => {
+ if (!this.isMeetingNotificationOwner(owner) || !owner.surface) return;
+ this.setMeetingNotificationSurface(owner, {
+ ...owner.surface,
+ revision: owner.layoutRevision + 1,
+ focus: "keep",
+ });
+ win.webContents.send("meeting-notification-surface-resized", {
+ revision: owner.layoutRevision,
+ });
+ };
+ for (const event of ["display-metrics-changed", "display-removed", "display-added"])
+ screen.on(event, refit);
+ win.on("closed", () => {
+ for (const event of ["display-metrics-changed", "display-removed", "display-added"])
+ screen.removeListener(event, refit);
+ });
// Everything past the load addresses `win` directly: a replacement taking
// over mid-load must not have this prompt's data, countdown or force-show
@@ -2163,6 +2368,7 @@ class WindowManager {
dismissMeetingNotification({ notifyEngine = true, flushQueued = true } = {}) {
const notification = this._pendingNotificationData;
+ this._meetingNotificationOwner = null;
this._pendingNotificationData = null;
if (this._notificationReadyFallback) {
clearTimeout(this._notificationReadyFallback);
@@ -2191,18 +2397,146 @@ class WindowManager {
}
}
- async queueMeetingNoteNavigation(payload) {
- this._pendingMeetingNoteNavigation = payload;
- await this.createControlPanelWindow();
- this.sendToControlPanel("meeting-note-navigation-pending");
+ async queueMeetingNoteNavigation(payload, options) {
+ if (!payload.navigationId) {
+ this._pendingMeetingNoteNavigation = payload;
+ await this.createControlPanelWindow();
+ this.sendToControlPanel("meeting-note-navigation-pending");
+ return;
+ }
+ if (!this.isMeetingNotificationOwner(options.owner))
+ return { success: false, code: "STALE_NOTIFICATION" };
+ this._cancelMeetingNavigation("STALE_NOTIFICATION");
+ let resolve;
+ const result = new Promise((done) => {
+ resolve = done;
+ });
+ const operation = {
+ payload,
+ owner: options.owner,
+ resolve,
+ consumed: false,
+ panel: null,
+ };
+ this._meetingNavigationOperation = operation;
+ // Bound panel creation as well as the renderer handshake; reset at delivery.
+ operation.timer = setTimeout(
+ () => this._settleMeetingNavigation(operation, { success: false, code: "START_FAILED" }),
+ 15000
+ );
+ void (async () => {
+ try {
+ await this.createControlPanelWindow();
+ if (this._meetingNavigationOperation !== operation) return;
+ const panel = this.controlPanelWindow;
+ if (!panel || panel.isDestroyed()) throw new Error("Panel unavailable");
+ operation.panel = panel;
+ operation.contents = panel.webContents;
+ operation.onClose = () =>
+ this._settleMeetingNavigation(operation, { success: false, code: "START_FAILED" });
+ panel.once("closed", operation.onClose);
+ panel.webContents.once("render-process-gone", operation.onClose);
+ const deliver = () => {
+ if (this._meetingNavigationOperation !== operation) return;
+ if (this.controlPanelWindow !== panel || panel.isDestroyed()) {
+ this._settleMeetingNavigation(operation, {
+ success: false,
+ code: "STALE_NOTIFICATION",
+ });
+ return;
+ }
+ clearTimeout(operation.timer);
+ operation.timer = setTimeout(
+ () =>
+ this._settleMeetingNavigation(operation, { success: false, code: "START_FAILED" }),
+ 15000
+ );
+ this._pendingMeetingNoteNavigation = payload;
+ panel.webContents.send("meeting-note-navigation-pending");
+ };
+ operation.deliver = deliver;
+ // Not did-finish-load: creating a panel resolves inside it, with isLoading() still true.
+ // Waiting keeps a reloading panel's outgoing document from taking the navigation.
+ if (panel.webContents.isLoading()) panel.webContents.once("did-stop-loading", deliver);
+ else deliver();
+ } catch {
+ this._settleMeetingNavigation(operation, { success: false, code: "START_FAILED" });
+ }
+ })();
+ return result;
+ }
+
+ _settleMeetingNavigation(operation, result) {
+ if (this._meetingNavigationOperation !== operation) return;
+ this._meetingNavigationOperation = null;
+ clearTimeout(operation.timer);
+ operation.panel?.removeListener("closed", operation.onClose);
+ operation.contents?.removeListener("render-process-gone", operation.onClose);
+ if (operation.deliver) operation.contents.removeListener("did-stop-loading", operation.deliver);
+ if (this._pendingMeetingNoteNavigation === operation.payload)
+ this._pendingMeetingNoteNavigation = null;
+ operation.resolve(result);
+ }
+
+ _cancelMeetingNavigation(code) {
+ const operation = this._meetingNavigationOperation;
+ if (operation) this._settleMeetingNavigation(operation, { success: false, code });
}
- consumePendingMeetingNoteNavigation() {
+ consumePendingMeetingNoteNavigation(sender) {
const payload = this._pendingMeetingNoteNavigation;
+ if (payload?.navigationId) {
+ const operation = this._meetingNavigationOperation;
+ if (
+ !operation ||
+ operation.payload !== payload ||
+ operation.panel !== this.controlPanelWindow ||
+ operation.contents !== sender
+ )
+ return null;
+ operation.consumed = true;
+ }
this._pendingMeetingNoteNavigation = null;
return payload;
}
+ confirmMeetingNoteNavigation(sender, navigationId, status = "ready") {
+ const operation = this._meetingNavigationOperation;
+ if (
+ !operation ||
+ operation.payload.navigationId !== navigationId ||
+ !operation.consumed ||
+ operation.panel !== this.controlPanelWindow ||
+ operation.contents !== sender
+ ) {
+ return { success: false, code: "STALE_NOTIFICATION" };
+ }
+ let result;
+ if (status === "cancel") result = { success: false, code: "START_FAILED" };
+ else if (status !== "ready") return { success: false, code: "INVALID_REQUEST" };
+ else {
+ try {
+ const db = this.meetingDetectionEngine.databaseManager;
+ const note = db.getNote(operation.payload.noteId);
+ if (!describeMeetingNote(db, note)) result = { success: false, code: "NOTE_UNAVAILABLE" };
+ else if (
+ note.space_id !== operation.payload.spaceId ||
+ note.folder_id !== operation.payload.folderId
+ ) {
+ result = {
+ success: false,
+ code: "LINKED_NOTE_CHANGED",
+ context: meetingDestinationContext(db, operation.owner, this.meetingRecentDestinations),
+ };
+ } else result = { success: true, value: note };
+ } catch {
+ result = { success: false, code: "NOTE_UNAVAILABLE" };
+ }
+ }
+ this._settleMeetingNavigation(operation, result);
+ return result;
+ }
+
async queueNoteNavigation(payload) {
this._pendingNoteNavigation = payload;
await this.createControlPanelWindow();
diff --git a/src/locales/ar/translation.json b/src/locales/ar/translation.json
index a0af9a69c..51eebeeb4 100644
--- a/src/locales/ar/translation.json
+++ b/src/locales/ar/translation.json
@@ -4895,7 +4895,42 @@
"underway": "يبدو أن اجتماعك جارٍ بالفعل. هل ترغب في تدوين الملاحظات؟"
},
"start": "تدوين الملاحظات",
- "join": "انضمام وتفريغ صوتي"
+ "join": "انضمام وتفريغ صوتي",
+ "folders": {
+ "choose": "اختيار مجلد الاجتماع",
+ "search": "البحث عن مجلدات",
+ "clear": "مسح البحث",
+ "private": "خاص",
+ "shared": "مشترك",
+ "current": "الموقع الحالي",
+ "recent": "المستخدمة مؤخرًا",
+ "folders": "المجلدات",
+ "new": "مجلد جديد",
+ "name": "الاسم",
+ "location": "الموقع",
+ "cancel": "إلغاء",
+ "create": "إنشاء واختيار",
+ "empty": "لم يتم العثور على مجلدات. جرّب اسمًا آخر أو أنشئ مجلدًا.",
+ "loading": "جارٍ تحميل المجلدات…",
+ "unavailable": "تعذر تحميل المجلدات.",
+ "retry": "إعادة المحاولة",
+ "dismiss": "إغلاق إشعار الاجتماع",
+ "selected": "تم اختيار {{destination}}",
+ "linked": "لهذا الاجتماع ملاحظة بالفعل. ستبقى في {{destination}} عند الانضمام.",
+ "errors": {
+ "STALE_NOTIFICATION": "لم يعد هذا الإشعار ساريًا.",
+ "INVALID_REQUEST": "تعذر الإكمال. حاول مجددًا.",
+ "FOLDERS_UNAVAILABLE": "تعذر تحميل المجلدات.",
+ "FOLDER_UNAVAILABLE": "هذا الموقع غير متاح. اختر مجلدًا آخر.",
+ "SPACE_UNAVAILABLE": "هذا الموقع غير متاح. اختر مجلدًا آخر.",
+ "FOLDER_NAME_REQUIRED": "أدخل اسم المجلد.",
+ "FOLDER_NAME_TAKEN": "يوجد مجلد بهذا الاسم في هذا الموقع.",
+ "CREATE_FAILED": "تعذر الإكمال. حاول مجددًا.",
+ "LINKED_NOTE_CHANGED": "راجع الموقع، ثم انضم مجددًا.",
+ "NOTE_UNAVAILABLE": "هذه الملاحظة غير متاحة. أعد المحاولة دون إنشاء بديل.",
+ "START_FAILED": "تعذر الإكمال. حاول مجددًا."
+ }
+ }
},
"providerErrors": {
"authFailed": "رفض {{provider}} مفتاح API الخاص بك.",
diff --git a/src/locales/de/translation.json b/src/locales/de/translation.json
index 672723297..fbe174ba7 100644
--- a/src/locales/de/translation.json
+++ b/src/locales/de/translation.json
@@ -4773,7 +4773,42 @@
"underway": "Es klingt, als wäre dein Meeting schon im Gange. Notizen aufnehmen?"
},
"start": "Notizen aufnehmen",
- "join": "Beitreten & transkribieren"
+ "join": "Beitreten & transkribieren",
+ "folders": {
+ "choose": "Besprechungsordner auswählen",
+ "search": "Ordner suchen",
+ "clear": "Suche löschen",
+ "private": "Privat",
+ "shared": "Geteilt",
+ "current": "Aktueller Speicherort",
+ "recent": "Zuletzt verwendet",
+ "folders": "Ordner",
+ "new": "Neuer Ordner",
+ "name": "Name",
+ "location": "Speicherort",
+ "cancel": "Abbrechen",
+ "create": "Erstellen und auswählen",
+ "empty": "Keine Ordner gefunden. Suche einen anderen Namen oder erstelle einen Ordner.",
+ "loading": "Ordner werden geladen…",
+ "unavailable": "Ordner konnten nicht geladen werden.",
+ "retry": "Erneut versuchen",
+ "dismiss": "Besprechungsbenachrichtigung schließen",
+ "selected": "{{destination}} ausgewählt",
+ "linked": "Für diese Besprechung gibt es bereits eine Notiz. Beim Beitreten bleibt sie in {{destination}}.",
+ "errors": {
+ "STALE_NOTIFICATION": "Diese Benachrichtigung ist nicht mehr aktuell.",
+ "INVALID_REQUEST": "Vorgang fehlgeschlagen. Bitte erneut versuchen.",
+ "FOLDERS_UNAVAILABLE": "Ordner konnten nicht geladen werden.",
+ "FOLDER_UNAVAILABLE": "Dieser Speicherort ist nicht verfügbar. Wähle einen anderen Ordner.",
+ "SPACE_UNAVAILABLE": "Dieser Speicherort ist nicht verfügbar. Wähle einen anderen Ordner.",
+ "FOLDER_NAME_REQUIRED": "Gib einen Ordnernamen ein.",
+ "FOLDER_NAME_TAKEN": "An diesem Speicherort existiert bereits ein Ordner mit diesem Namen.",
+ "CREATE_FAILED": "Vorgang fehlgeschlagen. Bitte erneut versuchen.",
+ "LINKED_NOTE_CHANGED": "Prüfe den Speicherort und tritt erneut bei.",
+ "NOTE_UNAVAILABLE": "Diese Notiz ist nicht verfügbar. Versuche es erneut, ohne eine neue zu erstellen.",
+ "START_FAILED": "Vorgang fehlgeschlagen. Bitte erneut versuchen."
+ }
+ }
},
"providerErrors": {
"authFailed": "{{provider}} hat Ihren API-Schlüssel abgelehnt.",
diff --git a/src/locales/en/translation.json b/src/locales/en/translation.json
index aab15ea85..0956d90d0 100644
--- a/src/locales/en/translation.json
+++ b/src/locales/en/translation.json
@@ -4773,7 +4773,42 @@
"underway": "It sounds like your meeting is underway. Want to take notes?"
},
"start": "Take notes",
- "join": "Join & transcribe"
+ "join": "Join and transcribe",
+ "folders": {
+ "choose": "Choose meeting folder",
+ "search": "Search folders",
+ "clear": "Clear search",
+ "private": "Private",
+ "shared": "Shared",
+ "current": "Current destination",
+ "recent": "Recently used",
+ "folders": "Folders",
+ "new": "New folder",
+ "name": "Name",
+ "location": "Location",
+ "cancel": "Cancel",
+ "create": "Create & select",
+ "empty": "No folders found. Try another name, or create a folder.",
+ "loading": "Loading folders…",
+ "unavailable": "Folders could not be loaded.",
+ "retry": "Retry",
+ "dismiss": "Dismiss meeting notification",
+ "selected": "Selected {{destination}}",
+ "linked": "This meeting already has a note. Joining keeps it in {{destination}}.",
+ "errors": {
+ "STALE_NOTIFICATION": "This notification is no longer current.",
+ "INVALID_REQUEST": "Could not finish. Please retry.",
+ "FOLDERS_UNAVAILABLE": "Folders could not be loaded.",
+ "FOLDER_UNAVAILABLE": "This destination is unavailable. Choose another folder.",
+ "SPACE_UNAVAILABLE": "This destination is unavailable. Choose another folder.",
+ "FOLDER_NAME_REQUIRED": "Enter a folder name.",
+ "FOLDER_NAME_TAKEN": "A folder with that name already exists in this location.",
+ "CREATE_FAILED": "Could not finish. Please retry.",
+ "LINKED_NOTE_CHANGED": "Review the destination, then join again.",
+ "NOTE_UNAVAILABLE": "This note is unavailable. Retry without creating a replacement.",
+ "START_FAILED": "Could not finish. Please retry."
+ }
+ }
},
"providerErrors": {
"authFailed": "{{provider}} rejected your API key.",
diff --git a/src/locales/es/translation.json b/src/locales/es/translation.json
index bf97741b6..bd12226ee 100644
--- a/src/locales/es/translation.json
+++ b/src/locales/es/translation.json
@@ -4773,7 +4773,42 @@
"underway": "Parece que tu reunión ya está en curso. ¿Quieres tomar notas?"
},
"start": "Tomar notas",
- "join": "Unirse y transcribir"
+ "join": "Unirse y transcribir",
+ "folders": {
+ "choose": "Elegir carpeta de la reunión",
+ "search": "Buscar carpetas",
+ "clear": "Borrar búsqueda",
+ "private": "Privado",
+ "shared": "Compartido",
+ "current": "Destino actual",
+ "recent": "Usadas recientemente",
+ "folders": "Carpetas",
+ "new": "Nueva carpeta",
+ "name": "Nombre",
+ "location": "Ubicación",
+ "cancel": "Cancelar",
+ "create": "Crear y seleccionar",
+ "empty": "No se encontraron carpetas. Prueba otro nombre o crea una carpeta.",
+ "loading": "Cargando carpetas…",
+ "unavailable": "No se pudieron cargar las carpetas.",
+ "retry": "Reintentar",
+ "dismiss": "Cerrar notificación de reunión",
+ "selected": "{{destination}} seleccionado",
+ "linked": "Esta reunión ya tiene una nota. Al unirte, permanecerá en {{destination}}.",
+ "errors": {
+ "STALE_NOTIFICATION": "Esta notificación ya no está vigente.",
+ "INVALID_REQUEST": "No se pudo completar. Vuelve a intentarlo.",
+ "FOLDERS_UNAVAILABLE": "No se pudieron cargar las carpetas.",
+ "FOLDER_UNAVAILABLE": "Este destino no está disponible. Elige otra carpeta.",
+ "SPACE_UNAVAILABLE": "Este destino no está disponible. Elige otra carpeta.",
+ "FOLDER_NAME_REQUIRED": "Introduce un nombre de carpeta.",
+ "FOLDER_NAME_TAKEN": "Ya existe una carpeta con ese nombre en esta ubicación.",
+ "CREATE_FAILED": "No se pudo completar. Vuelve a intentarlo.",
+ "LINKED_NOTE_CHANGED": "Revisa el destino y vuelve a unirte.",
+ "NOTE_UNAVAILABLE": "Esta nota no está disponible. Reintenta sin crear otra.",
+ "START_FAILED": "No se pudo completar. Vuelve a intentarlo."
+ }
+ }
},
"providerErrors": {
"authFailed": "{{provider}} rechazó tu clave de API.",
diff --git a/src/locales/fr/translation.json b/src/locales/fr/translation.json
index a3ea51d55..548468a17 100644
--- a/src/locales/fr/translation.json
+++ b/src/locales/fr/translation.json
@@ -4773,7 +4773,42 @@
"underway": "On dirait que votre réunion est déjà en cours. Vous voulez prendre des notes ?"
},
"start": "Prendre des notes",
- "join": "Rejoindre et transcrire"
+ "join": "Rejoindre et transcrire",
+ "folders": {
+ "choose": "Choisir le dossier de réunion",
+ "search": "Rechercher des dossiers",
+ "clear": "Effacer la recherche",
+ "private": "Privé",
+ "shared": "Partagé",
+ "current": "Destination actuelle",
+ "recent": "Récemment utilisés",
+ "folders": "Dossiers",
+ "new": "Nouveau dossier",
+ "name": "Nom",
+ "location": "Emplacement",
+ "cancel": "Annuler",
+ "create": "Créer et sélectionner",
+ "empty": "Aucun dossier trouvé. Essayez un autre nom ou créez un dossier.",
+ "loading": "Chargement des dossiers…",
+ "unavailable": "Impossible de charger les dossiers.",
+ "retry": "Réessayer",
+ "dismiss": "Fermer la notification de réunion",
+ "selected": "{{destination}} sélectionné",
+ "linked": "Cette réunion a déjà une note. Elle restera dans {{destination}} lorsque vous rejoindrez la réunion.",
+ "errors": {
+ "STALE_NOTIFICATION": "Cette notification n’est plus à jour.",
+ "INVALID_REQUEST": "Impossible de terminer. Réessayez.",
+ "FOLDERS_UNAVAILABLE": "Impossible de charger les dossiers.",
+ "FOLDER_UNAVAILABLE": "Cette destination est indisponible. Choisissez un autre dossier.",
+ "SPACE_UNAVAILABLE": "Cette destination est indisponible. Choisissez un autre dossier.",
+ "FOLDER_NAME_REQUIRED": "Saisissez un nom de dossier.",
+ "FOLDER_NAME_TAKEN": "Un dossier porte déjà ce nom à cet emplacement.",
+ "CREATE_FAILED": "Impossible de terminer. Réessayez.",
+ "LINKED_NOTE_CHANGED": "Vérifiez la destination, puis rejoignez à nouveau.",
+ "NOTE_UNAVAILABLE": "Cette note est indisponible. Réessayez sans en créer une autre.",
+ "START_FAILED": "Impossible de terminer. Réessayez."
+ }
+ }
},
"providerErrors": {
"authFailed": "{{provider}} a rejeté votre clé API.",
diff --git a/src/locales/it/translation.json b/src/locales/it/translation.json
index 40fdcff82..3bc108a7e 100644
--- a/src/locales/it/translation.json
+++ b/src/locales/it/translation.json
@@ -4773,7 +4773,42 @@
"underway": "Sembra che la tua riunione sia già in corso. Vuoi prendere appunti?"
},
"start": "Prendi appunti",
- "join": "Partecipa e trascrivi"
+ "join": "Partecipa e trascrivi",
+ "folders": {
+ "choose": "Scegli cartella della riunione",
+ "search": "Cerca cartelle",
+ "clear": "Cancella ricerca",
+ "private": "Privato",
+ "shared": "Condiviso",
+ "current": "Destinazione attuale",
+ "recent": "Usate di recente",
+ "folders": "Cartelle",
+ "new": "Nuova cartella",
+ "name": "Nome",
+ "location": "Posizione",
+ "cancel": "Annulla",
+ "create": "Crea e seleziona",
+ "empty": "Nessuna cartella trovata. Prova un altro nome o crea una cartella.",
+ "loading": "Caricamento cartelle…",
+ "unavailable": "Impossibile caricare le cartelle.",
+ "retry": "Riprova",
+ "dismiss": "Chiudi notifica riunione",
+ "selected": "{{destination}} selezionato",
+ "linked": "Questa riunione ha già una nota. Partecipando, la nota resterà in {{destination}}.",
+ "errors": {
+ "STALE_NOTIFICATION": "Questa notifica non è più attuale.",
+ "INVALID_REQUEST": "Impossibile completare. Riprova.",
+ "FOLDERS_UNAVAILABLE": "Impossibile caricare le cartelle.",
+ "FOLDER_UNAVAILABLE": "Questa destinazione non è disponibile. Scegli un’altra cartella.",
+ "SPACE_UNAVAILABLE": "Questa destinazione non è disponibile. Scegli un’altra cartella.",
+ "FOLDER_NAME_REQUIRED": "Inserisci un nome per la cartella.",
+ "FOLDER_NAME_TAKEN": "Esiste già una cartella con questo nome in questa posizione.",
+ "CREATE_FAILED": "Impossibile completare. Riprova.",
+ "LINKED_NOTE_CHANGED": "Controlla la destinazione, poi partecipa di nuovo.",
+ "NOTE_UNAVAILABLE": "Questa nota non è disponibile. Riprova senza crearne un’altra.",
+ "START_FAILED": "Impossibile completare. Riprova."
+ }
+ }
},
"providerErrors": {
"authFailed": "{{provider}} ha rifiutato la tua chiave API.",
diff --git a/src/locales/ja/translation.json b/src/locales/ja/translation.json
index 77a456fe7..1ac96940c 100644
--- a/src/locales/ja/translation.json
+++ b/src/locales/ja/translation.json
@@ -4773,7 +4773,42 @@
"underway": "会議はすでに進行中のようです。メモを取りますか?"
},
"start": "メモを取る",
- "join": "参加して文字起こし"
+ "join": "参加して文字起こし",
+ "folders": {
+ "choose": "会議フォルダーを選択",
+ "search": "フォルダーを検索",
+ "clear": "検索をクリア",
+ "private": "プライベート",
+ "shared": "共有",
+ "current": "現在の保存先",
+ "recent": "最近使用したフォルダー",
+ "folders": "フォルダー",
+ "new": "新しいフォルダー",
+ "name": "名前",
+ "location": "保存先",
+ "cancel": "キャンセル",
+ "create": "作成して選択",
+ "empty": "フォルダーが見つかりません。別の名前を検索するか、作成してください。",
+ "loading": "フォルダーを読み込み中…",
+ "unavailable": "フォルダーを読み込めませんでした。",
+ "retry": "再試行",
+ "dismiss": "会議通知を閉じる",
+ "selected": "{{destination}}を選択しました",
+ "linked": "この会議にはすでにノートがあります。参加しても{{destination}}に保存されます。",
+ "errors": {
+ "STALE_NOTIFICATION": "この通知は無効になりました。",
+ "INVALID_REQUEST": "完了できませんでした。再試行してください。",
+ "FOLDERS_UNAVAILABLE": "フォルダーを読み込めませんでした。",
+ "FOLDER_UNAVAILABLE": "この保存先は利用できません。別のフォルダーを選択してください。",
+ "SPACE_UNAVAILABLE": "この保存先は利用できません。別のフォルダーを選択してください。",
+ "FOLDER_NAME_REQUIRED": "フォルダー名を入力してください。",
+ "FOLDER_NAME_TAKEN": "この保存先には同名のフォルダーがあります。",
+ "CREATE_FAILED": "完了できませんでした。再試行してください。",
+ "LINKED_NOTE_CHANGED": "保存先を確認し、もう一度参加してください。",
+ "NOTE_UNAVAILABLE": "このノートは利用できません。新規作成せずに再試行してください。",
+ "START_FAILED": "完了できませんでした。再試行してください。"
+ }
+ }
},
"providerErrors": {
"authFailed": "{{provider}} がAPIキーを拒否しました。",
diff --git a/src/locales/pt/translation.json b/src/locales/pt/translation.json
index 90110a10d..417459b95 100644
--- a/src/locales/pt/translation.json
+++ b/src/locales/pt/translation.json
@@ -4773,7 +4773,42 @@
"underway": "Parece que sua reunião já está em andamento. Quer fazer anotações?"
},
"start": "Fazer anotações",
- "join": "Entrar e transcrever"
+ "join": "Entrar e transcrever",
+ "folders": {
+ "choose": "Escolher pasta da reunião",
+ "search": "Pesquisar pastas",
+ "clear": "Limpar pesquisa",
+ "private": "Privado",
+ "shared": "Compartilhado",
+ "current": "Destino atual",
+ "recent": "Usadas recentemente",
+ "folders": "Pastas",
+ "new": "Nova pasta",
+ "name": "Nome",
+ "location": "Local",
+ "cancel": "Cancelar",
+ "create": "Criar e selecionar",
+ "empty": "Nenhuma pasta encontrada. Tente outro nome ou crie uma pasta.",
+ "loading": "Carregando pastas…",
+ "unavailable": "Não foi possível carregar as pastas.",
+ "retry": "Tentar novamente",
+ "dismiss": "Fechar notificação de reunião",
+ "selected": "{{destination}} selecionado",
+ "linked": "Esta reunião já tem uma nota. Ao entrar, ela permanecerá em {{destination}}.",
+ "errors": {
+ "STALE_NOTIFICATION": "Esta notificação não está mais atualizada.",
+ "INVALID_REQUEST": "Não foi possível concluir. Tente novamente.",
+ "FOLDERS_UNAVAILABLE": "Não foi possível carregar as pastas.",
+ "FOLDER_UNAVAILABLE": "Este destino não está disponível. Escolha outra pasta.",
+ "SPACE_UNAVAILABLE": "Este destino não está disponível. Escolha outra pasta.",
+ "FOLDER_NAME_REQUIRED": "Digite um nome para a pasta.",
+ "FOLDER_NAME_TAKEN": "Já existe uma pasta com esse nome neste local.",
+ "CREATE_FAILED": "Não foi possível concluir. Tente novamente.",
+ "LINKED_NOTE_CHANGED": "Confira o destino e entre novamente.",
+ "NOTE_UNAVAILABLE": "Esta nota não está disponível. Tente novamente sem criar outra.",
+ "START_FAILED": "Não foi possível concluir. Tente novamente."
+ }
+ }
},
"providerErrors": {
"authFailed": "{{provider}} rejeitou sua chave de API.",
diff --git a/src/locales/ru/translation.json b/src/locales/ru/translation.json
index 20ebe0c76..b0fe0e4b7 100644
--- a/src/locales/ru/translation.json
+++ b/src/locales/ru/translation.json
@@ -4819,7 +4819,42 @@
"underway": "Похоже, ваша встреча уже идёт. Хотите вести заметки?"
},
"start": "Вести заметки",
- "join": "Присоединиться и вести заметки"
+ "join": "Присоединиться и вести заметки",
+ "folders": {
+ "choose": "Выбрать папку встречи",
+ "search": "Поиск папок",
+ "clear": "Очистить поиск",
+ "private": "Личное",
+ "shared": "Общий доступ",
+ "current": "Текущее расположение",
+ "recent": "Недавно использованные",
+ "folders": "Папки",
+ "new": "Новая папка",
+ "name": "Название",
+ "location": "Расположение",
+ "cancel": "Отмена",
+ "create": "Создать и выбрать",
+ "empty": "Папки не найдены. Попробуйте другое название или создайте папку.",
+ "loading": "Загрузка папок…",
+ "unavailable": "Не удалось загрузить папки.",
+ "retry": "Повторить",
+ "dismiss": "Закрыть уведомление о встрече",
+ "selected": "Выбрано: {{destination}}",
+ "linked": "Для этой встречи уже есть заметка. При подключении она останется в {{destination}}.",
+ "errors": {
+ "STALE_NOTIFICATION": "Это уведомление больше не актуально.",
+ "INVALID_REQUEST": "Не удалось завершить. Повторите попытку.",
+ "FOLDERS_UNAVAILABLE": "Не удалось загрузить папки.",
+ "FOLDER_UNAVAILABLE": "Расположение недоступно. Выберите другую папку.",
+ "SPACE_UNAVAILABLE": "Расположение недоступно. Выберите другую папку.",
+ "FOLDER_NAME_REQUIRED": "Введите название папки.",
+ "FOLDER_NAME_TAKEN": "В этом расположении уже есть папка с таким названием.",
+ "CREATE_FAILED": "Не удалось завершить. Повторите попытку.",
+ "LINKED_NOTE_CHANGED": "Проверьте расположение и подключитесь снова.",
+ "NOTE_UNAVAILABLE": "Заметка недоступна. Повторите попытку, не создавая новую.",
+ "START_FAILED": "Не удалось завершить. Повторите попытку."
+ }
+ }
},
"providerErrors": {
"authFailed": "{{provider}} отклонил ваш API-ключ.",
diff --git a/src/locales/zh-CN/translation.json b/src/locales/zh-CN/translation.json
index e6657a3c3..df5b032c4 100644
--- a/src/locales/zh-CN/translation.json
+++ b/src/locales/zh-CN/translation.json
@@ -4773,7 +4773,42 @@
"underway": "你的会议似乎已在进行中。要开始记录吗?"
},
"start": "开始记录",
- "join": "加入并转录"
+ "join": "加入并转录",
+ "folders": {
+ "choose": "选择会议文件夹",
+ "search": "搜索文件夹",
+ "clear": "清除搜索",
+ "private": "私密",
+ "shared": "共享",
+ "current": "当前保存位置",
+ "recent": "最近使用",
+ "folders": "文件夹",
+ "new": "新建文件夹",
+ "name": "名称",
+ "location": "位置",
+ "cancel": "取消",
+ "create": "创建并选择",
+ "empty": "未找到文件夹。请搜索其他名称或创建文件夹。",
+ "loading": "正在加载文件夹…",
+ "unavailable": "无法加载文件夹。",
+ "retry": "重试",
+ "dismiss": "关闭会议通知",
+ "selected": "已选择{{destination}}",
+ "linked": "此会议已有笔记。加入后,笔记仍保存在{{destination}}。",
+ "errors": {
+ "STALE_NOTIFICATION": "此通知已失效。",
+ "INVALID_REQUEST": "无法完成,请重试。",
+ "FOLDERS_UNAVAILABLE": "无法加载文件夹。",
+ "FOLDER_UNAVAILABLE": "此保存位置不可用。请选择其他文件夹。",
+ "SPACE_UNAVAILABLE": "此保存位置不可用。请选择其他文件夹。",
+ "FOLDER_NAME_REQUIRED": "请输入文件夹名称。",
+ "FOLDER_NAME_TAKEN": "此位置已存在同名文件夹。",
+ "CREATE_FAILED": "无法完成,请重试。",
+ "LINKED_NOTE_CHANGED": "请检查保存位置,然后重新加入。",
+ "NOTE_UNAVAILABLE": "此笔记不可用。请重试,不要创建替代笔记。",
+ "START_FAILED": "无法完成,请重试。"
+ }
+ }
},
"providerErrors": {
"authFailed": "{{provider}} 拒绝了你的 API 密钥。",
diff --git a/src/locales/zh-TW/translation.json b/src/locales/zh-TW/translation.json
index 82dda0e2b..01b01f155 100644
--- a/src/locales/zh-TW/translation.json
+++ b/src/locales/zh-TW/translation.json
@@ -4773,7 +4773,42 @@
"underway": "你的會議似乎已在進行中。要開始記錄嗎?"
},
"start": "開始記錄",
- "join": "加入並轉錄"
+ "join": "加入並轉錄",
+ "folders": {
+ "choose": "選擇會議資料夾",
+ "search": "搜尋資料夾",
+ "clear": "清除搜尋",
+ "private": "私人",
+ "shared": "共用",
+ "current": "目前儲存位置",
+ "recent": "最近使用",
+ "folders": "資料夾",
+ "new": "新增資料夾",
+ "name": "名稱",
+ "location": "位置",
+ "cancel": "取消",
+ "create": "建立並選取",
+ "empty": "找不到資料夾。請搜尋其他名稱或建立資料夾。",
+ "loading": "正在載入資料夾…",
+ "unavailable": "無法載入資料夾。",
+ "retry": "重試",
+ "dismiss": "關閉會議通知",
+ "selected": "已選取{{destination}}",
+ "linked": "此會議已有筆記。加入後,筆記仍儲存在{{destination}}。",
+ "errors": {
+ "STALE_NOTIFICATION": "此通知已失效。",
+ "INVALID_REQUEST": "無法完成,請重試。",
+ "FOLDERS_UNAVAILABLE": "無法載入資料夾。",
+ "FOLDER_UNAVAILABLE": "此儲存位置無法使用。請選擇其他資料夾。",
+ "SPACE_UNAVAILABLE": "此儲存位置無法使用。請選擇其他資料夾。",
+ "FOLDER_NAME_REQUIRED": "請輸入資料夾名稱。",
+ "FOLDER_NAME_TAKEN": "此位置已有同名資料夾。",
+ "CREATE_FAILED": "無法完成,請重試。",
+ "LINKED_NOTE_CHANGED": "請檢查儲存位置,然後重新加入。",
+ "NOTE_UNAVAILABLE": "此筆記無法使用。請重試,不要建立替代筆記。",
+ "START_FAILED": "無法完成,請重試。"
+ }
+ }
},
"providerErrors": {
"authFailed": "{{provider}} 拒絕了你的 API 金鑰。",
diff --git a/src/stores/noteStore.ts b/src/stores/noteStore.ts
index f3cb16eba..473d7c19b 100644
--- a/src/stores/noteStore.ts
+++ b/src/stores/noteStore.ts
@@ -357,6 +357,21 @@ export async function loadFolders(): Promise<FolderItem[]> {
return items;
}
+// The notification does not boot SyncService. A mounted panel refreshes local
+// rows first, then lets the existing sync policy decide whether to push them.
+export function subscribeMeetingNotificationFolders(): (() => void) | undefined {
+ return window.electronAPI.onMeetingNotificationFolderCreated?.(async ({ folderId }) => {
+ try {
+ const folders = await loadFolders();
+ if (folders.some((folder) => folder.id === folderId)) {
+ syncService.debouncedPush("folder", folderId);
+ }
+ } catch {
+ /* Startup loading and pending SQLite rows recover a lost hint. */
+ }
+ });
+}
+
const containerLoadGenerations = new Map<string, number>();
const containerLoadsInFlight = new Map<string, Promise<NoteItem[]>>();
diff --git a/src/styles/meeting-notification.css b/src/styles/meeting-notification.css
new file mode 100644
index 000000000..767f30e61
--- /dev/null
+++ b/src/styles/meeting-notification.css
@@ -0,0 +1,272 @@
+.meeting-folder-compound {
+ overflow: hidden;
+}
+.meeting-folder-trigger {
+ display: grid;
+ align-items: center;
+ justify-items: center;
+ width: 27px;
+ border-inline-start: 1px solid #ffffff55;
+ outline-offset: -2px;
+}
+.meeting-folder-trigger svg {
+ grid-area: 1/1;
+ transition: opacity 400ms ease-in-out;
+}
+.meeting-folder-confirmation {
+ opacity: 0;
+}
+.feedback-enter svg,
+.feedback-hold svg {
+ transition-duration: 200ms;
+}
+.feedback-enter .meeting-folder-chevron,
+.feedback-hold .meeting-folder-chevron {
+ opacity: 0;
+}
+.feedback-enter .meeting-folder-confirmation,
+.feedback-hold .meeting-folder-confirmation {
+ opacity: 1;
+}
+.meeting-folder-picker {
+ position: relative;
+ max-height: calc(var(--meeting-surface-height, 512px) - 108px);
+ overflow: auto;
+ overscroll-behavior: contain;
+ width: 288px;
+ max-width: 100%;
+ margin: 12px 0 0 auto;
+ padding: 6px;
+ border-radius: 12px;
+ background: var(--color-card);
+ color: var(--color-foreground);
+ border: 1px solid var(--color-border);
+ box-shadow: 0 4px 12px #0002;
+ font-size: 12px;
+}
+.meeting-folder-picker button:focus-visible,
+.meeting-folder-picker input:focus-visible {
+ outline: 1px solid color-mix(in srgb, var(--color-primary) 55%, transparent);
+ outline-offset: 1px;
+}
+.meeting-folder-picker button:disabled {
+ opacity: 0.5;
+}
+.meeting-folder-search {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ min-height: 32px;
+ margin: 3px;
+ padding-block: 6px;
+ padding-inline: 12px;
+ border: 1px solid var(--color-border);
+ border-radius: 999px;
+ background: color-mix(in srgb, var(--color-foreground) 4%, transparent);
+ color: var(--color-muted-foreground);
+}
+.dark .meeting-folder-search {
+ border-color: #ffffff1a;
+ background: #ffffff0d;
+}
+.meeting-folder-search:focus-within {
+ outline: 1px solid color-mix(in srgb, var(--color-primary) 55%, transparent);
+ outline-offset: 1px;
+}
+.meeting-folder-search input:focus-visible {
+ outline: none;
+}
+.meeting-folder-search > button {
+ display: grid;
+ place-items: center;
+ flex-shrink: 0;
+ padding: 2px;
+ border-radius: 999px;
+}
+.meeting-folder-search input {
+ width: 100%;
+ min-width: 0;
+ padding-inline: 2px;
+ outline: 0;
+ background: transparent;
+ color: var(--color-foreground);
+ font-size: 12px;
+}
+.meeting-folder-results {
+ max-height: 240px;
+ overflow: auto;
+ overscroll-behavior: contain;
+ scrollbar-width: thin;
+}
+.meeting-folder-results::before {
+ content: "";
+ position: sticky;
+ top: 0;
+ z-index: 1;
+ display: block;
+ height: 16px;
+ margin-bottom: -16px;
+ pointer-events: none;
+ backdrop-filter: blur(3px);
+ background: color-mix(in srgb, var(--color-card) 25%, transparent);
+ mask-image: linear-gradient(#000, transparent);
+}
+.meeting-folder-group {
+ font-size: 10px;
+ color: var(--color-muted-foreground);
+ font-weight: 500;
+ padding: 10px 8px 5px;
+}
+.meeting-folder-option {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ width: 100%;
+ min-height: 36px;
+ padding: 6px 8px;
+ text-align: start;
+ border-radius: 6px;
+}
+.meeting-folder-option:hover,
+.meeting-folder-option.active,
+.meeting-folder-locations [role="menuitemradio"]:focus {
+ background: var(--color-muted);
+}
+.meeting-folder-name {
+ display: block;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ font-size: 12px;
+ line-height: 16px;
+}
+.meeting-folder-space {
+ display: block;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ font-size: 9px;
+ line-height: 12px;
+ color: var(--color-muted-foreground);
+}
+.meeting-folder-new {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ width: 100%;
+ border-top: 1px solid var(--color-border);
+ margin-top: 5px;
+ padding: 9px 8px 7px;
+ font-size: 11px;
+ color: var(--color-muted-foreground);
+}
+.meeting-folder-form {
+ padding: 0 6px 6px;
+}
+.meeting-folder-form h3 {
+ font-size: 12px;
+ font-weight: 500;
+ margin: 7px 2px 10px;
+}
+.meeting-folder-field {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ min-width: 0;
+ padding: 5px 0;
+}
+.meeting-folder-field > span {
+ width: 48px;
+ flex-shrink: 0;
+ font-size: 10px;
+ color: var(--color-muted-foreground);
+}
+.meeting-folder-field input {
+ min-width: 0;
+ width: 100%;
+ font-size: 12px;
+ padding-block: 7px;
+ padding-inline: 10px;
+ border-radius: 6px;
+ border: 1px solid var(--color-border);
+ background: var(--color-background);
+}
+.meeting-folder-location {
+ position: relative;
+ flex: 1;
+ min-width: 0;
+}
+.meeting-folder-location-trigger {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ width: 100%;
+ border: 1px solid var(--color-border);
+ background: var(--color-background);
+ font-size: 11px;
+ border-radius: 6px;
+ padding-block: 7px;
+ padding-inline: 10px;
+ text-align: start;
+}
+.meeting-folder-location-trigger > span {
+ flex: 1;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+.meeting-folder-locations {
+ width: var(--radix-dropdown-menu-trigger-width);
+ z-index: 5;
+ background: var(--color-card);
+ padding: 4px;
+ border: 1px solid var(--color-border);
+ border-radius: 8px;
+ box-shadow: 0 3px 10px #0002;
+ max-height: min(120px, var(--radix-dropdown-menu-content-available-height));
+ overflow: auto;
+}
+.meeting-folder-locations [role="menuitemradio"] {
+ display: flex;
+ justify-content: space-between;
+ gap: 4px;
+ width: 100%;
+ font-size: 11px;
+ padding: 6px;
+ text-align: start;
+ border-radius: 4px;
+}
+.meeting-folder-form-actions {
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ gap: 8px;
+ margin-top: 9px;
+}
+.meeting-folder-form-actions button {
+ font-size: 10px;
+ padding: 6px 10px;
+ border-radius: 999px;
+ color: var(--color-muted-foreground);
+}
+.meeting-folder-form-actions button[type="submit"] {
+ background: var(--color-primary);
+ color: var(--color-primary-foreground);
+}
+.meeting-folder-error {
+ padding: 5px 8px;
+ font-size: 10px;
+ line-height: 1.5;
+ color: var(--color-destructive);
+}
+@media (prefers-reduced-motion: reduce) {
+ .meeting-folder-trigger svg {
+ transition: none;
+ }
+ .feedback-exit .meeting-folder-confirmation {
+ opacity: 1;
+ }
+ .feedback-exit .meeting-folder-chevron {
+ opacity: 0;
+ }
+}
diff --git a/src/types/electron.ts b/src/types/electron.ts
index 6dcb856ad..66751ec7d 100644
--- a/src/types/electron.ts
+++ b/src/types/electron.ts
@@ -155,6 +155,52 @@ export interface MeetingNotificationData {
joinUrl: string | null;
}
+export interface MeetingFolderRef {
+ folderId: number;
+ spaceId: number;
+}
+export interface MeetingExistingNote {
+ noteId: number;
+ spaceId: number;
+ folderId: number | null;
+ spaceName: string;
+ folderName: string | null;
+ shared: boolean;
+}
+export interface MeetingDestinationContext {
+ folders: FolderItem[];
+ spaces: SpaceItem[];
+ defaultDestination: MeetingFolderRef | null;
+ selectedDestination: MeetingFolderRef | null;
+ recentDestinations: MeetingFolderRef[];
+ existingNote: MeetingExistingNote | null;
+}
+
+export interface MeetingSurfaceState {
+ revision: number;
+ mode: "closed" | "list" | "form";
+ contentHeight: number;
+ regions: { x: number; y: number; width: number; height: number }[];
+ focus: "request" | "release" | "keep";
+}
+
+export type MeetingError =
+ | "STALE_NOTIFICATION"
+ | "INVALID_REQUEST"
+ | "FOLDERS_UNAVAILABLE"
+ | "FOLDER_UNAVAILABLE"
+ | "SPACE_UNAVAILABLE"
+ | "FOLDER_NAME_REQUIRED"
+ | "FOLDER_NAME_TAKEN"
+ | "CREATE_FAILED"
+ | "LINKED_NOTE_CHANGED"
+ | "NOTE_UNAVAILABLE"
+ | "START_FAILED";
+
+export type MeetingResult<T> =
+ | { success: true; value: T }
+ | { success: false; code: MeetingError; context?: MeetingDestinationContext };
+
/** Why auto-end concluded the meeting is over. */
export type MeetingAutoEndReason = "mic-released" | "silence" | "process-exit";
@@ -3350,17 +3396,47 @@ declare global {
onMeetingAutoEndRequested?: (
callback: (request: MeetingAutoEndRequest) => void
) => () => void;
+ getMeetingNotificationDestination: () => Promise<MeetingResult<MeetingDestinationContext>>;
+ selectMeetingNotificationFolder: (
+ folder: MeetingFolderRef
+ ) => Promise<MeetingResult<MeetingDestinationContext>>;
+ createMeetingNotificationFolder: (request: {
+ requestId: string;
+ name: string;
+ spaceId: number;
+ }) => Promise<MeetingResult<MeetingDestinationContext & { createdFolder: MeetingFolderRef }>>;
+ onMeetingNotificationFolderCreated: (
+ callback: (hint: { folderId: number }) => void
+ ) => () => void;
+ setMeetingNotificationSurface: (
+ state: MeetingSurfaceState
+ ) => Promise<MeetingResult<{ width: number; height: number; maxHeight: number }>>;
+ onMeetingNotificationSurfaceClosed: (
+ callback: (data: { revision: number }) => void
+ ) => () => void;
+ onMeetingNotificationSurfaceResized: (
+ callback: (data: { revision: number }) => void
+ ) => () => void;
getMeetingNotificationData?: () => Promise<MeetingNotificationData | null>;
meetingNotificationReady?: () => Promise<void>;
meetingNotificationRespond?: (
detectionId: string,
- action: string
- ) => Promise<{ success: boolean }>;
+ action: string,
+ options?: {
+ existingNote?: Pick<MeetingExistingNote, "noteId" | "spaceId" | "folderId">;
+ }
+ ) => Promise<MeetingResult<null>>;
+ confirmMeetingNoteNavigation: (
+ navigationId: string,
+ status?: "ready" | "cancel"
+ ) => Promise<MeetingResult<NoteItem>>;
joinCalendarMeeting?: (eventId: string) => Promise<{ success: boolean }>;
startManualMeeting?: () => Promise<void>;
getPendingMeetingNoteNavigation?: () => Promise<{
+ navigationId?: string;
+ spaceId?: number;
noteId: number;
- folderId: number;
+ folderId: number | null;
event: any;
trigger?: "hotkey" | "manual" | "calendar-join";
} | null>;
diff --git a/test/components/fieldDirectionPolicy.test.js b/test/components/fieldDirectionPolicy.test.js
index 9847bca1b..4e33e26b9 100644
--- a/test/components/fieldDirectionPolicy.test.js
+++ b/test/components/fieldDirectionPolicy.test.js
@@ -88,6 +88,8 @@ const EXPECTED_SHARED_FIELD_DIRECTIONS = {
const EXPECTED_NATIVE_FIELD_DIRECTIONS = {
"src/components/ApiKeysSection.tsx": ["inherit"],
"src/components/CommandSearch.tsx": ["auto"],
+ // Folder names and search accept user text in any script.
+ "src/components/MeetingNotificationFolderPicker.tsx": ["auto", "auto"],
"src/components/MemberPickList.tsx": ["auto"],
"src/components/ReferralDashboard.tsx": ["ltr"],
"src/components/SettingsPage.tsx": ["inherit"],
diff --git a/test/components/meetingNotificationDestinationNavigation.test.js b/test/components/meetingNotificationDestinationNavigation.test.js
new file mode 100644
index 000000000..f430056bb
--- /dev/null
+++ b/test/components/meetingNotificationDestinationNavigation.test.js
@@ -0,0 +1,84 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+const { createRendererServer, installBrowserGlobals } = require("../lib/rendererTestHarness");
+async function fixture(t) {
+ installBrowserGlobals(t);
+ const calls = [];
+ const row = { id: 9, space_id: 2, folder_id: null, title: "Root meeting", note_type: "meeting" };
+ let release;
+ globalThis.window.electronAPI = {
+ getSpaces: async () => [
+ { id: 1, kind: "private" },
+ { id: 2, kind: "team" },
+ ],
+ getFolders: async () => [],
+ getFolderNoteCounts: async () => [],
+ getNotes: async () => [],
+ getContainerNotes: async () => [],
+ getNote: async () => row,
+ confirmMeetingNoteNavigation: async (id, status) => {
+ calls.push(["confirm", id, status]);
+ return { success: true, value: row };
+ },
+ };
+ const vite = await createRendererServer(t, {
+ cachePrefix: "meeting-navigation-",
+ mockModules: { "/services/SyncService.js": "export const syncService={setNoteOpen(){}};" },
+ });
+ const store = await vite.ssrLoadModule("/stores/noteStore.ts");
+ const { navigateMeetingNotification } = await vite.ssrLoadModule(
+ "/components/meetingNotificationNavigation.ts"
+ );
+ const prepare = () => new Promise((r) => (release = r));
+ return {
+ row,
+ calls,
+ store,
+ run: (isCurrent = () => true) =>
+ navigateMeetingNotification(
+ { navigationId: "nav", noteId: 9, spaceId: 2, folderId: null },
+ isCurrent,
+ prepare,
+ (note) => calls.push(["record", note])
+ ),
+ release: () => release(),
+ };
+}
+test("root navigation waits for editor loading then records the freshly confirmed row", async (t) => {
+ const f = await fixture(t);
+ const pending = f.run();
+ await new Promise(setImmediate);
+ assert.deepEqual(f.calls, []);
+ f.release();
+ await pending;
+ assert.equal(f.store.getActiveNoteIdValue(), 9);
+ assert.equal(f.store.getActiveFolderIdValue(), null);
+ assert.deepEqual(f.calls, [
+ ["confirm", "nav", "ready"],
+ ["record", f.row],
+ ]);
+});
+test("unmount/account change during delayed editor loading cancels without recording", async (t) => {
+ const f = await fixture(t);
+ let current = true;
+ const pending = f.run(() => current);
+ await new Promise(setImmediate);
+ current = false;
+ f.release();
+ await pending;
+ assert.deepEqual(f.calls, [["confirm", "nav", "cancel"]]);
+ assert.equal(f.store.getActiveNoteIdValue(), null);
+});
+test("failed live-note confirmation does not use a cached note to start", async (t) => {
+ const f = await fixture(t);
+ globalThis.window.electronAPI.confirmMeetingNoteNavigation = async () => ({
+ success: false,
+ code: "NOTE_UNAVAILABLE",
+ });
+ const pending = f.run();
+ await new Promise(setImmediate);
+ f.release();
+ await pending;
+ assert.deepEqual(f.calls, []);
+ assert.equal(f.store.getActiveNoteIdValue(), null);
+});
diff --git a/test/components/meetingNotificationFolderPicker.test.js b/test/components/meetingNotificationFolderPicker.test.js
new file mode 100644
index 000000000..4defb41f2
--- /dev/null
+++ b/test/components/meetingNotificationFolderPicker.test.js
@@ -0,0 +1,608 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+const React = require("react");
+const { createRendererServer } = require("../lib/rendererTestHarness");
+const contexts = () => ({
+ spaces: [
+ { id: 1, kind: "private", name: "Private" },
+ { id: 2, kind: "team", name: "Team" },
+ ],
+ folders: Array.from({ length: 8 }, (_, i) => ({
+ id: i + 1,
+ space_id: i === 6 ? 2 : 1,
+ name: i === 0 ? "Meetings" : "Calls " + i,
+ is_default: i === 0 ? 1 : 0,
+ })),
+ defaultDestination: { folderId: 1, spaceId: 1 },
+ selectedDestination: null,
+ recentDestinations: [],
+ existingNote: null,
+});
+async function mount(t, overrides = {}, setupDom = () => {}) {
+ let root;
+ const original = {};
+ let dom;
+ t.after(async () => {
+ if (root) await React.act(async () => root.unmount());
+ await dom?.happyDOM.close();
+ for (const [key, value] of Object.entries(original)) {
+ if (value) Object.defineProperty(globalThis, key, value);
+ else delete globalThis[key];
+ }
+ });
+ const { Window } = await import("happy-dom");
+ dom = new Window({ url: "http://localhost:5173" });
+ for (const key of [
+ "window",
+ "document",
+ "navigator",
+ "HTMLElement",
+ "HTMLInputElement",
+ "Node",
+ "NodeFilter",
+ "CustomEvent",
+ "MutationObserver",
+ "getComputedStyle",
+ "Element",
+ "Event",
+ "KeyboardEvent",
+ "MouseEvent",
+ "CompositionEvent",
+ "localStorage",
+ "requestAnimationFrame",
+ "cancelAnimationFrame",
+ "ResizeObserver",
+ ]) {
+ original[key] = Object.getOwnPropertyDescriptor(globalThis, key);
+ Object.defineProperty(globalThis, key, {
+ value:
+ typeof dom[key] === "function" &&
+ (key.includes("AnimationFrame") || key === "getComputedStyle")
+ ? dom[key].bind(dom)
+ : dom[key],
+ writable: true,
+ configurable: true,
+ });
+ }
+ original.IS_REACT_ACT_ENVIRONMENT = Object.getOwnPropertyDescriptor(
+ globalThis,
+ "IS_REACT_ACT_ENVIRONMENT"
+ );
+ globalThis.IS_REACT_ACT_ENVIRONMENT = true;
+ setupDom(dom);
+ const data = {
+ detectionId: "event",
+ source: "calendar",
+ key: "event",
+ event: { summary: "Investor call" },
+ variant: "starting",
+ joinUrl: "https://example.test",
+ };
+ let context = contexts();
+ const calls = [];
+ const callbacks = {};
+ const api = {
+ getMeetingNotificationData: async () => data,
+ onMeetingNotificationData: (cb) => ((callbacks.data = cb), () => {}),
+ meetingNotificationReady: async () => {},
+ setNotificationInteractivity: async () => {},
+ setMeetingNotificationSurface: async (s) => ({
+ success: true,
+ value: { width: 416, height: s.contentHeight },
+ }),
+ onMeetingNotificationSurfaceClosed: (cb) => ((callbacks.blur = cb), () => {}),
+ onMeetingNotificationSurfaceResized: () => () => {},
+ getMeetingNotificationDestination: async () => ({ success: true, value: context }),
+ selectMeetingNotificationFolder: async (ref) => {
+ calls.push(["select", ref]);
+ context = { ...context, selectedDestination: ref, recentDestinations: [ref] };
+ return { success: true, value: context };
+ },
+ createMeetingNotificationFolder: async (req) => {
+ calls.push(["create", req]);
+ const ref = { folderId: 99, spaceId: req.spaceId };
+ context = {
+ ...context,
+ folders: [
+ ...context.folders,
+ { id: 99, space_id: req.spaceId, name: req.name, is_default: 0 },
+ ],
+ };
+ return { success: true, value: { ...context, createdFolder: ref } };
+ },
+ meetingNotificationRespond: async (...args) => {
+ calls.push(["start", ...args]);
+ return { success: true, value: null };
+ },
+ ...overrides,
+ };
+ globalThis.window.electronAPI = api;
+ const vite = await createRendererServer(t, {
+ cachePrefix: "meeting-folder-picker-",
+ noExternal: ["react-i18next"],
+ mockModules: {
+ "react-i18next": `import en from '/locales/en/translation.json';const t=(key,values={})=>{let s=key.split('.').reduce((v,k)=>v?.[k],en)??key;return String(s).replace(/{{(\\w+)}}/g,(_,k)=>values[k]??'');};export const useTranslation=()=>({t,i18n:{language:'en'}});`,
+ },
+ });
+ const { default: Overlay } = await vite.ssrLoadModule(
+ "/components/MeetingNotificationOverlay.tsx"
+ );
+ const { createRoot } = require("react-dom/client");
+ const container = globalThis.document.createElement("div");
+ globalThis.document.body.append(container);
+ root = createRoot(container);
+ await React.act(async () => {
+ root.render(React.createElement(Overlay));
+ await new Promise((r) => setTimeout(r, 30));
+ });
+ const byLabel = (label) => container.querySelector(`[aria-label="${label}"]`);
+ const button = (text) =>
+ [...container.querySelectorAll("button")].find((b) => b.textContent.trim() === text);
+ const click = async (el) => {
+ assert.ok(el, "control exists");
+ await React.act(async () =>
+ el.dispatchEvent(new globalThis.window.MouseEvent("click", { bubbles: true, detail: 1 }))
+ );
+ };
+ const type = async (el, text) => {
+ await React.act(async () => {
+ const setter = Object.getOwnPropertyDescriptor(
+ globalThis.window.HTMLInputElement.prototype,
+ "value"
+ ).set;
+ setter.call(el, text);
+ el.dispatchEvent(new globalThis.window.Event("input", { bubbles: true }));
+ });
+ };
+ return {
+ container,
+ calls,
+ api,
+ callbacks,
+ byLabel,
+ button,
+ click,
+ type,
+ setContext: (c) => (context = c),
+ };
+}
+
+test("cold start honestly lists five folders and selection never starts a meeting", async (t) => {
+ const c = await mount(t);
+ await c.click(c.byLabel("Choose meeting folder"));
+ assert.equal(c.container.querySelectorAll('[role="option"]').length, 5);
+ assert.ok(!c.container.textContent.includes("Recently used"));
+ await c.click(c.byLabel("Private / Calls 1"));
+ assert.equal(c.calls.filter((x) => x[0] === "select").length, 1);
+ assert.equal(c.calls.filter((x) => x[0] === "start").length, 0);
+ await c.click(c.button("Join and transcribe"));
+ assert.equal(c.calls.filter((x) => x[0] === "start").length, 1);
+});
+
+test("search reaches shared folders and creation starts Private with an unmatched name", async (t) => {
+ const c = await mount(t);
+ await c.click(c.byLabel("Choose meeting folder"));
+ await c.type(c.byLabel("Search folders"), "Unique folder");
+ await c.click(c.button("New folder"));
+ assert.equal(c.byLabel("Name").value, "Unique folder");
+ assert.ok(c.button("Private"));
+ await c.click(c.button("Create & select"));
+ assert.equal(c.calls[0][0], "create");
+ assert.equal(c.calls[0][1].spaceId, 1);
+ assert.equal(c.calls[1][0], "select");
+ assert.equal(c.calls.filter((x) => x[0] === "start").length, 0);
+});
+
+test("canceling a delayed create ignores its late selection and keeps Start disabled until settlement", async (t) => {
+ let resolve;
+ const c = await mount(t, {
+ createMeetingNotificationFolder: () => new Promise((r) => (resolve = r)),
+ });
+ await c.click(c.byLabel("Choose meeting folder"));
+ await c.click(c.button("New folder"));
+ await c.type(c.byLabel("Name"), "Late folder");
+ await c.click(c.button("Create & select"));
+ await c.click(c.button("Cancel"));
+ assert.equal(c.button("Join and transcribe").disabled, true);
+ await React.act(async () =>
+ resolve({
+ success: true,
+ value: { ...contexts(), createdFolder: { folderId: 99, spaceId: 1 } },
+ })
+ );
+ assert.equal(c.calls.length, 0);
+ assert.equal(c.button("Join and transcribe").disabled, false);
+});
+module.exports = { mount, contexts };
+
+test("two recents fill with three fallbacks and an outside selection remains visible", async (t) => {
+ const c = await mount(t);
+ c.setContext({
+ ...contexts(),
+ recentDestinations: [
+ { folderId: 7, spaceId: 2 },
+ { folderId: 6, spaceId: 1 },
+ ],
+ selectedDestination: { folderId: 8, spaceId: 1 },
+ });
+ await c.click(c.byLabel("Choose meeting folder"));
+ assert.equal(c.container.querySelectorAll('[role="option"]').length, 6);
+ assert.ok(c.byLabel("Team / Calls 6 · Shared"));
+ assert.ok(c.byLabel("Private / Calls 7"));
+ await c.type(c.byLabel("Search folders"), "Calls 6");
+ assert.equal(c.container.querySelectorAll('[role="option"]').length, 1);
+ await c.click(c.byLabel("Clear search"));
+ assert.equal(c.container.querySelectorAll('[role="option"]').length, 6);
+});
+
+test("a successful create with a failed selection retries only selection", async (t) => {
+ const c = await mount(t);
+ let selections = 0;
+ c.api.selectMeetingNotificationFolder = async (ref) => {
+ selections++;
+ c.calls.push(["select", ref]);
+ return selections === 1
+ ? { success: false, code: "FOLDER_UNAVAILABLE" }
+ : { success: true, value: { ...contexts(), selectedDestination: ref } };
+ };
+ await c.click(c.byLabel("Choose meeting folder"));
+ await c.click(c.button("New folder"));
+ await c.type(c.byLabel("Name"), "Retry folder");
+ await c.click(c.button("Create & select"));
+ assert.ok(c.container.querySelector('[role="alert"]'));
+ await c.click(c.button("Create & select"));
+ const creates = c.calls.filter((x) => x[0] === "create");
+ assert.equal(creates.length, 2);
+ assert.equal(creates[1][1].requestId, creates[0][1].requestId);
+ assert.equal(selections, 2);
+ assert.equal(c.container.querySelector('[role="dialog"]'), null);
+});
+
+test("IME commit Enter cannot create; the next explicit Enter can", async (t) => {
+ const c = await mount(t);
+ await c.click(c.byLabel("Choose meeting folder"));
+ await c.click(c.button("New folder"));
+ const input = c.byLabel("Name");
+ await c.type(input, "会議");
+ await React.act(async () => {
+ input.dispatchEvent(
+ new globalThis.window.CompositionEvent("compositionstart", { bubbles: true })
+ );
+ input.dispatchEvent(
+ new globalThis.window.CompositionEvent("compositionend", { bubbles: true })
+ );
+ input.dispatchEvent(
+ new globalThis.window.KeyboardEvent("keydown", {
+ key: "Enter",
+ bubbles: true,
+ cancelable: true,
+ })
+ );
+ input.form.dispatchEvent(
+ new globalThis.window.Event("submit", { bubbles: true, cancelable: true })
+ );
+ });
+ assert.equal(c.calls.length, 0);
+ await React.act(async () =>
+ input.dispatchEvent(
+ new globalThis.window.KeyboardEvent("keyup", { key: "Enter", bubbles: true })
+ )
+ );
+ await c.click(c.button("Create & select"));
+ assert.equal(c.calls[0][0], "create");
+});
+
+test("default Start remains available when destination loading fails", async (t) => {
+ const c = await mount(t, {
+ getMeetingNotificationDestination: async () => ({
+ success: false,
+ code: "FOLDERS_UNAVAILABLE",
+ }),
+ });
+ await c.click(c.button("Join and transcribe"));
+ assert.equal(c.calls.filter((x) => x[0] === "start").length, 1);
+});
+
+test("a failed dismiss never opens the folder picker", async (t) => {
+ const c = await mount(t, {
+ meetingNotificationRespond: async () => ({ success: false, code: "STALE_NOTIFICATION" }),
+ });
+ t.mock.timers.enable({ apis: ["setTimeout"] });
+ await c.click(c.byLabel("Dismiss meeting notification"));
+ await React.act(async () => t.mock.timers.tick(200));
+ t.mock.timers.reset();
+ assert.equal(c.container.querySelector('[role="dialog"]'), null);
+});
+
+test("a late existing root note replaces choices with an explanation in the same dropdown", async (t) => {
+ const linked = {
+ noteId: 4,
+ spaceId: 2,
+ folderId: null,
+ spaceName: "Team",
+ folderName: null,
+ shared: true,
+ };
+ const c = await mount(t, {
+ meetingNotificationRespond: async () => ({
+ success: false,
+ code: "LINKED_NOTE_CHANGED",
+ context: { ...contexts(), existingNote: linked },
+ }),
+ });
+ await c.click(c.button("Join and transcribe"));
+ assert.equal(c.container.querySelectorAll('[role="dialog"]').length, 1);
+ assert.equal(c.container.querySelector('[role="listbox"]'), null);
+ assert.ok(c.container.textContent.includes("Team · Shared"));
+ assert.ok(c.button("Join and transcribe"));
+});
+
+test("folder refresh cannot discard the intentional focus acknowledgment", async (t) => {
+ const c = await mount(t);
+ let focusReply;
+ c.api.setMeetingNotificationSurface = async (state) =>
+ state.focus === "request"
+ ? new Promise((r) => (focusReply = r))
+ : { success: true, value: { width: 416, height: 84 } };
+ await c.click(c.byLabel("Choose meeting folder"));
+ assert.ok(focusReply);
+ await React.act(async () => focusReply({ success: true, value: { width: 416, height: 300 } }));
+ assert.equal(globalThis.document.activeElement, c.byLabel("Search folders"));
+});
+
+test("pointer Create works after accepting an IME candidate without keyup", async (t) => {
+ const c = await mount(t);
+ await c.click(c.byLabel("Choose meeting folder"));
+ await c.click(c.button("New folder"));
+ const input = c.byLabel("Name");
+ await c.type(input, "会議");
+ await React.act(async () => {
+ input.dispatchEvent(
+ new globalThis.window.CompositionEvent("compositionstart", { bubbles: true })
+ );
+ input.dispatchEvent(
+ new globalThis.window.CompositionEvent("compositionend", { bubbles: true })
+ );
+ });
+ await c.click(c.button("Create & select"));
+ assert.equal(c.calls.filter((x) => x[0] === "create").length, 1);
+});
+
+test("captured card swipe keeps pointer interactivity until release", async (t) => {
+ const interactivity = [];
+ const c = await mount(t, {
+ setNotificationInteractivity: async (value) => interactivity.push(value),
+ });
+ await React.act(async () => new Promise((r) => setTimeout(r, 60)));
+ const surface = c.container.querySelector(".meeting-notification-window");
+ surface.setPointerCapture = () => {};
+ surface.hasPointerCapture = () => true;
+ surface.releasePointerCapture = () => {};
+ const event = (type, x) =>
+ new globalThis.window.PointerEvent(type, {
+ bubbles: true,
+ isPrimary: true,
+ button: 0,
+ pointerId: 1,
+ clientX: x,
+ });
+ await React.act(async () => surface.dispatchEvent(event("pointerdown", 30)));
+ await React.act(async () =>
+ surface.dispatchEvent(
+ new globalThis.window.MouseEvent("mousemove", { bubbles: true, clientX: 50 })
+ )
+ );
+ assert.equal(interactivity.at(-1), true);
+ t.mock.timers.enable({ apis: ["setTimeout"] });
+ await React.act(async () => surface.dispatchEvent(event("pointerup", 150)));
+ const dismissals = () => c.calls.filter((x) => x[0] === "start" && x[2] === "dismiss").length;
+ assert.equal(dismissals(), 0, "the card slides out before main closes the window");
+ await React.act(async () => t.mock.timers.tick(200));
+ t.mock.timers.reset();
+ assert.equal(dismissals(), 1);
+});
+
+test("selection feedback uses 200/600/400 milliseconds and repeats from a fresh start", async (t) => {
+ const c = await mount(t);
+ t.mock.timers.enable({ apis: ["setTimeout"] });
+ await c.click(c.byLabel("Choose meeting folder"));
+ await c.click(c.byLabel("Private / Calls 1"));
+ const trigger = () => c.byLabel("Choose meeting folder");
+ assert.ok(trigger().classList.contains("feedback-enter"));
+ await React.act(async () => t.mock.timers.tick(200));
+ assert.ok(trigger().classList.contains("feedback-hold"));
+ await React.act(async () => t.mock.timers.tick(600));
+ assert.ok(trigger().classList.contains("feedback-exit"));
+ await React.act(async () => t.mock.timers.tick(399));
+ assert.ok(trigger().classList.contains("feedback-exit"));
+ await c.click(trigger());
+ await c.click(c.byLabel("Private / Calls 2"));
+ await React.act(async () => t.mock.timers.tick(1));
+ assert.ok(trigger().classList.contains("feedback-enter"));
+ await React.act(async () => t.mock.timers.tick(1199));
+ assert.ok(trigger().classList.contains("feedback-idle"));
+ t.mock.timers.reset();
+});
+
+test("linked root explanation receives focus and Escape closes it", async (t) => {
+ const c = await mount(t, {
+ getMeetingNotificationDestination: async () => ({
+ success: true,
+ value: {
+ ...contexts(),
+ existingNote: {
+ noteId: 4,
+ spaceId: 1,
+ folderId: null,
+ spaceName: "Private",
+ folderName: null,
+ shared: false,
+ },
+ },
+ }),
+ });
+ await c.click(c.byLabel("Choose meeting folder"));
+ const dialog = c.container.querySelector('[role="dialog"]');
+ assert.equal(globalThis.document.activeElement, dialog);
+ await React.act(async () =>
+ globalThis.document.activeElement.dispatchEvent(
+ new globalThis.window.KeyboardEvent("keydown", {
+ key: "Escape",
+ bubbles: true,
+ cancelable: true,
+ })
+ )
+ );
+ assert.equal(c.container.querySelector('[role="dialog"]'), null);
+});
+
+test("initial surface includes tall localized card layout before entrance animation", async (t) => {
+ const reports = [];
+ await mount(
+ t,
+ {
+ setMeetingNotificationSurface: async (state) => {
+ reports.push(state);
+ return { success: true, value: { width: 416, height: state.contentHeight } };
+ },
+ },
+ (dom) => {
+ const p = dom.HTMLElement.prototype;
+ for (const [key, value] of Object.entries({
+ offsetWidth: 392,
+ offsetHeight: 106,
+ offsetLeft: 12,
+ offsetTop: 12,
+ })) {
+ Object.defineProperty(p, key, {
+ configurable: true,
+ get() {
+ return this.getAttribute("data-meeting-region") === "card" ? value : 0;
+ },
+ });
+ }
+ p.getBoundingClientRect = () => ({ x: 500, y: 12, width: 392, height: 106 });
+ }
+ );
+ assert.ok(reports.length);
+ assert.ok(reports.every((report) => report.contentHeight >= 130));
+});
+
+test("Shared folders appear alongside Private folders in the same search results", async (t) => {
+ const c = await mount(t);
+ await c.click(c.byLabel("Choose meeting folder"));
+ assert.equal(c.container.querySelector('[role="group"][aria-label="Location"]'), null);
+ await c.type(c.byLabel("Search folders"), "Calls");
+ assert.equal(c.calls.length, 0);
+ assert.ok(c.byLabel("Private / Calls 1"));
+ assert.ok(c.byLabel("Team / Calls 6 · Shared"));
+ assert.equal(c.container.querySelectorAll('#meeting-folder-results [role="option"]').length, 7);
+ await c.click(c.byLabel("Team / Calls 6 · Shared"));
+ assert.deepEqual(c.calls, [["select", { folderId: 7, spaceId: 2 }]]);
+ await c.click(c.byLabel("Choose meeting folder"));
+ await c.click(c.button("New folder"));
+ assert.ok(c.button("Private"), "creation still starts Private after Shared selection");
+});
+
+test("search matches the visible teamspace and exact folder path", async (t) => {
+ const c = await mount(t);
+ await c.click(c.byLabel("Choose meeting folder"));
+ await c.type(c.byLabel("Search folders"), "Team");
+ assert.ok(c.byLabel("Team / Calls 6 · Shared"));
+ await c.type(c.byLabel("Search folders"), "Team / Calls 6");
+ await c.click(c.byLabel("Team / Calls 6 · Shared"));
+ assert.deepEqual(c.calls, [["select", { folderId: 7, spaceId: 2 }]]);
+});
+
+test("existing and created selections keep the same visible card with confirmation only", async (t) => {
+ const c = await mount(t);
+ await React.act(async () => new Promise((r) => setTimeout(r, 70)));
+ const card = c.container.querySelector('[data-meeting-region="card"]');
+ const motion = card.parentElement;
+ const surfaceCalls = [];
+ c.api.setMeetingNotificationSurface = async (state) => {
+ surfaceCalls.push(state);
+ return { success: true, value: { width: 416, height: state.contentHeight } };
+ };
+ for (const create of [false, true]) {
+ await c.click(c.byLabel("Choose meeting folder"));
+ if (create) {
+ await c.click(c.button("New folder"));
+ await c.type(c.byLabel("Name"), "New stable folder");
+ await c.click(c.button("Create & select"));
+ } else await c.click(c.byLabel("Private / Calls 1"));
+ assert.equal(c.container.querySelector('[data-meeting-region="card"]'), card);
+ assert.equal(motion.style.opacity, "1");
+ assert.equal(motion.style.transform, "translateX(0) scale(1)");
+ assert.ok(c.byLabel("Choose meeting folder").classList.contains("feedback-enter"));
+ assert.equal(surfaceCalls.at(-1).focus, "release");
+ assert.equal(surfaceCalls.at(-1).mode, "closed");
+ }
+ assert.equal(c.calls.filter(([action]) => action === "start").length, 0);
+});
+
+test("matching a teamspace path does not prefill an existing destination as a new folder", async (t) => {
+ const c = await mount(t);
+ await c.click(c.byLabel("Choose meeting folder"));
+ await c.type(c.byLabel("Search folders"), "Team / Calls 6");
+ await c.click(c.button("New folder"));
+ assert.equal(c.byLabel("Name").value, "");
+});
+
+test("location dropdown opens with the keyboard and Escape preserves the folder form", async (t) => {
+ const c = await mount(t);
+ await c.click(c.byLabel("Choose meeting folder"));
+ await c.click(c.button("New folder"));
+ const location = c.button("Private");
+ await React.act(async () => {
+ location.focus();
+ location.dispatchEvent(
+ new globalThis.window.KeyboardEvent("keydown", {
+ key: "ArrowDown",
+ bubbles: true,
+ cancelable: true,
+ })
+ );
+ });
+ const menu = c.container.querySelector('[role="menu"]');
+ assert.ok(menu, "location opens as a keyboard-accessible dropdown");
+ await React.act(async () =>
+ menu.dispatchEvent(
+ new globalThis.window.KeyboardEvent("keydown", {
+ key: "Escape",
+ bubbles: true,
+ cancelable: true,
+ })
+ )
+ );
+ assert.equal(c.container.querySelector('[role="menu"]'), null);
+ assert.ok(c.byLabel("Name"), "Escape only dismisses the location menu");
+ assert.equal(c.calls.length, 0);
+});
+
+test("choosing a Shared location keeps the draft and creates only on submit", async (t) => {
+ const c = await mount(t);
+ await c.click(c.byLabel("Choose meeting folder"));
+ await c.click(c.button("New folder"));
+ await c.type(c.byLabel("Name"), "Team planning");
+ await React.act(async () =>
+ c.button("Private").dispatchEvent(
+ new globalThis.window.KeyboardEvent("keydown", {
+ key: "ArrowDown",
+ bubbles: true,
+ cancelable: true,
+ })
+ )
+ );
+ const option = [...c.container.querySelectorAll('[role="menuitemradio"]')].find((el) =>
+ el.textContent.includes("Team")
+ );
+ await c.click(option);
+ assert.equal(c.container.querySelector('[role="menu"]'), null);
+ assert.equal(c.byLabel("Name").value, "Team planning");
+ assert.equal(c.calls.length, 0);
+ await c.click(c.button("Create & select"));
+ assert.equal(c.calls[0][0], "create");
+ assert.equal(c.calls[0][1].spaceId, 2);
+ assert.equal(c.calls[0][1].name, "Team planning");
+});
diff --git a/test/components/meetingNotificationFolderRefresh.test.js b/test/components/meetingNotificationFolderRefresh.test.js
new file mode 100644
index 000000000..5e2e400f0
--- /dev/null
+++ b/test/components/meetingNotificationFolderRefresh.test.js
@@ -0,0 +1,53 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+const React = require("react");
+const { createRoot } = require("react-dom/client");
+const {
+ createRendererServer,
+ installBrowserGlobals,
+ installHookDom,
+} = require("../lib/rendererTestHarness");
+async function setup(t) {
+ let root;
+ t.after(async () => {
+ if (root) await React.act(async () => root.unmount());
+ delete globalThis.__meetingFolderPush;
+ });
+ installBrowserGlobals(t);
+ const container = installHookDom(t);
+ const listeners = {};
+ const pushed = [];
+ globalThis.__meetingFolderPush = pushed;
+ Object.assign(globalThis.window.electronAPI, {
+ onMeetingNotificationFolderCreated: (cb) => (
+ (listeners.folder = cb),
+ () => delete listeners.folder
+ ),
+ getFolders: async () => [{ id: 4, space_id: 1, name: "Test" }],
+ getFolderNoteCounts: async () => [],
+ });
+ const vite = await createRendererServer(t, {
+ cachePrefix: "meeting-folder-refresh-",
+ mockModules: {
+ "/services/SyncService.js":
+ "export const syncService={debouncedPush:(...args)=>globalThis.__meetingFolderPush.push(args)};",
+ },
+ });
+ const store = await vite.ssrLoadModule("/stores/noteStore.ts");
+ function Mounted() {
+ React.useEffect(store.subscribeMeetingNotificationFolders, []);
+ return null;
+ }
+ root = createRoot(container);
+ await React.act(async () => root.render(React.createElement(Mounted)));
+
+ return { store, listeners, pushed };
+}
+test("mounted local folder hint refreshes without a cloud lease and schedules existing sync", async (t) => {
+ const { store, listeners, pushed } = await setup(t);
+ await listeners.folder({ folderId: 4 });
+ assert.equal(store.getFoldersValue()[0].id, 4);
+ assert.deepEqual(pushed, [["folder", 4]]);
+ await listeners.folder({ folderId: 9 });
+ assert.equal(pushed.length, 1);
+});
diff --git a/test/helpers/accountScopeIpc.test.js b/test/helpers/accountScopeIpc.test.js
index 47bd66d78..cd35455a8 100644
--- a/test/helpers/accountScopeIpc.test.js
+++ b/test/helpers/accountScopeIpc.test.js
@@ -206,3 +206,23 @@ test("a sign-out in main stops connects without waiting for the renderer", async
["auth-token-state-changed", { generation: 8, hasToken: false }],
]);
});
+
+test("meeting prompt retirement precedes scope mutation and skips a true no-op", async () => {
+ tokenState = { token: "meeting-test-token", generation: 20 };
+ const originalManager = fakeThis.windowManager;
+ const calls = [];
+ fakeThis.windowManager = {
+ retireMeetingNotificationScope: () => calls.push(databaseManager.activeAccountId),
+ };
+ databaseManager.activeAccountId = "old-account";
+ await setScope("meeting-account", 20);
+ assert.deepEqual(calls, ["old-account"]);
+ databaseManager.activeAccountId = "meeting-account";
+ await setScope("meeting-account", 20);
+ assert.deepEqual(calls, ["old-account"]);
+ handleAuthTokenChange({ token: "rotated", generation: 21 });
+ assert.deepEqual(calls, ["old-account", "meeting-account"]);
+ handleAuthTokenChange({ token: null, generation: 22 });
+ assert.deepEqual(calls, ["old-account", "meeting-account", "meeting-account"]);
+ fakeThis.windowManager = originalManager;
+});
diff --git a/test/helpers/meetingDetectionEngine.test.js b/test/helpers/meetingDetectionEngine.test.js
index cb7a51fbf..9ca0cb69d 100644
--- a/test/helpers/meetingDetectionEngine.test.js
+++ b/test/helpers/meetingDetectionEngine.test.js
@@ -5,13 +5,14 @@ const { EventEmitter } = require("node:events");
const enginePath = require.resolve("../../src/helpers/meetingDetectionEngine");
const originalLoad = Module._load;
+const openedUrls = [];
function loadEngine() {
delete require.cache[enginePath];
Module._load = function loadWithMocks(request, parent, isMain) {
if (request === "electron") {
- return { shell: { openExternal: async () => {} } };
+ return { shell: { openExternal: async (url) => openedUrls.push(url) } };
}
if (request === "./debugLogger") {
return { info() {}, warn() {}, debug() {}, error() {} };
@@ -113,7 +114,8 @@ test("explicitly dismissing an audio prompt still starts the mic cooldown", asyn
engine.setPreferences({ audioDetection: true, processDetection: true });
audioDetector.emit("sustained-audio-detected", { durationMs: 2000, detectedAt: 0 });
- await engine.handleNotificationResponse(shown[0].detectionId, "dismiss");
+ const owner = { prompt: shown[0], detection: engine.activeDetections.get(shown[0].detectionId) };
+ await engine.handleNotificationResponse(shown[0].detectionId, "dismiss", {}, owner);
assert.equal(audioDetector.dismissals, 1, "an explicit decline must keep its cooldown");
});
@@ -283,3 +285,160 @@ test("disabling notifications preserves active auto-end and releases both detect
assert.equal(audioDetector.running, false);
assert.equal(processDetector.running, false);
});
+
+function ownedNotification(t) {
+ const ctx = createEngine();
+ const { createDb } = require("./harness/db");
+ const db = createDb(t);
+ if (!db) return null;
+ ctx.engine.databaseManager = db;
+ const detection = {
+ source: "calendar",
+ key: "event",
+ event: { id: "event", calendar_id: "test-calendar", summary: "Weekly" },
+ };
+ ctx.engine.activeDetections.set("calendar:event", detection);
+ const owner = {
+ prompt: { detectionId: "calendar:event" },
+ detection,
+ selectedDestination: null,
+ };
+ let current = true;
+ Object.assign(ctx.windowManager, {
+ meetingRecentDestinations: [],
+ isMeetingNotificationOwner: (o) => current && o === owner,
+ updateMeetingNotificationPause() {},
+ dismissMeetingNotification() {
+ current = false;
+ },
+ queueMeetingNoteNavigation: async (payload) => {
+ ctx.meetingNavigations.push(payload);
+ return { success: true, value: db.getNote(payload.noteId) };
+ },
+ });
+ return {
+ ...ctx,
+ db,
+ owner,
+ respond: (options) =>
+ ctx.engine.handleNotificationResponse("calendar:event", "start", options, owner),
+ };
+}
+
+test("notification Start saves directly in selected folder and duplicate clicks share navigation", async (t) => {
+ const c = ownedNotification(t);
+ if (!c) return;
+ const folder = c.db.createFolder("Chosen").folder;
+ c.owner.selectedDestination = { folderId: folder.id, spaceId: folder.space_id };
+ let finish;
+ c.windowManager.queueMeetingNoteNavigation = (payload) => {
+ c.meetingNavigations.push(payload);
+ return new Promise((r) => (finish = r));
+ };
+ const one = c.respond();
+ const two = c.respond();
+ await new Promise(setImmediate);
+ assert.equal(c.meetingNavigations.length, 1);
+ const note = c.db.getNote(c.meetingNavigations[0].noteId);
+ assert.equal(note.folder_id, folder.id);
+ assert.equal(note.space_id, folder.space_id);
+ finish({ success: true, value: note });
+ assert.equal((await one).success, true);
+ assert.equal((await two).success, true);
+ assert.equal(c.db.getNotes().length, 1);
+});
+
+test("a linked root note requires current acknowledgment and is never moved or copied", async (t) => {
+ const c = ownedNotification(t);
+ if (!c) return;
+ const note = c.db.saveNote("Linked", "", "meeting").note;
+ c.db.updateNote(note.id, { calendar_event_id: "event", folder_id: null });
+ const first = await c.respond();
+ assert.equal(first.code, "LINKED_NOTE_CHANGED");
+ assert.equal(first.context.existingNote.folderId, null);
+ assert.equal(c.meetingNavigations.length, 0);
+ assert.equal(c.db.getNotes().length, 1);
+ const second = await c.respond({
+ existingNote: { noteId: note.id, spaceId: note.space_id, folderId: null },
+ });
+ assert.equal(second.success, true);
+ assert.equal(c.meetingNavigations[0].folderId, null);
+ assert.equal(c.db.getNotes().length, 1);
+});
+
+test("unavailable explicit destination never falls back to Meetings", async (t) => {
+ const c = ownedNotification(t);
+ if (!c) return;
+ c.owner.selectedDestination = { folderId: 999, spaceId: c.db.getPrivateSpaceId() };
+ assert.equal((await c.respond()).code, "FOLDER_UNAVAILABLE");
+ assert.equal(c.db.getNotes().length, 0);
+ assert.equal(c.meetingNavigations.length, 0);
+});
+
+test("strict lookup failure and vanished acknowledged note never create a replacement", async (t) => {
+ const c = ownedNotification(t);
+ if (!c) return;
+ const lookup = c.db.getOwnNoteByCalendarEventId;
+ c.db.getOwnNoteByCalendarEventId = () => {
+ throw Error("database busy");
+ };
+ assert.equal((await c.respond()).success, false);
+ assert.equal(c.db.getNotes().length, 0);
+ c.db.getOwnNoteByCalendarEventId = lookup;
+ assert.equal(
+ (await c.respond({ existingNote: { noteId: 999, spaceId: 1, folderId: null } })).code,
+ "NOTE_UNAVAILABLE"
+ );
+ assert.equal(c.db.getNotes().length, 0);
+});
+
+test("navigation failure retains committed note and retries without duplicate writes", async (t) => {
+ const c = ownedNotification(t);
+ if (!c) return;
+ let calls = 0;
+ c.windowManager.queueMeetingNoteNavigation = async (payload) => {
+ calls++;
+ return calls === 1
+ ? { success: false, code: "START_FAILED" }
+ : { success: true, value: c.db.getNote(payload.noteId) };
+ };
+ assert.equal((await c.respond()).code, "START_FAILED");
+ c.engine.handleCalendarReminder({ id: "next" });
+ assert.equal(c.shown.length, 1, "a failed Start must not leave prompts suppressed");
+ assert.equal(c.db.getNotes().length, 1);
+ assert.equal((await c.respond()).success, true);
+ assert.equal(c.db.getNotes().length, 1);
+ assert.equal(calls, 2);
+});
+
+test("Join opens the link and suppresses new prompts while navigation is pending", async (t) => {
+ const c = ownedNotification(t);
+ if (!c) return;
+ openedUrls.length = 0;
+ c.owner.detection.event.hangout_link = "https://meet.example/join?pwd=1";
+ let finish;
+ c.windowManager.queueMeetingNoteNavigation = () => new Promise((r) => (finish = r));
+ const joining = c.engine.handleNotificationResponse("calendar:event", "join", {}, c.owner);
+ await new Promise(setImmediate);
+ assert.deepEqual(openedUrls, ["https://meet.example/join?pwd=1"]);
+ c.engine.handleCalendarReminder({ id: "next" });
+ assert.equal(c.shown.length, 0);
+ finish({ success: true });
+ assert.equal((await joining).success, true);
+});
+
+test("coalesced audio detections cannot suppress the next meeting after a queued calendar prompt", () => {
+ const { engine, shown } = createEngine();
+ engine.setPreferences({ audioDetection: true, processDetection: true });
+ engine._userRecording = true;
+ engine._handleDetection("calendar", "event", { event: { summary: "Queued calendar" } });
+ engine._handleDetection("audio", "sustained-audio", {});
+ assert.equal(engine.activeDetections.size, 2);
+ engine._userRecording = false;
+ engine._flushNotificationQueue();
+ assert.equal(shown.length, 1);
+ assert.equal(engine.activeDetections.has("audio:sustained-audio"), false);
+ engine.handleDetectionNotificationClosed("calendar:event");
+ engine._handleDetection("audio", "sustained-audio", {});
+ assert.equal(shown.length, 2);
+});
diff --git a/test/helpers/meetingNotificationDestination.test.js b/test/helpers/meetingNotificationDestination.test.js
new file mode 100644
index 000000000..b9365585b
--- /dev/null
+++ b/test/helpers/meetingNotificationDestination.test.js
@@ -0,0 +1,68 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+const { createDb } = require("./harness/db");
+const destination = require("../../src/helpers/meetingNotificationDestination");
+
+test("eligible destinations preserve database order and exclude retracted/deleted/account rows", (t) => {
+ const db = createDb(t);
+ if (!db) return;
+ db.setActiveAccountId("first-account");
+ const first = db.createFolder("Calls").folder;
+ const removed = db.createFolder("Removed").folder;
+ db.db.prepare("UPDATE folders SET left_team=1 WHERE id=?").run(removed.id);
+ const ctx = destination.listMeetingDestinations(db);
+ assert.ok(ctx.folders.some((f) => f.id === first.id));
+ assert.ok(!ctx.folders.some((f) => f.id === removed.id));
+ assert.equal(ctx.defaultDestination.folderId, db.getMeetingsFolder().id);
+ assert.equal(
+ destination.resolveMeetingDestination(db, { folderId: first.id, spaceId: first.space_id + 99 }),
+ null
+ );
+ assert.equal(
+ destination.resolveMeetingDestination(db, { folderId: first.id, spaceId: first.space_id }).id,
+ first.id
+ );
+ db.setActiveAccountId("another-account");
+ assert.equal(
+ destination.resolveMeetingDestination(db, { folderId: first.id, spaceId: first.space_id }),
+ null
+ );
+});
+
+test("five recent selections are deduplicated and pruned by exact space; default does not promote", () => {
+ let history = [];
+ for (let i = 1; i <= 7; i++)
+ history = destination.rememberMeetingDestination(history, { folderId: i, spaceId: 1 });
+ assert.deepEqual(
+ history.map((r) => r.folderId),
+ [7, 6, 5, 4, 3]
+ );
+ const next = destination.rememberMeetingDestination(history, { folderId: 5, spaceId: 1 });
+ assert.deepEqual(
+ next.map((r) => r.folderId),
+ [5, 7, 6, 4, 3]
+ );
+ assert.deepEqual(
+ history.map((r) => r.folderId),
+ [7, 6, 5, 4, 3]
+ );
+ assert.deepEqual(
+ destination.pruneMeetingDestinations(next, [
+ { id: 5, space_id: 2 },
+ { id: 7, space_id: 1 },
+ ]),
+ [{ folderId: 7, spaceId: 1 }]
+ );
+});
+
+test("context failure is an error rather than an empty folder list", () => {
+ assert.throws(
+ () =>
+ destination.listMeetingDestinations({
+ getSpaces() {
+ throw Error("offline db");
+ },
+ }),
+ /offline db/
+ );
+});
diff --git a/test/helpers/meetingNotificationIpc.test.js b/test/helpers/meetingNotificationIpc.test.js
new file mode 100644
index 000000000..d7f50452e
--- /dev/null
+++ b/test/helpers/meetingNotificationIpc.test.js
@@ -0,0 +1,213 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+const fs = require("node:fs");
+const os = require("node:os");
+const path = require("node:path");
+const Module = require("node:module");
+
+const handlersModulePath = require.resolve("../../src/helpers/ipcHandlers");
+const originalLoad = Module._load;
+
+// Registers the real handler closures against a fake `this` (the scaffolding
+// from agentDictationPillIpc.test.js), with userData in a temporary directory.
+const handlers = new Map();
+const userDataDirectory = fs.mkdtempSync(path.join(os.tmpdir(), "account-scope-ipc-"));
+
+const electronStub = {
+ app: {
+ getPath: () => userDataDirectory,
+ getName: () => "test",
+ getVersion: () => "0.0.0",
+ isPackaged: false,
+ on: () => {},
+ requestSingleInstanceLock: () => true,
+ },
+ ipcMain: {
+ handle: (channel, fn) => handlers.set(channel, fn),
+ on: () => {},
+ removeHandler: () => {},
+ },
+ net: {
+ fetch: async () => ({
+ ok: true,
+ status: 200,
+ json: async () => ({}),
+ text: async () => "{}",
+ }),
+ },
+ BrowserWindow: class BrowserWindow {
+ static getAllWindows() {
+ return [];
+ }
+ static fromWebContents() {
+ return null;
+ }
+ },
+ shell: {},
+ dialog: {},
+ screen: { getPrimaryDisplay: () => ({ workAreaSize: { width: 0, height: 0 } }) },
+ systemPreferences: { getMediaAccessStatus: () => "granted" },
+ session: { fromPartition: () => ({}) },
+ clipboard: {},
+ nativeImage: {},
+ globalShortcut: {},
+ utilityProcess: {},
+ MessageChannelMain: class {},
+};
+
+Module._load = function loadWithMocks(request, parent, isMain) {
+ if (request === "electron") return electronStub;
+ return originalLoad.call(this, request, parent, isMain);
+};
+
+function anything() {
+ return new Proxy(function () {}, {
+ get: (target, property) => {
+ if (property === Symbol.toPrimitive || property === "toString") return () => "";
+ if (property === "then") return undefined;
+ return anything();
+ },
+ apply: () => anything(),
+ });
+}
+
+function buildFakeThis() {
+ const target = { sessionId: "test-session" };
+ return new Proxy(target, {
+ get: (value, property) => (property in value ? value[property] : anything()),
+ });
+}
+
+let fakeThis;
+let IPCHandlersClass;
+
+test.before(() => {
+ delete require.cache[handlersModulePath];
+ const IPCHandlers = require(handlersModulePath);
+ IPCHandlersClass = IPCHandlers;
+ const Ctor = IPCHandlers.default || IPCHandlers;
+ fakeThis = buildFakeThis();
+ Ctor.prototype.setupHandlers.call(fakeThis);
+});
+
+test.after(() => {
+ Module._load = originalLoad;
+ fs.rmSync(userDataDirectory, { recursive: true, force: true });
+});
+
+function setupMeeting(t) {
+ const { createDb } = require("./harness/db");
+ const db = createDb(t);
+ if (!db) return null;
+ const sender = {};
+ const owner = {
+ detection: {},
+ selectedDestination: null,
+ createRequests: new Map(),
+ };
+ const manager = {
+ meetingRecentDestinations: [],
+ captureMeetingNotificationOwner: (s) => (s === sender ? owner : null),
+ isMeetingNotificationOwner: (o) => o === owner,
+ sendToControlPanel: () => {},
+ };
+ const service = Object.create(IPCHandlersClass.prototype);
+ Object.assign(service, { databaseManager: db, windowManager: manager, _noteFilesEnabled: false });
+ Object.assign(fakeThis, {
+ databaseManager: db,
+ windowManager: manager,
+ getMeetingNotificationDestination: service.getMeetingNotificationDestination.bind(service),
+ selectMeetingNotificationFolder: service.selectMeetingNotificationFolder.bind(service),
+ createMeetingNotificationFolder: service.createMeetingNotificationFolder.bind(service),
+ });
+ return {
+ db,
+ owner,
+ sender,
+ service,
+ manager,
+ };
+}
+
+test("only the current notification sender can read/select/create", (t) => {
+ const ctx = setupMeeting(t);
+ if (!ctx) return;
+ assert.equal(
+ handlers.get("get-meeting-notification-destination")({ sender: {} }).code,
+ "STALE_NOTIFICATION"
+ );
+ const result = handlers.get("get-meeting-notification-destination")({ sender: ctx.sender });
+ assert.equal(result.success, true);
+ assert.equal(result.value.recentDestinations.length, 0);
+});
+
+test("selection rejects a moved row without discarding the accepted choice", (t) => {
+ const ctx = setupMeeting(t);
+ if (!ctx) return;
+ const folder = ctx.db.createFolder("Calls").folder;
+ const ref = { folderId: folder.id, spaceId: folder.space_id };
+ assert.equal(ctx.service.selectMeetingNotificationFolder(ctx.owner, ref).success, true);
+ const rejected = ctx.service.selectMeetingNotificationFolder(ctx.owner, { ...ref, spaceId: 999 });
+ assert.equal(rejected.code, "FOLDER_UNAVAILABLE");
+ assert.deepEqual(ctx.owner.selectedDestination, ref);
+ assert.deepEqual(ctx.manager.meetingRecentDestinations, [ref]);
+});
+
+test("create retry returns one committed row without selecting or promoting it", async (t) => {
+ const ctx = setupMeeting(t);
+ if (!ctx) return;
+ const request = { requestId: "one", name: " New folder ", spaceId: ctx.db.getPrivateSpaceId() };
+ const first = ctx.service.createMeetingNotificationFolder(ctx.owner, request);
+ assert.equal(first.success, true);
+ const second = ctx.service.createMeetingNotificationFolder(ctx.owner, request);
+ assert.deepEqual(second.value.createdFolder, first.value.createdFolder);
+ assert.equal(ctx.db.getFolders().filter((f) => f.name === "New folder").length, 1);
+ assert.equal(ctx.owner.selectedDestination, null);
+ assert.deepEqual(ctx.manager.meetingRecentDestinations, []);
+ assert.equal(
+ ctx.service.createMeetingNotificationFolder(ctx.owner, { ...request, name: "Different" }).code,
+ "INVALID_REQUEST"
+ );
+ ctx.db.deleteFolder(first.value.createdFolder.folderId);
+ assert.equal(
+ ctx.service.createMeetingNotificationFolder(ctx.owner, request).code,
+ "FOLDER_UNAVAILABLE"
+ );
+ assert.equal(ctx.db.getFolders().filter((f) => f.name === "New folder").length, 0);
+ await new Promise(setImmediate);
+});
+
+test("folder errors preserve request and destination; context lookup failure is retryable", (t) => {
+ const ctx = setupMeeting(t);
+ if (!ctx) return;
+ const spaceId = ctx.db.getPrivateSpaceId();
+ assert.equal(
+ ctx.service.createMeetingNotificationFolder(ctx.owner, {
+ requestId: "blank",
+ name: " ",
+ spaceId,
+ }).code,
+ "FOLDER_NAME_REQUIRED"
+ );
+ ctx.db.createFolder("Exact");
+ assert.equal(
+ ctx.service.createMeetingNotificationFolder(ctx.owner, {
+ requestId: "dup",
+ name: "Exact",
+ spaceId,
+ }).code,
+ "FOLDER_NAME_TAKEN"
+ );
+ assert.equal(
+ ctx.service.createMeetingNotificationFolder(ctx.owner, { requestId: "bad", name: 42, spaceId })
+ .code,
+ "INVALID_REQUEST"
+ );
+ ctx.db.getSpaces = () => {
+ throw Error("database busy");
+ };
+ assert.equal(
+ ctx.service.getMeetingNotificationDestination(ctx.owner).code,
+ "FOLDERS_UNAVAILABLE"
+ );
+});
diff --git a/test/helpers/meetingNotificationNoteCreation.test.js b/test/helpers/meetingNotificationNoteCreation.test.js
new file mode 100644
index 000000000..882f27cb4
--- /dev/null
+++ b/test/helpers/meetingNotificationNoteCreation.test.js
@@ -0,0 +1,53 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+const { createDb } = require("./harness/db");
+function input(db) {
+ const folder = db.getFolders().find((f) => f.id === db.getMeetingsFolder().id);
+ return {
+ title: "Test meeting",
+ folderId: folder.id,
+ spaceId: folder.space_id,
+ eventId: "event",
+ participants: "[]",
+ };
+}
+test("notification note creation atomically links metadata and reuses the owned calendar note", (t) => {
+ const db = createDb(t);
+ if (!db) return;
+ const request = input(db);
+ const first = db.createMeetingNoteForNotification(request);
+ const second = db.createMeetingNoteForNotification(request);
+ assert.equal(first.created, true);
+ assert.equal(second.created, false);
+ assert.equal(first.note.id, second.note.id);
+ assert.equal(first.note.calendar_event_id, "event");
+ assert.equal(db.getNotes().length, 1);
+});
+test("failed calendar metadata rolls the new note back, so retry creates just one note", (t) => {
+ const db = createDb(t);
+ if (!db) return;
+ const original = db.updateNote;
+ db.updateNote = () => ({ success: false });
+ assert.throws(() => db.createMeetingNoteForNotification(input(db)), /metadata/i);
+ assert.equal(db.getNotes().length, 0);
+ db.updateNote = original;
+ assert.equal(db.createMeetingNoteForNotification(input(db)).created, true);
+ assert.equal(db.getNotes().length, 1);
+});
+test("strict calendar lookup throws but legacy lookup retains its null fallback", (t) => {
+ const db = createDb(t);
+ if (!db) return;
+ db.db.exec("DROP TABLE notes");
+ assert.equal(db.getOwnNoteByCalendarEventId("event"), null);
+ assert.throws(() => db.getOwnNoteByCalendarEventId("event", { throwOnError: true }));
+});
+test("another account owned note is never reused by a notification", (t) => {
+ const db = createDb(t);
+ if (!db) return;
+ db.setActiveAccountId("a");
+ const first = db.createMeetingNoteForNotification(input(db));
+ db.setActiveAccountId("b");
+ const second = db.createMeetingNoteForNotification(input(db));
+ assert.equal(second.created, true);
+ assert.notEqual(first.note.id, second.note.id);
+});
diff --git a/test/helpers/windowManagerMeetingNotification.test.js b/test/helpers/windowManagerMeetingNotification.test.js
index 3ce3d8f64..b5de0536f 100644
--- a/test/helpers/windowManagerMeetingNotification.test.js
+++ b/test/helpers/windowManagerMeetingNotification.test.js
@@ -15,6 +15,9 @@ function createDeferred() {
const createdWindows = [];
let devServerWaitPromise = Promise.resolve();
+let tokenState = { token: null, generation: 0 };
+let bindingScope = null;
+let workArea = { x: 0, y: 0, width: 1200, height: 900 };
class FakeBrowserWindow extends EventEmitter {
constructor(options) {
@@ -26,13 +29,36 @@ class FakeBrowserWindow extends EventEmitter {
this.loadUrlCount = 0;
this.showCount = 0;
this.ignoreMouseEvents = [];
- this.webContents = {
+ this.webContents = Object.assign(new EventEmitter(), {
send: (channel, payload) => this.messages.push({ channel, payload }),
- };
+ });
createdWindows.push(this);
}
- setContentProtection() {}
+ setContentProtection(value) {
+ this.protected = value;
+ }
+ getBounds() {
+ return this.bounds || { x: 608, y: 16, width: 416, height: 84 };
+ }
+ setBounds(bounds) {
+ this.bounds = bounds;
+ }
+ setFocusable(value) {
+ (this.focusEvents ||= []).push(value ? "focusable" : "passive");
+ }
+ focus() {
+ (this.focusEvents ||= []).push("focus");
+ }
+ show() {
+ (this.focusEvents ||= []).push("show");
+ }
+ blur() {
+ (this.focusEvents ||= []).push("blur");
+ }
+ setShape(regions) {
+ this.shape = regions;
+ }
setIgnoreMouseEvents(ignore, options) {
this.ignoreMouseEvents.push({ ignore, options });
@@ -77,10 +103,22 @@ class FakeDragManager {
const originalLoad = Module._load;
Module._load = function loadWindowManagerWithStubs(request, parent, isMain) {
+ if (request === "./tokenStore") return { getState: () => tokenState };
+ if (request === "./accountScopeBinding")
+ return {
+ read: () => ({}),
+ resolveActiveAccountScope: () => bindingScope,
+ };
if (request === "electron") {
return {
app: { on: () => undefined },
- screen: { getPrimaryDisplay: () => ({}), on: () => undefined },
+ screen: {
+ getPrimaryDisplay: () => ({ workArea }),
+ getDisplayMatching: () => ({ workArea }),
+ getCursorScreenPoint: () => ({ x: -10000, y: -10000 }),
+ on: () => undefined,
+ removeListener: () => undefined,
+ },
BrowserWindow: FakeBrowserWindow,
shell: {},
dialog: {},
@@ -108,8 +146,9 @@ Module._load = function loadWindowManagerWithStubs(request, parent, isMain) {
if (request === "./dockManager") return {};
if (request === "./i18nMain") return { i18nMain: { t: (key) => key } };
if (request === "./windowConfig") {
- const notificationSize = { width: 392, height: 92 };
+ const notificationSize = { width: 416, height: 84 };
return {
+ ...originalLoad.call(this, request, parent, isMain),
MAIN_WINDOW_CONFIG: {},
CONTROL_PANEL_CONFIG: {},
NOTIFICATION_WINDOW_CONFIG: { ...notificationSize, acceptFirstMouse: true },
@@ -177,6 +216,9 @@ function installFakeTimers() {
test.beforeEach(() => {
createdWindows.length = 0;
+ tokenState = { token: null, generation: 0 };
+ bindingScope = null;
+ workArea = { x: 0, y: 0, width: 1200, height: 900 };
});
test("native push-to-talk force-stops after the safety timeout", () => {
@@ -390,7 +432,7 @@ test("window creation uses the notification dimensions and position", async () =
x: notificationWindow.options.x,
y: notificationWindow.options.y,
},
- { acceptFirstMouse: true, width: 392, height: 92, x: 608, y: 16 }
+ { acceptFirstMouse: true, width: 416, height: 84, x: 584, y: 16 }
);
// The payload the overlay fetches is stored verbatim.
assert.deepEqual(manager._pendingNotificationData, notification);
@@ -680,3 +722,406 @@ test("the tray's Ask assistant asks the renderer without showing or focusing the
capturing.sendOpenAssistantPanel();
assert.deepEqual(capturingEvents, []);
});
+
+async function showOwned(manager, id = "calendar:editing") {
+ manager.meetingDetectionEngine ||= {
+ databaseManager: { activeAccountId: null },
+ activeDetections: new Map(),
+ handleNotificationTimeout() {},
+ };
+ manager.meetingDetectionEngine.activeDetections.set(id, { source: "calendar", key: id });
+ const showing = manager.showMeetingNotification({ detectionId: id, source: "calendar" });
+ const win = manager.notificationWindow;
+ win.loadDeferred.resolve();
+ await showing;
+ manager.showNotificationWindow(win.webContents);
+ return { win, owner: manager.captureMeetingNotificationOwner(win.webContents) };
+}
+const surface = (revision, mode = "form", focus = "keep") => ({
+ revision,
+ mode,
+ focus,
+ contentHeight: mode === "closed" ? 84 : 260,
+ regions: [
+ { x: 12, y: 12, width: 392, height: 60 },
+ ...(mode === "closed" ? [] : [{ x: 116, y: 84, width: 288, height: 164 }]),
+ ],
+});
+
+test("leaving the card cannot resume an open form countdown", async () => {
+ const timers = installFakeTimers();
+ const manager = createNormalWindowManager();
+ try {
+ const { win, owner } = await showOwned(manager);
+ assert.ok(owner);
+ manager.setNotificationInteractivity(win.webContents, true);
+ manager.setMeetingNotificationSurface(owner, surface(1, "form", "request"));
+ manager.setNotificationInteractivity(win.webContents, false);
+ assert.equal(owner.pointerInside, false);
+ timers.runAll();
+ assert.equal(win.isDestroyed(), false);
+ manager.setMeetingNotificationSurface(owner, surface(2, "closed", "release"));
+ timers.runAll();
+ assert.equal(win.isDestroyed(), true);
+ } finally {
+ manager.dismissMeetingNotification();
+ timers.restore();
+ }
+});
+
+test("only deliberate open activates; closing avoids macOS window restacking", async () => {
+ const manager = createNormalWindowManager();
+ try {
+ const { win, owner } = await showOwned(manager);
+ assert.equal(win.protected, true);
+ assert.deepEqual(win.focusEvents || [], []);
+ manager.setMeetingNotificationSurface(owner, surface(1, "list"));
+ assert.deepEqual(win.focusEvents || [], []);
+ manager.setMeetingNotificationSurface(owner, surface(2, "form", "request"));
+ // Linux stays focusable from construction; setFocusable is only supported
+ // by the macOS/Windows path. Both paths must activate only on request.
+ const activation =
+ process.platform === "linux" ? ["show", "focus"] : ["focusable", "show", "focus"];
+ assert.deepEqual(win.focusEvents, activation);
+ manager.setMeetingNotificationSurface(owner, surface(3, "closed", "release"));
+ const release =
+ process.platform === "darwin"
+ ? ["passive"]
+ : process.platform === "linux"
+ ? ["blur"]
+ : ["blur", "passive"];
+ assert.deepEqual(win.focusEvents, [...activation, ...release]);
+ assert.equal(win.getBounds().height, 84);
+ } finally {
+ manager.dismissMeetingNotification();
+ }
+});
+
+test("reused detection strings and stale layout cannot mutate the current prompt", async () => {
+ const manager = createNormalWindowManager();
+ try {
+ const first = await showOwned(manager);
+ const second = await showOwned(manager);
+ assert.equal(manager.captureMeetingNotificationOwner(first.win.webContents), null);
+ assert.equal(
+ manager.setMeetingNotificationSurface(first.owner, surface(20)).code,
+ "STALE_NOTIFICATION"
+ );
+ assert.equal(manager.setMeetingNotificationSurface(second.owner, surface(2)).success, true);
+ assert.equal(manager.setMeetingNotificationSurface(second.owner, surface(1)).success, false);
+ for (const invalid of [NaN, Infinity, -1]) {
+ assert.equal(
+ manager.setMeetingNotificationSurface(second.owner, {
+ ...surface(3),
+ contentHeight: invalid,
+ }).success,
+ false
+ );
+ }
+ assert.equal(second.win.getBounds().height, 260);
+ } finally {
+ manager.dismissMeetingNotification();
+ }
+});
+
+test("small negative-origin displays bound the full surface and its input regions", async () => {
+ const platform = Object.getOwnPropertyDescriptor(process, "platform");
+ Object.defineProperty(process, "platform", { value: "linux" });
+ const manager = createNormalWindowManager();
+ try {
+ const { win, owner } = await showOwned(manager);
+ workArea = { x: -320, y: -240, width: 320, height: 240 };
+ const result = manager.setMeetingNotificationSurface(owner, surface(1));
+ assert.deepEqual(result.value, { width: 320, height: 240, maxHeight: 240 });
+ assert.deepEqual(win.getBounds(), { x: -320, y: -240, width: 320, height: 240 });
+ assert.ok(
+ win.shape.every((r) => r.x >= 0 && r.y >= 0 && r.x + r.width <= 320 && r.y + r.height <= 240)
+ );
+ } finally {
+ manager.dismissMeetingNotification();
+ Object.defineProperty(process, "platform", platform);
+ }
+});
+
+test("credential replacement fences ownership before database account reconciliation", async () => {
+ const manager = createNormalWindowManager();
+ try {
+ const { owner } = await showOwned(manager);
+ manager.retireMeetingNotificationScope();
+ assert.equal(manager.isMeetingNotificationOwner(owner), false);
+ assert.equal(manager.notificationWindow, null);
+ assert.deepEqual(manager.meetingRecentDestinations, []);
+ } finally {
+ manager.dismissMeetingNotification();
+ }
+});
+
+test("a stored token without an account binding scopes the prompt as signed out", async () => {
+ tokenState = { token: "signed-out-token", generation: 0 };
+ const manager = createNormalWindowManager();
+ try {
+ const { owner } = await showOwned(manager);
+ assert.equal(manager.isMeetingNotificationOwner(owner), true);
+ manager.meetingDetectionEngine.databaseManager.activeAccountId = "unbound-account";
+ assert.equal(manager.isMeetingNotificationOwner(owner), false);
+ } finally {
+ manager.dismissMeetingNotification();
+ }
+});
+
+async function navigationFixture() {
+ const manager = createNormalWindowManager();
+ const { owner } = await showOwned(manager);
+ let row = { id: 9, space_id: 1, folder_id: 3, deleted_at: null, left_team: 0 };
+ manager.meetingDetectionEngine.databaseManager = {
+ activeAccountId: null,
+ getNote: () => row,
+ getSpace: (id) => (id === 1 ? { id: 1, name: "Private", kind: "private" } : null),
+ getFolders: () => [
+ { id: 3, space_id: 1, name: "Meetings" },
+ { id: 4, space_id: 1, name: "Moved" },
+ ],
+ getSpaces: () => [{ id: 1, name: "Private", kind: "private" }],
+ getMeetingsFolder: () => ({ id: 3 }),
+ };
+ owner.committedNoteId = 9;
+ const panel = new EventEmitter();
+ let loading = false;
+ panel.isDestroyed = () => false;
+ panel.webContents = new EventEmitter();
+ panel.webContents.isLoading = () => loading;
+ panel.webContents.send = () => {};
+ manager.controlPanelWindow = panel;
+ manager.createControlPanelWindow = async () => {};
+ const payload = { navigationId: "navigate-one", noteId: 9, spaceId: 1, folderId: 3 };
+ return {
+ manager,
+ owner,
+ panel,
+ payload,
+ setRow: (next) => {
+ row = next;
+ },
+ row,
+ start: () => manager.queueMeetingNoteNavigation(payload, { owner }),
+ // Like Electron, a new panel's load resolves inside did-finish-load, while
+ // isLoading() is still true; did-stop-loading clears it a tick later.
+ createPanel: async () => {
+ loading = true;
+ setImmediate(() => {
+ loading = false;
+ panel.webContents.emit("did-stop-loading");
+ });
+ },
+ };
+}
+
+test("only the consuming current panel can confirm a navigation once", async () => {
+ const f = await navigationFixture();
+ try {
+ const pending = f.start();
+ await new Promise(setImmediate);
+ assert.equal(f.manager.consumePendingMeetingNoteNavigation({}), null);
+ assert.deepEqual(f.manager.consumePendingMeetingNoteNavigation(f.panel.webContents), f.payload);
+ assert.equal(
+ f.manager.confirmMeetingNoteNavigation({}, "navigate-one").code,
+ "STALE_NOTIFICATION"
+ );
+ assert.equal(
+ f.manager.confirmMeetingNoteNavigation(f.panel.webContents, "navigate-one").success,
+ true
+ );
+ assert.equal((await pending).success, true);
+ assert.equal(
+ f.manager.confirmMeetingNoteNavigation(f.panel.webContents, "navigate-one").success,
+ false
+ );
+ } finally {
+ f.manager.dismissMeetingNotification();
+ }
+});
+
+test("deleted, retracted, and moved notes fail final confirmation after delayed editor load", async () => {
+ for (const change of [
+ { deleted_at: "now" },
+ { left_team: 1 },
+ { folder_id: 4 },
+ { folder_id: null },
+ ]) {
+ const f = await navigationFixture();
+ try {
+ const pending = f.start();
+ await new Promise(setImmediate);
+ f.manager.consumePendingMeetingNoteNavigation(f.panel.webContents);
+ f.setRow({ ...f.row, ...change });
+ const result = f.manager.confirmMeetingNoteNavigation(f.panel.webContents, "navigate-one");
+ assert.equal(result.code, "folder_id" in change ? "LINKED_NOTE_CHANGED" : "NOTE_UNAVAILABLE");
+ if ("folder_id" in change)
+ assert.equal(result.context.existingNote.folderId, change.folder_id);
+ assert.equal((await pending).success, false);
+ assert.equal(f.manager.notificationWindow.isDestroyed(), false);
+ } finally {
+ f.manager.dismissMeetingNotification();
+ }
+ }
+});
+
+test("an absent editor times out and late confirmation cannot authorize recording", async () => {
+ const timers = installFakeTimers();
+ const f = await navigationFixture();
+ try {
+ const pending = f.start();
+ await new Promise(setImmediate);
+ timers.runDelay(15000);
+ assert.equal((await pending).code, "START_FAILED");
+ assert.equal(
+ f.manager.confirmMeetingNoteNavigation(f.panel.webContents, "navigate-one").success,
+ false
+ );
+ } finally {
+ f.manager.dismissMeetingNotification();
+ timers.restore();
+ }
+});
+
+test("panel destruction and account retirement cancel pending navigation", async () => {
+ for (const cause of ["panel", "account"]) {
+ const f = await navigationFixture();
+ const contents = f.panel.webContents;
+ try {
+ const pending = f.start();
+ await new Promise(setImmediate);
+ if (cause === "panel") {
+ // Electron's getter throws once the window is destroyed.
+ Object.defineProperty(f.panel, "webContents", {
+ get() {
+ throw new Error("Object has been destroyed");
+ },
+ });
+ f.panel.emit("closed");
+ }
+ if (cause === "account") f.manager.retireMeetingNotificationScope();
+ assert.equal((await pending).success, false);
+ assert.equal(f.manager.confirmMeetingNoteNavigation(contents, "navigate-one").success, false);
+ } finally {
+ f.manager.dismissMeetingNotification();
+ }
+ }
+});
+
+test("a Start that creates the panel delivers once it loads, past the onboarding gate", async () => {
+ const f = await navigationFixture();
+ try {
+ // A fresh control panel document raises the gate, which hides every prompt.
+ f.manager.createControlPanelWindow = async () => {
+ f.manager.setOnboardingActive(true);
+ await f.createPanel();
+ };
+ const pending = f.start();
+ await new Promise(setImmediate);
+ assert.equal(f.manager.notificationWindow, null);
+ assert.deepEqual(f.manager.consumePendingMeetingNoteNavigation(f.panel.webContents), f.payload);
+ assert.equal(
+ f.manager.confirmMeetingNoteNavigation(f.panel.webContents, "navigate-one").success,
+ true
+ );
+ assert.equal((await pending).success, true);
+ } finally {
+ f.manager.dismissMeetingNotification();
+ }
+});
+
+test("replacing an audio prompt retires only its captured detection", async () => {
+ const manager = createNormalWindowManager();
+ try {
+ await showOwned(manager, "audio:sustained-audio");
+ manager.meetingDetectionEngine.activeDetections.set("queued", { source: "calendar" });
+ await showOwned(manager, "calendar:replacement");
+ assert.equal(
+ manager.meetingDetectionEngine.activeDetections.has("audio:sustained-audio"),
+ false
+ );
+ assert.equal(manager.meetingDetectionEngine.activeDetections.has("calendar:replacement"), true);
+ assert.equal(manager.meetingDetectionEngine.activeDetections.has("queued"), true);
+ } finally {
+ manager.dismissMeetingNotification();
+ }
+});
+
+test("notification renderer crash retires its owner even while the window survives", async () => {
+ const manager = createNormalWindowManager();
+ const { win, owner } = await showOwned(manager);
+ win.webContents.emit("render-process-gone", {}, { reason: "crashed" });
+ assert.equal(manager.isMeetingNotificationOwner(owner), false);
+ assert.equal(manager.notificationWindow, null);
+});
+
+test("identical layout reports do not resize or show the notification again", async () => {
+ const manager = createNormalWindowManager();
+ try {
+ const { win, owner } = await showOwned(manager);
+ const sizes = [];
+ const initialLoads = win.loadUrlCount;
+ const resize = win.setBounds.bind(win);
+ win.setBounds = (bounds) => {
+ sizes.push(bounds);
+ resize(bounds);
+ };
+ manager.setMeetingNotificationSurface(owner, surface(1, "list", "request"));
+ const opens = win.focusEvents.slice();
+ manager.setMeetingNotificationSurface(owner, surface(2, "list"));
+ assert.equal(sizes.length, 1);
+ manager.setMeetingNotificationSurface(owner, surface(3, "closed", "release"));
+ manager.setMeetingNotificationSurface(owner, surface(4, "closed"));
+ assert.equal(sizes.length, 2);
+ assert.deepEqual(win.focusEvents, [
+ ...opens,
+ ...(process.platform === "darwin" ? [] : ["blur"]),
+ ...(process.platform === "linux" ? [] : ["passive"]),
+ ]);
+ assert.equal(win.loadUrlCount, initialLoads);
+ } finally {
+ manager.dismissMeetingNotification();
+ }
+});
+
+test("closing a destroyed native window does not read its webContents getter", async () => {
+ const manager = createNormalWindowManager();
+ const { win } = await showOwned(manager);
+ const contents = win.webContents;
+ Object.defineProperty(win, "webContents", {
+ get() {
+ if (win.destroyed) throw new Error("Object has been destroyed");
+ return contents;
+ },
+ });
+ assert.doesNotThrow(() => manager.dismissMeetingNotification());
+ assert.equal(contents.listenerCount("render-process-gone"), 0);
+});
+
+test("release preserves macOS stacking while Windows and Linux still blur", async () => {
+ const platform = Object.getOwnPropertyDescriptor(process, "platform");
+ try {
+ for (const name of ["darwin", "win32", "linux"]) {
+ Object.defineProperty(process, "platform", { value: name });
+ const manager = createNormalWindowManager();
+ try {
+ const { win, owner } = await showOwned(manager);
+ manager.setMeetingNotificationSurface(owner, surface(1, "form", "request"));
+ win.focusEvents = [];
+ manager.setMeetingNotificationSurface(owner, surface(2, "closed", "release"));
+ assert.deepEqual(
+ win.focusEvents,
+ name === "darwin" ? ["passive"] : name === "win32" ? ["blur", "passive"] : ["blur"],
+ name
+ );
+ assert.equal(manager.notificationWindow, win);
+ assert.equal(win.isDestroyed(), false);
+ } finally {
+ manager.dismissMeetingNotification();
+ }
+ }
+ } finally {
+ Object.defineProperty(process, "platform", platform);
+ }
+});