package com.cottondb.android.ui.photos import android.graphics.Bitmap import android.graphics.Color import androidx.compose.runtime.key import androidx.compose.runtime.mutableLongStateOf import androidx.compose.runtime.mutableStateOf import androidx.compose.ui.test.assertIsEnabled import androidx.compose.ui.test.assertIsNotEnabled import androidx.compose.ui.test.junit4.createComposeRule import androidx.compose.ui.test.onAllNodesWithContentDescription import androidx.compose.ui.test.onNodeWithContentDescription import androidx.compose.ui.test.onNodeWithText import androidx.compose.ui.test.performClick import androidx.compose.ui.test.performTextClearance import androidx.compose.ui.test.performTextInput import androidx.compose.ui.test.performScrollTo import androidx.compose.ui.test.onRoot import androidx.compose.ui.test.captureToImage import androidx.compose.ui.graphics.asAndroidBitmap import androidx.test.ext.junit.runners.AndroidJUnit4 import com.cottondb.android.PhotosModels import com.cottondb.android.FeatureModels import com.cottondb.android.PasswordModels import com.cottondb.android.ScreenEvidence import com.cottondb.android.core.CoreException import com.cottondb.android.core.CottonCalling import com.cottondb.android.core.CottonEvent import com.cottondb.android.core.MalformedCoreEventException import com.cottondb.android.design.CottonTheme import com.cottondb.android.home.HomeState import com.cottondb.android.boot.BootRead import com.cottondb.android.media.LocalMedia import com.cottondb.android.media.LocalMediaFile import com.cottondb.android.media.LocalMediaSource import com.cottondb.android.media.MediaSource import com.cottondb.android.media.MediaPathTier import com.cottondb.android.media.EnsuredMedia import com.cottondb.android.navigation.Route import java.io.File import java.io.FileOutputStream import java.time.Clock import java.time.Instant import java.time.ZoneOffset import java.util.concurrent.atomic.AtomicInteger 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.serialization.json.JsonElement import kotlinx.serialization.json.JsonNull import kotlinx.serialization.json.JsonObject import kotlinx.serialization.json.JsonPrimitive import kotlinx.serialization.json.jsonObject import kotlinx.serialization.json.jsonPrimitive import kotlinx.serialization.json.buildJsonArray import kotlinx.serialization.json.buildJsonObject import kotlinx.serialization.json.put import org.junit.After import org.junit.Assert.assertEquals import org.junit.Assert.assertFalse import org.junit.Assert.assertNull import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith /** Route-level regressions: retained writes must never be replayed by recomposition or revision reads. */ @RunWith(AndroidJUnit4::class) class AlbumsRouteTest { @get:Rule val compose = createComposeRule() private var fixture: Fixture? = null @After fun closeFixture() { val current = fixture ?: return compose.runOnIdle { current.visible.value = false } compose.waitForIdle() compose.runOnIdle { current.close() } fixture = null } @Test fun confirmedTitleWithFailedRereadSurvivesRemountWithoutReplay() { val f = show(Route.PhotosAlbum(ALBUM)) await("Album title") compose.onNodeWithContentDescription("Album title").performScrollTo() compose.onNodeWithContentDescription("Album title").performTextClearance() compose.onNodeWithContentDescription("Album title").performTextInput("After") f.core.failAlbumReads = true compose.runOnIdle { assertEquals("After", f.models.album(Route.PhotosAlbum(ALBUM)).state.value.titleDraft) } compose.onNodeWithContentDescription("Save album title").assertIsEnabled().performScrollTo().performClick() compose.waitUntil(5_000) { f.core.writes.get() == 1 && f.core.albumReads.get() >= 2 } compose.onNodeWithText("Synthetic reread failed").assertExists() f.remount() compose.waitUntil(5_000) { f.core.albumReads.get() >= 3 } assertEquals(1, f.core.writes.get()) assertEquals("update_album", f.core.tools.single()) } @Test fun unknownTitleReceiptStaysFrozenAcrossRevisionReads() { val f = show(Route.PhotosAlbum(ALBUM)) await("Album title") compose.onNodeWithContentDescription("Album title").performScrollTo() compose.onNodeWithContentDescription("Album title").performTextClearance() compose.onNodeWithContentDescription("Album title").performTextInput("After") f.core.malformedWrite = true compose.runOnIdle { assertEquals("After", f.models.album(Route.PhotosAlbum(ALBUM)).state.value.titleDraft) } compose.onNodeWithContentDescription("Save album title").assertIsEnabled().performScrollTo().performClick() compose.waitUntil(5_000) { f.core.writes.get() == 1 } compose.runOnIdle { f.revision.longValue += 1 } compose.waitForIdle() compose.onNodeWithContentDescription("Save album title").assertIsNotEnabled() compose.runOnIdle { assertFalse(f.models.album(Route.PhotosAlbum(ALBUM)).state.value.canAct) } assertEquals(1, f.core.writes.get()) } @Test fun selectedAddConfirmsBackOnceAndDoesNotReplayOnRemount() { val f = show(Route.PhotosAlbumAdd(ALBUM)) await("Photo tile photo:add: Picture") compose.onNodeWithContentDescription("Photo tile photo:add: Picture").performClick() compose.onNodeWithContentDescription("Add the selected pictures").performClick() compose.waitUntil(5_000) { f.back.get() == 1 && f.core.writes.get() == 1 } f.remount() compose.waitForIdle() assertEquals(1, f.back.get()) assertEquals(1, f.core.writes.get()) } @Test fun appNavigationDeepLinkOpensAlbumAddsAndRetiresTheCompletedAddVisit() { val f = Fixture(); fixture = f val features = f.features() compose.setContent { CottonTheme { if (f.visible.value) com.cottondb.android.ui.navigation.AppNavigation( home = HomeState.Error("Synthetic home"), boot = BootRead(true, "joined", null, "synthetic-workspace", null, "Cotton", null), features = features, onJoin = {}, onLeave = {}, onRefreshHome = {}, onSaveArrangement = {}, notificationRoute = Route.PhotosAlbums, ) } } await("Album Before") ScreenEvidence.capture("albums-list-route") { compose.onRoot().captureToImage().asAndroidBitmap() } compose.onNodeWithContentDescription("Album Before").performClick() await("Album title") ScreenEvidence.capture("album-detail-route") { compose.onRoot().captureToImage().asAndroidBitmap() } compose.onNodeWithContentDescription("Add photos").performClick() await("Photo tile photo:add: Picture") lateinit var retired: com.cottondb.android.traffic.photos.albums.AlbumAddModel compose.runOnIdle { retired = features.photos.albumAdd(Route.PhotosAlbumAdd(ALBUM)) } compose.onNodeWithContentDescription("Photo tile photo:add: Picture").performClick() compose.onNodeWithContentDescription("Add the selected pictures").performClick() compose.waitUntil(5_000) { f.core.writes.get() == 1 } await("Album title") compose.runOnIdle { assertNull(retired.refresh()) } } @Test fun knownAddRefusalKeepsSelectionOnTheAddRoute() { val f = show(Route.PhotosAlbumAdd(ALBUM)) await("Photo tile photo:add: Picture") compose.onNodeWithContentDescription("Photo tile photo:add: Picture").performClick() f.core.refuseWrite = true compose.onNodeWithContentDescription("Add the selected pictures").performClick() compose.waitUntil(5_000) { f.core.writes.get() == 1 } compose.onNodeWithText("Album is locked").assertExists() assertEquals(0, f.back.get()) compose.onNodeWithText("1 selected").assertExists() } private fun show(route: Route): Fixture { val fresh = Fixture(); fixture = fresh compose.setContent { CottonTheme { if (fresh.visible.value) key(fresh.remount.value) { AlbumsRoute(route, fresh.models, fresh.media, CLOCK, fresh.revision.longValue, { fresh.back.incrementAndGet() }, {}) } } } return fresh } private fun await(description: String) = compose.waitUntil(5_000) { compose.onAllNodesWithContentDescription(description).fetchSemanticsNodes().isNotEmpty() } private class Fixture { val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate) val core = Core(); val models = PhotosModels(core, scope); val media = LocalOnlyMedia() val visible = mutableStateOf(true); val remount = mutableLongStateOf(0); val revision = mutableLongStateOf(0) val back = AtomicInteger() fun remount() { composeMain { remount.longValue++ } } fun features(): FeatureModels { val context = androidx.test.platform.app.InstrumentationRegistry.getInstrumentation().targetContext val access = com.cottondb.android.passwords.VaultAccess(core) val session = com.cottondb.android.passwords.VaultSession( access, com.cottondb.android.passwords.VaultOperations(access, com.cottondb.android.passwords.VaultKeyRepublisher {}), scope, {}, ) return FeatureModels( core, CLOCK, scope, media, com.cottondb.android.ui.traffic.messages.AndroidWhatsAppExportStager(context), PasswordModels(core, scope, CLOCK, session) {}, object : com.cottondb.android.search.SearchRecentsStore { override fun load() = emptyList(); override fun save(recents: List) = Unit }, com.cottondb.android.ui.imports.AndroidSafFileStager(context, "album-route-test", "document"), ) } fun close() { models.retain(emptyList()); scope.cancel(); media.close() } } private class Core : CottonCalling { override val events: SharedFlow = MutableSharedFlow() override val eventErrors: SharedFlow = MutableSharedFlow() val albumReads = AtomicInteger(); val writes = AtomicInteger(); val tools = mutableListOf() var failAlbumReads = false; var malformedWrite = false; var refuseWrite = false private var title = "Before" override suspend fun call(method: String, request: JsonObject): JsonElement = when (method) { "read.album" -> { albumReads.incrementAndGet(); if (failAlbumReads) throw IllegalStateException("Synthetic reread failed") else album(title) } "read.addablePhotos" -> addable() "read.albums" -> buildJsonObject { put("albums", buildJsonArray { add(card(title)) }) } "write" -> { writes.incrementAndGet(); tools += request["tool"]!!.jsonPrimitive.content if (refuseWrite) throw CoreException("locked", "Album is locked", null) if (malformedWrite) buildJsonObject { put("answer", buildJsonObject {}) } else { request["args"]!!.jsonObject["title"]?.jsonPrimitive?.content?.let { title = it } buildJsonObject { put("answer", receipt(title)) } } } else -> error(method) } override suspend fun close() = Unit } private class LocalOnlyMedia : MediaSource { private val file = File(androidx.test.platform.app.InstrumentationRegistry.getInstrumentation().targetContext.cacheDir, "album-cover.png").also { target -> val bitmap = Bitmap.createBitmap(12, 12, Bitmap.Config.ARGB_8888) try { bitmap.eraseColor(Color.rgb(26, 61, 85)); FileOutputStream(target).use { check(bitmap.compress(Bitmap.CompressFormat.PNG, 100, it)) } } finally { bitmap.recycle() } } override suspend fun local(key: String, tier: MediaPathTier): LocalMedia = if (key == "cover") LocalMedia.Present(LocalMediaFile(file), com.cottondb.android.media.ResolvedMediaTier.Thumb) else LocalMedia.Absent override suspend fun ensure(key: String): EnsuredMedia = error("album renderer must not fetch") override suspend fun viewed(key: String): Boolean = false fun close() { file.delete() } } } private const val ALBUM = "album:synthetic" private val CLOCK: Clock = Clock.fixed(Instant.parse("2026-01-01T00:00:00Z"), ZoneOffset.UTC) private fun composeMain(block: () -> Unit) = androidx.test.platform.app.InstrumentationRegistry.getInstrumentation().runOnMainSync(block) private fun card(title: String) = buildJsonObject { put("id", ALBUM); listOf("kind","state","decidedAt","title","titleBy","startsAt","endsAt","homeLabel","coverId","createdAt","updatedAt").forEach { put(it, if (it == "state") JsonPrimitive("open") else if (it == "title") JsonPrimitive(title) else JsonNull) }; put("members", 1); put("people", buildJsonArray {}); put("cover", buildJsonObject { put("key", "cover"); put("preview", JsonNull) }) } private fun album(title: String) = card(title).toMutableMap().apply { put("items", buildJsonArray { add(buildJsonObject { put("id", "photo:member"); put("kind", "photo"); put("addedBy", JsonNull); put("sortAt", JsonNull) }) }); put("projects", buildJsonArray {}) }.let(::JsonObject) private fun addable() = buildJsonObject { put("photos", buildJsonArray { add(buildJsonObject { put("id", "photo:add"); listOf("key","preview","description","takenAt","contentType").forEach { put(it, JsonNull) }; put("caption", "Picture"); put("sizeBytes", 0); put("favourite", false); put("people", buildJsonArray {}); put("projects", buildJsonArray {}) }) }) } private fun receipt(title: String) = buildJsonObject { card(title).forEach { (key, value) -> put(key, value) }; put("items", buildJsonArray {}); put("projects", buildJsonArray {}) }