package com.cottondb.notes import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.async import kotlinx.coroutines.cancelAndJoin import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking import kotlinx.coroutines.yield import kotlinx.serialization.json.JsonObject import kotlinx.serialization.json.JsonPrimitive import org.junit.Assert.assertEquals import org.junit.Test /** * Moving a checklist line with Move up pressed quickly left the line in the note two and three times (the emulator, * 22 Nov 2026): a save cancelled by the next keystroke after the core wrote it never moved its base on, so the next save * went with an older base and the core's merge kept both places of the moved line. Every save must go with the text the * core holds as this writer's. */ class NoteSavesTest { /** The core as the writer sees it: the text it holds, and the base each save came with. */ private class Core(var held: String) { val bases = mutableListOf() var gate: CompletableDeferred? = null suspend fun edit(text: String, base: String?): JsonObject { bases += base held = text gate?.await() return JsonObject(mapOf("text" to JsonPrimitive(text))) } } private val a = "- [ ] one\n- [ ] two\n- [ ] three" private val b = "- [ ] two\n- [ ] one\n- [ ] three" private val c = "- [ ] two\n- [ ] three\n- [ ] one" @Test fun `a save cancelled once the core has it still moves the base on`() = runBlocking { val core = Core(a) val saves = NoteSaves(a) core.gate = CompletableDeferred() // The first move's save is out; the next keystroke cancels its caller (LaunchedEffect(pending)). val first = launch { saves.save(b, core::edit) } while (core.bases.isEmpty()) yield() core.gate!!.complete(Unit) first.cancelAndJoin() core.gate = null saves.save(c, core::edit) assertEquals(listOf(a, b), core.bases) assertEquals(c, saves.loaded) } @Test fun `a second save waits for the first and goes with its text as the base`() = runBlocking { val core = Core(a) val saves = NoteSaves(a) core.gate = CompletableDeferred() val first = async { saves.save(b, core::edit) } while (core.bases.isEmpty()) yield() // A pass lands meanwhile and the writer saves what it holds. val second = async { saves.save(c, core::edit) } repeat(5) { yield() } assertEquals("the second save is not sent while the first is out", 1, core.bases.size) core.gate!!.complete(Unit) first.await(); second.await() assertEquals(listOf(a, b), core.bases) assertEquals(c, core.held) } }