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: spaces note content leak
Chadpihaa5336f53e25b
diff --git a/src/components/notes/NoteEditor.tsx b/src/components/notes/NoteEditor.tsxindex fde300ee7..68ae5785e 100644--- a/src/components/notes/NoteEditor.tsx+++ b/src/components/notes/NoteEditor.tsx@@ -96,7 +96,7 @@ function formatNoteDate(dateStr: string): string {export interface Enhancement {content: string;isStale: boolean;- onChange: (content: string) => void;+ onChange: (sourceNoteId: number, content: string) => void;}type MeetingViewMode = "raw" | "transcript" | "enhanced";@@ -173,8 +173,8 @@ function LiveMeetingTranscriptChat({interface NoteEditorProps {note: NoteItem;- onTitleChange: (title: string) => void;- onContentChange: (content: string) => void;+ onTitleChange: (sourceNoteId: number, title: string) => void;+ onContentChange: (sourceNoteId: number, content: string) => void;isSaving: boolean;isRecording: boolean;isProcessing: boolean;@@ -199,7 +199,7 @@ interface NoteEditorProps {onMoveToFolder?: (noteId: number, folderId: number) => void;onCreateFolderAndMove?: (noteId: number, folderName: string) => void;/** Cancels the owner's debounced autosaves before an external copy is applied. */- onCancelPendingSaves?: () => void;+ onCancelPendingSaves?: (noteId: number) => void;}export default function NoteEditor({@@ -712,9 +712,9 @@ export default function NoteEditor({const handleTitleInput = useCallback(() => {if (titleRef.current) {const text = titleRef.current.textContent || "";- onTitleChange(text);+ onTitleChange(note.id, text);}- }, [onTitleChange]);+ }, [note.id, onTitleChange]);const handleTitleKeyDown = useCallback((e: React.KeyboardEvent) => {if (e.key === "Enter") {@@ -739,16 +739,16 @@ export default function NoteEditor({const handleContentChange = useCallback((newValue: string) => {- onContentChange(newValue);+ onContentChange(note.id, newValue);},- [onContentChange]+ [note.id, onContentChange]);const handleEnhancedChange = useCallback((value: string) => {- enhancement?.onChange(value);+ enhancement?.onChange(note.id, value);},- [enhancement]+ [enhancement, note.id]);const handleAskSubmit = useCallback(@@ -774,7 +774,7 @@ export default function NoteEditor({// Cancel any queued autosave FIRST: a pending debounced save holds the// pre-refresh buffer and would both block the editor resync and clobber// the cloud copy in SQLite a second later.- onCancelPendingSaves?.();+ onCancelPendingSaves?.(note.id);const fresh = await window.electronAPI.upsertNoteFromCloud?.(conflict as unknown as Record<string, unknown>,note.folder_id,@@ -784,7 +784,7 @@ export default function NoteEditor({// With no save pending, the owner's external-update resync applies the// fresh copy to the visible editor buffer.if (fresh) updateNoteInStore(fresh);- }, [conflict, note.client_note_id, note.folder_id, note.space_id, onCancelPendingSaves]);+ }, [conflict, note.client_note_id, note.folder_id, note.id, note.space_id, onCancelPendingSaves]);// Keep the local edits, overwriting the cloud revision the user just saw.// Advancing the base first is what lets the next push succeed instead ofdiff --git a/src/components/notes/PersonalNotesView.tsx b/src/components/notes/PersonalNotesView.tsxindex 92d80ad3b..4c6aec269 100644--- a/src/components/notes/PersonalNotesView.tsx+++ b/src/components/notes/PersonalNotesView.tsx@@ -11,6 +11,7 @@ import ActionManagerDialog from "./ActionManagerDialog";import AddNotesToFolderDialog from "./AddNotesToFolderDialog";import { useActionProcessing } from "../../hooks/useActionProcessing";import type { NoteMoveTarget } from "../../hooks/useNoteDragAndDrop";+import type { NoteItem } from "../../types/electron";import {useSettingsStore,selectIsCloudNoteFormattingMode,@@ -57,14 +58,39 @@ import NotesOnboarding from "./NotesOnboarding";import { isRegenerableNoteTitle } from "../../helpers/regenerableNoteTitle";import { markIntroSeen, NOTES_STRUCTURE_INTRO, shouldShowIntro } from "../../lib/versionedIntro";import {- buildPendingNoteUpdates,+ applyNoteDraftMutation,+ collectPendingNoteWrites,+ planNoteTransition,shouldCancelPendingSavesForDelete,+ type NoteEditorDraft,+ type PendingDocumentSnapshot,+ type PendingEnhancedSnapshot,+ type PendingNoteWrite,} from "../../lib/noteEditorPendingSave";function makeContentHash(content: string): string {return String(content.length) + "-" + content.slice(0, 50);}+function draftFromNote(note: NoteItem): NoteEditorDraft {+ return {+ noteId: note.id,+ title: note.title,+ content: note.content,+ enhancedContent: note.enhanced_content ?? null,+ };+}++interface PendingDocumentSave extends PendingDocumentSnapshot {+ readonly timer: ReturnType<typeof setTimeout>;+}++interface PendingEnhancedSave extends PendingEnhancedSnapshot {+ readonly timer: ReturnType<typeof setTimeout>;+}++type PendingSaveReason = "switch" | "overview" | "unmount";+interface PersonalNotesViewProps {onOpenSettings?: (section: string) => void;onOpenSearch?: () => void;@@ -94,70 +120,80 @@ export default function PersonalNotesView({const isSidePanelLayout = isMeetingMode || (isNarrowWindow && activeNoteId != null);const activeFolderId = useActiveFolderId();const [isSaving, setIsSaving] = useState(false);- const [localTitle, setLocalTitle] = useState("");- const [localContent, setLocalContent] = useState("");- const [localEnhancedContent, setLocalEnhancedContent] = useState<string | null>(null);+ const [draft, setDraftState] = useState<NoteEditorDraft | null>(null);+ const draftRef = useRef<NoteEditorDraft | null>(null);const [showActionManager, setShowActionManager] = useState(false);const [showAddNotesDialog, setShowAddNotesDialog] = useState(false);- const saveTimeoutRef = useRef<NodeJS.Timeout | null>(null);- const enhancedSaveTimeoutRef = useRef<NodeJS.Timeout | null>(null);- const activeNoteRef = useRef<number | null>(null);- // The note the editor buffers below currently describe. Moves atomically with- // the buffers so a flush can refuse to write them to the wrong note id.- const bufferOwnerRef = useRef<number | null>(null);- const [syncedNoteId, setSyncedNoteIdState] = useState<number | null>(null);- const localContentRef = useRef(localContent);- const localTitleRef = useRef(localTitle);- const localEnhancedContentRef = useRef(localEnhancedContent);- useEffect(() => {- localContentRef.current = localContent;- localTitleRef.current = localTitle;- }, [localContent, localTitle]);- useEffect(() => {- localEnhancedContentRef.current = localEnhancedContent;- }, [localEnhancedContent]);- const markNoteAsSynced = (id: number | null) => {- activeNoteRef.current = id;- setSyncedNoteIdState(id);- };+ const pendingDocumentRef = useRef<PendingDocumentSave | null>(null);+ const pendingEnhancedRef = useRef<PendingEnhancedSave | null>(null);++ const commitDraft = useCallback((next: NoteEditorDraft | null) => {+ draftRef.current = next;+ setDraftState(next);+ }, []);+// Conflict-banner Refresh applies an external cloud copy: a queued// debounced save would clobber it with the pre-refresh buffer, so the- // editor cancels pending saves before the copy is applied. With the timers- // cleared, the external-update resync effect picks up the fresh note.- const cancelPendingSaves = useCallback(() => {- if (saveTimeoutRef.current) {- clearTimeout(saveTimeoutRef.current);- saveTimeoutRef.current = null;+ // editor cancels pending saves for that note before the copy is applied.+ const cancelPendingSaves = useCallback((noteId: number) => {+ const document = pendingDocumentRef.current;+ if (document?.noteId === noteId) {+ clearTimeout(document.timer);+ pendingDocumentRef.current = null;}- if (enhancedSaveTimeoutRef.current) {- clearTimeout(enhancedSaveTimeoutRef.current);- enhancedSaveTimeoutRef.current = null;+ const enhanced = pendingEnhancedRef.current;+ if (enhanced?.noteId === noteId) {+ clearTimeout(enhanced.timer);+ pendingEnhancedRef.current = null;}}, []);++ const takePendingSnapshots = useCallback((): {+ document: PendingDocumentSnapshot | null;+ enhanced: PendingEnhancedSnapshot | null;+ } => {+ const document = pendingDocumentRef.current;+ const enhanced = pendingEnhancedRef.current;++ if (document) clearTimeout(document.timer);+ if (enhanced) clearTimeout(enhanced.timer);+ pendingDocumentRef.current = null;+ pendingEnhancedRef.current = null;++ return { document, enhanced };+ }, []);++ const persistPendingWrites = useCallback(+ (writes: PendingNoteWrite[], reason: PendingSaveReason) => {+ for (const write of writes) {+ void window.electronAPI.updateNote(write.noteId, write.updates).catch((err: unknown) => {+ logger.warn(+ `Failed to flush note before ${reason}`,+ { error: (err as Error).message },+ "notes"+ );+ });+ }+ },+ []+ );+const flushPendingSaves = useCallback(- (reason: "switch" | "overview" | "unmount") => {- const noteId = activeNoteRef.current;- const updates = buildPendingNoteUpdates({- title: localTitleRef.current,- content: localContentRef.current,- enhancedContent: localEnhancedContentRef.current,- documentPending: saveTimeoutRef.current != null,- enhancedPending: enhancedSaveTimeoutRef.current != null,- bufferOwnerId: bufferOwnerRef.current,- targetNoteId: noteId,- });- cancelPendingSaves();- if (!noteId || !updates) return;-- void window.electronAPI.updateNote(noteId, updates).catch((err: unknown) => {- logger.warn(- `Failed to flush note before ${reason}`,- { error: (err as Error).message },- "notes"- );- });+ (reason: PendingSaveReason) => {+ const pending = takePendingSnapshots();+ persistPendingWrites(collectPendingNoteWrites(pending.document, pending.enhanced), reason);},- [cancelPendingSaves]+ [persistPendingWrites, takePendingSnapshots]+ );++ const transitionToNote = useCallback(+ (nextNote: NoteItem | null, reason: Extract<PendingSaveReason, "switch" | "overview">) => {+ const pending = takePendingSnapshots();+ const transition = planNoteTransition(nextNote, pending.document, pending.enhanced);+ persistPendingWrites(transition.writes, reason);+ commitDraft(transition.nextDraft);+ },+ [commitDraft, persistPendingWrites, takePendingSnapshots]);const { toast } = useToast();const isCloudMode = useSettingsStore(selectIsCloudNoteFormattingMode);@@ -284,8 +320,8 @@ export default function PersonalNotesView({}, [activeNote?.calendar_event_id]);const startRecording = useCallback(async () => {- const noteId = activeNoteRef.current;- const note = activeNote?.id === noteId ? activeNote : null;+ const note = activeNote ?? null;+ const noteId = note?.id ?? null;const seedSegments = note?.transcript ? parseTranscriptSegments(note.transcript) : [];await storeStartRecording({noteId,@@ -302,105 +338,134 @@ export default function PersonalNotesView({}, []);useEffect(() => {- if (activeNote && activeNote.id !== activeNoteRef.current) {- // Drain the old note before changing the ref that owns its save timers.- flushPendingSaves("switch");- markNoteAsSynced(activeNote.id);- setLocalTitle(activeNote.title);- setLocalContent(activeNote.content);- setLocalEnhancedContent(activeNote.enhanced_content ?? null);- localTitleRef.current = activeNote.title;- localContentRef.current = activeNote.content;- localEnhancedContentRef.current = activeNote.enhanced_content ?? null;- bufferOwnerRef.current = activeNote.id;- } else if (- activeNote &&- activeNote.id === activeNoteRef.current &&- !saveTimeoutRef.current &&- !enhancedSaveTimeoutRef.current- ) {- // External update (e.g. AI chat tool) — resync only when no user save is pending- if (activeNote.title !== localTitleRef.current) setLocalTitle(activeNote.title);- if (activeNote.content !== localContentRef.current) setLocalContent(activeNote.content);- if ((activeNote.enhanced_content ?? null) !== localEnhancedContentRef.current) {- setLocalEnhancedContent(activeNote.enhanced_content ?? null);- }- } else if (!activeNote) {+ const currentDraft = draftRef.current;++ if (!activeNote) {// Space/folder activation shows its overview by clearing activeNoteId.- // Persist pending editor buffers before that navigation discards them.- flushPendingSaves("overview");- markNoteAsSynced(null);- setLocalTitle("");- setLocalContent("");- setLocalEnhancedContent(null);- // Clear the buffers synchronously (mirroring the switch branch), so the- // previously-open note's text can't leak into a note created from the- // overview before the async state->ref effect catches up.- localTitleRef.current = "";- localContentRef.current = "";- localEnhancedContentRef.current = null;- bufferOwnerRef.current = null;- }- }, [activeNote, flushPendingSaves]);-- const debouncedSave = useCallback((noteId: number, title: string, content: string) => {- if (saveTimeoutRef.current) clearTimeout(saveTimeoutRef.current);- saveTimeoutRef.current = setTimeout(async () => {- saveTimeoutRef.current = null;- setIsSaving(true);- try {- await window.electronAPI.updateNote(noteId, { title, content });- } catch (err) {- logger.warn("Failed to save note", { error: (err as Error).message }, "notes");- } finally {- setIsSaving(false);+ if (currentDraft || pendingDocumentRef.current || pendingEnhancedRef.current) {+ transitionToNote(null, "overview");}- }, 1000);+ return;+ }++ if (!currentDraft || activeNote.id !== currentDraft.noteId) {+ // Captured writes retain the old owner while the complete next draft is+ // installed atomically.+ transitionToNote(activeNote, "switch");+ return;+ }++ const hasPendingLocalSave =+ pendingDocumentRef.current?.noteId === activeNote.id ||+ pendingEnhancedRef.current?.noteId === activeNote.id;+ if (!hasPendingLocalSave) {+ // External update (e.g. AI chat tool) — replace the complete draft only+ // when it has no local save pending.+ commitDraft(draftFromNote(activeNote));+ }+ }, [activeNote, commitDraft, transitionToNote]);++ const scheduleDocumentSave = useCallback((snapshot: NoteEditorDraft) => {+ const current = pendingDocumentRef.current;+ if (current) clearTimeout(current.timer);++ const pending: PendingDocumentSave = {+ noteId: snapshot.noteId,+ title: snapshot.title,+ content: snapshot.content,+ timer: setTimeout(async () => {+ if (pendingDocumentRef.current !== pending) return;+ pendingDocumentRef.current = null;+ setIsSaving(true);+ try {+ await window.electronAPI.updateNote(pending.noteId, {+ title: pending.title,+ content: pending.content,+ });+ } catch (err) {+ logger.warn("Failed to save note", { error: (err as Error).message }, "notes");+ } finally {+ setIsSaving(false);+ }+ }, 1000),+ };+ pendingDocumentRef.current = pending;}, []);- useEffect(() => {- return () => flushPendingSaves("unmount");- }, [flushPendingSaves]);+ const scheduleEnhancedSave = useCallback((snapshot: NoteEditorDraft) => {+ const current = pendingEnhancedRef.current;+ if (current) clearTimeout(current.timer);++ const pending: PendingEnhancedSave = {+ noteId: snapshot.noteId,+ enhancedContent: snapshot.enhancedContent,+ timer: setTimeout(async () => {+ if (pendingEnhancedRef.current !== pending) return;+ pendingEnhancedRef.current = null;+ setIsSaving(true);+ try {+ await window.electronAPI.updateNote(pending.noteId, {+ enhanced_content: pending.enhancedContent,+ });+ } catch (err) {+ logger.warn(+ "Failed to save enhanced note content",+ { error: (err as Error).message },+ "notes"+ );+ } finally {+ setIsSaving(false);+ }+ }, 1000),+ };+ pendingEnhancedRef.current = pending;+ }, []);const handleTitleChange = useCallback(- (title: string) => {- bufferOwnerRef.current = activeNoteRef.current;- localTitleRef.current = title;- setLocalTitle(title);- if (activeNoteRef.current)- debouncedSave(activeNoteRef.current, title, localContentRef.current);+ (sourceNoteId: number, title: string) => {+ const next = applyNoteDraftMutation(draftRef.current, {+ sourceNoteId,+ field: "title",+ value: title,+ });+ if (!next) return;+ commitDraft(next);+ scheduleDocumentSave(next);},- [debouncedSave]+ [commitDraft, scheduleDocumentSave]);const handleContentChange = useCallback(- (content: string) => {- bufferOwnerRef.current = activeNoteRef.current;- localContentRef.current = content;- setLocalContent(content);- if (activeNoteRef.current)- debouncedSave(activeNoteRef.current, localTitleRef.current, content);+ (sourceNoteId: number, content: string) => {+ const next = applyNoteDraftMutation(draftRef.current, {+ sourceNoteId,+ field: "content",+ value: content,+ });+ if (!next) return;+ commitDraft(next);+ scheduleDocumentSave(next);},- [debouncedSave]+ [commitDraft, scheduleDocumentSave]);- const handleEnhancedContentChange = useCallback((content: string) => {- bufferOwnerRef.current = activeNoteRef.current;- localEnhancedContentRef.current = content;- setLocalEnhancedContent(content);- if (!activeNoteRef.current) return;- const noteId = activeNoteRef.current;- if (enhancedSaveTimeoutRef.current) clearTimeout(enhancedSaveTimeoutRef.current);- enhancedSaveTimeoutRef.current = setTimeout(async () => {- enhancedSaveTimeoutRef.current = null;- setIsSaving(true);- try {- await window.electronAPI.updateNote(noteId, { enhanced_content: content });- } finally {- setIsSaving(false);- }- }, 1000);- }, []);+ const handleEnhancedContentChange = useCallback(+ (sourceNoteId: number, content: string) => {+ const next = applyNoteDraftMutation(draftRef.current, {+ sourceNoteId,+ field: "enhancedContent",+ value: content,+ });+ if (!next) return;+ commitDraft(next);+ scheduleEnhancedSave(next);+ },+ [commitDraft, scheduleEnhancedSave]+ );++ useEffect(() => {+ return () => flushPendingSaves("unmount");+ }, [flushPendingSaves]);const handleNewNoteIn = useCallback(async (spaceId: number, folderId: number | null) => {@@ -446,8 +511,8 @@ export default function PersonalNotesView({const handleDelete = useCallback(async (id: number) => {- if (shouldCancelPendingSavesForDelete(activeNoteRef.current, id)) {- cancelPendingSaves();+ if (shouldCancelPendingSavesForDelete(draftRef.current?.noteId ?? null, id)) {+ cancelPendingSaves(id);}await window.electronAPI.deleteNote(id);},@@ -506,16 +571,28 @@ export default function PersonalNotesView({(s) => s.recordingNoteId === activeNote?.id && !!s.transcript);const activeNoteRawTranscript = activeNote?.transcript || "";+ const activeDraft = draft?.noteId === activeNote?.id ? draft : null;+ const editorNote = activeNote+ ? {+ ...activeNote,+ title: activeDraft ? activeDraft.title : activeNote.title,+ content: activeDraft ? activeDraft.content : activeNote.content,+ enhanced_content: activeDraft+ ? activeDraft.enhancedContent+ : (activeNote.enhanced_content ?? null),+ }+ : null;+ const editorEnhancedContent = editorNote?.enhanced_content ?? null;const isEnhancementStale = useMemo(() => {- if (!activeNote?.enhanced_content || !activeNote?.enhanced_at_content_hash) return false;- const currentHash = makeContentHash(`${localContent}\n${activeNoteRawTranscript}`);+ if (!editorEnhancedContent || !activeNote?.enhanced_at_content_hash) return false;+ const currentHash = makeContentHash(`${editorNote?.content ?? ""}\n${activeNoteRawTranscript}`);return currentHash !== activeNote.enhanced_at_content_hash;}, [- activeNote?.enhanced_content,activeNote?.enhanced_at_content_hash,- localContent,activeNoteRawTranscript,+ editorEnhancedContent,+ editorNote?.content,]);const handleExportNote = useCallback(@@ -582,15 +659,7 @@ export default function PersonalNotesView({return () => clearInterval(interval);}, [isTranscribing]);- const isLocalSynced = syncedNoteId === activeNote?.id;const isActiveNoteRecording = isTranscribing && recordingNoteId === activeNote?.id;- const editorNote = activeNote- ? {- ...activeNote,- title: isLocalSynced ? localTitle : activeNote.title,- content: isLocalSynced ? localContent : activeNote.content,- }- : null;if (!isOnboardingComplete) {return (@@ -685,9 +754,9 @@ export default function PersonalNotesView({onExportNote={handleExportNote}onExportTranscript={handleExportTranscript}enhancement={- localEnhancedContent+ editorEnhancedContent? {- content: localEnhancedContent,+ content: editorEnhancedContent,isStale: isEnhancementStale,onChange: handleEnhancedContentChange,}diff --git a/src/components/ui/RichTextEditor.tsx b/src/components/ui/RichTextEditor.tsxindex 9c95976a8..1d679eff3 100644--- a/src/components/ui/RichTextEditor.tsx+++ b/src/components/ui/RichTextEditor.tsx@@ -92,7 +92,7 @@ export function RichTextEditor({// Sync editable stateuseEffect(() => {if (editor && !editor.isDestroyed) {- editor.setEditable(!disabled);+ editor.setEditable(!disabled, false);}}, [disabled, editor]);diff --git a/src/lib/noteEditorPendingSave.ts b/src/lib/noteEditorPendingSave.tsindex d65addd2c..a0c12212a 100644--- a/src/lib/noteEditorPendingSave.ts+++ b/src/lib/noteEditorPendingSave.ts@@ -1,19 +1,48 @@-export interface PendingNoteSnapshot {- title: string;- content: string;- enhancedContent: string | null;- documentPending: boolean;- enhancedPending: boolean;- bufferOwnerId: number | null;- targetNoteId: number | null;+export interface NoteEditorDraft {+ readonly noteId: number;+ readonly title: string;+ readonly content: string;+ readonly enhancedContent: string | null;+}++export type NoteDraftMutation =+ | { sourceNoteId: number; field: "title" | "content"; value: string }+ | { sourceNoteId: number; field: "enhancedContent"; value: string | null };++export interface PendingDocumentSnapshot {+ readonly noteId: number;+ readonly title: string;+ readonly content: string;+}++export interface PendingEnhancedSnapshot {+ readonly noteId: number;+ readonly enhancedContent: string | null;}export type PendingNoteUpdates = {- title?: string;- content?: string;- enhanced_content?: string | null;+ readonly title?: string;+ readonly content?: string;+ readonly enhanced_content?: string | null;};+export interface PendingNoteWrite {+ readonly noteId: number;+ readonly updates: PendingNoteUpdates;+}++interface NoteDraftSource {+ readonly id: number;+ readonly title: string;+ readonly content: string;+ readonly enhanced_content: string | null;+}++export interface NoteTransitionPlan {+ readonly writes: PendingNoteWrite[];+ readonly nextDraft: NoteEditorDraft | null;+}+export function shouldCancelPendingSavesForDelete(activeNoteId: number | null,deletedNoteId: number@@ -21,24 +50,66 @@ export function shouldCancelPendingSavesForDelete(return activeNoteId === deletedNoteId;}-/**- * Build the smallest update that drains the editor's pending save timers.- * Keeping this decision separate from the timers makes note-to-note and- * note-to-overview navigation share the same lossless behavior.- */-export function buildPendingNoteUpdates(snapshot: PendingNoteSnapshot): PendingNoteUpdates | null {- // Never write a buffer to a note it does not belong to. During- // create-from-overview + drag the active-note ref can be repointed at the- // new note while the buffers still hold the previously-open note's content;- // without this guard the flush would fill the new note with that text.- if (snapshot.bufferOwnerId !== snapshot.targetNoteId) return null;- const updates: PendingNoteUpdates = {};- if (snapshot.documentPending) {- updates.title = snapshot.title;- updates.content = snapshot.content;+export function applyNoteDraftMutation(+ draft: NoteEditorDraft | null,+ mutation: NoteDraftMutation+): NoteEditorDraft | null {+ if (!draft || mutation.sourceNoteId !== draft.noteId) return null;++ if (mutation.field === "enhancedContent") {+ return { ...draft, enhancedContent: mutation.value };+ }++ return { ...draft, [mutation.field]: mutation.value };+}++export function collectPendingNoteWrites(+ document: PendingDocumentSnapshot | null,+ enhanced: PendingEnhancedSnapshot | null+): PendingNoteWrite[] {+ if (document && enhanced && document.noteId === enhanced.noteId) {+ return [+ {+ noteId: document.noteId,+ updates: {+ title: document.title,+ content: document.content,+ enhanced_content: enhanced.enhancedContent,+ },+ },+ ];+ }++ const writes: PendingNoteWrite[] = [];+ if (document) {+ writes.push({+ noteId: document.noteId,+ updates: { title: document.title, content: document.content },+ });}- if (snapshot.enhancedPending) {- updates.enhanced_content = snapshot.enhancedContent;+ if (enhanced) {+ writes.push({+ noteId: enhanced.noteId,+ updates: { enhanced_content: enhanced.enhancedContent },+ });}- return Object.keys(updates).length > 0 ? updates : null;+ return writes;+}++export function planNoteTransition(+ nextNote: NoteDraftSource | null,+ document: PendingDocumentSnapshot | null,+ enhanced: PendingEnhancedSnapshot | null+): NoteTransitionPlan {+ return {+ writes: collectPendingNoteWrites(document, enhanced),+ nextDraft: nextNote+ ? {+ noteId: nextNote.id,+ title: nextNote.title,+ content: nextNote.content,+ enhancedContent: nextNote.enhanced_content ?? null,+ }+ : null,+ };}diff --git a/test/lib/noteEditorPendingSave.test.js b/test/lib/noteEditorPendingSave.test.jsindex 3bb44a0c3..157518b20 100644--- a/test/lib/noteEditorPendingSave.test.js+++ b/test/lib/noteEditorPendingSave.test.js@@ -3,84 +3,294 @@ const assert = require("node:assert/strict");const load = () => import("../../src/lib/noteEditorPendingSave.ts");-test("returns no update when the editor has no pending timers", async () => {- const { buildPendingNoteUpdates } = await load();+function note(id, content, enhancedContent = null) {+ return {+ id,+ title: `Note ${id}`,+ content,+ enhanced_content: enhancedContent,+ };+}- assert.equal(- buildPendingNoteUpdates({- title: "Title",- content: "Body",- enhancedContent: "Enhanced",- documentPending: false,- enhancedPending: false,- bufferOwnerId: 5,- targetNoteId: 5,+test("applies title, content, and enhanced mutations only for the draft owner", async () => {+ const { applyNoteDraftMutation } = await load();+ const original = {+ noteId: 1,+ title: "Original title",+ content: "Original body",+ enhancedContent: "Original enhancement",+ };++ assert.deepEqual(+ applyNoteDraftMutation(original, {+ sourceNoteId: 1,+ field: "title",+ value: "Edited title",}),- null+ { ...original, title: "Edited title" }+ );+ assert.deepEqual(+ applyNoteDraftMutation(original, {+ sourceNoteId: 1,+ field: "content",+ value: "Edited body",+ }),+ { ...original, content: "Edited body" });+ assert.deepEqual(+ applyNoteDraftMutation(original, {+ sourceNoteId: 1,+ field: "enhancedContent",+ value: "Edited enhancement",+ }),+ { ...original, enhancedContent: "Edited enhancement" }+ );+ assert.deepEqual(original, {+ noteId: 1,+ title: "Original title",+ content: "Original body",+ enhancedContent: "Original enhancement",+ });});-test("flushes only the editor buffers represented by pending timers", async () => {- const { buildPendingNoteUpdates } = await load();- const snapshot = {- title: "Latest title",- content: "Latest body",- enhancedContent: "Latest enhancement",- bufferOwnerId: 5,- targetNoteId: 5,+test("rejects foreign and stale source-note mutations without changing the draft", async () => {+ const { applyNoteDraftMutation } = await load();+ const draftA = {+ noteId: 1,+ title: "A title",+ content: "A body",+ enhancedContent: "A enhancement",};- assert.deepEqual(- buildPendingNoteUpdates({- ...snapshot,- documentPending: true,- enhancedPending: false,+ for (const mutation of [+ { sourceNoteId: 2, field: "title", value: "B title" },+ { sourceNoteId: 2, field: "content", value: "B body" },+ { sourceNoteId: 2, field: "enhancedContent", value: "B enhancement" },+ ]) {+ assert.equal(applyNoteDraftMutation(draftA, mutation), null);+ }+ assert.equal(+ applyNoteDraftMutation(null, {+ sourceNoteId: 1,+ field: "content",+ value: "No owner",}),- { title: "Latest title", content: "Latest body" }+ null);- assert.deepEqual(- buildPendingNoteUpdates({- ...snapshot,- documentPending: false,- enhancedPending: true,+ assert.deepEqual(draftA, {+ noteId: 1,+ title: "A title",+ content: "A body",+ enhancedContent: "A enhancement",+ });++ const draftB = { ...draftA, noteId: 2 };+ assert.equal(+ applyNoteDraftMutation(draftB, {+ sourceNoteId: 1,+ field: "content",+ value: "Stale A callback",}),- { enhanced_content: "Latest enhancement" }+ null);+});++test("collects document and enhanced writes under their captured owner", async () => {+ const { collectPendingNoteWrites } = await load();+ const documentA = { noteId: 1, title: "A title", content: "A body" };+ const enhancedA = { noteId: 1, enhancedContent: "A enhancement" };++ assert.deepEqual(collectPendingNoteWrites(null, null), []);+ assert.deepEqual(collectPendingNoteWrites(documentA, null), [+ {+ noteId: 1,+ updates: { title: "A title", content: "A body" },+ },+ ]);+ assert.deepEqual(collectPendingNoteWrites(null, enhancedA), [+ {+ noteId: 1,+ updates: { enhanced_content: "A enhancement" },+ },+ ]);+ assert.deepEqual(collectPendingNoteWrites(documentA, enhancedA), [+ {+ noteId: 1,+ updates: {+ title: "A title",+ content: "A body",+ enhanced_content: "A enhancement",+ },+ },+ ]);+});++test("keeps document and enhanced writes with different owners separate", async () => {+ const { collectPendingNoteWrites } = await load();+assert.deepEqual(- buildPendingNoteUpdates({- ...snapshot,- documentPending: true,- enhancedPending: true,+ collectPendingNoteWrites(+ { noteId: 1, title: "A title", content: "0" },+ { noteId: 2, enhancedContent: null }+ ),+ [+ {+ noteId: 1,+ updates: { title: "A title", content: "0" },+ },+ {+ noteId: 2,+ updates: { enhanced_content: null },+ },+ ]+ );+});++test("models B's editor event before the A-to-B parent transition, then returns to A", async () => {+ const { applyNoteDraftMutation, planNoteTransition } = await load();+ const noteA = note(1, "A body", "A enhancement");+ const noteB = note(2, "B body", "B enhancement");++ let draft = planNoteTransition(noteA, null, null).nextDraft;+ assert.equal(+ applyNoteDraftMutation(draft, {+ sourceNoteId: 2,+ field: "content",+ value: "B early mount event",}),- {- title: "Latest title",- content: "Latest body",- enhanced_content: "Latest enhancement",- }+ null);++ const toB = planNoteTransition(noteB, null, null);+ assert.deepEqual(toB.writes, []);+ assert.deepEqual(toB.nextDraft, {+ noteId: 2,+ title: "Note 2",+ content: "B body",+ enhancedContent: "B enhancement",+ });++ draft = toB.nextDraft;+ assert.equal(+ applyNoteDraftMutation(draft, {+ sourceNoteId: 1,+ field: "content",+ value: "A stale callback",+ }),+ null+ );++ const backToA = planNoteTransition(noteA, null, null);+ assert.deepEqual(backToA.writes, []);+ assert.deepEqual(backToA.nextDraft, {+ noteId: 1,+ title: "Note 1",+ content: "A body",+ enhancedContent: "A enhancement",+ });});-test("never writes a buffer to a note it does not belong to", async () => {- const { buildPendingNoteUpdates } = await load();+test("edit A then immediately switch to B keeps empty, zero, and raw content owned by A", async () => {+ const { applyNoteDraftMutation, planNoteTransition } = await load();+ const noteA = note(1, "Original A");+ const noteB = note(2, "Original B");- // The editor buffer still holds note A's content while the active-note ref- // has already been repointed at the freshly created note B. A flush here- // must write nothing, otherwise B silently fills with A's text.+ for (const content of ["", "0", "Edited raw A"]) {+ const draftA = planNoteTransition(noteA, null, null).nextDraft;+ const editedA = applyNoteDraftMutation(draftA, {+ sourceNoteId: 1,+ field: "content",+ value: content,+ });+ assert.ok(editedA);++ const pendingA = {+ noteId: editedA.noteId,+ title: editedA.title,+ content: editedA.content,+ };+ assert.equal(+ applyNoteDraftMutation(editedA, {+ sourceNoteId: 2,+ field: "content",+ value: "B early mount event",+ }),+ null+ );++ const toB = planNoteTransition(noteB, pendingA, null);+ assert.deepEqual(toB.writes, [+ {+ noteId: 1,+ updates: { title: "Note 1", content },+ },+ ]);+ assert.equal(toB.nextDraft.noteId, 2);+ assert.equal(pendingA.noteId, 1);+ }+});++test("an enhanced A edit flushes only to A during an immediate B transition", async () => {+ const { applyNoteDraftMutation, planNoteTransition } = await load();+ const noteA = note(1, "A body", "Old enhanced A");+ const noteB = note(2, "B body", "Enhanced B");+ const draftA = planNoteTransition(noteA, null, null).nextDraft;+ const editedA = applyNoteDraftMutation(draftA, {+ sourceNoteId: 1,+ field: "enhancedContent",+ value: "New enhanced A",+ });+ assert.ok(editedA);++ const pendingEnhancedA = {+ noteId: editedA.noteId,+ enhancedContent: editedA.enhancedContent,+ };assert.equal(- buildPendingNoteUpdates({- title: "A's title",- content: "A's body",- enhancedContent: "A's enhancement",- documentPending: true,- enhancedPending: true,- bufferOwnerId: 1,- targetNoteId: 2,+ applyNoteDraftMutation(editedA, {+ sourceNoteId: 2,+ field: "enhancedContent",+ value: "B early enhanced event",}),null);++ const toB = planNoteTransition(noteB, null, pendingEnhancedA);+ assert.deepEqual(toB.writes, [+ {+ noteId: 1,+ updates: { enhanced_content: "New enhanced A" },+ },+ ]);+ assert.equal(toB.nextDraft.noteId, 2);+ assert.equal(pendingEnhancedA.noteId, 1);+});++test("an overview transition flushes captured owners and clears the draft", async () => {+ const { planNoteTransition } = await load();++ const transition = planNoteTransition(+ null,+ { noteId: 1, title: "A title", content: "A body" },+ { noteId: 2, enhancedContent: "B enhancement" }+ );++ assert.deepEqual(transition, {+ writes: [+ {+ noteId: 1,+ updates: { title: "A title", content: "A body" },+ },+ {+ noteId: 2,+ updates: { enhanced_content: "B enhancement" },+ },+ ],+ nextDraft: null,+ });});-test("deleting another sidebar note keeps the active note's pending save", async () => {+test("deleting inactive B does not cancel A's pending save", async () => {const { shouldCancelPendingSavesForDelete } = await load();assert.equal(shouldCancelPendingSavesForDelete(17, 23), false);