Modern Apps git

← Modern-Apps.git

notes: fix editor save races that lost or duplicated notes

Commit
7f89be14bdc03e450cf6d221f97463f52ad49357
Author
Vayun Mathur <[email protected]>
When
2026-11-07 20:14 UTC (28 days ago)
Parents
a1ea0d7
Symptom: three related editor defects. (1) Typing in the title
right after a save landed reverted the field to the saved text and
dropped keystrokes. (2) A brand-new note could insert duplicate
rows. (3) Leaving the editor within the 300ms debounce window lost
the last edit entirely.

Root cause: editableNote copied every database emission into local
state unconditionally, kept saving values whose id was still 0
(each upsert with id 0 inserts a new row) until the flow happened
to round-trip, and only persisted through a composition-scoped
debounced collector that disposal cancelled.

Fix: adopt the database copy only when no unsaved edit is pending;
save under the already-assigned id and stamp it into local state
after the first insert; clear the pending slot once its value is
persisted; and flush any pending write from viewModelScope on
dispose (suppressed for a note the user just deleted, tracked in
delete()).

Verification: new NotesPagesTest case edits a new note twice,
disposes inside the debounce window, and asserts exactly one row
with the latest title reaches the repository. Full notes unit-test
suite run at the end of this stack.

Diff

notes/src/main/java/com/vayunmathur/notes/platform/NotesViewModel.kt
diff --git a/notes/src/main/java/com/vayunmathur/notes/platform/NotesViewModel.kt b/notes/src/main/java/com/vayunmathur/notes/platform/NotesViewModel.ktindex e752728e9e..bff522f7cc 100644--- a/notes/src/main/java/com/vayunmathur/notes/platform/NotesViewModel.kt+++ b/notes/src/main/java/com/vayunmathur/notes/platform/NotesViewModel.kt@@ -4,6 +4,7 @@ import android.app.Application import android.net.Uri import com.vayunmathur.library.log.Log import androidx.compose.runtime.Composable+import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.MutableState import androidx.lifecycle.compose.collectAsStateWithLifecycle@@ -48,7 +49,12 @@ class NotesViewModel(     val notes: StateFlow<List<Note>> = repository.notes         .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptyList()) +    // Ids deleted from the editor, so a dispose-time flush of a pending edit+    // cannot resurrect a note the user just deleted.+    private val deletedNoteIds = mutableSetOf<Long>()+     fun delete(note: Note) {+        synchronized(deletedNoteIds) { deletedNoteIds.add(note.id) }         viewModelScope.launch(Dispatchers.IO) { repository.delete(note) }     } @@ -65,16 +71,55 @@ class NotesViewModel(         val dbNote by noteFlow.collectAsStateWithLifecycle(initialValue = null)          val localState = remember { mutableStateOf<Note?>(null) }+        val pendingWrites = remember { MutableStateFlow<Note?>(null) } +        // Only adopt the database copy when there is no unsaved local edit.+        // Unconditionally copying dbNote here reverted the title field to the+        // last saved value whenever a save landed mid-typing, dropping the+        // keystrokes typed since that save was enqueued.         LaunchedEffect(dbNote, currentId) {-            dbNote?.let { localState.value = it }+            val db = dbNote ?: return@LaunchedEffect+            if (localState.value == null || pendingWrites.value == null) {+                localState.value = db+            }         } -        val pendingWrites = remember { MutableStateFlow<Note?>(null) }         LaunchedEffect(Unit) {             pendingWrites.filterNotNull().debounce(SAVE_DEBOUNCE_MS).collectLatest { newValue ->-                val newId = withContext(Dispatchers.IO) { repository.upsert(newValue) }-                if (currentId == 0L) currentId = newId+                // A brand-new note keeps id 0 in local state until the flow+                // round-trips; save under the already-assigned id instead of+                // inserting a duplicate row per debounce window.+                val toSave = if (newValue.id == 0L && currentId != 0L) {+                    newValue.copy(id = currentId)+                } else {+                    newValue+                }+                val newId = withContext(Dispatchers.IO) { repository.upsert(toSave) }+                if (currentId == 0L) {+                    currentId = newId+                    if (localState.value?.id == 0L) {+                        localState.value = localState.value?.copy(id = newId)+                    }+                }+                if (pendingWrites.value == newValue) pendingWrites.value = null+            }+        }++        // Leaving the editor inside the debounce window must not lose the+        // last edit: flush any pending write from the ViewModel scope (which+        // outlives the composition), unless the note was just deleted.+        DisposableEffect(Unit) {+            onDispose {+                val pending = pendingWrites.value ?: return@onDispose+                val wasDeleted = synchronized(deletedNoteIds) { pending.id in deletedNoteIds }+                if (!wasDeleted) {+                    val toSave = if (pending.id == 0L && currentId != 0L) {+                        pending.copy(id = currentId)+                    } else {+                        pending+                    }+                    viewModelScope.launch(Dispatchers.IO) { repository.upsert(toSave) }+                }             }         } 
notes/src/test/java/com/vayunmathur/notes/ui/NotesPagesTest.kt
diff --git a/notes/src/test/java/com/vayunmathur/notes/ui/NotesPagesTest.kt b/notes/src/test/java/com/vayunmathur/notes/ui/NotesPagesTest.ktindex 27560c5a25..aae06b7c2b 100644--- a/notes/src/test/java/com/vayunmathur/notes/ui/NotesPagesTest.kt+++ b/notes/src/test/java/com/vayunmathur/notes/ui/NotesPagesTest.kt@@ -243,6 +243,39 @@ class NotesPagesTest {         assertEquals("Locally Written", observed)     } +    @Test fun editableNoteNewNoteSavesOnceAndFlushesOnDispose() {+        val vm = vm()+        var setter: ((Note) -> Unit)? = null+        var observed: Note? = null+        var show by mutableStateOf(true)+        rule.setContent {+            if (show) {+                val state = vm.editableNote(0) { Note(0, "", "") }+                observed = state.value+                setter = { state.value = it }+            }+        }+        idle()+        rule.runOnUiThread { setter!!.invoke(Note(0, "First Draft", "body", syncId = "dup-check")) }+        // The debounced collector runs on the compose test clock and cannot be+        // driven reliably under Robolectric, so go straight to the dispose+        // flush: a second edit inside the debounce window, then leave. The+        // flush must write exactly one row carrying the latest edit, not a+        // duplicate per edit or nothing at all.+        rule.runOnUiThread { setter!!.invoke(observed!!.copy(title = "Second Draft")) }+        rule.runOnUiThread { show = false }+        rule.waitForIdle()+        val deadline2 = System.currentTimeMillis() + 8000+        while (System.currentTimeMillis() < deadline2) {+            val all = runBlocking { repo.getAll() }+            if (all.size == 1 && all.single().title == "Second Draft") break+            Thread.sleep(30)+        }+        val all = runBlocking { repo.getAll() }+        assertEquals(1, all.size, "new note must be a single row: $all")+        assertEquals("Second Draft", all.single().title)+    }+     @Test fun notePageImageBlockResizeMoveDelete() {         // seed an image file + a note referencing it, plus a text block after it         val imgDir = java.io.File(app.filesDir, "note_images").apply { mkdirs() }