Skip to content

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

feat: cloud notes — local-first storage, FTS5, cloud sync and semantic search

Gabriel Steinb85d90fb567a
diff --git a/preload.js b/preload.js
index 975d5629d..824545850 100644
--- a/preload.js
+++ b/preload.js
@@ -68,6 +68,8 @@ contextBridge.exposeInMainWorld("electronAPI", {
updateNote: (id, updates) => ipcRenderer.invoke("db-update-note", id, updates),
deleteNote: (id) => ipcRenderer.invoke("db-delete-note", id),
exportNote: (noteId, format) => ipcRenderer.invoke("export-note", noteId, format),
+ searchNotes: (query, limit) => ipcRenderer.invoke("db-search-notes", query, limit),
+ updateNoteCloudId: (id, cloudId) => ipcRenderer.invoke("db-update-note-cloud-id", id, cloudId),
// Folder functions
getFolders: () => ipcRenderer.invoke("db-get-folders"),
diff --git a/src/components/NoteEditor.tsx b/src/components/NoteEditor.tsx
new file mode 100644
index 000000000..85c10d3f1
--- /dev/null
+++ b/src/components/NoteEditor.tsx
@@ -0,0 +1,187 @@
+import { useState, useEffect, useRef, useCallback } from "react";
+import { useTranslation } from "react-i18next";
+import { Loader2, Trash2 } from "lucide-react";
+import { Button } from "./ui/button";
+import { ConfirmDialog } from "./ui/dialog.js";
+import { cn } from "./lib/utils";
+import type { NoteItem } from "../types/electron.js";
+import { syncNoteUpdateToCloud, syncNoteDeleteToCloud } from "../stores/noteStore.js";
+
+const NOTE_TYPE_COLORS: Record<NoteItem["note_type"], string> = {
+ personal: "bg-foreground/5 text-foreground/50",
+ meeting: "bg-blue-500/8 text-blue-500/60 dark:bg-blue-400/10 dark:text-blue-400/60",
+ upload: "bg-amber-500/8 text-amber-600/60 dark:bg-amber-400/10 dark:text-amber-400/60",
+};
+
+type SaveState = "idle" | "saving" | "saved";
+
+interface NoteEditorProps {
+ note: NoteItem;
+ cloudEnabled: boolean;
+ onDelete: (id: number) => void;
+ onUpdate: (note: NoteItem) => void;
+}
+
+export default function NoteEditor({ note, cloudEnabled, onDelete, onUpdate }: NoteEditorProps) {
+ const { t } = useTranslation();
+ const [title, setTitle] = useState(note.title);
+ const [content, setContent] = useState(note.content);
+ const [saveState, setSaveState] = useState<SaveState>("idle");
+ const [confirmOpen, setConfirmOpen] = useState(false);
+ const saveTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
+ const fadeTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
+ const textareaRef = useRef<HTMLTextAreaElement>(null);
+
+ useEffect(() => {
+ setTitle(note.title);
+ setContent(note.content);
+ setSaveState("idle");
+ }, [note.id]);
+
+ const autoResize = useCallback(() => {
+ const ta = textareaRef.current;
+ if (!ta) return;
+ ta.style.height = "auto";
+ ta.style.height = `${ta.scrollHeight}px`;
+ }, []);
+
+ useEffect(() => {
+ autoResize();
+ }, [content, autoResize]);
+
+ const scheduleAutoSave = useCallback(
+ (updatedTitle: string, updatedContent: string) => {
+ if (saveTimerRef.current) clearTimeout(saveTimerRef.current);
+ if (fadeTimerRef.current) clearTimeout(fadeTimerRef.current);
+
+ saveTimerRef.current = setTimeout(async () => {
+ setSaveState("saving");
+ const updates = { title: updatedTitle, content: updatedContent };
+ try {
+ await window.electronAPI.updateNote(note.id, updates);
+ const updated = { ...note, ...updates };
+ onUpdate(updated);
+ if (cloudEnabled) {
+ syncNoteUpdateToCloud(updated, updates).catch(() => {});
+ }
+ setSaveState("saved");
+ fadeTimerRef.current = setTimeout(() => setSaveState("idle"), 2000);
+ } catch {
+ setSaveState("idle");
+ }
+ }, 800);
+ },
+ [note, cloudEnabled, onUpdate]
+ );
+
+ useEffect(() => {
+ return () => {
+ if (saveTimerRef.current) clearTimeout(saveTimerRef.current);
+ if (fadeTimerRef.current) clearTimeout(fadeTimerRef.current);
+ };
+ }, []);
+
+ const handleTitleChange = useCallback(
+ (e: React.ChangeEvent<HTMLInputElement>) => {
+ const next = e.target.value;
+ setTitle(next);
+ scheduleAutoSave(next, content);
+ },
+ [content, scheduleAutoSave]
+ );
+
+ const handleContentChange = useCallback(
+ (e: React.ChangeEvent<HTMLTextAreaElement>) => {
+ const next = e.target.value;
+ setContent(next);
+ autoResize();
+ scheduleAutoSave(title, next);
+ },
+ [title, scheduleAutoSave, autoResize]
+ );
+
+ const handleConfirmDelete = useCallback(async () => {
+ await window.electronAPI.deleteNote(note.id);
+ if (cloudEnabled && note.cloud_id) {
+ syncNoteDeleteToCloud(note.cloud_id).catch(() => {});
+ }
+ onDelete(note.id);
+ }, [note, cloudEnabled, onDelete]);
+
+ return (
+ <div className="flex flex-col h-full min-h-0">
+ <div className="flex items-center justify-between px-5 pt-4 pb-2 gap-3">
+ <div className="flex items-center gap-2 min-w-0">
+ <span
+ className={cn(
+ "shrink-0 text-[10px] font-medium px-1.5 py-px rounded-sm",
+ NOTE_TYPE_COLORS[note.note_type]
+ )}
+ >
+ {t(`notesView.noteType.${note.note_type}`)}
+ </span>
+ </div>
+ <div className="flex items-center gap-3 shrink-0">
+ <span
+ className={cn(
+ "text-xs text-muted-foreground/50 transition-opacity duration-300",
+ saveState === "idle" && "opacity-0",
+ saveState === "saving" && "opacity-100",
+ saveState === "saved" && "opacity-100"
+ )}
+ >
+ {saveState === "saving" ? (
+ <span className="flex items-center gap-1">
+ <Loader2 size={10} className="animate-spin" />
+ {t("notes.editor.saving")}
+ </span>
+ ) : (
+ t("noteEditor.saved")
+ )}
+ </span>
+ <Button
+ variant="ghost"
+ size="icon"
+ className="h-7 w-7 text-muted-foreground/50 hover:text-destructive hover:bg-destructive/8"
+ onClick={() => setConfirmOpen(true)}
+ aria-label={t("noteEditor.deleteNote")}
+ >
+ <Trash2 size={13} />
+ </Button>
+ </div>
+ </div>
+
+ <div className="px-5 pb-2">
+ <input
+ type="text"
+ value={title}
+ onChange={handleTitleChange}
+ placeholder={t("notes.editor.untitled")}
+ className="w-full bg-transparent outline-none border-none text-lg font-medium text-foreground placeholder:text-foreground/20 tracking-[-0.01em]"
+ />
+ </div>
+
+ <div className="flex-1 overflow-y-auto px-5 pb-6 min-h-0">
+ <textarea
+ ref={textareaRef}
+ value={content}
+ onChange={handleContentChange}
+ placeholder={t("notes.editor.startWriting")}
+ rows={1}
+ className="w-full bg-transparent outline-none border-none resize-none text-sm text-foreground/80 placeholder:text-foreground/20 leading-relaxed"
+ />
+ </div>
+
+ <ConfirmDialog
+ open={confirmOpen}
+ onOpenChange={setConfirmOpen}
+ title={t("noteEditor.deleteConfirmTitle")}
+ description={t("noteEditor.deleteConfirmDescription")}
+ confirmText={t("noteEditor.deleteConfirm")}
+ cancelText={t("common.cancel")}
+ onConfirm={handleConfirmDelete}
+ variant="destructive"
+ />
+ </div>
+ );
+}
diff --git a/src/components/NotesView.tsx b/src/components/NotesView.tsx
new file mode 100644
index 000000000..e82c19da0
--- /dev/null
+++ b/src/components/NotesView.tsx
@@ -0,0 +1,255 @@
+import { useState, useEffect, useCallback, useMemo, useRef } from "react";
+import { useTranslation } from "react-i18next";
+import { Loader2, StickyNote, Plus } from "lucide-react";
+import { Button } from "./ui/button";
+import { Input } from "./ui/input";
+import { cn } from "./lib/utils";
+import type { NoteItem } from "../types/electron.js";
+import { formatDateGroup } from "../utils/dateFormatting";
+import { normalizeDbDate } from "../utils/dateFormatting";
+
+const NOTE_TYPE_COLORS: Record<NoteItem["note_type"], string> = {
+ personal: "bg-foreground/5 text-foreground/50",
+ meeting: "bg-blue-500/8 text-blue-500/60 dark:bg-blue-400/10 dark:text-blue-400/60",
+ upload: "bg-amber-500/8 text-amber-600/60 dark:bg-amber-400/10 dark:text-amber-400/60",
+};
+
+function relativeTime(
+ dateStr: string,
+ t: (key: string, opts?: Record<string, unknown>) => string
+): string {
+ const date = normalizeDbDate(dateStr);
+ if (Number.isNaN(date.getTime())) return dateStr;
+ const diff = Date.now() - date.getTime();
+ const minutes = Math.floor(diff / 60000);
+ const hours = Math.floor(diff / 3600000);
+ const days = Math.floor(diff / 86400000);
+ if (minutes < 1) return t("notes.list.timeNow");
+ if (minutes < 60) return t("notes.list.minutesAgo", { count: minutes });
+ if (hours < 24) return t("notes.list.hoursAgo", { count: hours });
+ if (days < 7) return t("notes.list.daysAgo", { count: days });
+ return date.toLocaleDateString(undefined, { month: "short", day: "numeric" });
+}
+
+const RE_HEADING = /#{1,6}\s+/g;
+const RE_EMPHASIS = /[*_~`]+/g;
+const RE_LINK = /\[([^\]]+)\]\([^)]+\)/g;
+const RE_IMAGE = /!\[([^\]]*)\]\([^)]+\)/g;
+const RE_BLOCKQUOTE = />\s+/g;
+const RE_NEWLINES = /\n+/g;
+
+function stripMarkdown(text: string): string {
+ return text
+ .replace(RE_HEADING, "")
+ .replace(RE_EMPHASIS, "")
+ .replace(RE_LINK, "$1")
+ .replace(RE_IMAGE, "$1")
+ .replace(RE_BLOCKQUOTE, "")
+ .replace(RE_NEWLINES, " ")
+ .trim();
+}
+
+export interface NotesViewProps {
+ notes: NoteItem[];
+ isLoading: boolean;
+ activeNoteId: number | null;
+ onNoteSelect: (id: number) => void;
+ onNewNote: () => void;
+ cloudEnabled: boolean;
+}
+
+export default function NotesView({
+ notes,
+ isLoading,
+ activeNoteId,
+ onNoteSelect,
+ onNewNote,
+ cloudEnabled,
+}: NotesViewProps) {
+ const { t } = useTranslation();
+ const [query, setQuery] = useState("");
+ const [displayedNotes, setDisplayedNotes] = useState<NoteItem[]>(notes);
+ const cloudTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
+
+ useEffect(() => {
+ if (!query.trim()) setDisplayedNotes(notes);
+ }, [notes, query]);
+
+ const handleSearch = useCallback(
+ async (value: string) => {
+ if (cloudTimerRef.current) clearTimeout(cloudTimerRef.current);
+
+ if (!value.trim()) {
+ setDisplayedNotes(notes);
+ return;
+ }
+
+ const localResults = await window.electronAPI.searchNotes(value).catch(() => notes);
+ setDisplayedNotes(localResults);
+
+ if (!cloudEnabled) return;
+
+ cloudTimerRef.current = setTimeout(async () => {
+ try {
+ const { NotesService } = await import("../services/NotesService.js");
+ const { notes: cloudNotes } = await NotesService.search(value);
+ const byClientId = new Map(notes.map((n) => [String(n.id), n]));
+ const mapped = cloudNotes
+ .map((cn) => byClientId.get(cn.client_note_id ?? ""))
+ .filter((n): n is NoteItem => n !== undefined);
+ if (mapped.length > 0) setDisplayedNotes(mapped);
+ } catch {
+ // keep local results silently
+ }
+ }, 300);
+ },
+ [notes, cloudEnabled]
+ );
+
+ useEffect(() => {
+ handleSearch(query);
+ return () => {
+ if (cloudTimerRef.current) clearTimeout(cloudTimerRef.current);
+ };
+ }, [query, handleSearch]);
+
+ const groupedNotes = useMemo(() => {
+ if (displayedNotes.length === 0) return [];
+
+ const groups: { label: string; items: NoteItem[] }[] = [];
+ let currentLabel: string | null = null;
+
+ for (const note of displayedNotes) {
+ const label = formatDateGroup(note.updated_at, t);
+ if (label !== currentLabel) {
+ groups.push({ label, items: [note] });
+ currentLabel = label;
+ } else {
+ groups[groups.length - 1].items.push(note);
+ }
+ }
+
+ return groups;
+ }, [displayedNotes, t]);
+
+ return (
+ <div className="px-4 pt-4 pb-6">
+ <div className="max-w-3xl mx-auto">
+ <div className="flex items-center gap-2 mb-4">
+ <Input
+ value={query}
+ onChange={(e) => setQuery(e.target.value)}
+ placeholder={t("notesView.searchPlaceholder")}
+ className="h-8 text-xs bg-card/50 dark:bg-card/60 border-border/50"
+ />
+ <Button size="sm" className="h-8 text-xs shrink-0 gap-1.5" onClick={onNewNote}>
+ <Plus size={13} />
+ {t("notesView.newNote")}
+ </Button>
+ </div>
+
+ {isLoading ? (
+ <div className="rounded-lg border border-border bg-card/50 dark:bg-card/60 backdrop-blur-sm">
+ <div className="flex items-center justify-center gap-2 py-8">
+ <Loader2 size={14} className="animate-spin text-primary" />
+ <span className="text-sm text-muted-foreground">{t("controlPanel.loading")}</span>
+ </div>
+ </div>
+ ) : query.trim() && displayedNotes.length === 0 ? (
+ <div className="rounded-lg border border-border bg-card/50 dark:bg-card/60 backdrop-blur-sm">
+ <div className="flex flex-col items-center justify-center py-16 px-4">
+ <h3 className="text-xs font-semibold text-foreground/70 dark:text-foreground/60 mb-1">
+ {t("notesView.searchEmpty.title")}
+ </h3>
+ <p className="text-xs text-foreground/50 dark:text-foreground/25">
+ {t("notesView.searchEmpty.description", { query })}
+ </p>
+ </div>
+ </div>
+ ) : displayedNotes.length === 0 ? (
+ <div className="rounded-lg border border-border bg-card/50 dark:bg-card/60 backdrop-blur-sm">
+ <div className="flex flex-col items-center justify-center py-16 px-4">
+ <StickyNote
+ size={40}
+ className="text-foreground/10 dark:text-foreground/8 mb-4"
+ strokeWidth={1.25}
+ />
+ <h3 className="text-xs font-semibold text-foreground/70 dark:text-foreground/60 mb-1">
+ {t("notesView.empty.title")}
+ </h3>
+ <p className="text-xs text-foreground/50 dark:text-foreground/25 mb-4">
+ {t("notesView.empty.description")}
+ </p>
+ <Button size="sm" className="h-7 text-xs gap-1.5" onClick={onNewNote}>
+ <Plus size={12} />
+ {t("notesView.newNote")}
+ </Button>
+ </div>
+ </div>
+ ) : (
+ <div>
+ {groupedNotes.map((group, index) => (
+ <div key={group.label} className={index > 0 ? "mt-4" : ""}>
+ <div className="sticky -top-1 z-10 -mx-4 px-5 pt-2 pb-2 bg-background">
+ <span className="text-[11px] font-semibold text-muted-foreground dark:text-muted-foreground uppercase tracking-wide">
+ {group.label}
+ </span>
+ </div>
+ <div className="space-y-1.5 relative z-0">
+ {group.items.map((note) => {
+ const isActive = note.id === activeNoteId;
+ const preview = stripMarkdown(note.content).slice(0, 120);
+
+ return (
+ <button
+ key={note.id}
+ type="button"
+ onClick={() => onNoteSelect(note.id)}
+ className={cn(
+ "group w-full text-left rounded-lg border px-4 py-3 transition-all duration-150",
+ "focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-primary/30",
+ isActive
+ ? "border-primary/20 bg-primary/5 dark:bg-primary/8"
+ : "border-border/50 bg-card/50 dark:bg-card/60 hover:border-border hover:bg-card dark:hover:bg-card/80"
+ )}
+ >
+ <div className="flex items-start justify-between gap-2">
+ <p
+ className={cn(
+ "text-xs font-medium truncate text-foreground",
+ !note.title && "italic text-foreground/40"
+ )}
+ >
+ {note.title || t("notes.list.untitled")}
+ </p>
+ <div className="flex items-center gap-1.5 shrink-0">
+ <span
+ className={cn(
+ "text-[10px] font-medium px-1.5 py-px rounded-sm",
+ NOTE_TYPE_COLORS[note.note_type]
+ )}
+ >
+ {t(`notesView.noteType.${note.note_type}`)}
+ </span>
+ <span className="text-xs text-muted-foreground/60 dark:text-muted-foreground/30 tabular-nums">
+ {relativeTime(note.updated_at, t)}
+ </span>
+ </div>
+ </div>
+ {preview && (
+ <p className="text-xs text-muted-foreground/70 dark:text-muted-foreground/35 mt-0.5 line-clamp-1">
+ {preview}
+ </p>
+ )}
+ </button>
+ );
+ })}
+ </div>
+ </div>
+ ))}
+ </div>
+ )}
+ </div>
+ </div>
+ );
+}
diff --git a/src/components/SettingsPage.tsx b/src/components/SettingsPage.tsx
index 49e265165..bd51458d2 100644
--- a/src/components/SettingsPage.tsx
+++ b/src/components/SettingsPage.tsx
@@ -62,6 +62,7 @@ import logger from "../utils/logger";
import { SettingsRow } from "./ui/SettingsSection";
import { useUsage } from "../hooks/useUsage";
import { cn } from "./lib/utils";
+import { startMigration, useMigration } from "../stores/noteStore.js";
export type SettingsSectionType =
| "account"
@@ -679,6 +680,8 @@ export default function SettingsPage({ activeSection = "general" }: SettingsPage
setFloatingIconAutoHide,
cloudBackupEnabled,
setCloudBackupEnabled,
+ cloudNotesEnabled,
+ setCloudNotesEnabled,
telemetryEnabled,
setTelemetryEnabled,
customDictionary,
@@ -712,6 +715,8 @@ export default function SettingsPage({ activeSection = "general" }: SettingsPage
const isUpdateAvailable =
!updateStatus.isDevelopment && (updateStatus.updateAvailable || updateStatus.updateDownloaded);
+ const migration = useMigration();
+
const whisperHook = useWhisper();
const permissionsHook = usePermissions(showAlertDialog);
useClipboard(showAlertDialog);
@@ -2343,16 +2348,57 @@ export default function SettingsPage({ activeSection = "general" }: SettingsPage
/>
{isSignedIn && (
- <SettingsPanel className="mb-4">
- <SettingsPanelRow>
- <SettingsRow
- label={t("settingsPage.privacy.cloudBackup")}
- description={t("settingsPage.privacy.cloudBackupDescription")}
- >
- <Toggle checked={cloudBackupEnabled} onChange={setCloudBackupEnabled} />
- </SettingsRow>
- </SettingsPanelRow>
- </SettingsPanel>
+ <div className="mb-4">
+ <SettingsPanel className="mb-2">
+ <SettingsPanelRow>
+ <SettingsRow
+ label={t("settingsPage.privacy.cloudBackup")}
+ description={t("settingsPage.privacy.cloudBackupDescription")}
+ >
+ <Toggle checked={cloudBackupEnabled} onChange={setCloudBackupEnabled} />
+ </SettingsRow>
+ </SettingsPanelRow>
+ <SettingsPanelRow>
+ <SettingsRow
+ label={t("settingsPage.privacy.cloudNotesBackup")}
+ description={t("settingsPage.privacy.cloudNotesBackupDescription")}
+ >
+ <Toggle
+ checked={cloudNotesEnabled}
+ onChange={(v) => {
+ setCloudNotesEnabled(v);
+ if (v) startMigration().catch(console.error);
+ }}
+ />
+ </SettingsRow>
+ </SettingsPanelRow>
+ </SettingsPanel>
+ {migration && (
+ <div className="mt-2 space-y-1">
+ <div className="flex items-center justify-between text-xs text-muted-foreground">
+ <span className="flex items-center gap-1.5">
+ <Loader2 className="h-3 w-3 animate-spin" />
+ {t("settingsPage.privacy.cloudNotesMigration", {
+ done: migration.done,
+ total: migration.total,
+ })}
+ </span>
+ <span>{Math.round((migration.done / migration.total) * 100)}%</span>
+ </div>
+ <div className="h-1 w-full rounded-full bg-muted overflow-hidden">
+ <div
+ className="h-full bg-primary transition-all duration-300 ease-out"
+ style={{ width: `${(migration.done / migration.total) * 100}%` }}
+ />
+ </div>
+ </div>
+ )}
+ {!migration && cloudNotesEnabled && isSignedIn && (
+ <p className="mt-1 text-xs text-muted-foreground">
+ {t("settingsPage.privacy.cloudNotesMigrationDone")}
+ </p>
+ )}
+ </div>
)}
<SettingsPanel>
diff --git a/src/helpers/database.js b/src/helpers/database.js
index 423c8faa7..00b43622d 100644
--- a/src/helpers/database.js
+++ b/src/helpers/database.js
@@ -65,6 +65,54 @@ class DatabaseManager {
} catch (err) {
if (!err.message.includes("duplicate column")) throw err;
}
+ try {
+ this.db.exec("ALTER TABLE notes ADD COLUMN cloud_id TEXT");
+ } catch (err) {
+ if (!err.message.includes("duplicate column")) throw err;
+ }
+
+ this.db.exec(`
+ CREATE VIRTUAL TABLE IF NOT EXISTS notes_fts USING fts5(
+ title,
+ content,
+ enhanced_content,
+ content='notes',
+ content_rowid='id'
+ )
+ `);
+
+ this.db.exec(`
+ CREATE TRIGGER IF NOT EXISTS notes_fts_insert AFTER INSERT ON notes BEGIN
+ INSERT INTO notes_fts(rowid, title, content, enhanced_content)
+ VALUES (new.id, new.title, new.content, new.enhanced_content);
+ END
+ `);
+
+ this.db.exec(`
+ CREATE TRIGGER IF NOT EXISTS notes_fts_update AFTER UPDATE ON notes BEGIN
+ INSERT INTO notes_fts(notes_fts, rowid, title, content, enhanced_content)
+ VALUES ('delete', old.id, old.title, old.content, old.enhanced_content);
+ INSERT INTO notes_fts(rowid, title, content, enhanced_content)
+ VALUES (new.id, new.title, new.content, new.enhanced_content);
+ END
+ `);
+
+ this.db.exec(`
+ CREATE TRIGGER IF NOT EXISTS notes_fts_delete AFTER DELETE ON notes BEGIN
+ INSERT INTO notes_fts(notes_fts, rowid, title, content, enhanced_content)
+ VALUES ('delete', old.id, old.title, old.content, old.enhanced_content);
+ END
+ `);
+
+ this.db
+ .prepare(
+ `
+ INSERT OR IGNORE INTO notes_fts(rowid, title, content, enhanced_content)
+ SELECT id, COALESCE(title, ''), COALESCE(content, ''), COALESCE(enhanced_content, '')
+ FROM notes
+ `
+ )
+ .run();
this.db.exec(`
CREATE TABLE IF NOT EXISTS folders (
@@ -530,6 +578,44 @@ class DatabaseManager {
}
}
+ searchNotes(query, limit = 50) {
+ try {
+ if (!this.db) throw new Error("Database not initialized");
+ const term = query
+ .trim()
+ .replace(/[^\w\s]/g, " ")
+ .trim();
+ if (!term) return [];
+ return this.db
+ .prepare(
+ `
+ SELECT n.*
+ FROM notes n
+ JOIN notes_fts ON notes_fts.rowid = n.id
+ WHERE notes_fts MATCH ?
+ AND n.deleted_at IS NULL
+ ORDER BY notes_fts.rank
+ LIMIT ?
+ `
+ )
+ .all(term + "*", limit);
+ } catch (error) {
+ debugLogger.error("Error searching notes", { error: error.message }, "database");
+ throw error;
+ }
+ }
+
+ updateNoteCloudId(id, cloudId) {
+ try {
+ if (!this.db) throw new Error("Database not initialized");
+ this.db.prepare("UPDATE notes SET cloud_id = ? WHERE id = ?").run(cloudId, id);
+ return this.db.prepare("SELECT * FROM notes WHERE id = ?").get(id);
+ } catch (error) {
+ debugLogger.error("Error updating note cloud_id", { error: error.message }, "database");
+ throw error;
+ }
+ }
+
cleanup() {
try {
const dbPath = path.join(
diff --git a/src/helpers/ipcHandlers.js b/src/helpers/ipcHandlers.js
index d6f4eac20..f585c8e50 100644
--- a/src/helpers/ipcHandlers.js
+++ b/src/helpers/ipcHandlers.js
@@ -446,6 +446,14 @@ class IPCHandlers {
return result;
});
+ ipcMain.handle("db-search-notes", async (event, query, limit) => {
+ return this.databaseManager.searchNotes(query, limit);
+ });
+
+ ipcMain.handle("db-update-note-cloud-id", async (event, id, cloudId) => {
+ return this.databaseManager.updateNoteCloudId(id, cloudId);
+ });
+
ipcMain.handle("db-get-folders", async () => {
return this.databaseManager.getFolders();
});
diff --git a/src/hooks/useSettings.ts b/src/hooks/useSettings.ts
index 230576d8f..34a5d2dba 100644
--- a/src/hooks/useSettings.ts
+++ b/src/hooks/useSettings.ts
@@ -52,6 +52,7 @@ export interface ApiKeySettings {
export interface PrivacySettings {
cloudBackupEnabled: boolean;
+ cloudNotesEnabled: boolean;
telemetryEnabled: boolean;
}
@@ -223,6 +224,8 @@ function useSettingsInternal() {
setAutoLearnCorrections,
cloudBackupEnabled: store.cloudBackupEnabled,
setCloudBackupEnabled: store.setCloudBackupEnabled,
+ cloudNotesEnabled: store.cloudNotesEnabled,
+ setCloudNotesEnabled: store.setCloudNotesEnabled,
telemetryEnabled: store.telemetryEnabled,
setTelemetryEnabled: store.setTelemetryEnabled,
updateTranscriptionSettings: store.updateTranscriptionSettings,
diff --git a/src/locales/de/translation.json b/src/locales/de/translation.json
index fe5547928..4765a26d2 100644
--- a/src/locales/de/translation.json
+++ b/src/locales/de/translation.json
@@ -1159,6 +1159,10 @@
"privacy": {
"cloudBackup": "Cloud-Backup",
"cloudBackupDescription": "Speichern Sie Ihre Transkriptionen in der Cloud, damit sie nicht verloren gehen.",
+ "cloudNotesBackup": "Notizen in der Cloud sichern",
+ "cloudNotesBackupDescription": "Synchronisieren Sie Ihre Notizen mit der Cloud für semantische Suche und geräteübergreifenden Zugriff.",
+ "cloudNotesMigration": "Notizen werden gesichert… {{done}} / {{total}}",
+ "cloudNotesMigrationDone": "Alle Notizen gesichert",
"description": "Steuern Sie, welche Daten Ihr Gerät verlassen. Standardmäßig ist alles deaktiviert.",
"title": "Datenschutz",
"usageAnalytics": "Nutzungsanalysen",
@@ -1595,5 +1599,29 @@
"redirectTitle": "Weiterleitung zur App...",
"closeTab": "Du kannst diesen Tab schließen."
}
+ },
+ "notesView": {
+ "searchPlaceholder": "Notizen durchsuchen…",
+ "newNote": "Neue Notiz",
+ "empty": {
+ "title": "Noch keine Notizen",
+ "description": "Erstellen Sie Ihre erste Notiz, um zu beginnen."
+ },
+ "searchEmpty": {
+ "title": "Keine Ergebnisse",
+ "description": "Keine Notizen für \u201e{{query}}\u201c gefunden."
+ },
+ "noteType": {
+ "personal": "persönlich",
+ "meeting": "Meeting",
+ "upload": "Upload"
+ }
+ },
+ "noteEditor": {
+ "saved": "Gespeichert",
+ "deleteNote": "Notiz löschen",
+ "deleteConfirmTitle": "Notiz löschen?",
+ "deleteConfirmDescription": "Diese Notiz wird dauerhaft gelöscht und kann nicht wiederhergestellt werden.",
+ "deleteConfirm": "Löschen"
}
}
diff --git a/src/locales/en/translation.json b/src/locales/en/translation.json
index cd2922bc0..63553cb71 100644
--- a/src/locales/en/translation.json
+++ b/src/locales/en/translation.json
@@ -1159,6 +1159,10 @@
"privacy": {
"cloudBackup": "Cloud backup",
"cloudBackupDescription": "Save your transcriptions to the cloud so you never lose them.",
+ "cloudNotesBackup": "Back up notes to the cloud",
+ "cloudNotesBackupDescription": "Sync your notes to the cloud to enable semantic search and cross-device access.",
+ "cloudNotesMigration": "Backing up notes… {{done}} / {{total}}",
+ "cloudNotesMigrationDone": "All notes backed up",
"description": "Control what data leaves your device. Everything is off by default.",
"title": "Privacy",
"usageAnalytics": "Usage analytics",
@@ -1595,5 +1599,29 @@
"redirectTitle": "Redirecting to app...",
"closeTab": "You can close this tab."
}
+ },
+ "notesView": {
+ "searchPlaceholder": "Search notes…",
+ "newNote": "New Note",
+ "empty": {
+ "title": "No notes yet",
+ "description": "Create your first note to get started."
+ },
+ "searchEmpty": {
+ "title": "No results",
+ "description": "No notes found for \"{{query}}\"."
+ },
+ "noteType": {
+ "personal": "personal",
+ "meeting": "meeting",
+ "upload": "upload"
+ }
+ },
+ "noteEditor": {
+ "saved": "Saved",
+ "deleteNote": "Delete note",
+ "deleteConfirmTitle": "Delete note?",
+ "deleteConfirmDescription": "This note will be permanently deleted and cannot be recovered.",
+ "deleteConfirm": "Delete"
}
}
diff --git a/src/locales/es/translation.json b/src/locales/es/translation.json
index c8df40722..4fd0e4a07 100644
--- a/src/locales/es/translation.json
+++ b/src/locales/es/translation.json
@@ -1163,6 +1163,10 @@
"privacy": {
"cloudBackup": "Respaldo en la nube",
"cloudBackupDescription": "Guarda tus transcripciones en la nube para no perderlas nunca.",
+ "cloudNotesBackup": "Respaldar notas en la nube",
+ "cloudNotesBackupDescription": "Sincroniza tus notas con la nube para habilitar búsqueda semántica y acceso desde cualquier dispositivo.",
+ "cloudNotesMigration": "Respaldando notas… {{done}} / {{total}}",
+ "cloudNotesMigrationDone": "Todas las notas respaldadas",
"description": "Controla qué datos salen de tu dispositivo. Todo está desactivado por defecto.",
"title": "Privacidad",
"usageAnalytics": "Analíticas de uso",
@@ -1599,5 +1603,29 @@
"redirectTitle": "Redirigiendo a la app...",
"closeTab": "Puedes cerrar esta pestaña."
}
+ },
+ "notesView": {
+ "searchPlaceholder": "Buscar notas…",
+ "newNote": "Nueva nota",
+ "empty": {
+ "title": "Sin notas todavía",
+ "description": "Crea tu primera nota para empezar."
+ },
+ "searchEmpty": {
+ "title": "Sin resultados",
+ "description": "No se encontraron notas para \"{{query}}\"."
+ },
+ "noteType": {
+ "personal": "personal",
+ "meeting": "reunión",
+ "upload": "subida"
+ }
+ },
+ "noteEditor": {
+ "saved": "Guardado",
+ "deleteNote": "Eliminar nota",
+ "deleteConfirmTitle": "¿Eliminar nota?",
+ "deleteConfirmDescription": "Esta nota se eliminará permanentemente y no se podrá recuperar.",
+ "deleteConfirm": "Eliminar"
}
}
diff --git a/src/locales/fr/translation.json b/src/locales/fr/translation.json
index 96d2e1741..211c1fc23 100644
--- a/src/locales/fr/translation.json
+++ b/src/locales/fr/translation.json
@@ -1163,6 +1163,10 @@
"privacy": {
"cloudBackup": "Sauvegarde cloud",
"cloudBackupDescription": "Sauvegardez vos transcriptions dans le cloud pour ne jamais les perdre.",
+ "cloudNotesBackup": "Sauvegarder les notes dans le cloud",
+ "cloudNotesBackupDescription": "Synchronisez vos notes avec le cloud pour activer la recherche sémantique et l'accès multi-appareils.",
+ "cloudNotesMigration": "Sauvegarde des notes… {{done}} / {{total}}",
+ "cloudNotesMigrationDone": "Toutes les notes sauvegardées",
"description": "Contrôlez quelles données quittent votre appareil. Tout est désactivé par défaut.",
"title": "Confidentialité",
"usageAnalytics": "Analyse d'utilisation",
@@ -1599,5 +1603,29 @@
"redirectTitle": "Redirection vers l'app...",
"closeTab": "Vous pouvez fermer cet onglet."
}
+ },
+ "notesView": {
+ "searchPlaceholder": "Rechercher des notes…",
+ "newNote": "Nouvelle note",
+ "empty": {
+ "title": "Aucune note pour l'instant",
+ "description": "Créez votre première note pour commencer."
+ },
+ "searchEmpty": {
+ "title": "Aucun résultat",
+ "description": "Aucune note trouvée pour « {{query}} »."
+ },
+ "noteType": {
+ "personal": "personnel",
+ "meeting": "réunion",
+ "upload": "import"
+ }
+ },
+ "noteEditor": {
+ "saved": "Enregistré",
+ "deleteNote": "Supprimer la note",
+ "deleteConfirmTitle": "Supprimer la note ?",
+ "deleteConfirmDescription": "Cette note sera supprimée définitivement et ne pourra pas être récupérée.",
+ "deleteConfirm": "Supprimer"
}
}
diff --git a/src/locales/it/translation.json b/src/locales/it/translation.json
index c71f63dfc..831030549 100644
--- a/src/locales/it/translation.json
+++ b/src/locales/it/translation.json
@@ -1163,6 +1163,10 @@
"privacy": {
"cloudBackup": "Backup cloud",
"cloudBackupDescription": "Salva le trascrizioni nel cloud per non perderle mai.",
+ "cloudNotesBackup": "Esegui il backup delle note nel cloud",
+ "cloudNotesBackupDescription": "Sincronizza le tue note con il cloud per abilitare la ricerca semantica e l'accesso da più dispositivi.",
+ "cloudNotesMigration": "Backup delle note in corso… {{done}} / {{total}}",
+ "cloudNotesMigrationDone": "Tutte le note salvate nel cloud",
"description": "Controlla quali dati escono dal tuo dispositivo. Tutto è disattivato per impostazione predefinita.",
"title": "Privacy",
"usageAnalytics": "Analisi dell'utilizzo",
@@ -1599,5 +1603,29 @@
"redirectTitle": "Reindirizzamento all'app...",
"closeTab": "Puoi chiudere questa scheda."
}
+ },
+ "notesView": {
+ "searchPlaceholder": "Cerca note…",
+ "newNote": "Nuova nota",
+ "empty": {
+ "title": "Nessuna nota ancora",
+ "description": "Crea la tua prima nota per iniziare."
+ },
+ "searchEmpty": {
+ "title": "Nessun risultato",
+ "description": "Nessuna nota trovata per «{{query}}»."
+ },
+ "noteType": {
+ "personal": "personale",
+ "meeting": "riunione",
+ "upload": "caricamento"
+ }
+ },
+ "noteEditor": {
+ "saved": "Salvato",
+ "deleteNote": "Elimina nota",
+ "deleteConfirmTitle": "Eliminare la nota?",
+ "deleteConfirmDescription": "Questa nota verrà eliminata definitivamente e non potrà essere recuperata.",
+ "deleteConfirm": "Elimina"
}
}
diff --git a/src/locales/ja/translation.json b/src/locales/ja/translation.json
index 6a166b211..32de38cc6 100644
--- a/src/locales/ja/translation.json
+++ b/src/locales/ja/translation.json
@@ -1159,6 +1159,10 @@
"privacy": {
"cloudBackup": "クラウドバックアップ",
"cloudBackupDescription": "文字起こしをクラウドに保存してデータを失わないようにします。",
+ "cloudNotesBackup": "ノートをクラウドにバックアップ",
+ "cloudNotesBackupDescription": "ノートをクラウドに同期してセマンティック検索と複数デバイスでのアクセスを有効にします。",
+ "cloudNotesMigration": "ノートをバックアップ中… {{done}} / {{total}}",
+ "cloudNotesMigrationDone": "すべてのノートがバックアップされました",
"description": "デバイスからのデータ送信を管理します。初期設定ではすべてオフです。",
"title": "プライバシー",
"usageAnalytics": "使用状況の分析",
@@ -1595,5 +1599,29 @@
"redirectTitle": "アプリにリダイレクト中...",
"closeTab": "このタブを閉じてください。"
}
+ },
+ "notesView": {
+ "searchPlaceholder": "ノートを検索…",
+ "newNote": "新しいノート",
+ "empty": {
+ "title": "ノートがまだありません",
+ "description": "最初のノートを作成してください。"
+ },
+ "searchEmpty": {
+ "title": "結果なし",
+ "description": "「{{query}}」に一致するノートが見つかりませんでした。"
+ },
+ "noteType": {
+ "personal": "個人",
+ "meeting": "会議",
+ "upload": "アップロード"
+ }
+ },
+ "noteEditor": {
+ "saved": "保存済み",
+ "deleteNote": "ノートを削除",
+ "deleteConfirmTitle": "ノートを削除しますか?",
+ "deleteConfirmDescription": "このノートは完全に削除され、復元できません。",
+ "deleteConfirm": "削除"
}
}
diff --git a/src/locales/pt/translation.json b/src/locales/pt/translation.json
index e62f39dba..04b1c4b5a 100644
--- a/src/locales/pt/translation.json
+++ b/src/locales/pt/translation.json
@@ -1135,6 +1135,10 @@
"privacy": {
"cloudBackup": "Backup na nuvem",
"cloudBackupDescription": "Salve suas transcrições na nuvem para nunca perdê-las.",
+ "cloudNotesBackup": "Fazer backup das notas na nuvem",
+ "cloudNotesBackupDescription": "Sincronize suas notas com a nuvem para ativar pesquisa semântica e acesso em múltiplos dispositivos.",
+ "cloudNotesMigration": "Fazendo backup das notas… {{done}} / {{total}}",
+ "cloudNotesMigrationDone": "Todas as notas salvas na nuvem",
"description": "Controle quais dados saem do seu dispositivo. Tudo está desativado por padrão.",
"title": "Privacidade",
"usageAnalytics": "Análise de uso",
@@ -1599,5 +1603,29 @@
"redirectTitle": "Redirecionando para o app...",
"closeTab": "Você pode fechar esta aba."
}
+ },
+ "notesView": {
+ "searchPlaceholder": "Pesquisar notas…",
+ "newNote": "Nova nota",
+ "empty": {
+ "title": "Nenhuma nota ainda",
+ "description": "Crie sua primeira nota para começar."
+ },
+ "searchEmpty": {
+ "title": "Sem resultados",
+ "description": "Nenhuma nota encontrada para \"{{query}}\"."
+ },
+ "noteType": {
+ "personal": "pessoal",
+ "meeting": "reunião",
+ "upload": "upload"
+ }
+ },
+ "noteEditor": {
+ "saved": "Salvo",
+ "deleteNote": "Excluir nota",
+ "deleteConfirmTitle": "Excluir nota?",
+ "deleteConfirmDescription": "Esta nota será excluída permanentemente e não poderá ser recuperada.",
+ "deleteConfirm": "Excluir"
}
}
diff --git a/src/locales/ru/translation.json b/src/locales/ru/translation.json
index 977d90c08..6d7943987 100644
--- a/src/locales/ru/translation.json
+++ b/src/locales/ru/translation.json
@@ -1163,6 +1163,10 @@
"privacy": {
"cloudBackup": "Облачное резервное копирование",
"cloudBackupDescription": "Сохраняйте транскрипции в облаке, чтобы никогда их не потерять.",
+ "cloudNotesBackup": "Резервное копирование заметок в облако",
+ "cloudNotesBackupDescription": "Синхронизируйте заметки с облаком для семантического поиска и доступа с разных устройств.",
+ "cloudNotesMigration": "Резервное копирование заметок… {{done}} / {{total}}",
+ "cloudNotesMigrationDone": "Все заметки скопированы в облако",
"description": "Контролируйте, какие данные покидают ваше устройство. По умолчанию всё отключено.",
"title": "Конфиденциальность",
"usageAnalytics": "Аналитика использования",
@@ -1599,5 +1603,29 @@
"redirectTitle": "Перенаправление в приложение...",
"closeTab": "Можете закрыть эту вкладку."
}
+ },
+ "notesView": {
+ "searchPlaceholder": "Поиск заметок…",
+ "newNote": "Новая заметка",
+ "empty": {
+ "title": "Заметок пока нет",
+ "description": "Создайте первую заметку, чтобы начать."
+ },
+ "searchEmpty": {
+ "title": "Нет результатов",
+ "description": "По запросу «{{query}}» заметки не найдены."
+ },
+ "noteType": {
+ "personal": "личная",
+ "meeting": "встреча",
+ "upload": "загрузка"
+ }
+ },
+ "noteEditor": {
+ "saved": "Сохранено",
+ "deleteNote": "Удалить заметку",
+ "deleteConfirmTitle": "Удалить заметку?",
+ "deleteConfirmDescription": "Эта заметка будет удалена безвозвратно.",
+ "deleteConfirm": "Удалить"
}
}
diff --git a/src/locales/zh-CN/translation.json b/src/locales/zh-CN/translation.json
index 6011ba8b6..2fd0515a3 100644
--- a/src/locales/zh-CN/translation.json
+++ b/src/locales/zh-CN/translation.json
@@ -1159,6 +1159,10 @@
"privacy": {
"cloudBackup": "云端备份",
"cloudBackupDescription": "将转录记录保存到云端,确保永不丢失。",
+ "cloudNotesBackup": "将笔记备份到云端",
+ "cloudNotesBackupDescription": "将笔记同步到云端,以启用语义搜索和跨设备访问。",
+ "cloudNotesMigration": "正在备份笔记… {{done}} / {{total}}",
+ "cloudNotesMigrationDone": "所有笔记已备份",
"description": "控制哪些数据会离开你的设备。默认全部关闭。",
"title": "隐私",
"usageAnalytics": "使用分析",
@@ -1595,5 +1599,29 @@
"redirectTitle": "正在跳转到应用...",
"closeTab": "您可以关闭此标签页。"
}
+ },
+ "notesView": {
+ "searchPlaceholder": "搜索笔记…",
+ "newNote": "新建笔记",
+ "empty": {
+ "title": "暂无笔记",
+ "description": "创建你的第一条笔记开始使用。"
+ },
+ "searchEmpty": {
+ "title": "无结果",
+ "description": "未找到与\u201c{{query}}\u201d匹配的笔记。"
+ },
+ "noteType": {
+ "personal": "个人",
+ "meeting": "会议",
+ "upload": "上传"
+ }
+ },
+ "noteEditor": {
+ "saved": "已保存",
+ "deleteNote": "删除笔记",
+ "deleteConfirmTitle": "删除笔记?",
+ "deleteConfirmDescription": "此笔记将被永久删除,无法恢复。",
+ "deleteConfirm": "删除"
}
}
diff --git a/src/locales/zh-TW/translation.json b/src/locales/zh-TW/translation.json
index ed2b16179..167a4cdfd 100644
--- a/src/locales/zh-TW/translation.json
+++ b/src/locales/zh-TW/translation.json
@@ -1159,6 +1159,10 @@
"privacy": {
"cloudBackup": "雲端備份",
"cloudBackupDescription": "將轉錄記錄儲存至雲端,確保不會遺失。",
+ "cloudNotesBackup": "將筆記備份至雲端",
+ "cloudNotesBackupDescription": "將筆記同步至雲端,啟用語義搜尋及跨裝置存取。",
+ "cloudNotesMigration": "正在備份筆記… {{done}} / {{total}}",
+ "cloudNotesMigrationDone": "所有筆記已備份",
"description": "控制哪些資料會離開你的裝置。預設全部關閉。",
"title": "隱私權",
"usageAnalytics": "使用分析",
@@ -1595,5 +1599,29 @@
"redirectTitle": "正在跳轉到應用程式...",
"closeTab": "您可以關閉此分頁。"
}
+ },
+ "notesView": {
+ "searchPlaceholder": "搜尋筆記…",
+ "newNote": "新建筆記",
+ "empty": {
+ "title": "尚無筆記",
+ "description": "建立你的第一則筆記開始使用。"
+ },
+ "searchEmpty": {
+ "title": "無結果",
+ "description": "找不到與「{{query}}」相符的筆記。"
+ },
+ "noteType": {
+ "personal": "個人",
+ "meeting": "會議",
+ "upload": "上傳"
+ }
+ },
+ "noteEditor": {
+ "saved": "已儲存",
+ "deleteNote": "刪除筆記",
+ "deleteConfirmTitle": "刪除筆記?",
+ "deleteConfirmDescription": "此筆記將被永久刪除,無法復原。",
+ "deleteConfirm": "刪除"
}
}
diff --git a/src/services/NotesService.ts b/src/services/NotesService.ts
new file mode 100644
index 000000000..4d8dae576
--- /dev/null
+++ b/src/services/NotesService.ts
@@ -0,0 +1,101 @@
+import { OPENWHISPR_API_URL } from "../config/constants.js";
+
+interface NoteInput {
+ client_note_id?: string;
+ title?: string | null;
+ content?: string;
+ enhanced_content?: string | null;
+ enhancement_prompt?: string | null;
+ note_type?: "personal" | "meeting" | "upload";
+ source_file?: string | null;
+ audio_duration_seconds?: number | null;
+ created_at?: string;
+ updated_at?: string;
+}
+
+interface CloudNote {
+ id: string;
+ client_note_id: string | null;
+ title: string | null;
+ content: string;
+ enhanced_content: string | null;
+ note_type: string;
+ created_at: string;
+ updated_at: string;
+}
+
+interface SearchResult extends CloudNote {
+ score: number;
+}
+
+async function create(note: NoteInput): Promise<CloudNote> {
+ const res = await fetch(`${OPENWHISPR_API_URL}/api/notes/create`, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ credentials: "include",
+ body: JSON.stringify(note),
+ });
+ if (!res.ok) throw new Error(await res.text());
+ return res.json() as Promise<CloudNote>;
+}
+
+async function batchCreate(
+ notes: NoteInput[]
+): Promise<{ created: { client_note_id: string; id: string }[] }> {
+ const res = await fetch(`${OPENWHISPR_API_URL}/api/notes/batch-create`, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ credentials: "include",
+ body: JSON.stringify({ notes }),
+ });
+ if (!res.ok) throw new Error(await res.text());
+ return res.json() as Promise<{ created: { client_note_id: string; id: string }[] }>;
+}
+
+async function update(id: string, updates: Partial<NoteInput>): Promise<CloudNote> {
+ const res = await fetch(`${OPENWHISPR_API_URL}/api/notes/update`, {
+ method: "PATCH",
+ headers: { "Content-Type": "application/json" },
+ credentials: "include",
+ body: JSON.stringify({ id, ...updates }),
+ });
+ if (!res.ok) throw new Error(await res.text());
+ return res.json() as Promise<CloudNote>;
+}
+
+async function deleteNote(id: string): Promise<void> {
+ const res = await fetch(`${OPENWHISPR_API_URL}/api/notes/delete`, {
+ method: "DELETE",
+ headers: { "Content-Type": "application/json" },
+ credentials: "include",
+ body: JSON.stringify({ id }),
+ });
+ if (!res.ok) throw new Error(await res.text());
+}
+
+async function list(limit?: number, before?: string): Promise<{ notes: CloudNote[] }> {
+ const params = new URLSearchParams();
+ if (limit !== undefined) params.set("limit", String(limit));
+ if (before !== undefined) params.set("before", before);
+ const query = params.toString();
+ const res = await fetch(`${OPENWHISPR_API_URL}/api/notes/list${query ? `?${query}` : ""}`, {
+ credentials: "include",
+ });
+ if (!res.ok) throw new Error(await res.text());
+ return res.json() as Promise<{ notes: CloudNote[] }>;
+}
+
+async function search(query: string, limit?: number): Promise<{ notes: SearchResult[] }> {
+ const res = await fetch(`${OPENWHISPR_API_URL}/api/notes/search`, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ credentials: "include",
+ body: JSON.stringify({ query, ...(limit !== undefined ? { limit } : {}) }),
+ });
+ if (!res.ok) throw new Error(await res.text());
+ return res.json() as Promise<{ notes: SearchResult[] }>;
+}
+
+export { create, batchCreate, update, deleteNote, list, search };
+
+export const NotesService = { create, batchCreate, update, delete: deleteNote, list, search };
diff --git a/src/stores/noteStore.ts b/src/stores/noteStore.ts
index 773748d83..10eb2a641 100644
--- a/src/stores/noteStore.ts
+++ b/src/stores/noteStore.ts
@@ -5,12 +5,14 @@ interface NoteState {
notes: NoteItem[];
activeNoteId: number | null;
activeFolderId: number | null;
+ migration: { total: number; done: number } | null;
}
const useNoteStore = create<NoteState>()(() => ({
notes: [],
activeNoteId: null,
activeFolderId: null,
+ migration: null,
}));
let hasBoundIpcListeners = false;
@@ -127,3 +129,90 @@ export function useActiveNoteId(): number | null {
export function useActiveFolderId(): number | null {
return useNoteStore((state) => state.activeFolderId);
}
+
+export function useMigration(): { total: number; done: number } | null {
+ return useNoteStore((state) => state.migration);
+}
+
+export async function syncNoteToCloud(note: NoteItem): Promise<void> {
+ const { NotesService } = await import("../services/NotesService.js");
+ const cloudNote = await NotesService.create({
+ client_note_id: String(note.id),
+ title: note.title,
+ content: note.content,
+ enhanced_content: note.enhanced_content,
+ enhancement_prompt: note.enhancement_prompt,
+ note_type: note.note_type,
+ source_file: note.source_file,
+ audio_duration_seconds: note.audio_duration_seconds,
+ created_at: note.created_at,
+ updated_at: note.updated_at,
+ });
+ await window.electronAPI.updateNoteCloudId(note.id, cloudNote.id);
+ updateNoteInStore({ ...note, cloud_id: cloudNote.id });
+}
+
+export async function syncNoteUpdateToCloud(
+ note: NoteItem,
+ updates: Partial<NoteItem>
+): Promise<void> {
+ const { NotesService } = await import("../services/NotesService.js");
+ if (note.cloud_id) {
+ await NotesService.update(note.cloud_id, updates);
+ } else {
+ await syncNoteToCloud(note);
+ }
+}
+
+export async function syncNoteDeleteToCloud(cloudId: string): Promise<void> {
+ const { NotesService } = await import("../services/NotesService.js");
+ await NotesService.delete(cloudId);
+}
+
+export async function startMigration(): Promise<void> {
+ const allNotes = (await window.electronAPI?.getNotes(null, 9999, null)) ?? [];
+ const unsynced = allNotes.filter((n) => !n.cloud_id);
+ if (unsynced.length === 0) return;
+
+ useNoteStore.setState({ migration: { total: unsynced.length, done: 0 } });
+
+ const { NotesService } = await import("../services/NotesService.js");
+ const CHUNK_SIZE = 50;
+
+ for (let i = 0; i < unsynced.length; i += CHUNK_SIZE) {
+ const chunk = unsynced.slice(i, i + CHUNK_SIZE);
+ try {
+ const { created } = await NotesService.batchCreate(
+ chunk.map((n) => ({
+ client_note_id: String(n.id),
+ title: n.title,
+ content: n.content,
+ enhanced_content: n.enhanced_content,
+ enhancement_prompt: n.enhancement_prompt,
+ note_type: n.note_type,
+ source_file: n.source_file,
+ audio_duration_seconds: n.audio_duration_seconds,
+ created_at: n.created_at,
+ updated_at: n.updated_at,
+ }))
+ );
+ await Promise.all(
+ created.map(({ client_note_id, id: cloudId }) =>
+ window.electronAPI.updateNoteCloudId(parseInt(client_note_id, 10), cloudId)
+ )
+ );
+ useNoteStore.setState((s) => ({
+ migration: s.migration
+ ? {
+ total: s.migration.total,
+ done: Math.min(s.migration.done + chunk.length, s.migration.total),
+ }
+ : null,
+ }));
+ } catch (err) {
+ console.error("Migration chunk failed:", err);
+ }
+ }
+
+ useNoteStore.setState({ migration: null });
+}
diff --git a/src/stores/settingsStore.ts b/src/stores/settingsStore.ts
index 583487d2f..2eee4602f 100644
--- a/src/stores/settingsStore.ts
+++ b/src/stores/settingsStore.ts
@@ -52,6 +52,7 @@ const BOOLEAN_SETTINGS = new Set([
"useReasoningModel",
"preferBuiltInMic",
"cloudBackupEnabled",
+ "cloudNotesEnabled",
"telemetryEnabled",
"audioCuesEnabled",
"floatingIconAutoHide",
@@ -122,6 +123,7 @@ export interface SettingsState
setTheme: (value: "light" | "dark" | "auto") => void;
setCloudBackupEnabled: (value: boolean) => void;
+ setCloudNotesEnabled: (value: boolean) => void;
setTelemetryEnabled: (value: boolean) => void;
setAudioCuesEnabled: (value: boolean) => void;
setFloatingIconAutoHide: (enabled: boolean) => void;
@@ -233,6 +235,7 @@ export const useSettingsStore = create<SettingsState>()((set, get) => ({
return "auto" as const;
})(),
cloudBackupEnabled: readBoolean("cloudBackupEnabled", false),
+ cloudNotesEnabled: readBoolean("cloudNotesEnabled", false),
telemetryEnabled: readBoolean("telemetryEnabled", false),
audioCuesEnabled: readBoolean("audioCuesEnabled", true),
floatingIconAutoHide: readBoolean("floatingIconAutoHide", false),
@@ -357,6 +360,7 @@ export const useSettingsStore = create<SettingsState>()((set, get) => ({
},
setCloudBackupEnabled: createBooleanSetter("cloudBackupEnabled"),
+ setCloudNotesEnabled: createBooleanSetter("cloudNotesEnabled"),
setTelemetryEnabled: createBooleanSetter("telemetryEnabled"),
setAudioCuesEnabled: createBooleanSetter("audioCuesEnabled"),
diff --git a/src/types/electron.ts b/src/types/electron.ts
index 51dcba4df..31d6c252a 100644
--- a/src/types/electron.ts
+++ b/src/types/electron.ts
@@ -18,6 +18,7 @@ export interface NoteItem {
source_file: string | null;
audio_duration_seconds: number | null;
folder_id: number | null;
+ cloud_id: string | null;
created_at: string;
updated_at: string;
}
@@ -323,6 +324,8 @@ declare global {
noteId: number,
format: "txt" | "md"
) => Promise<{ success: boolean; error?: string }>;
+ searchNotes: (query: string, limit?: number) => Promise<NoteItem[]>;
+ updateNoteCloudId: (id: number, cloudId: string) => Promise<NoteItem>;
// Folder operations
getFolders: () => Promise<FolderItem[]>;