Voice-to-text dictation app with local (Nvidia Parakeet/Whisper) and cloud models (BYOK). Privacy-first and available cross-platform.
JavaScript aianthropiccross-platformgeminigroqlinuxmacosnvidiaopen-sourceopenaiparakeetspeech-to-texttranscribewhisperwindows
fix(notes): prevent clientNoteId collisions on Granola CSV imports sharing title and date (#1954) (#1955)
Henry Suc73e3027b397
diff --git a/src/helpers/granolaImport.js b/src/helpers/granolaImport.jsindex 75d4afe1a..23d0823b9 100644--- a/src/helpers/granolaImport.js+++ b/src/helpers/granolaImport.js@@ -269,6 +269,40 @@ export function deterministicUuid(key) {return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${withVersion}-${withVariant}-${hex.slice(20, 32)}`;}+const shortHash = (value) => createHash("sha256").update(value).digest("hex").slice(0, 16);++/**+ * Allocate stable note keys across every CSV file in one Granola import.+ * The first missing-id row retains the released fallback identity; only later+ * collisions receive a versioned key.+ *+ * @returns {(fields: {+ * id: string,+ * title: string,+ * rawDate: string,+ * }) => string}+ */+export function createGranolaNoteKeyAllocator() {+ const claimedLegacyFallbackKeys = new Set();+ const fallbackOccurrences = new Map();++ return ({ id, title, rawDate }) => {+ if (id) return id;++ const legacyFallbackKey = shortHash(`${title}|${rawDate}`);+ const fallbackTuple = JSON.stringify([title, rawDate]);+ const occurrence = fallbackOccurrences.get(fallbackTuple) ?? 0;+ fallbackOccurrences.set(fallbackTuple, occurrence + 1);++ if (!claimedLegacyFallbackKeys.has(legacyFallbackKey)) {+ claimedLegacyFallbackKeys.add(legacyFallbackKey);+ return legacyFallbackKey;+ }++ return shortHash(JSON.stringify(["v2", title, rawDate, occurrence]));+ };+}+const NAME_EMAIL_RE = /^(.*?)\s*<([^<>\s]+@[^<>\s]+)>$/;const BARE_EMAIL_RE = /^\S+@\S+\.\S+$/;@@ -290,6 +324,7 @@ const parseAttendees = (cell) =>* Parse a Granola CSV export into insert-ready note rows.** @param {string} text+ * @param {{ allocateNoteKey?: ReturnType<typeof createGranolaNoteKeyAllocator> }} [options]* @returns {{* ok: boolean,* error?: { code: "EMPTY_FILE"|"HEADERS_UNRECOGNIZED"|"NO_DATA_ROWS" },@@ -301,7 +336,7 @@ const parseAttendees = (cell) =>* warnings: Array<{ code: string, row?: number, detail?: string }>,* }}*/-export function parseGranolaCsv(text) {+export function parseGranolaCsv(text, { allocateNoteKey = createGranolaNoteKeyAllocator() } = {}) {const src = String(text ?? "");const emptyHeaderInfo = { mapped: {}, unknown: [] };if (!src.trim()) {@@ -375,14 +410,18 @@ export function parseGranolaCsv(text) {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 rawTranscript = cell("transcript");+ const rawAttendees = cell("attendees");+ const key = allocateNoteKey({+ id,+ title,+ rawDate,+ });const anchorMs = createdAt ? Date.parse(`${createdAt.replace(" ", "T")}Z`) : 0;- const segments = parseTranscriptToSegments(cell("transcript"), anchorMs);- const attendees = parseAttendees(cell("attendees"));+ const segments = parseTranscriptToSegments(rawTranscript, anchorMs);+ const attendees = parseAttendees(rawAttendees);notes.push({clientNoteId: deterministicUuid(key),diff --git a/src/helpers/ipcHandlers.js b/src/helpers/ipcHandlers.jsindex 6233ed6dc..3a358cb59 100644--- a/src/helpers/ipcHandlers.js+++ b/src/helpers/ipcHandlers.js@@ -10884,16 +10884,21 @@ class IPCHandlers {if (result.canceled || !result.filePaths.length) {return { canceled: true };}+ const filePaths = [...result.filePaths].sort();const MAX_IMPORT_BYTES = 200 * 1024 * 1024;- const { parseGranolaCsv } = await import("./granolaImport.js");+ const { createGranolaNoteKeyAllocator, parseGranolaCsv } =+ await import("./granolaImport.js");+ const allocateNoteKey = createGranolaNoteKeyAllocator();const notes = [];const seenIds = new Set();let rowIssueCount = 0;- for (const filePath of result.filePaths) {+ for (const filePath of 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"));+ const parsed = parseGranolaCsv(fs.readFileSync(filePath, "utf8"), {+ allocateNoteKey,+ });if (!parsed.ok) {return { canceled: false, success: false, error: parsed.error.code };}@@ -10917,7 +10922,7 @@ class IPCHandlers {return {canceled: false,success: true,- fileName: result.filePaths.map((p) => path.basename(p)).join(", "),+ fileName: filePaths.map((p) => path.basename(p)).join(", "),total: notes.length,newCount: freshNotes.length,duplicateCount: notes.length - freshNotes.length,diff --git a/test/helpers/granolaImport.test.js b/test/helpers/granolaImport.test.jsindex 4158c850e..501dd4279 100644--- a/test/helpers/granolaImport.test.js+++ b/test/helpers/granolaImport.test.js@@ -348,15 +348,134 @@ test("parseGranolaCsv reports header mapping and derives stable ids", async () =);});-test("parseGranolaCsv falls back to a title+date hash key without an id column", async () => {+test("parseGranolaCsv preserves the released title+date fallback key for the first note", 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}$/);+ assert.equal(result.notes[0].sourceFile, "granola:0852623745d4c283");const again = parseGranolaCsv(csv);assert.equal(again.notes[0].clientNoteId, result.notes[0].clientNoteId);});+test("parseGranolaCsv generates distinct fallback keys for notes sharing title and date without an id column", async () => {+ const { parseGranolaCsv } = await load();+ const csv = [+ "title,summary,created_at",+ 'Sync,"Morning sync notes",2026-07-15T14:30:00Z',+ 'Sync,"Afternoon sync notes",2026-07-15T14:30:00Z',+ ].join("\n");+ const result = parseGranolaCsv(csv);+ assert.equal(result.notes.length, 2);+ assert.notEqual(result.notes[0].clientNoteId, result.notes[1].clientNoteId);+ assert.notEqual(result.notes[0].sourceFile, result.notes[1].sourceFile);+});++test("parseGranolaCsv keeps a colliding note id when its summary changes", async () => {+ const { parseGranolaCsv } = await load();+ const originalCsv = [+ "title,summary,created_at",+ 'Sync,"First meeting",2026-07-15T14:30:00Z',+ 'Sync,"Original second meeting",2026-07-15T14:30:00Z',+ ].join("\n");+ const editedCsv = [+ "title,summary,created_at",+ 'Sync,"First meeting",2026-07-15T14:30:00Z',+ 'Sync,"Edited second meeting",2026-07-15T14:30:00Z',+ ].join("\n");++ const original = parseGranolaCsv(originalCsv);+ const edited = parseGranolaCsv(editedCsv);++ assert.equal(edited.notes[1].clientNoteId, original.notes[1].clientNoteId);+});++test("createGranolaNoteKeyAllocator disambiguates legacy title and date tuples", async () => {+ const { createGranolaNoteKeyAllocator } = await load();+ const sharedFields = { id: "" };+ const leftFields = { ...sharedFields, title: "A|B", rawDate: "C" };+ const rightFields = { ...sharedFields, title: "A", rawDate: "B|C" };++ const leftFirstAllocator = createGranolaNoteKeyAllocator();+ const leftLegacyKey = leftFirstAllocator(leftFields);+ const rightVersionedKey = leftFirstAllocator(rightFields);+ const rightFirstAllocator = createGranolaNoteKeyAllocator();+ const rightLegacyKey = rightFirstAllocator(rightFields);+ const leftVersionedKey = rightFirstAllocator(leftFields);++ assert.equal(leftLegacyKey, rightLegacyKey);+ assert.notEqual(leftVersionedKey, rightVersionedKey);+});++test("createGranolaNoteKeyAllocator counts delimiter-colliding tuples independently", async () => {+ const { createGranolaNoteKeyAllocator } = await load();+ const leftFields = { id: "", title: "A|B", rawDate: "C" };+ const rightFields = { id: "", title: "A", rawDate: "B|C" };++ const allocatorWithCollision = createGranolaNoteKeyAllocator();+ allocatorWithCollision(leftFields);+ allocatorWithCollision(rightFields);+ const secondLeftKeyAfterCollision = allocatorWithCollision(leftFields);++ const allocatorWithoutCollision = createGranolaNoteKeyAllocator();+ allocatorWithoutCollision(leftFields);+ const secondLeftKey = allocatorWithoutCollision(leftFields);++ assert.equal(secondLeftKeyAfterCollision, secondLeftKey);+});++test("parseGranolaCsv distinguishes notes with matching content but different transcripts", async () => {+ const { parseGranolaCsv } = await load();+ const csv = [+ "title,summary,created_at,transcript",+ 'Sync,"Same summary",2026-07-15T14:30:00Z,"Alice: First meeting"',+ 'Sync,"Same summary",2026-07-15T14:30:00Z,"Bob: Second meeting"',+ 'Sync,"Same summary",2026-07-15T14:30:00Z,"Carol: Third meeting"',+ ].join("\n");+ const result = parseGranolaCsv(csv);+ assert.equal(result.notes.length, 3);+ assert.equal(new Set(result.notes.map((note) => note.clientNoteId)).size, 3);+ assert.equal(new Set(result.notes.map((note) => note.sourceFile)).size, 3);+});++test("parseGranolaCsv assigns distinct fallback keys to identical source rows", async () => {+ const { parseGranolaCsv } = await load();+ const csv = [+ "title,summary,created_at",+ 'Sync,"Same summary",2026-07-15T14:30:00Z',+ 'Sync,"Same summary",2026-07-15T14:30:00Z',+ 'Sync,"Same summary",2026-07-15T14:30:00Z',+ ].join("\n");+ const result = parseGranolaCsv(csv);+ assert.equal(result.notes.length, 3);+ assert.equal(new Set(result.notes.map((note) => note.clientNoteId)).size, 3);+ assert.equal(new Set(result.notes.map((note) => note.sourceFile)).size, 3);+});++test("parseGranolaCsv shares fallback collision allocation across CSV files", async () => {+ const { createGranolaNoteKeyAllocator, parseGranolaCsv } = await load();+ assert.equal(typeof createGranolaNoteKeyAllocator, "function");+ const allocateNoteKey = createGranolaNoteKeyAllocator();+ const csv = 'title,summary,created_at\nSync,"Same summary",2026-07-15T14:30:00Z';+ const notes = [+ ...parseGranolaCsv(csv, { allocateNoteKey }).notes,+ ...parseGranolaCsv(csv, { allocateNoteKey }).notes,+ ...parseGranolaCsv(csv, { allocateNoteKey }).notes,+ ];+ assert.equal(new Set(notes.map((note) => note.clientNoteId)).size, 3);+ assert.equal(new Set(notes.map((note) => note.sourceFile)).size, 3);+});++test("parseGranolaCsv generates distinct fallback keys for multiple untitled notes without dates", async () => {+ const { parseGranolaCsv } = await load();+ const csv = ["summary", '"First untitled meeting"', '"Second untitled meeting"'].join("\n");+ const result = parseGranolaCsv(csv);+ assert.equal(result.notes.length, 2);+ assert.equal(result.notes[0].title, "Untitled");+ assert.equal(result.notes[1].title, "Untitled");+ assert.notEqual(result.notes[0].clientNoteId, result.notes[1].clientNoteId);+ assert.notEqual(result.notes[0].sourceFile, result.notes[1].sourceFile);+});+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"');diff --git a/test/helpers/granolaImportDatabase.test.js b/test/helpers/granolaImportDatabase.test.jsindex ec0378794..e71405bee 100644--- a/test/helpers/granolaImportDatabase.test.js+++ b/test/helpers/granolaImportDatabase.test.js@@ -24,6 +24,7 @@ Module._load = function patchedLoad(request, parent, isMain) {process.env.NODE_ENV = "test";const DatabaseManager = require("../../src/helpers/database.js");+const loadGranolaImport = () => import("../../src/helpers/granolaImport.js");function isNativeBindingUnavailable(error) {const message = String(error?.message || error);@@ -108,6 +109,52 @@ test("importNotes is idempotent across re-runs", (t) => {db.db.close();});+test("a released Granola fallback id remains idempotent after the parser upgrade", async (t) => {+ const db = createDb(t);+ if (!db) return;+ const { parseGranolaCsv } = await loadGranolaImport();+ const csv = 'title,summary,created_at\nSync,"Some notes",2026-07-15T14:30:00Z';+ const legacyRow = {+ clientNoteId: "d9182b86-aa74-4c1a-8dbe-5060160ef305",+ sourceFile: "granola:0852623745d4c283",+ title: "Sync",+ content: "Some notes",+ transcript: null,+ participants: null,+ createdAt: "2026-07-15 14:30:00",+ };+ db.importNotes([legacyRow]);++ const result = db.importNotes(parseGranolaCsv(csv).notes);++ assert.equal(result.imported, 0);+ assert.equal(result.skipped, 1);+ assert.equal(db.db.prepare("SELECT COUNT(*) AS count FROM notes").get().count, 1);+ db.db.close();+});++test("parsed Granola fallback collisions persist distinctly and remain idempotent", async (t) => {+ const db = createDb(t);+ if (!db) return;+ const { parseGranolaCsv } = await loadGranolaImport();+ const csv = [+ "title,summary,created_at,transcript",+ 'Sync,"Same summary",2026-07-15T14:30:00Z,"Alice: First meeting"',+ 'Sync,"Same summary",2026-07-15T14:30:00Z,"Bob: Second meeting"',+ 'Sync,"Same summary",2026-07-15T14:30:00Z,"Carol: Third meeting"',+ ].join("\n");++ const firstImport = db.importNotes(parseGranolaCsv(csv).notes);+ const secondImport = db.importNotes(parseGranolaCsv(csv).notes);++ assert.equal(firstImport.imported, 3);+ assert.equal(firstImport.skipped, 0);+ assert.equal(secondImport.imported, 0);+ assert.equal(secondImport.skipped, 3);+ assert.equal(db.db.prepare("SELECT COUNT(*) AS count FROM notes").get().count, 3);+ db.db.close();+});+test("importNotes handles a mixed batch of new and duplicate rows", (t) => {const db = createDb(t);if (!db) return;diff --git a/test/helpers/granolaImportIpc.test.js b/test/helpers/granolaImportIpc.test.jsnew file mode 100644index 000000000..addaaa096--- /dev/null+++ b/test/helpers/granolaImportIpc.test.js@@ -0,0 +1,136 @@+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;+const handlers = new Map();+const importDir = fs.mkdtempSync(path.join(os.tmpdir(), "openwhispr-granola-ipc-"));+const csvPaths = ["granola-000.csv", "granola-001.csv", "granola-002.csv"].map((name, index) => {+ const filePath = path.join(importDir, name);+ fs.writeFileSync(+ filePath,+ `title,summary,created_at\nSync,"Summary ${index + 1}",2026-07-15T14:30:00Z`+ );+ return filePath;+});+let selectedCsvPaths = csvPaths;++const electronStub = {+ app: {+ getPath: () => importDir,+ getName: () => "test",+ getVersion: () => "0.0.0",+ isPackaged: false,+ on: () => {},+ requestSingleInstanceLock: () => true,+ },+ ipcMain: {+ handle: (channel, handler) => handlers.set(channel, handler),+ on: () => {},+ removeHandler: () => {},+ },+ net: { fetch: async () => ({ ok: true, status: 200, json: async () => ({}) }) },+ BrowserWindow: class BrowserWindow {+ static getAllWindows() {+ return [];+ }++ static fromWebContents() {+ return null;+ }+ },+ shell: {},+ dialog: {+ showOpenDialog: async () => ({ canceled: false, filePaths: selectedCsvPaths }),+ },+ screen: { getPrimaryDisplay: () => ({ workAreaSize: { width: 0, height: 0 } }) },+ systemPreferences: { getMediaAccessStatus: () => "granted" },+ session: { fromPartition: () => ({}) },+ clipboard: {},+ nativeImage: {},+ globalShortcut: {},+ utilityProcess: {},+ MessageChannelMain: class {},+};++Module._load = function loadWithElectronStub(request, parent, isMain) {+ if (request === "electron") return electronStub;+ if (parent?.filename === handlersModulePath && request === "./debugLogger") {+ return new Proxy({}, { get: () => () => {} });+ }+ 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(),+ });+}++let target;+test.before(() => {+ delete require.cache[handlersModulePath];+ const IPCHandlers = require(handlersModulePath);+ const Ctor = IPCHandlers.default || IPCHandlers;+ target = {+ databaseManager: {+ getExistingClientNoteIds: () => [],+ },+ };+ Ctor.prototype.setupHandlers.call(+ new Proxy(target, {+ get: (value, property) => (property in value ? value[property] : anything()),+ })+ );+ assert.ok(+ handlers.get("granola-import-pick-and-preview"),+ "granola preview handler must be registered"+ );+});++test.after(() => {+ Module._load = originalLoad;+ fs.rmSync(importDir, { recursive: true, force: true });+});++test("multi-file Granola preview allocates distinct fallback ids across files", async () => {+ selectedCsvPaths = csvPaths;+ const result = await handlers.get("granola-import-pick-and-preview")({ sender: {} });++ assert.equal(result.success, true);+ assert.equal(result.total, 3);+ assert.equal(target._granolaImportPending.notes.length, 3);+ assert.equal(+ new Set(target._granolaImportPending.notes.map((note) => note.clientNoteId)).size,+ 3+ );+});++test("multi-file Granola preview is stable when file picker order changes", async () => {+ selectedCsvPaths = csvPaths;+ await handlers.get("granola-import-pick-and-preview")({ sender: {} });+ const firstIdsByContent = Object.fromEntries(+ target._granolaImportPending.notes+ .map((note) => [note.content, note.clientNoteId])+ .sort(([leftContent], [rightContent]) => leftContent.localeCompare(rightContent))+ );++ selectedCsvPaths = [...csvPaths].reverse();+ await handlers.get("granola-import-pick-and-preview")({ sender: {} });+ const reversedIdsByContent = Object.fromEntries(+ target._granolaImportPending.notes+ .map((note) => [note.content, note.clientNoteId])+ .sort(([leftContent], [rightContent]) => leftContent.localeCompare(rightContent))+ );++ assert.deepEqual(reversedIdsByContent, firstIdsByContent);+});