Skip to content

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

feat(notes): import Granola meeting notes from CSV export (#1813)

Chad Piha97d5291e050d
diff --git a/preload.js b/preload.js
index d23e14ab5..d81a7e1e3 100644
--- a/preload.js
+++ b/preload.js
@@ -207,6 +207,8 @@ contextBridge.exposeInMainWorld("electronAPI", {
noteFilesRebuild: () => ipcRenderer.invoke("note-files-rebuild"),
noteFilesGetDefaultPath: () => ipcRenderer.invoke("note-files-get-default-path"),
noteFilesPickFolder: () => ipcRenderer.invoke("note-files-pick-folder"),
+ granolaImportPickAndPreview: () => ipcRenderer.invoke("granola-import-pick-and-preview"),
+ granolaImportRun: () => ipcRenderer.invoke("granola-import-run"),
showNoteFile: (noteId) => ipcRenderer.invoke("show-note-file", noteId),
showFolderInExplorer: (folderName) => ipcRenderer.invoke("show-folder-in-explorer", folderName),
diff --git a/src/components/SettingsPage.tsx b/src/components/SettingsPage.tsx
index ae9c9d011..c2e0b01fa 100644
--- a/src/components/SettingsPage.tsx
+++ b/src/components/SettingsPage.tsx
@@ -109,7 +109,12 @@ import { useUsage } from "../hooks/useUsage";
import { cn } from "./lib/utils";
import { GRADIENT_CIRCLE } from "./ui/gradientCircle";
import { Popover, PopoverContent, PopoverTrigger } from "./ui/popover";
-import { startMigration, useMigration } from "../stores/noteStore.js";
+import {
+ startMigration,
+ useMigration,
+ loadFolders,
+ initializeNotesTree,
+} from "../stores/noteStore.js";
import { syncService } from "../services/SyncService.js";
import { formatBytes } from "../utils/formatBytes";
import {
@@ -230,6 +235,243 @@ function SectionHeader({
);
}
+interface GranolaImportPreview {
+ total: number;
+ newCount: number;
+ duplicateCount: number;
+ sampleTitles: string[];
+ warningCount: number;
+}
+
+type GranolaImportState =
+ | { phase: "idle" }
+ | { phase: "picking" }
+ | { phase: "preview"; preview: GranolaImportPreview }
+ | { phase: "importing"; preview: GranolaImportPreview }
+ | { phase: "done"; imported: number; skipped: number };
+
+function GranolaImportSection({
+ showAlertDialog,
+}: {
+ showAlertDialog: (options: { title: string; description?: string }) => void;
+}) {
+ const { t } = useTranslation();
+ const [state, setState] = useState<GranolaImportState>({ phase: "idle" });
+ // Guards double-clicks: handlers read stale closure state, so state alone
+ // can't prevent a second dialog/run being started in the same frame.
+ const requestInFlightRef = useRef(false);
+
+ const errorDescription = (code?: string) => {
+ switch (code) {
+ case "EMPTY_FILE":
+ return t("settings.granolaImport.error.EMPTY_FILE");
+ case "HEADERS_UNRECOGNIZED":
+ return t("settings.granolaImport.error.HEADERS_UNRECOGNIZED");
+ case "NO_DATA_ROWS":
+ return t("settings.granolaImport.error.NO_DATA_ROWS");
+ case "FILE_TOO_LARGE":
+ return t("settings.granolaImport.error.FILE_TOO_LARGE");
+ default:
+ return t("settings.granolaImport.error.generic");
+ }
+ };
+
+ const showImportError = (code?: string) => {
+ showAlertDialog({
+ title: t("settings.granolaImport.error.title"),
+ description: errorDescription(code),
+ });
+ };
+
+ const handleChooseFile = async () => {
+ if (requestInFlightRef.current) return;
+ requestInFlightRef.current = true;
+ setState({ phase: "picking" });
+ try {
+ let result:
+ | Awaited<ReturnType<NonNullable<typeof window.electronAPI.granolaImportPickAndPreview>>>
+ | undefined;
+ try {
+ result = await window.electronAPI?.granolaImportPickAndPreview?.();
+ } catch {
+ setState({ phase: "idle" });
+ showImportError();
+ return;
+ }
+ if (!result || result.canceled) {
+ setState({ phase: "idle" });
+ return;
+ }
+ if (!result.success) {
+ setState({ phase: "idle" });
+ showImportError(result.error);
+ return;
+ }
+ setState({
+ phase: "preview",
+ preview: {
+ total: result.total ?? 0,
+ newCount: result.newCount ?? 0,
+ duplicateCount: result.duplicateCount ?? 0,
+ sampleTitles: result.sampleTitles ?? [],
+ warningCount: result.rowIssueCount ?? 0,
+ },
+ });
+ } finally {
+ requestInFlightRef.current = false;
+ }
+ };
+
+ const handleConfirm = async () => {
+ if (state.phase !== "preview" || requestInFlightRef.current) return;
+ requestInFlightRef.current = true;
+ setState({ phase: "importing", preview: state.preview });
+ try {
+ let result:
+ Awaited<ReturnType<NonNullable<typeof window.electronAPI.granolaImportRun>>> | undefined;
+ try {
+ result = await window.electronAPI?.granolaImportRun?.();
+ } catch {
+ result = undefined;
+ }
+ if (!result?.success) {
+ setState({ phase: "idle" });
+ showImportError(result?.error);
+ return;
+ }
+ const imported = result.imported ?? 0;
+ setState({ phase: "done", imported, skipped: result.skipped ?? 0 });
+ if (imported > 0) {
+ // One refresh + one batched sync pass — never per-note pushes.
+ void loadFolders();
+ void initializeNotesTree();
+ void syncService.requestSyncAll("manual");
+ }
+ } finally {
+ requestInFlightRef.current = false;
+ }
+ };
+
+ const dialogOpen =
+ state.phase === "preview" || state.phase === "importing" || state.phase === "done";
+ const preview = state.phase === "preview" || state.phase === "importing" ? state.preview : null;
+
+ return (
+ <div>
+ <SectionHeader
+ title={t("settings.granolaImport.title")}
+ description={t("settings.granolaImport.howTo")}
+ />
+ <SettingsPanel>
+ <SettingsPanelRow>
+ <SettingsRow
+ label={t("settings.granolaImport.title")}
+ description={t("settings.granolaImport.description")}
+ >
+ <Button
+ variant="outline"
+ size="sm"
+ className="h-7 text-xs"
+ disabled={state.phase === "picking"}
+ onClick={handleChooseFile}
+ >
+ {state.phase === "picking" ? (
+ <Loader2 className="h-3 w-3 animate-spin" />
+ ) : (
+ t("settings.granolaImport.chooseFile")
+ )}
+ </Button>
+ </SettingsRow>
+ </SettingsPanelRow>
+ </SettingsPanel>
+
+ <Dialog
+ open={dialogOpen}
+ onOpenChange={(open) => {
+ if (!open && state.phase !== "importing") setState({ phase: "idle" });
+ }}
+ >
+ <DialogContent className="sm:max-w-90">
+ <DialogHeader>
+ <DialogTitle>
+ {state.phase === "done"
+ ? t("settings.granolaImport.done.title")
+ : t("settings.granolaImport.preview.title")}
+ </DialogTitle>
+ {state.phase === "done" ? (
+ <DialogDescription>
+ {t("settings.granolaImport.done.summary", {
+ imported: state.imported,
+ skipped: state.skipped,
+ })}
+ </DialogDescription>
+ ) : (
+ preview && (
+ <DialogDescription>
+ {preview.newCount === 0
+ ? t("settings.granolaImport.preview.nothingNew")
+ : t("settings.granolaImport.preview.summary", {
+ total: preview.total,
+ newCount: preview.newCount,
+ duplicateCount: preview.duplicateCount,
+ })}
+ </DialogDescription>
+ )
+ )}
+ </DialogHeader>
+ {preview && (
+ <div className="space-y-2">
+ {preview.sampleTitles.length > 0 && (
+ <ul className="text-xs text-muted-foreground space-y-1">
+ {preview.sampleTitles.map((title, index) => (
+ <li key={`${index}-${title}`} className="truncate">
+ {title}
+ </li>
+ ))}
+ </ul>
+ )}
+ {preview.warningCount > 0 && (
+ <p className="text-xs text-muted-foreground/80">
+ {t("settings.granolaImport.preview.warnings", {
+ warningCount: preview.warningCount,
+ })}
+ </p>
+ )}
+ </div>
+ )}
+ <DialogFooter>
+ {state.phase === "done" ? (
+ <Button size="sm" onClick={() => setState({ phase: "idle" })}>
+ {t("common.close")}
+ </Button>
+ ) : (
+ <>
+ <Button
+ variant="outline"
+ size="sm"
+ disabled={state.phase === "importing"}
+ onClick={() => setState({ phase: "idle" })}
+ >
+ {t("common.cancel")}
+ </Button>
+ <Button size="sm" disabled={state.phase === "importing"} onClick={handleConfirm}>
+ {state.phase === "importing" ? (
+ <Loader2 className="h-3 w-3 animate-spin" />
+ ) : (
+ t("settings.granolaImport.preview.confirm", {
+ newCount: preview?.newCount ?? 0,
+ })
+ )}
+ </Button>
+ </>
+ )}
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ </div>
+ );
+}
+
interface TranscriptionSectionProps {
isSignedIn: boolean;
startOnboarding: () => void;
@@ -2806,6 +3048,9 @@ export default function SettingsPage({
</SettingsPanel>
</div>
+ {/* Import from Granola */}
+ <GranolaImportSection showAlertDialog={showAlertDialog} />
+
{/* Floating Icon */}
<div>
<SectionHeader
diff --git a/src/helpers/database.js b/src/helpers/database.js
index 373c1f20b..9a48f23de 100644
--- a/src/helpers/database.js
+++ b/src/helpers/database.js
@@ -1994,6 +1994,97 @@ class DatabaseManager {
}
}
+ /**
+ * Bulk-insert externally imported notes (e.g. a Granola CSV export).
+ * Unlike saveNote, rows carry their own client_note_id and original
+ * created_at/updated_at; the UNIQUE client_note_id index makes re-imports
+ * idempotent (duplicates are skipped, never overwritten).
+ */
+ importNotes(rows, { noteType = "meeting", folderName = "Imported" } = {}) {
+ try {
+ if (!this.db) throw new Error("Database not initialized");
+ const spaceId = this.getPrivateSpaceId();
+
+ let folderId = null;
+ try {
+ const existing = this.db
+ .prepare("SELECT id FROM folders WHERE name = ? AND space_id = ? AND deleted_at IS NULL")
+ .get(folderName, spaceId);
+ folderId = existing?.id ?? this.createFolder(folderName, spaceId)?.folder?.id ?? null;
+ } catch (folderError) {
+ debugLogger.error(
+ "Import folder resolution failed; importing without a folder",
+ { error: folderError.message },
+ "notes"
+ );
+ }
+
+ const insert = this.db.prepare(`
+ INSERT INTO notes (client_note_id, title, content, note_type, source_file,
+ folder_id, space_id, transcript, participants, sync_status, created_at, updated_at)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 'pending',
+ COALESCE(?, datetime('now')), COALESCE(?, datetime('now')))
+ ON CONFLICT(client_note_id) DO NOTHING
+ `);
+
+ let imported = 0;
+ let skipped = 0;
+ const noteIds = [];
+ const errors = [];
+ this.db.transaction(() => {
+ for (const row of rows) {
+ try {
+ const result = insert.run(
+ row.clientNoteId,
+ row.title,
+ row.content,
+ noteType,
+ row.sourceFile,
+ folderId,
+ spaceId,
+ row.transcript,
+ row.participants,
+ row.createdAt,
+ row.createdAt
+ );
+ if (result.changes === 1) {
+ imported++;
+ noteIds.push(Number(result.lastInsertRowid));
+ } else {
+ skipped++;
+ }
+ } catch (rowError) {
+ errors.push({ clientNoteId: row.clientNoteId, error: rowError.message });
+ }
+ }
+ })();
+
+ return { success: true, imported, skipped, folderId, noteIds, errors };
+ } catch (error) {
+ debugLogger.error("Error importing notes", { error: error.message }, "notes");
+ throw error;
+ }
+ }
+
+ getExistingClientNoteIds(clientNoteIds) {
+ try {
+ if (!this.db) throw new Error("Database not initialized");
+ const existing = [];
+ for (let i = 0; i < clientNoteIds.length; i += 500) {
+ const chunk = clientNoteIds.slice(i, i + 500);
+ const placeholders = chunk.map(() => "?").join(",");
+ const found = this.db
+ .prepare(`SELECT client_note_id FROM notes WHERE client_note_id IN (${placeholders})`)
+ .all(...chunk);
+ existing.push(...found.map((row) => row.client_note_id));
+ }
+ return existing;
+ } catch (error) {
+ debugLogger.error("Error checking client note ids", { error: error.message }, "notes");
+ throw error;
+ }
+ }
+
getNote(id) {
try {
if (!this.db) {
diff --git a/src/helpers/granolaImport.js b/src/helpers/granolaImport.js
new file mode 100644
index 000000000..75d4afe1a
--- /dev/null
+++ b/src/helpers/granolaImport.js
@@ -0,0 +1,399 @@
+import { createHash } from "node:crypto";
+
+/**
+ * Granola CSV import parsing. Pure module: no fs, no Electron.
+ *
+ * Granola's official CSV export (Settings → Profile → Generate CSV) is the only
+ * data source available since Granola encrypted its local cache (v6+). The column
+ * set is undocumented and has varied between exports, so parsing is header-driven
+ * and tolerant: unknown columns are ignored, the transcript column is optional,
+ * and per-row problems produce warnings instead of aborting the import.
+ */
+
+/**
+ * RFC-4180 CSV tokenizer. Handles quoted fields with embedded commas/newlines,
+ * doubled-quote escapes, CRLF and LF endings, and a leading UTF-8 BOM.
+ * An unclosed quote at EOF is recovered (rest of input becomes the field).
+ *
+ * @param {string} text
+ * @returns {{ rows: string[][], warnings: Array<{ code: string }> }}
+ */
+export function parseCsv(text) {
+ const warnings = [];
+ let src = String(text ?? "");
+ if (src.charCodeAt(0) === 0xfeff) src = src.slice(1);
+
+ const rows = [];
+ let row = [];
+ let field = "";
+ let inQuotes = false;
+
+ const pushField = () => {
+ row.push(field);
+ field = "";
+ };
+ const pushRow = () => {
+ pushField();
+ rows.push(row);
+ row = [];
+ };
+
+ for (let i = 0; i < src.length; i++) {
+ const ch = src[i];
+ if (inQuotes) {
+ if (ch === '"') {
+ if (src[i + 1] === '"') {
+ field += '"';
+ i++;
+ } else {
+ inQuotes = false;
+ }
+ } else {
+ field += ch;
+ }
+ } else if (ch === '"' && field === "") {
+ inQuotes = true;
+ } else if (ch === ",") {
+ pushField();
+ } else if (ch === "\n" || ch === "\r") {
+ if (ch === "\r" && src[i + 1] === "\n") i++;
+ pushRow();
+ } else {
+ field += ch;
+ }
+ }
+
+ if (inQuotes) warnings.push({ code: "MALFORMED_QUOTE_RECOVERED" });
+ if (field !== "" || row.length > 0) pushRow();
+
+ return { rows, warnings };
+}
+
+// Reconciled against a real 2026-08-24 export: document_id, user_email,
+// document_title, workspace_name, document_created, summary, notes, transcript.
+// "summary" is the AI notes; "notes" is what the user typed themselves.
+const HEADER_SYNONYMS = {
+ id: ["id", "noteid", "docid", "documentid"],
+ title: ["title", "documenttitle", "notetitle", "name", "meetingtitle"],
+ summary: ["summary", "ainotes", "aisummary", "enhancednotes", "content"],
+ userNotes: ["notes", "mynotes", "usernotes"],
+ transcript: ["transcript", "transcription", "fulltranscript"],
+ createdAt: [
+ "createdat",
+ "documentcreated",
+ "date",
+ "created",
+ "meetingdate",
+ "starttime",
+ "datetime",
+ ],
+ attendees: ["attendees", "participants", "people", "guests"],
+};
+
+const normalizeHeader = (header) =>
+ String(header ?? "")
+ .toLowerCase()
+ .replace(/[^a-z0-9]/g, "");
+
+/**
+ * Map a CSV header row onto the note fields the importer understands.
+ * Matching is case/space/punctuation-insensitive; unknown columns are
+ * reported but never fatal.
+ *
+ * @param {string[]} headerRow
+ * @returns {{
+ * mapping: Partial<Record<"id"|"title"|"summary"|"userNotes"|"transcript"|"createdAt"|"attendees", number>>,
+ * unknown: string[],
+ * warnings: Array<{ code: string, detail?: string }>,
+ * }}
+ */
+export function mapHeaders(headerRow) {
+ const warnings = [];
+ const normalized = headerRow.map(normalizeHeader);
+ const claimed = new Set();
+ const mapping = {};
+
+ for (const [field, synonyms] of Object.entries(HEADER_SYNONYMS)) {
+ for (const synonym of synonyms) {
+ const index = normalized.findIndex((header, i) => header === synonym && !claimed.has(i));
+ if (index !== -1) {
+ mapping[field] = index;
+ claimed.add(index);
+ break;
+ }
+ }
+ }
+
+ const unknown = headerRow.filter((_, i) => !claimed.has(i));
+ if (unknown.length > 0) {
+ warnings.push({ code: "UNKNOWN_COLUMNS_IGNORED", detail: unknown.join(", ") });
+ }
+
+ return { mapping, unknown, warnings };
+}
+
+const pad2 = (value) => String(value).padStart(2, "0");
+
+const formatSqliteUtc = (date) =>
+ `${date.getUTCFullYear()}-${pad2(date.getUTCMonth() + 1)}-${pad2(date.getUTCDate())} ` +
+ `${pad2(date.getUTCHours())}:${pad2(date.getUTCMinutes())}:${pad2(date.getUTCSeconds())}`;
+
+const ISO_DATE_RE =
+ /^(\d{4})-(\d{2})-(\d{2})(?:[T ](\d{2}):(\d{2})(?::(\d{2}))?(?:\.\d+)?(Z|[+-]\d{2}:?\d{2})?)?$/;
+const US_DATE_RE =
+ /^(\d{1,2})\/(\d{1,2})\/(\d{4})(?:,?\s+(\d{1,2}):(\d{2})(?::(\d{2}))?\s*(AM|PM)?)?$/i;
+
+/**
+ * Normalize a CSV date cell to SQLite's `"YYYY-MM-DD HH:MM:SS"` UTC format
+ * (matching CURRENT_TIMESTAMP rows so imported notes sort correctly), or null
+ * when the value can't be parsed. Timezone-less values are treated as UTC for
+ * determinism; slash dates are read month-first (Granola is US-based) unless
+ * the month would be impossible.
+ *
+ * @param {unknown} value
+ * @returns {string | null}
+ */
+export function normalizeDate(value) {
+ const raw = String(value ?? "").trim();
+ if (!raw) return null;
+
+ if (/^\d{10,13}$/.test(raw)) {
+ const num = Number(raw);
+ return formatSqliteUtc(new Date(raw.length >= 13 ? num : num * 1000));
+ }
+
+ let match = raw.match(ISO_DATE_RE);
+ if (match) {
+ const [, year, month, day, hour = "00", minute = "00", second = "00", tz] = match;
+ if (tz && tz !== "Z") {
+ const date = new Date(`${year}-${month}-${day}T${hour}:${minute}:${second}${tz}`);
+ return Number.isNaN(date.getTime()) ? null : formatSqliteUtc(date);
+ }
+ return formatSqliteUtc(new Date(Date.UTC(+year, +month - 1, +day, +hour, +minute, +second)));
+ }
+
+ match = raw.match(US_DATE_RE);
+ if (match) {
+ const [, monthRaw, dayRaw, year, hourRaw = "0", minuteRaw = "0", secondRaw = "0", ampm] = match;
+ let month = +monthRaw;
+ let day = +dayRaw;
+ if (month > 12 && day <= 12) [month, day] = [day, month];
+ if (month > 12 || day > 31) return null;
+ let hour = +hourRaw;
+ if (ampm?.toUpperCase() === "PM" && hour < 12) hour += 12;
+ if (ampm?.toUpperCase() === "AM" && hour === 12) hour = 0;
+ return formatSqliteUtc(new Date(Date.UTC(+year, month - 1, day, hour, +minuteRaw, +secondRaw)));
+ }
+
+ const parsed = new Date(raw);
+ return Number.isNaN(parsed.getTime()) ? null : formatSqliteUtc(parsed);
+}
+
+const SPEAKER_LINE_RE = /^([^:\n]{1,60}):\s+(\S.*)$/;
+const SPEAKER_LINE_RATIO = 0.6;
+const SPEAKER_NAME_MAX_WORDS = 4;
+
+const matchSpeakerLine = (line) => {
+ const match = line.match(SPEAKER_LINE_RE);
+ if (!match) return null;
+ const speakerName = match[1].trim();
+ if (speakerName.split(/\s+/).length > SPEAKER_NAME_MAX_WORDS) return null;
+ return { speakerName, text: match[2].trim() };
+};
+
+/**
+ * Convert a transcript cell into `notes.transcript` segments. When most lines
+ * look like "Speaker: text" (and at least two distinct speakers appear), each
+ * line becomes its own segment with the name locked as a user-provided mapping
+ * so diarization never fights it; otherwise each paragraph becomes its own
+ * unlabeled segment.
+ * Timestamps are epoch-ms anchored at the note's creation time, +1ms per
+ * segment to preserve order (the app rebases relative offsets on export).
+ *
+ * @param {unknown} text
+ * @param {number} anchorMs
+ * @returns {Array<object>}
+ */
+export function parseTranscriptToSegments(text, anchorMs) {
+ const trimmed = String(text ?? "").trim();
+ if (!trimmed) return [];
+
+ const lines = trimmed
+ .split(/\r?\n/)
+ .map((line) => line.trim())
+ .filter(Boolean);
+ const parsedLines = lines.map(matchSpeakerLine);
+ const speakerLines = parsedLines.filter(Boolean);
+ const distinctSpeakers = new Set(speakerLines.map((line) => line.speakerName));
+
+ const useSpeakerMode =
+ speakerLines.length / lines.length >= SPEAKER_LINE_RATIO && distinctSpeakers.size >= 2;
+ if (!useSpeakerMode) {
+ return lines.map((line, i) => ({ text: line, source: "system", timestamp: anchorMs + i }));
+ }
+
+ const segments = [];
+ lines.forEach((line, i) => {
+ const parsed = parsedLines[i];
+ if (parsed) {
+ segments.push({
+ text: parsed.text,
+ source: "system",
+ timestamp: anchorMs + segments.length,
+ speakerName: parsed.speakerName,
+ speakerLocked: true,
+ speakerLockSource: "user",
+ });
+ } else if (segments.length > 0) {
+ segments[segments.length - 1].text += `\n${line}`;
+ } else {
+ segments.push({ text: line, source: "system", timestamp: anchorMs });
+ }
+ });
+ return segments;
+}
+
+/**
+ * Deterministic RFC-4122-shaped UUID from a stable key, so re-running the same
+ * import maps to the same `client_note_id` and the UNIQUE index makes the
+ * operation idempotent.
+ *
+ * @param {string} key
+ * @returns {string}
+ */
+export function deterministicUuid(key) {
+ const hex = createHash("sha256").update(`openwhispr-granola:${key}`).digest("hex");
+ const withVersion = `4${hex.slice(13, 16)}`;
+ const variantNibble = ((parseInt(hex[16], 16) & 0x3) | 0x8).toString(16);
+ const withVariant = `${variantNibble}${hex.slice(17, 20)}`;
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${withVersion}-${withVariant}-${hex.slice(20, 32)}`;
+}
+
+const NAME_EMAIL_RE = /^(.*?)\s*<([^<>\s]+@[^<>\s]+)>$/;
+const BARE_EMAIL_RE = /^\S+@\S+\.\S+$/;
+
+// Consumers of notes.participants require an email (e.g. SpeakerPicker reads
+// p.email unguarded), so name-only tokens are dropped rather than emitted.
+const parseAttendees = (cell) =>
+ String(cell ?? "")
+ .split(/[,;\n]/)
+ .map((token) => token.trim())
+ .filter(Boolean)
+ .flatMap((token) => {
+ const named = token.match(NAME_EMAIL_RE);
+ if (named) return [{ displayName: named[1] || named[2], email: named[2] }];
+ if (BARE_EMAIL_RE.test(token)) return [{ displayName: token, email: token }];
+ return [];
+ });
+
+/**
+ * Parse a Granola CSV export into insert-ready note rows.
+ *
+ * @param {string} text
+ * @returns {{
+ * ok: boolean,
+ * error?: { code: "EMPTY_FILE"|"HEADERS_UNRECOGNIZED"|"NO_DATA_ROWS" },
+ * headerInfo: { mapped: Record<string, string>, unknown: string[] },
+ * notes: Array<{
+ * clientNoteId: string, sourceFile: string, title: string, content: string,
+ * transcript: string | null, participants: string | null, createdAt: string | null,
+ * }>,
+ * warnings: Array<{ code: string, row?: number, detail?: string }>,
+ * }}
+ */
+export function parseGranolaCsv(text) {
+ const src = String(text ?? "");
+ const emptyHeaderInfo = { mapped: {}, unknown: [] };
+ if (!src.trim()) {
+ return {
+ ok: false,
+ error: { code: "EMPTY_FILE" },
+ headerInfo: emptyHeaderInfo,
+ notes: [],
+ warnings: [],
+ };
+ }
+
+ const { rows, warnings: csvWarnings } = parseCsv(src);
+ const [headerRow, ...dataRows] = rows;
+ const { mapping, unknown, warnings: headerWarnings } = mapHeaders(headerRow);
+ const warnings = [...csvWarnings, ...headerWarnings];
+ const headerInfo = {
+ mapped: Object.fromEntries(
+ Object.entries(mapping).map(([field, index]) => [field, headerRow[index]])
+ ),
+ unknown,
+ };
+
+ if (
+ mapping.title === undefined &&
+ mapping.summary === undefined &&
+ mapping.userNotes === undefined
+ ) {
+ return { ok: false, error: { code: "HEADERS_UNRECOGNIZED" }, headerInfo, notes: [], warnings };
+ }
+ if (dataRows.length === 0) {
+ return { ok: false, error: { code: "NO_DATA_ROWS" }, headerInfo, notes: [], warnings };
+ }
+ if (mapping.transcript === undefined) {
+ warnings.push({ code: "TRANSCRIPT_COLUMN_MISSING" });
+ }
+
+ const notes = [];
+ dataRows.forEach((rawRow, i) => {
+ const rowNumber = i + 2; // 1-based line number in the CSV, counting the header
+ if (rawRow.every((value) => !value.trim())) {
+ warnings.push({ code: "ROW_EMPTY_SKIPPED", row: rowNumber });
+ return;
+ }
+
+ let row = rawRow;
+ if (row.length !== headerRow.length) {
+ warnings.push({ code: "ROW_COLUMN_COUNT_MISMATCH", row: rowNumber });
+ row = row.slice(0, headerRow.length);
+ while (row.length < headerRow.length) row.push("");
+ }
+ const cell = (field) =>
+ mapping[field] === undefined ? "" : (row[mapping[field]] ?? "").trim();
+
+ // AI summary first, the user's own typed notes beneath it; either alone works.
+ const content = [cell("summary"), cell("userNotes")].filter(Boolean).join("\n\n---\n\n");
+ if (!content) {
+ warnings.push({ code: "ROW_NO_SUMMARY_SKIPPED", row: rowNumber });
+ return;
+ }
+
+ let title = cell("title");
+ if (!title) {
+ title = "Untitled";
+ warnings.push({ code: "TITLE_MISSING_DEFAULTED", row: rowNumber });
+ }
+
+ const rawDate = cell("createdAt");
+ const createdAt = rawDate ? normalizeDate(rawDate) : null;
+ if (rawDate && createdAt === null) {
+ warnings.push({ code: "DATE_UNPARSEABLE", row: rowNumber, detail: rawDate });
+ }
+
+ // Stable per-note key: Granola's own id when the export carries one,
+ // otherwise a hash of title + raw date (re-import stays idempotent either way).
+ const id = cell("id");
+ const key = id || createHash("sha256").update(`${title}|${rawDate}`).digest("hex").slice(0, 16);
+
+ const anchorMs = createdAt ? Date.parse(`${createdAt.replace(" ", "T")}Z`) : 0;
+ const segments = parseTranscriptToSegments(cell("transcript"), anchorMs);
+ const attendees = parseAttendees(cell("attendees"));
+
+ notes.push({
+ clientNoteId: deterministicUuid(key),
+ sourceFile: `granola:${key}`,
+ title,
+ content,
+ transcript: segments.length > 0 ? JSON.stringify(segments) : null,
+ participants: attendees.length > 0 ? JSON.stringify(attendees) : null,
+ createdAt,
+ });
+ });
+
+ return { ok: true, headerInfo, notes, warnings };
+}
diff --git a/src/helpers/ipcHandlers.js b/src/helpers/ipcHandlers.js
index 32ca2ef78..4a8dfd797 100644
--- a/src/helpers/ipcHandlers.js
+++ b/src/helpers/ipcHandlers.js
@@ -610,6 +610,7 @@ class IPCHandlers {
this._retentionSettings = { ...DEFAULT_RETENTION_SETTINGS }; // Synced from renderer
this._retentionSettingsSynced = false;
this._noteFilesEnabled = false;
+ this._granolaImportPending = null;
this.speakerDiarizationEnabled = true;
this.activeMeetingSpeakerConfig = null;
this.whisperVadSettings = {
@@ -10445,6 +10446,120 @@ class IPCHandlers {
}
});
+ ipcMain.handle("granola-import-pick-and-preview", async (event) => {
+ try {
+ const { dialog } = require("electron");
+ // Parent the dialog so it opens as a sheet on the settings window —
+ // a parentless panel can land invisible on another display/Space.
+ const parentWindow = BrowserWindow.fromWebContents(event.sender);
+ // Granola chunks large exports into numbered files (…-000.csv, -001, …),
+ // so let the user grab the whole set in one pick.
+ const dialogOptions = {
+ properties: ["openFile", "multiSelections"],
+ filters: [{ name: "CSV", extensions: ["csv"] }],
+ };
+ const result = parentWindow
+ ? await dialog.showOpenDialog(parentWindow, dialogOptions)
+ : await dialog.showOpenDialog(dialogOptions);
+ if (result.canceled || !result.filePaths.length) {
+ return { canceled: true };
+ }
+ const MAX_IMPORT_BYTES = 200 * 1024 * 1024;
+ const { parseGranolaCsv } = await import("./granolaImport.js");
+ const notes = [];
+ const seenIds = new Set();
+ let rowIssueCount = 0;
+ for (const filePath of result.filePaths) {
+ if (fs.statSync(filePath).size > MAX_IMPORT_BYTES) {
+ return { canceled: false, success: false, error: "FILE_TOO_LARGE" };
+ }
+ const parsed = parseGranolaCsv(fs.readFileSync(filePath, "utf8"));
+ if (!parsed.ok) {
+ return { canceled: false, success: false, error: parsed.error.code };
+ }
+ // File-level warnings (e.g. ignored columns) are expected on every
+ // real export; only row-scoped problems belong in the issue count.
+ rowIssueCount += parsed.warnings.filter((warning) => warning.row != null).length;
+ for (const note of parsed.notes) {
+ if (!seenIds.has(note.clientNoteId)) {
+ seenIds.add(note.clientNoteId);
+ notes.push(note);
+ }
+ }
+ }
+ const existing = new Set(
+ this.databaseManager.getExistingClientNoteIds(notes.map((n) => n.clientNoteId))
+ );
+ const freshNotes = notes.filter((n) => !existing.has(n.clientNoteId));
+ // The run handler only ever imports what this preview parsed — the
+ // renderer never sends a file path across the bridge.
+ this._granolaImportPending = { notes };
+ return {
+ canceled: false,
+ success: true,
+ fileName: result.filePaths.map((p) => path.basename(p)).join(", "),
+ total: notes.length,
+ newCount: freshNotes.length,
+ duplicateCount: notes.length - freshNotes.length,
+ sampleTitles: freshNotes.slice(0, 5).map((n) => n.title),
+ rowIssueCount,
+ };
+ } catch (error) {
+ debugLogger.error(
+ "Granola import preview failed",
+ { error: error.message },
+ "granola-import"
+ );
+ return { canceled: false, success: false, error: "READ_FAILED" };
+ }
+ });
+
+ ipcMain.handle("granola-import-run", async () => {
+ const pending = this._granolaImportPending;
+ this._granolaImportPending = null;
+ if (!pending) return { success: false, error: "NO_PENDING_IMPORT" };
+ try {
+ const result = this.databaseManager.importNotes(pending.notes);
+ if (result.imported > 0) {
+ const importedIds = result.noteIds;
+ // One-shot side effects: batched vector upsert of just the new notes
+ // and a single mirror rebuild — never per-note work (sync storm /
+ // O(notes × files) mirror scans).
+ setImmediate(() => {
+ try {
+ const vectorIndex = require("./vectorIndex");
+ if (vectorIndex.isReady()) {
+ const importedNotes = importedIds
+ .map((id) => this.databaseManager.getNote(id))
+ .filter(Boolean);
+ vectorIndex
+ .reindexAll(importedNotes, (done, total) => {
+ broadcastToWindows("semantic-reindex-progress", { done, total });
+ })
+ .catch(() => {});
+ }
+ if (this._noteFilesEnabled) this._rebuildMirror();
+ } catch (sideEffectError) {
+ debugLogger.error(
+ "Granola import side effects failed",
+ { error: sideEffectError.message },
+ "granola-import"
+ );
+ }
+ });
+ }
+ return {
+ success: true,
+ imported: result.imported,
+ skipped: result.skipped,
+ errors: result.errors,
+ };
+ } catch (error) {
+ debugLogger.error("Granola import failed", { error: error.message }, "granola-import");
+ return { success: false, error: "IMPORT_FAILED" };
+ }
+ });
+
ipcMain.handle("get-speaker-mappings", async (_event, noteId) => {
return this.databaseManager.getSpeakerMappings(noteId);
});
diff --git a/src/locales/de/translation.json b/src/locales/de/translation.json
index 158f4ee52..08ed20461 100644
--- a/src/locales/de/translation.json
+++ b/src/locales/de/translation.json
@@ -25,6 +25,31 @@
"description": "Die Notizdateien konnten nicht neu erstellt werden. Stellen Sie sicher, dass die Funktion aktiviert ist und der Ordner beschreibbar ist."
}
},
+ "granolaImport": {
+ "title": "Aus Granola importieren",
+ "description": "Meeting-Notizen aus einem Granola-CSV-Export importieren",
+ "howTo": "In Granola: Settings → Profile → Export historical data → Generate CSV. Der Export wird per E-Mail zugestellt, in der Regel innerhalb weniger Stunden.",
+ "chooseFile": "CSV-Datei auswählen",
+ "preview": {
+ "title": "Aus Granola importieren",
+ "summary": "{{total}} Notizen gefunden: {{newCount}} neu, {{duplicateCount}} bereits importiert",
+ "warnings": "{{warningCount}} Zeilen haben Probleme (übersprungen oder ohne Datum importiert)",
+ "confirm": "{{newCount}} Notizen importieren",
+ "nothingNew": "Alle Notizen in dieser Datei wurden bereits importiert."
+ },
+ "done": {
+ "title": "Import abgeschlossen",
+ "summary": "{{imported}} Notizen in den Ordner „Imported“ importiert, {{skipped}} Duplikate übersprungen"
+ },
+ "error": {
+ "title": "Import fehlgeschlagen",
+ "EMPTY_FILE": "Die Datei ist leer.",
+ "HEADERS_UNRECOGNIZED": "Das sieht nicht wie ein Granola-CSV-Export aus.",
+ "NO_DATA_ROWS": "In dieser Datei wurden keine Notizen gefunden.",
+ "FILE_TOO_LARGE": "Diese Datei ist zu groß zum Importieren.",
+ "generic": "Beim Lesen der Datei ist ein Fehler aufgetreten."
+ }
+ },
"meeting": {
"speakerDetection": {
"title": "Sprecher erkennen und beschriften",
diff --git a/src/locales/en/translation.json b/src/locales/en/translation.json
index 41695fdab..2a41b6db7 100644
--- a/src/locales/en/translation.json
+++ b/src/locales/en/translation.json
@@ -25,6 +25,31 @@
"description": "Could not rebuild note files. Make sure the feature is enabled and the folder is writable."
}
},
+ "granolaImport": {
+ "title": "Import from Granola",
+ "description": "Import your meeting notes from a Granola CSV export",
+ "howTo": "In Granola: Settings → Profile → Export historical data → Generate CSV. The export is emailed to you, typically within a few hours.",
+ "chooseFile": "Choose CSV file",
+ "preview": {
+ "title": "Import from Granola",
+ "summary": "Found {{total}} notes: {{newCount}} new, {{duplicateCount}} already imported",
+ "warnings": "{{warningCount}} rows have issues (skipped or imported without a date)",
+ "confirm": "Import {{newCount}} notes",
+ "nothingNew": "All notes in this file have already been imported."
+ },
+ "done": {
+ "title": "Import complete",
+ "summary": "Imported {{imported}} notes into the \"Imported\" folder, skipped {{skipped}} duplicates"
+ },
+ "error": {
+ "title": "Import failed",
+ "EMPTY_FILE": "The file is empty.",
+ "HEADERS_UNRECOGNIZED": "This doesn't look like a Granola CSV export.",
+ "NO_DATA_ROWS": "No notes were found in this file.",
+ "FILE_TOO_LARGE": "This file is too large to import.",
+ "generic": "Something went wrong reading the file."
+ }
+ },
"meeting": {
"speakerDetection": {
"title": "Identify and label speakers",
diff --git a/src/locales/es/translation.json b/src/locales/es/translation.json
index 6c7a84afb..5959bbebb 100644
--- a/src/locales/es/translation.json
+++ b/src/locales/es/translation.json
@@ -25,6 +25,31 @@
"description": "No se pudieron reconstruir los archivos de notas. Asegúrate de que la función esté habilitada y la carpeta tenga permisos de escritura."
}
},
+ "granolaImport": {
+ "title": "Importar desde Granola",
+ "description": "Importar notas de reuniones desde una exportación CSV de Granola",
+ "howTo": "En Granola: Settings → Profile → Export historical data → Generate CSV. La exportación llega por correo electrónico, normalmente en unas horas.",
+ "chooseFile": "Elegir archivo CSV",
+ "preview": {
+ "title": "Importar desde Granola",
+ "summary": "Se encontraron {{total}} notas: {{newCount}} nuevas, {{duplicateCount}} ya importadas",
+ "warnings": "{{warningCount}} filas tienen problemas (omitidas o importadas sin fecha)",
+ "confirm": "Importar {{newCount}} notas",
+ "nothingNew": "Todas las notas de este archivo ya se han importado."
+ },
+ "done": {
+ "title": "Importación completada",
+ "summary": "Se importaron {{imported}} notas a la carpeta \"Imported\" y se omitieron {{skipped}} duplicadas"
+ },
+ "error": {
+ "title": "Error al importar",
+ "EMPTY_FILE": "El archivo está vacío.",
+ "HEADERS_UNRECOGNIZED": "Esto no parece una exportación CSV de Granola.",
+ "NO_DATA_ROWS": "No se encontraron notas en este archivo.",
+ "FILE_TOO_LARGE": "Este archivo es demasiado grande para importarlo.",
+ "generic": "Algo salió mal al leer el archivo."
+ }
+ },
"meeting": {
"speakerDetection": {
"title": "Identificar y etiquetar participantes",
diff --git a/src/locales/fr/translation.json b/src/locales/fr/translation.json
index 9ae02c2af..60174dc68 100644
--- a/src/locales/fr/translation.json
+++ b/src/locales/fr/translation.json
@@ -25,6 +25,31 @@
"description": "Impossible de reconstruire les fichiers de notes. Assurez-vous que la fonctionnalité est activée et que le dossier est accessible en écriture."
}
},
+ "granolaImport": {
+ "title": "Importer depuis Granola",
+ "description": "Importer les notes de réunion depuis un export CSV de Granola",
+ "howTo": "Dans Granola : Settings → Profile → Export historical data → Generate CSV. L'export est envoyé par e-mail, généralement en quelques heures.",
+ "chooseFile": "Choisir le fichier CSV",
+ "preview": {
+ "title": "Importer depuis Granola",
+ "summary": "{{total}} notes trouvées : {{newCount}} nouvelles, {{duplicateCount}} déjà importées",
+ "warnings": "{{warningCount}} lignes posent problème (ignorées ou importées sans date)",
+ "confirm": "Importer {{newCount}} notes",
+ "nothingNew": "Toutes les notes de ce fichier ont déjà été importées."
+ },
+ "done": {
+ "title": "Import terminé",
+ "summary": "{{imported}} notes importées dans le dossier « Imported », {{skipped}} doublons ignorés"
+ },
+ "error": {
+ "title": "Échec de l'import",
+ "EMPTY_FILE": "Le fichier est vide.",
+ "HEADERS_UNRECOGNIZED": "Ce fichier ne ressemble pas à un export CSV de Granola.",
+ "NO_DATA_ROWS": "Aucune note trouvée dans ce fichier.",
+ "FILE_TOO_LARGE": "Ce fichier est trop volumineux pour être importé.",
+ "generic": "Une erreur s'est produite lors de la lecture du fichier."
+ }
+ },
"meeting": {
"speakerDetection": {
"title": "Identifier et étiqueter les intervenants",
diff --git a/src/locales/it/translation.json b/src/locales/it/translation.json
index fb804ca81..3a3d1b75a 100644
--- a/src/locales/it/translation.json
+++ b/src/locales/it/translation.json
@@ -25,6 +25,31 @@
"description": "Impossibile ricostruire i file delle note. Assicurati che la funzione sia abilitata e che la cartella sia scrivibile."
}
},
+ "granolaImport": {
+ "title": "Importa da Granola",
+ "description": "Importa le note delle riunioni da un'esportazione CSV di Granola",
+ "howTo": "In Granola: Settings → Profile → Export historical data → Generate CSV. L'esportazione arriva via e-mail, di solito entro poche ore.",
+ "chooseFile": "Scegli file CSV",
+ "preview": {
+ "title": "Importa da Granola",
+ "summary": "Trovate {{total}} note: {{newCount}} nuove, {{duplicateCount}} già importate",
+ "warnings": "{{warningCount}} righe presentano problemi (saltate o importate senza data)",
+ "confirm": "Importa {{newCount}} note",
+ "nothingNew": "Tutte le note di questo file sono già state importate."
+ },
+ "done": {
+ "title": "Importazione completata",
+ "summary": "{{imported}} note importate nella cartella \"Imported\", {{skipped}} duplicati saltati"
+ },
+ "error": {
+ "title": "Importazione non riuscita",
+ "EMPTY_FILE": "Il file è vuoto.",
+ "HEADERS_UNRECOGNIZED": "Questo non sembra un'esportazione CSV di Granola.",
+ "NO_DATA_ROWS": "Nessuna nota trovata in questo file.",
+ "FILE_TOO_LARGE": "Questo file è troppo grande per essere importato.",
+ "generic": "Si è verificato un errore durante la lettura del file."
+ }
+ },
"meeting": {
"speakerDetection": {
"title": "Identifica ed etichetta i partecipanti",
diff --git a/src/locales/ja/translation.json b/src/locales/ja/translation.json
index 5b54be0c2..19f48c9bc 100644
--- a/src/locales/ja/translation.json
+++ b/src/locales/ja/translation.json
@@ -25,6 +25,31 @@
"description": "ノートファイルを再構築できませんでした。機能が有効になっており、フォルダーに書き込み可能であることを確認してください。"
}
},
+ "granolaImport": {
+ "title": "Granola からインポート",
+ "description": "Granola の CSV エクスポートから会議ノートをインポート",
+ "howTo": "Granola で Settings → Profile → Export historical data → Generate CSV を実行します。エクスポートは通常数時間以内にメールで届きます。",
+ "chooseFile": "CSV ファイルを選択",
+ "preview": {
+ "title": "Granola からインポート",
+ "summary": "{{total}} 件のノートが見つかりました: 新規 {{newCount}} 件、インポート済み {{duplicateCount}} 件",
+ "warnings": "{{warningCount}} 行に問題があります(スキップ、または日付なしでインポート)",
+ "confirm": "{{newCount}} 件のノートをインポート",
+ "nothingNew": "このファイルのノートはすべてインポート済みです。"
+ },
+ "done": {
+ "title": "インポート完了",
+ "summary": "{{imported}} 件のノートを「Imported」フォルダにインポートし、{{skipped}} 件の重複をスキップしました"
+ },
+ "error": {
+ "title": "インポートに失敗しました",
+ "EMPTY_FILE": "ファイルが空です。",
+ "HEADERS_UNRECOGNIZED": "Granola の CSV エクスポートではないようです。",
+ "NO_DATA_ROWS": "このファイルにはノートが見つかりませんでした。",
+ "FILE_TOO_LARGE": "このファイルは大きすぎてインポートできません。",
+ "generic": "ファイルの読み込み中に問題が発生しました。"
+ }
+ },
"meeting": {
"speakerDetection": {
"title": "話者を識別してラベル付け",
diff --git a/src/locales/pt/translation.json b/src/locales/pt/translation.json
index ca3f9a176..64c9b834b 100644
--- a/src/locales/pt/translation.json
+++ b/src/locales/pt/translation.json
@@ -25,6 +25,31 @@
"description": "Não foi possível reconstruir os arquivos de notas. Verifique se o recurso está ativado e se a pasta permite gravação."
}
},
+ "granolaImport": {
+ "title": "Importar do Granola",
+ "description": "Importar notas de reunião de uma exportação CSV do Granola",
+ "howTo": "No Granola: Settings → Profile → Export historical data → Generate CSV. A exportação chega por e-mail, normalmente em algumas horas.",
+ "chooseFile": "Escolher arquivo CSV",
+ "preview": {
+ "title": "Importar do Granola",
+ "summary": "{{total}} notas encontradas: {{newCount}} novas, {{duplicateCount}} já importadas",
+ "warnings": "{{warningCount}} linhas têm problemas (ignoradas ou importadas sem data)",
+ "confirm": "Importar {{newCount}} notas",
+ "nothingNew": "Todas as notas deste arquivo já foram importadas."
+ },
+ "done": {
+ "title": "Importação concluída",
+ "summary": "{{imported}} notas importadas para a pasta \"Imported\", {{skipped}} duplicatas ignoradas"
+ },
+ "error": {
+ "title": "Falha na importação",
+ "EMPTY_FILE": "O arquivo está vazio.",
+ "HEADERS_UNRECOGNIZED": "Isto não parece uma exportação CSV do Granola.",
+ "NO_DATA_ROWS": "Nenhuma nota foi encontrada neste arquivo.",
+ "FILE_TOO_LARGE": "Este arquivo é grande demais para importar.",
+ "generic": "Algo deu errado ao ler o arquivo."
+ }
+ },
"meeting": {
"speakerDetection": {
"title": "Identificar e rotular participantes",
diff --git a/src/locales/ru/translation.json b/src/locales/ru/translation.json
index 23fd3857f..f0fc5b3bf 100644
--- a/src/locales/ru/translation.json
+++ b/src/locales/ru/translation.json
@@ -25,6 +25,31 @@
"description": "Не удалось пересоздать файлы заметок. Убедитесь, что функция включена и в папку можно записывать."
}
},
+ "granolaImport": {
+ "title": "Импорт из Granola",
+ "description": "Импорт заметок о встречах из CSV-экспорта Granola",
+ "howTo": "В Granola: Settings → Profile → Export historical data → Generate CSV. Экспорт придёт по электронной почте, обычно в течение нескольких часов.",
+ "chooseFile": "Выбрать CSV-файл",
+ "preview": {
+ "title": "Импорт из Granola",
+ "summary": "Найдено заметок: {{total}}, новых: {{newCount}}, уже импортировано: {{duplicateCount}}",
+ "warnings": "Строк с проблемами: {{warningCount}} (пропущены или импортированы без даты)",
+ "confirm": "Импортировать заметки: {{newCount}}",
+ "nothingNew": "Все заметки из этого файла уже импортированы."
+ },
+ "done": {
+ "title": "Импорт завершён",
+ "summary": "Импортировано заметок в папку «Imported»: {{imported}}, пропущено дубликатов: {{skipped}}"
+ },
+ "error": {
+ "title": "Ошибка импорта",
+ "EMPTY_FILE": "Файл пуст.",
+ "HEADERS_UNRECOGNIZED": "Это не похоже на CSV-экспорт Granola.",
+ "NO_DATA_ROWS": "В этом файле не найдено заметок.",
+ "FILE_TOO_LARGE": "Файл слишком большой для импорта.",
+ "generic": "Не удалось прочитать файл."
+ }
+ },
"meeting": {
"speakerDetection": {
"title": "Распознавать и подписывать участников",
diff --git a/src/locales/zh-CN/translation.json b/src/locales/zh-CN/translation.json
index b3c928d75..c7edf54be 100644
--- a/src/locales/zh-CN/translation.json
+++ b/src/locales/zh-CN/translation.json
@@ -25,6 +25,31 @@
"description": "无法重建笔记文件。请确保已启用该功能,并且文件夹可写。"
}
},
+ "granolaImport": {
+ "title": "从 Granola 导入",
+ "description": "从 Granola 的 CSV 导出文件导入会议笔记",
+ "howTo": "在 Granola 中:Settings → Profile → Export historical data → Generate CSV。导出文件将通过邮件发送,通常在几小时内送达。",
+ "chooseFile": "选择 CSV 文件",
+ "preview": {
+ "title": "从 Granola 导入",
+ "summary": "共找到 {{total}} 条笔记:{{newCount}} 条新笔记,{{duplicateCount}} 条已导入",
+ "warnings": "{{warningCount}} 行存在问题(已跳过或导入时缺少日期)",
+ "confirm": "导入 {{newCount}} 条笔记",
+ "nothingNew": "此文件中的笔记均已导入。"
+ },
+ "done": {
+ "title": "导入完成",
+ "summary": "已将 {{imported}} 条笔记导入到“Imported”文件夹,跳过 {{skipped}} 条重复项"
+ },
+ "error": {
+ "title": "导入失败",
+ "EMPTY_FILE": "文件为空。",
+ "HEADERS_UNRECOGNIZED": "这看起来不像 Granola 的 CSV 导出文件。",
+ "NO_DATA_ROWS": "此文件中未找到笔记。",
+ "FILE_TOO_LARGE": "此文件过大,无法导入。",
+ "generic": "读取文件时出错。"
+ }
+ },
"meeting": {
"speakerDetection": {
"title": "识别并标记发言者",
diff --git a/src/locales/zh-TW/translation.json b/src/locales/zh-TW/translation.json
index 4a7257f29..39270f302 100644
--- a/src/locales/zh-TW/translation.json
+++ b/src/locales/zh-TW/translation.json
@@ -25,6 +25,31 @@
"description": "無法重建筆記檔案。請確認功能已啟用,且資料夾可寫入。"
}
},
+ "granolaImport": {
+ "title": "從 Granola 匯入",
+ "description": "從 Granola 的 CSV 匯出檔案匯入會議筆記",
+ "howTo": "在 Granola 中:Settings → Profile → Export historical data → Generate CSV。匯出檔案會透過電子郵件寄送,通常在幾小時內送達。",
+ "chooseFile": "選擇 CSV 檔案",
+ "preview": {
+ "title": "從 Granola 匯入",
+ "summary": "共找到 {{total}} 則筆記:{{newCount}} 則新筆記,{{duplicateCount}} 則已匯入",
+ "warnings": "{{warningCount}} 列有問題(已略過或匯入時缺少日期)",
+ "confirm": "匯入 {{newCount}} 則筆記",
+ "nothingNew": "此檔案中的筆記皆已匯入。"
+ },
+ "done": {
+ "title": "匯入完成",
+ "summary": "已將 {{imported}} 則筆記匯入「Imported」資料夾,略過 {{skipped}} 則重複項"
+ },
+ "error": {
+ "title": "匯入失敗",
+ "EMPTY_FILE": "檔案是空的。",
+ "HEADERS_UNRECOGNIZED": "這看起來不像 Granola 的 CSV 匯出檔案。",
+ "NO_DATA_ROWS": "此檔案中找不到筆記。",
+ "FILE_TOO_LARGE": "此檔案太大,無法匯入。",
+ "generic": "讀取檔案時發生錯誤。"
+ }
+ },
"meeting": {
"speakerDetection": {
"title": "辨識並標記發言者",
diff --git a/src/types/electron.ts b/src/types/electron.ts
index b2f0a24e6..e6405b0d3 100644
--- a/src/types/electron.ts
+++ b/src/types/electron.ts
@@ -1249,6 +1249,24 @@ declare global {
noteFilesRebuild?: () => Promise<{ success: boolean; error?: string }>;
noteFilesGetDefaultPath?: () => Promise<string>;
noteFilesPickFolder?: () => Promise<{ canceled: boolean; path?: string }>;
+ granolaImportPickAndPreview?: () => Promise<{
+ canceled: boolean;
+ success?: boolean;
+ error?: string;
+ fileName?: string;
+ total?: number;
+ newCount?: number;
+ duplicateCount?: number;
+ sampleTitles?: string[];
+ rowIssueCount?: number;
+ }>;
+ granolaImportRun?: () => Promise<{
+ success: boolean;
+ error?: string;
+ imported?: number;
+ skipped?: number;
+ errors?: Array<{ clientNoteId: string; error: string }>;
+ }>;
showNoteFile?: (noteId: number) => Promise<{ success: boolean }>;
showFolderInExplorer?: (folderName: string) => Promise<{ success: boolean }>;
diff --git a/test/helpers/fixtures/granola-export-sample.csv b/test/helpers/fixtures/granola-export-sample.csv
new file mode 100644
index 000000000..61d27737e
--- /dev/null
+++ b/test/helpers/fixtures/granola-export-sample.csv
@@ -0,0 +1,21 @@
+document_id,user_email,document_title,workspace_name,document_created,summary,notes,transcript
+11111111-2222-4333-8444-555555555555,[email protected],Product Design Review,Example Workspace,2026-08-20T17:46:57.650Z,"# UI Cleanup Priorities
+
+- Overall goal: make the UI more opinionated, visual, and systematized
+- Key pain points identified:
+ - Share and export should be combined into one button with a dropdown
+ - Meeting view is too stacked (attendees, folders, nested folders)
+
+# Templates
+
+- Plan to build out template testing
+ - Users can preview what different templates look like before applying
+ - Team-created templates plus user-created templates
+
+---
+
+Chat with meeting transcript: [https://notes.example.com/t/00000000-0000-4000-8000-000000000000](https://notes.example.com/t/00000000-0000-4000-8000-000000000000)",,"Button here. Like maybe we should actually have the share and export in one button and have a drop down there. We just need overall a clean up the UI, make it more opinionated.
+Okay. But essentially, you can test out what different templates look like. So if we just do something like this.
+So here. So there's everything from, like, building out different templates, for example. So having all these different templates, we have our own team ones, and then allow them to create their own.
+Sweet. Cool, guys. So I guess the only thing that's left right now is just my thoughts on the onboarding. Let's try to get that merged in, I suppose.
+Thanks, guys. Thank you, guys."
diff --git a/test/helpers/granolaImport.test.js b/test/helpers/granolaImport.test.js
new file mode 100644
index 000000000..4158c850e
--- /dev/null
+++ b/test/helpers/granolaImport.test.js
@@ -0,0 +1,469 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+const fs = require("node:fs");
+const path = require("node:path");
+
+const load = () => import("../../src/helpers/granolaImport.js");
+
+// ---------------------------------------------------------------------------
+// parseCsv — RFC-4180 tokenizer
+// ---------------------------------------------------------------------------
+
+test("parseCsv splits simple rows and fields", async () => {
+ const { parseCsv } = await load();
+ const { rows, warnings } = parseCsv("a,b,c\n1,2,3");
+ assert.deepEqual(rows, [
+ ["a", "b", "c"],
+ ["1", "2", "3"],
+ ]);
+ assert.deepEqual(warnings, []);
+});
+
+test("parseCsv keeps embedded commas and newlines inside quoted fields", async () => {
+ const { parseCsv } = await load();
+ const { rows } = parseCsv('title,notes\n"Meeting, one","line1\nline2"');
+ assert.deepEqual(rows, [
+ ["title", "notes"],
+ ["Meeting, one", "line1\nline2"],
+ ]);
+});
+
+test('parseCsv unescapes doubled quotes ("") inside quoted fields', async () => {
+ const { parseCsv } = await load();
+ const { rows } = parseCsv('a\n"He said ""hi"" twice"');
+ assert.deepEqual(rows, [["a"], ['He said "hi" twice']]);
+});
+
+test("parseCsv treats CRLF line endings like LF", async () => {
+ const { parseCsv } = await load();
+ const { rows } = parseCsv("a,b\r\n1,2\r\n");
+ assert.deepEqual(rows, [
+ ["a", "b"],
+ ["1", "2"],
+ ]);
+});
+
+test("parseCsv preserves CRLF inside quoted fields as-is", async () => {
+ const { parseCsv } = await load();
+ const { rows } = parseCsv('a\n"x\r\ny"');
+ assert.deepEqual(rows, [["a"], ["x\r\ny"]]);
+});
+
+test("parseCsv strips a leading UTF-8 BOM", async () => {
+ const { parseCsv } = await load();
+ const { rows } = parseCsv("a,b\n1,2");
+ assert.deepEqual(rows, [
+ ["a", "b"],
+ ["1", "2"],
+ ]);
+});
+
+test("parseCsv ignores a trailing newline instead of producing an empty row", async () => {
+ const { parseCsv } = await load();
+ const { rows } = parseCsv("a,b\n1,2\n");
+ assert.equal(rows.length, 2);
+});
+
+test("parseCsv recovers from an unclosed quote at EOF with a warning", async () => {
+ const { parseCsv } = await load();
+ const { rows, warnings } = parseCsv('a\n"unterminated rest');
+ assert.deepEqual(rows, [["a"], ["unterminated rest"]]);
+ assert.equal(warnings.length, 1);
+ assert.equal(warnings[0].code, "MALFORMED_QUOTE_RECOVERED");
+});
+
+// ---------------------------------------------------------------------------
+// mapHeaders — fuzzy, header-driven column mapping
+// ---------------------------------------------------------------------------
+
+test("mapHeaders maps exact lowercase headers to column indices", async () => {
+ const { mapHeaders } = await load();
+ const { mapping, unknown } = mapHeaders([
+ "id",
+ "title",
+ "summary",
+ "transcript",
+ "created_at",
+ "attendees",
+ ]);
+ assert.deepEqual(mapping, {
+ id: 0,
+ title: 1,
+ summary: 2,
+ transcript: 3,
+ createdAt: 4,
+ attendees: 5,
+ });
+ assert.deepEqual(unknown, []);
+});
+
+test("mapHeaders matches case, space, and punctuation variants", async () => {
+ const { mapHeaders } = await load();
+ const { mapping } = mapHeaders(["Note Title", "AI Notes", "Created At"]);
+ assert.deepEqual(mapping, { title: 0, summary: 1, createdAt: 2 });
+});
+
+test("mapHeaders records unknown columns with a warning instead of failing", async () => {
+ const { mapHeaders } = await load();
+ const { mapping, unknown, warnings } = mapHeaders(["title", "summary", "workspace"]);
+ assert.deepEqual(mapping, { title: 0, summary: 1 });
+ assert.deepEqual(unknown, ["workspace"]);
+ assert.equal(warnings.length, 1);
+ assert.equal(warnings[0].code, "UNKNOWN_COLUMNS_IGNORED");
+});
+
+test("mapHeaders leaves transcript unmapped when the column is absent", async () => {
+ const { mapHeaders } = await load();
+ const { mapping } = mapHeaders(["title", "summary", "created_at"]);
+ assert.equal(mapping.transcript, undefined);
+});
+
+test("mapHeaders maps summary and user-notes columns independently", async () => {
+ const { mapHeaders } = await load();
+ const { mapping, unknown } = mapHeaders(["notes", "summary", "title"]);
+ assert.equal(mapping.summary, 1);
+ assert.equal(mapping.userNotes, 0);
+ assert.deepEqual(unknown, []);
+});
+
+// ---------------------------------------------------------------------------
+// normalizeDate — anything plausible → SQLite "YYYY-MM-DD HH:MM:SS" UTC
+// ---------------------------------------------------------------------------
+
+test("normalizeDate converts ISO-8601 with Z", async () => {
+ const { normalizeDate } = await load();
+ assert.equal(normalizeDate("2026-07-15T14:30:05Z"), "2026-07-15 14:30:05");
+});
+
+test("normalizeDate converts ISO-8601 with a UTC offset", async () => {
+ const { normalizeDate } = await load();
+ assert.equal(normalizeDate("2026-07-15T14:30:00-04:00"), "2026-07-15 18:30:00");
+});
+
+test("normalizeDate treats ISO-8601 without timezone as UTC for determinism", async () => {
+ const { normalizeDate } = await load();
+ assert.equal(normalizeDate("2026-07-15T14:30:00"), "2026-07-15 14:30:00");
+ assert.equal(normalizeDate("2026-07-15 14:30"), "2026-07-15 14:30:00");
+});
+
+test("normalizeDate accepts a bare date", async () => {
+ const { normalizeDate } = await load();
+ assert.equal(normalizeDate("2026-07-15"), "2026-07-15 00:00:00");
+});
+
+test("normalizeDate accepts epoch milliseconds and seconds", async () => {
+ const { normalizeDate } = await load();
+ const ms = Date.UTC(2026, 0, 2, 3, 4, 5);
+ assert.equal(normalizeDate(String(ms)), "2026-01-02 03:04:05");
+ assert.equal(normalizeDate(String(ms / 1000)), "2026-01-02 03:04:05");
+});
+
+test("normalizeDate accepts US M/D/YYYY with 12-hour time", async () => {
+ const { normalizeDate } = await load();
+ assert.equal(normalizeDate("7/15/2026, 2:30 PM"), "2026-07-15 14:30:00");
+ assert.equal(normalizeDate("7/15/2026 12:05 AM"), "2026-07-15 00:05:00");
+ assert.equal(normalizeDate("7/15/2026"), "2026-07-15 00:00:00");
+});
+
+test("normalizeDate reinterprets day-first order when the month is impossible", async () => {
+ const { normalizeDate } = await load();
+ assert.equal(normalizeDate("13/5/2026"), "2026-05-13 00:00:00");
+});
+
+test("normalizeDate returns null for garbage or empty input", async () => {
+ const { normalizeDate } = await load();
+ assert.equal(normalizeDate("not a date"), null);
+ assert.equal(normalizeDate(""), null);
+ assert.equal(normalizeDate(undefined), null);
+});
+
+// ---------------------------------------------------------------------------
+// parseTranscriptToSegments — "Speaker: text" lines → native segments
+// ---------------------------------------------------------------------------
+
+test("parseTranscriptToSegments splits speaker-labeled lines into locked segments", async () => {
+ const { parseTranscriptToSegments } = await load();
+ const segments = parseTranscriptToSegments(
+ "Alice: Hello there\nBob: Hi Alice\nAlice: How are you?",
+ 1000
+ );
+ assert.deepEqual(segments, [
+ {
+ text: "Hello there",
+ source: "system",
+ timestamp: 1000,
+ speakerName: "Alice",
+ speakerLocked: true,
+ speakerLockSource: "user",
+ },
+ {
+ text: "Hi Alice",
+ source: "system",
+ timestamp: 1001,
+ speakerName: "Bob",
+ speakerLocked: true,
+ speakerLockSource: "user",
+ },
+ {
+ text: "How are you?",
+ source: "system",
+ timestamp: 1002,
+ speakerName: "Alice",
+ speakerLocked: true,
+ speakerLockSource: "user",
+ },
+ ]);
+});
+
+test("parseTranscriptToSegments falls back to one segment per paragraph for free text", async () => {
+ const { parseTranscriptToSegments } = await load();
+ const segments = parseTranscriptToSegments("Just a flowing paragraph.\nNo speakers here.", 500);
+ assert.deepEqual(segments, [
+ { text: "Just a flowing paragraph.", source: "system", timestamp: 500 },
+ { text: "No speakers here.", source: "system", timestamp: 501 },
+ ]);
+});
+
+test("parseTranscriptToSegments stays unlabeled below the speaker-line threshold", async () => {
+ const { parseTranscriptToSegments } = await load();
+ const text =
+ "Alice: Hi\nA long unstructured line without any label\nAnother unstructured line here";
+ const segments = parseTranscriptToSegments(text, 0);
+ assert.equal(segments.length, 3);
+ assert.ok(segments.every((segment) => segment.speakerName === undefined));
+});
+
+test("parseTranscriptToSegments requires two distinct speakers to label lines", async () => {
+ const { parseTranscriptToSegments } = await load();
+ const segments = parseTranscriptToSegments("Alice: Hi\nAlice: Bye", 0);
+ assert.ok(segments.every((segment) => segment.speakerName === undefined));
+});
+
+test("parseTranscriptToSegments does not mistake URLs for speaker labels", async () => {
+ const { parseTranscriptToSegments } = await load();
+ const segments = parseTranscriptToSegments(
+ "https://example.com/foo: bar baz\nhttps://example.com/x: qux quux",
+ 0
+ );
+ assert.ok(segments.every((segment) => segment.speakerName === undefined));
+});
+
+test("parseTranscriptToSegments rejects speaker names longer than four words", async () => {
+ const { parseTranscriptToSegments } = await load();
+ const segments = parseTranscriptToSegments(
+ "This is definitely not a speaker name: because it is long\nAnd this line is even less like one: yes",
+ 0
+ );
+ assert.ok(segments.every((segment) => segment.speakerName === undefined));
+});
+
+test("parseTranscriptToSegments returns no segments for empty input", async () => {
+ const { parseTranscriptToSegments } = await load();
+ assert.deepEqual(parseTranscriptToSegments("", 0), []);
+ assert.deepEqual(parseTranscriptToSegments(null, 0), []);
+});
+
+test("parseTranscriptToSegments appends unlabeled continuation lines to the previous segment", async () => {
+ const { parseTranscriptToSegments } = await load();
+ const segments = parseTranscriptToSegments(
+ "Alice: First point\ncontinued thought\nBob: Reply\nCarol: Another\nDave: More\nEve: Yet more",
+ 0
+ );
+ assert.equal(segments[0].text, "First point\ncontinued thought");
+ assert.equal(segments.length, 5);
+});
+
+// ---------------------------------------------------------------------------
+// deterministicUuid — stable identity for idempotent re-imports
+// ---------------------------------------------------------------------------
+
+test("deterministicUuid produces a valid RFC-4122-shaped UUID", async () => {
+ const { deterministicUuid } = await load();
+ assert.match(
+ deterministicUuid("granola:abc123"),
+ /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/
+ );
+});
+
+test("deterministicUuid is stable for the same key and distinct across keys", async () => {
+ const { deterministicUuid } = await load();
+ assert.equal(deterministicUuid("granola:abc"), deterministicUuid("granola:abc"));
+ assert.notEqual(deterministicUuid("granola:abc"), deterministicUuid("granola:abd"));
+});
+
+// ---------------------------------------------------------------------------
+// parseGranolaCsv — full composition
+// ---------------------------------------------------------------------------
+
+const FULL_CSV = [
+ "id,title,summary,transcript,created_at,attendees",
+ 'doc1,Weekly Sync,"- Discussed roadmap\n- Next steps","Alice: Hello\nBob: Hi there\nAlice: Bye",2026-07-15T14:30:00Z,"Alice <[email protected]>; Bob"',
+ 'doc2,1:1 with Bob,"Notes about the 1:1",,2026-07-16T09:00:00Z,',
+ 'doc3,,"Untitled meeting summary",,bad-date,',
+].join("\n");
+
+test("parseGranolaCsv maps a full export into insert-ready notes", async () => {
+ const { parseGranolaCsv } = await load();
+ const result = parseGranolaCsv(FULL_CSV);
+ assert.equal(result.ok, true);
+ assert.equal(result.notes.length, 3);
+
+ const [first, second, third] = result.notes;
+ assert.equal(first.title, "Weekly Sync");
+ assert.equal(first.content, "- Discussed roadmap\n- Next steps");
+ assert.equal(first.createdAt, "2026-07-15 14:30:00");
+ assert.equal(first.sourceFile, "granola:doc1");
+ // "Bob" has no email, so he is dropped: participants consumers require one.
+ assert.deepEqual(JSON.parse(first.participants), [
+ { displayName: "Alice", email: "[email protected]" },
+ ]);
+
+ const segments = JSON.parse(first.transcript);
+ assert.equal(first.transcript.startsWith("["), true);
+ assert.equal(segments.length, 3);
+ assert.equal(segments[0].speakerName, "Alice");
+ assert.equal(segments[0].source, "system");
+ assert.equal(segments[0].timestamp, Date.parse("2026-07-15T14:30:00Z"));
+
+ assert.equal(second.transcript, null);
+ assert.equal(second.participants, null);
+
+ assert.equal(third.title, "Untitled");
+ assert.equal(third.createdAt, null);
+ const codes = result.warnings.map((w) => w.code);
+ assert.ok(codes.includes("TITLE_MISSING_DEFAULTED"));
+ assert.ok(codes.includes("DATE_UNPARSEABLE"));
+});
+
+test("parseGranolaCsv reports header mapping and derives stable ids", async () => {
+ const { parseGranolaCsv, deterministicUuid } = await load();
+ const result = parseGranolaCsv(FULL_CSV);
+ assert.equal(result.headerInfo.mapped.title, "title");
+ assert.deepEqual(result.headerInfo.unknown, []);
+ assert.equal(result.notes[0].clientNoteId, deterministicUuid("doc1"));
+ const again = parseGranolaCsv(FULL_CSV);
+ assert.deepEqual(
+ again.notes.map((n) => n.clientNoteId),
+ result.notes.map((n) => n.clientNoteId)
+ );
+});
+
+test("parseGranolaCsv falls back to a title+date hash key without an id column", async () => {
+ const { parseGranolaCsv } = await load();
+ const csv = 'title,summary,created_at\nSync,"Some notes",2026-07-15T14:30:00Z';
+ const result = parseGranolaCsv(csv);
+ assert.match(result.notes[0].sourceFile, /^granola:[0-9a-f]{16}$/);
+ const again = parseGranolaCsv(csv);
+ assert.equal(again.notes[0].clientNoteId, result.notes[0].clientNoteId);
+});
+
+test("parseGranolaCsv warns once when the transcript column is missing", async () => {
+ const { parseGranolaCsv } = await load();
+ const result = parseGranolaCsv('title,summary\nA,"notes a"\nB,"notes b"');
+ assert.equal(result.ok, true);
+ const codes = result.warnings.filter((w) => w.code === "TRANSCRIPT_COLUMN_MISSING");
+ assert.equal(codes.length, 1);
+ assert.equal(result.notes[0].transcript, null);
+});
+
+test("parseGranolaCsv skips summary-less and empty rows with warnings", async () => {
+ const { parseGranolaCsv } = await load();
+ const result = parseGranolaCsv('title,summary\nHas Notes,"content"\nNo Notes,\n,\n');
+ assert.equal(result.notes.length, 1);
+ const codes = result.warnings.map((w) => w.code);
+ assert.ok(codes.includes("ROW_NO_SUMMARY_SKIPPED"));
+ assert.ok(codes.includes("ROW_EMPTY_SKIPPED"));
+});
+
+test("parseGranolaCsv pads short rows and truncates long rows with a warning", async () => {
+ const { parseGranolaCsv } = await load();
+ const result = parseGranolaCsv(
+ 'title,summary,created_at\nShort,"only two"\nLong,"x",2026-07-15,extra'
+ );
+ assert.equal(result.notes.length, 2);
+ assert.equal(result.notes[0].createdAt, null);
+ const codes = result.warnings.filter((w) => w.code === "ROW_COLUMN_COUNT_MISMATCH");
+ assert.equal(codes.length, 2);
+});
+
+test("parseGranolaCsv fails loud on empty files", async () => {
+ const { parseGranolaCsv } = await load();
+ const result = parseGranolaCsv("");
+ assert.equal(result.ok, false);
+ assert.equal(result.error.code, "EMPTY_FILE");
+});
+
+test("parseGranolaCsv fails loud when neither title nor summary maps", async () => {
+ const { parseGranolaCsv } = await load();
+ const result = parseGranolaCsv("foo,bar\n1,2");
+ assert.equal(result.ok, false);
+ assert.equal(result.error.code, "HEADERS_UNRECOGNIZED");
+});
+
+test("parseGranolaCsv fails loud on a header-only file", async () => {
+ const { parseGranolaCsv } = await load();
+ const result = parseGranolaCsv("title,summary");
+ assert.equal(result.ok, false);
+ assert.equal(result.error.code, "NO_DATA_ROWS");
+});
+
+// ---------------------------------------------------------------------------
+// Real export shape — reconciled against a live 2026-08-24 Granola export
+// ---------------------------------------------------------------------------
+
+const REAL_HEADER_ROW =
+ "document_id,user_email,document_title,workspace_name,document_created,summary,notes,transcript";
+
+test("parseGranolaCsv maps the real Granola export headers", async () => {
+ const { parseGranolaCsv } = await load();
+ const csv =
+ REAL_HEADER_ROW +
+ "\n" +
+ 'abc-123,[email protected],Design Review,Acme,2026-08-20T17:46:57.650Z,"# Notes\n- point",,"Para one.\nPara two."';
+ const result = parseGranolaCsv(csv);
+ assert.equal(result.ok, true);
+ const note = result.notes[0];
+ assert.equal(note.title, "Design Review");
+ assert.equal(note.createdAt, "2026-08-20 17:46:57");
+ assert.equal(note.sourceFile, "granola:abc-123");
+ assert.equal(note.content, "# Notes\n- point");
+ assert.deepEqual(result.headerInfo.unknown, ["user_email", "workspace_name"]);
+});
+
+test("parseGranolaCsv appends user notes beneath the AI summary", async () => {
+ const { parseGranolaCsv } = await load();
+ const result = parseGranolaCsv('title,summary,notes\nSync,"AI summary","My own notes"');
+ assert.equal(result.notes[0].content, "AI summary\n\n---\n\nMy own notes");
+});
+
+test("parseGranolaCsv uses user notes as content when the summary is empty", async () => {
+ const { parseGranolaCsv } = await load();
+ const result = parseGranolaCsv('title,summary,notes\nSync,,"My own notes"');
+ assert.equal(result.notes.length, 1);
+ assert.equal(result.notes[0].content, "My own notes");
+});
+
+test("parseGranolaCsv parses the sanitized real-export fixture end to end", async () => {
+ const { parseGranolaCsv } = await load();
+ const fixture = fs.readFileSync(
+ path.join(__dirname, "fixtures", "granola-export-sample.csv"),
+ "utf8"
+ );
+ const result = parseGranolaCsv(fixture);
+ assert.equal(result.ok, true);
+ assert.equal(result.notes.length, 1);
+ const note = result.notes[0];
+ assert.equal(note.title, "Product Design Review");
+ assert.equal(note.createdAt, "2026-08-20 17:46:57");
+ assert.match(note.content, /^# UI Cleanup Priorities/);
+ const segments = JSON.parse(note.transcript);
+ assert.ok(segments.length > 1);
+ assert.ok(segments.every((segment) => segment.speakerName === undefined));
+ // Anchor derives from the stored created_at, which is second-granular.
+ assert.equal(segments[0].timestamp, Date.parse("2026-08-20T17:46:57Z"));
+ assert.deepEqual(result.headerInfo.unknown, ["user_email", "workspace_name"]);
+ // The only warning a clean real export produces is the file-level unknown-columns one.
+ assert.deepEqual(result.warnings, [
+ { code: "UNKNOWN_COLUMNS_IGNORED", detail: "user_email, workspace_name" },
+ ]);
+});
diff --git a/test/helpers/granolaImportDatabase.test.js b/test/helpers/granolaImportDatabase.test.js
new file mode 100644
index 000000000..ec0378794
--- /dev/null
+++ b/test/helpers/granolaImportDatabase.test.js
@@ -0,0 +1,154 @@
+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");
+
+let userDataDir = fs.mkdtempSync(path.join(os.tmpdir(), "openwhispr-granola-db-"));
+const originalLoad = Module._load;
+
+Module._load = function patchedLoad(request, parent, isMain) {
+ if (request === "electron") {
+ return {
+ app: {
+ getPath: () => userDataDir,
+ getAppPath: () => process.cwd(),
+ isReady: () => false,
+ },
+ };
+ }
+ return originalLoad.call(this, request, parent, isMain);
+};
+
+process.env.NODE_ENV = "test";
+
+const DatabaseManager = require("../../src/helpers/database.js");
+
+function isNativeBindingUnavailable(error) {
+ const message = String(error?.message || error);
+ return (
+ message.includes("NODE_MODULE_VERSION") ||
+ message.includes("Could not locate the bindings file")
+ );
+}
+
+function createDb(t) {
+ userDataDir = fs.mkdtempSync(path.join(os.tmpdir(), "openwhispr-granola-db-"));
+ try {
+ return new DatabaseManager();
+ } catch (error) {
+ if (isNativeBindingUnavailable(error)) {
+ t.skip("better-sqlite3 native binding is not available for this Node runtime");
+ return null;
+ }
+ throw error;
+ }
+}
+
+function granolaRow(key, overrides = {}) {
+ return {
+ clientNoteId: `00000000-0000-4000-8000-${key.repeat(12).slice(0, 12)}`,
+ sourceFile: `granola:${key}`,
+ title: `Meeting ${key}`,
+ content: `Summary body ${key}`,
+ transcript: null,
+ participants: null,
+ createdAt: "2024-05-01 10:00:00",
+ ...overrides,
+ };
+}
+
+test("importNotes inserts backdated meeting notes into the Imported folder", (t) => {
+ const db = createDb(t);
+ if (!db) return;
+
+ const result = db.importNotes([granolaRow("a"), granolaRow("b")]);
+ assert.equal(result.success, true);
+ assert.equal(result.imported, 2);
+ assert.equal(result.skipped, 0);
+ assert.deepEqual(result.errors, []);
+ assert.equal(result.noteIds.length, 2);
+
+ const note = db.getNote(result.noteIds[0]);
+ assert.equal(note.created_at, "2024-05-01 10:00:00");
+ assert.equal(note.updated_at, "2024-05-01 10:00:00");
+ assert.equal(note.note_type, "meeting");
+ assert.equal(note.sync_status, "pending");
+ assert.equal(note.source_file, "granola:a");
+ assert.equal(note.space_id, db.getPrivateSpaceId());
+ assert.equal(note.folder_id, result.folderId);
+
+ const folder = db.getFolders().find((f) => f.id === result.folderId);
+ assert.equal(folder.name, "Imported");
+ db.db.close();
+});
+
+test("importNotes falls back to the current time when createdAt is null", (t) => {
+ const db = createDb(t);
+ if (!db) return;
+
+ const result = db.importNotes([granolaRow("c", { createdAt: null })]);
+ const note = db.getNote(result.noteIds[0]);
+ assert.match(note.created_at, /^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/);
+ db.db.close();
+});
+
+test("importNotes is idempotent across re-runs", (t) => {
+ const db = createDb(t);
+ if (!db) return;
+
+ const rows = [granolaRow("d"), granolaRow("e")];
+ db.importNotes(rows);
+ const rerun = db.importNotes(rows);
+ assert.equal(rerun.imported, 0);
+ assert.equal(rerun.skipped, 2);
+ const count = db.db.prepare("SELECT COUNT(*) AS n FROM notes").get().n;
+ assert.equal(count, 2);
+ db.db.close();
+});
+
+test("importNotes handles a mixed batch of new and duplicate rows", (t) => {
+ const db = createDb(t);
+ if (!db) return;
+
+ db.importNotes([granolaRow("f")]);
+ const result = db.importNotes([granolaRow("f"), granolaRow("1")]);
+ assert.equal(result.imported, 1);
+ assert.equal(result.skipped, 1);
+ db.db.close();
+});
+
+test("importNotes rows are searchable through FTS", (t) => {
+ const db = createDb(t);
+ if (!db) return;
+
+ db.importNotes([granolaRow("a", { title: "Quarterly Roadmap Review" })]);
+ const hits = db.searchNotes("Roadmap");
+ assert.equal(hits.length, 1);
+ assert.equal(hits[0].title, "Quarterly Roadmap Review");
+ db.db.close();
+});
+
+test("importNotes reuses an existing Imported folder", (t) => {
+ const db = createDb(t);
+ if (!db) return;
+
+ const created = db.createFolder("Imported");
+ const result = db.importNotes([granolaRow("a")]);
+ assert.equal(result.folderId, created.folder.id);
+ const folders = db.getFolders().filter((f) => f.name === "Imported");
+ assert.equal(folders.length, 1);
+ db.db.close();
+});
+
+test("getExistingClientNoteIds reports only ids already in the table", (t) => {
+ const db = createDb(t);
+ if (!db) return;
+
+ const rowA = granolaRow("a");
+ db.importNotes([rowA]);
+ const existing = db.getExistingClientNoteIds([rowA.clientNoteId, granolaRow("b").clientNoteId]);
+ assert.deepEqual(existing, [rowA.clientNoteId]);
+ db.db.close();
+});