package com.cottondb.android import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.platform.app.InstrumentationRegistry import com.cottondb.android.core.CottonCalling import com.cottondb.android.core.CottonEvent import com.cottondb.android.core.MalformedCoreEventException import com.cottondb.android.navigation.Route import com.cottondb.android.work.reader.ReaderMutationResult import java.util.concurrent.CopyOnWriteArrayList import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.cancel import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.SharedFlow import kotlinx.coroutines.runBlocking import kotlinx.serialization.json.JsonArray import kotlinx.serialization.json.JsonElement import kotlinx.serialization.json.JsonNull import kotlinx.serialization.json.JsonObject import kotlinx.serialization.json.JsonPrimitive import kotlinx.serialization.json.buildJsonObject import kotlinx.serialization.json.jsonObject import kotlinx.serialization.json.put import org.junit.After import org.junit.Assert.assertEquals import org.junit.Assert.assertFalse import org.junit.Assert.assertNotSame import org.junit.Assert.assertNull import org.junit.Assert.assertSame import org.junit.Assert.assertTrue import org.junit.Test import org.junit.runner.RunWith /** Exercises retained Reader hosts on Android's serial main dispatcher with real Reader wire shapes. */ @RunWith(AndroidJUnit4::class) class ReaderModelsTest { private val fixtures = CopyOnWriteArrayList() @After fun closeModels() = onMain { fixtures.forEach(Fixture::close) fixtures.clear() } @Test fun retainedReaderStackKeepsListAndPageIdentity() = onMain { val fixture = fixture() val list = fixture.models.list() val page = fixture.models.page("page-1") fixture.models.retain(listOf(Route.Reader, Route.ReaderPage("page-1"))) assertSame(list, fixture.models.list()) assertSame(page, fixture.models.page("page-1")) } @Test fun removingPageClosesItsWriterAndNewVisitResetsWebState() = onMain { val fixture = fixture() val retired = fixture.models.page("page-1") runBlocking { retired.model.refresh() } retired.navigated("https://reader.example.test/old", "Synthetic title") fixture.models.retain(listOf(Route.Reader)) val refused = runBlocking { retired.model.archive().await() } assertTrue(refused is ReaderMutationResult.Refused) assertEquals("This Reader page is no longer open.", (refused as ReaderMutationResult.Refused).message) assertTrue(fixture.writes.none { it.tool == "archive_page" }) val reopened = fixture.models.page("page-1") assertNotSame(retired, reopened) assertNull(reopened.web.value.liveAddress) assertNull(reopened.web.value.failure) assertEquals(0L, reopened.web.value.attempt) } @Test fun webStateKeepsAddressAcrossFailureAndRetryAndLearnsProviderTitleOnce() { val fixture = onMain { fixture() } val visit = onMain { fixture.models.page("page-1").also { runBlocking { it.model.refresh() } } } onMain { visit.navigated("https://reader.example.test/reader", " Learned page title ") visit.failed("Synthetic network failure") visit.retryWeb() visit.navigated("https://reader.example.test/reader", "Learned page title") } InstrumentationRegistry.getInstrumentation().waitForIdleSync() assertEquals("https://reader.example.test/reader", visit.web.value.liveAddress) assertNull(visit.web.value.failure) assertEquals(1L, visit.web.value.attempt) val titleWrites = fixture.writes.filter { it.tool == "update_page" } assertEquals(1, titleWrites.size) assertEquals("page-1", titleWrites.single().args["id"]?.jsonObjectOrPrimitiveContent()) assertEquals("Learned page title", titleWrites.single().args["title"]?.jsonObjectOrPrimitiveContent()) assertFalse(visit.model.mutation.value.busy) } private fun fixture() = Fixture().also(fixtures::add) private fun onMain(block: () -> T): T { var result: Result? = null InstrumentationRegistry.getInstrumentation().runOnMainSync { result = runCatching(block) } return requireNotNull(result).getOrThrow() } private class Fixture { private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate) val core = ReaderCore() val models = ReaderModels(core, scope) val writes get() = core.writes fun close() = scope.cancel() } private class ReaderCore : CottonCalling { data class Write(val tool: String, val args: JsonObject) override val events: SharedFlow = MutableSharedFlow() override val eventErrors: SharedFlow = MutableSharedFlow() val writes = CopyOnWriteArrayList() override suspend fun call(method: String, request: JsonObject): JsonElement = when (method) { "read.pages" -> buildJsonObject { put("pages", JsonArray(listOf(page()))) } "read.page" -> buildJsonObject { put("page", page()) put("projects", JsonArray(emptyList())) put("links", JsonArray(emptyList())) } "write" -> write(request) else -> error("Unexpected core method: $method") } override suspend fun close() = Unit private fun write(request: JsonObject): JsonElement { val tool = request["tool"]!!.jsonObjectOrPrimitiveContent() val args = request["args"]!!.jsonObject writes += Write(tool, args) return buildJsonObject { put("answer", buildJsonObject { when (tool) { "update_page" -> { put("id", args["id"]!!.jsonObjectOrPrimitiveContent()) put("changed", true) } "archive_page" -> { put("id", args["id"]!!.jsonObjectOrPrimitiveContent()) put("archived", true) } else -> error("Unexpected Reader write: $tool") } }) } } private fun page() = buildJsonObject { put("id", "page-1") put("url", "https://reader.example.test/reader") put("host", "reader.example.test") put("title", JsonNull) put("readAt", JsonNull) put("createdAt", "2026-09-22T09:00:00Z") put("updatedAt", "2026-09-22T09:00:00Z") put("archivedAt", JsonNull) put("sourceInboxId", JsonNull) } } } private fun JsonElement.jsonObjectOrPrimitiveContent(): String = when (this) { is JsonPrimitive -> content else -> error("Expected a string primitive.") }