package com.cottondb.notesimport kotlinx.coroutines.CompletableDeferredimport kotlinx.coroutines.asyncimport kotlinx.coroutines.cancelAndJoinimport kotlinx.coroutines.launchimport kotlinx.coroutines.runBlockingimport kotlinx.coroutines.yieldimport kotlinx.serialization.json.JsonObjectimport kotlinx.serialization.json.JsonPrimitiveimport org.junit.Assert.assertEqualsimport 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. */classNoteSavesTest {/** The core as the writer sees it: the text it holds, and the base each save came with. */privateclassCore(var held: String) {val bases = mutableListOf<String?>()var gate: CompletableDeferred<Unit>? = nullsuspendfun edit(text: String, base: String?): JsonObject { bases += base held = text gate?.await()returnJsonObject(mapOf("text" to JsonPrimitive(text))) } }privateval a = "- [ ] one\n- [ ] two\n- [ ] three"privateval b = "- [ ] two\n- [ ] one\n- [ ] three"privateval c = "- [ ] two\n- [ ] three\n- [ ] one" @Testfun `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) } @Testfun `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) }}