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.assertIsNotEnabled import androidx.compose.ui.test.captureToImage 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.onRoot import androidx.compose.ui.test.performClick import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.platform.app.InstrumentationRegistry import androidx.compose.ui.graphics.asAndroidBitmap import com.cottondb.android.FeatureModels import com.cottondb.android.PasswordModels import com.cottondb.android.PhotosModels import com.cottondb.android.ScreenEvidence import com.cottondb.android.boot.BootRead 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.media.EnsuredMedia import com.cottondb.android.media.LocalMedia import com.cottondb.android.media.LocalMediaFile import com.cottondb.android.media.MediaPathTier import com.cottondb.android.media.MediaSource import com.cottondb.android.media.ResolvedMediaTier import com.cottondb.android.navigation.Route import com.cottondb.android.traffic.photos.LibraryMedia import com.cottondb.android.traffic.photos.LibraryMediaKind import com.cottondb.android.traffic.photos.PhotosMonth import java.io.File import java.io.FileOutputStream import java.time.Clock import java.time.Instant import java.time.ZoneOffset import java.util.concurrent.CopyOnWriteArrayList 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.Json import kotlinx.serialization.json.JsonElement import kotlinx.serialization.json.JsonObject import kotlinx.serialization.json.buildJsonObject import kotlinx.serialization.json.jsonObject import kotlinx.serialization.json.jsonPrimitive 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 /** Retained review visits must never turn a remount or a reread into another decision write. */ @RunWith(AndroidJUnit4::class) class PhotoReviewRouteTest { @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 unknownReceiptStaysFrozenAcrossRemountAndRevisionWithoutAnotherWrite() { val f = show(Route.PhotosDuplicates) await("Keep this one — the other is a copy") f.core.malformedReceipt = true compose.onNodeWithContentDescription("Keep this one — the other is a copy").performClick() compose.waitUntil(5_000) { f.core.writes.get() == 1 } f.remount() f.revise() compose.waitForIdle() compose.onNodeWithContentDescription("Keep this one — the other is a copy").assertIsNotEnabled() compose.runOnIdle { assertFalse(f.models.review(Route.PhotosDuplicates).state.value.canAct) assertEquals(1, f.core.writes.get()) } } @Test fun knownRefusalKeepsTheCurrentProposalUsable() { val f = show(Route.PhotosDuplicates) await("Keep this one — the other is a copy") f.core.writeFailure = CoreException("refused", "Already decided elsewhere", null) compose.onNodeWithContentDescription("Keep this one — the other is a copy").performClick() compose.waitUntil(5_000) { f.core.writes.get() == 1 } compose.onNodeWithText("Already decided elsewhere").assertExists() f.core.writeFailure = null compose.onNodeWithContentDescription("Keep this one — the other is a copy").performClick() compose.waitUntil(5_000) { f.core.writes.get() == 2 } compose.runOnIdle { assertEquals("decide_duplicate", f.core.tools.last()) assertFalse(f.models.review(Route.PhotosDuplicates).state.value.outcomeUnknown) } } @Test fun confirmedRereadFailureCanRefreshWithoutReplayingDecision() { val f = show(Route.PhotosDuplicates) await("Keep this one — the other is a copy") f.core.failReviewReads = true compose.onNodeWithContentDescription("Keep this one — the other is a copy").performClick() compose.waitUntil(5_000) { f.core.writes.get() == 1 && f.core.duplicateReads.get() >= 2 } compose.onNodeWithText("Synthetic review reread failed").assertExists() f.core.failReviewReads = false compose.onNodeWithContentDescription("Try again").performClick() compose.waitUntil(5_000) { f.core.duplicateReads.get() >= 3 } assertEquals(1, f.core.writes.get()) } @Test fun removingReviewRouteClosesTheRetainedModel() { val f = show(Route.PhotosPeople) await("Yes, this is Ada") ScreenEvidence.capture("photo-review-people-route") { compose.onRoot().captureToImage().asAndroidBitmap() } lateinit var retired: com.cottondb.android.traffic.photos.review.PhotoReviewModel compose.runOnIdle { retired = f.models.review(Route.PhotosPeople) f.models.retain(emptyList()) } compose.runOnIdle { assertNull(retired.refresh()) } } @Test fun appNavigationDeepLinkOpensDuplicatesThenPhotoDetail() { 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.PhotosDuplicates, ) } } } await("Keep this one — the other is a copy") ScreenEvidence.capture("photo-review-duplicates-route") { compose.onRoot().captureToImage().asAndroidBitmap() } compose.waitUntil(5_000) { compose.onAllNodesWithContentDescription("Open the picture").fetchSemanticsNodes().size == 2 } compose.onAllNodesWithContentDescription("Open the picture")[0].performClick() compose.waitUntil(5_000) { f.core.photoReads.get() == 1 } compose.onNodeWithContentDescription("Back").assertExists() compose.onNodeWithText("Synthetic picture").assertExists() ScreenEvidence.capture("photo-review-detail-route") { compose.onRoot().captureToImage().asAndroidBitmap() } } @Test fun libraryMoreRoutesAlbumsDuplicatesAndPeopleDirectly() { val f = Fixture() fixture = f val opened = CopyOnWriteArrayList() compose.setContent { CottonTheme { PhotosScreen( state = PhotosScreenState( months = listOf(sampleMonth()), firstRead = false, duplicates = 1, faceSuggestions = 1, hasPhotos = true, ), media = f.media, dataRevision = 0, onBack = {}, onShowChange = {}, onPrintsChange = {}, onSearchingChange = {}, onQueryChange = {}, onRetry = {}, onStopSelecting = {}, onToggleSelected = {}, onOpen = { route -> opened += route }, ) } } selectMore("Albums") selectMore("Duplicates · 1") selectMore("People to confirm · 1") assertEquals(listOf(Route.PhotosAlbums, Route.PhotosDuplicates, Route.PhotosPeople), opened) } private fun selectMore(label: String) { compose.onNodeWithContentDescription("More actions").performClick() compose.onNodeWithText(label).performClick() } private fun show(route: Route): Fixture { val fresh = Fixture() fixture = fresh compose.setContent { CottonTheme { if (fresh.visible.value) { key(fresh.remount.longValue) { PhotoReviewRoute( route = route, models = fresh.models, media = fresh.media, dataRevision = fresh.revision.longValue, onBack = { fresh.back.incrementAndGet() }, onOpen = {}, ) } } } } 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 = ReviewCore() 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 += 1 } fun revise() = composeMain { revision.longValue += 1 } fun features(): FeatureModels { val context = 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, "photo-review-route-test", "document"), ) } fun close() { models.retain(emptyList()) scope.cancel() media.close() } } private class ReviewCore : CottonCalling { override val events: SharedFlow = MutableSharedFlow() override val eventErrors: SharedFlow = MutableSharedFlow() val duplicateReads = AtomicInteger() val faceReads = AtomicInteger() val photoReads = AtomicInteger() val writes = AtomicInteger() val tools = CopyOnWriteArrayList() var failReviewReads = false var malformedReceipt = false var writeFailure: Throwable? = null override suspend fun call(method: String, request: JsonObject): JsonElement = when (method) { "read.duplicates" -> { duplicateReads.incrementAndGet() if (failReviewReads) error("Synthetic review reread failed") duplicates() } "read.faceSuggestions" -> { faceReads.incrementAndGet() if (failReviewReads) error("Synthetic review reread failed") faces() } "read.photo" -> { photoReads.incrementAndGet() photoDetail() } "write" -> { writes.incrementAndGet() tools += request["tool"]!!.jsonPrimitive.content writeFailure?.let { throw it } receipt(request, malformedReceipt) } else -> error("Unexpected core method: $method") } override suspend fun close() = Unit } private class LocalOnlyMedia : MediaSource { private val file = File(InstrumentationRegistry.getInstrumentation().targetContext.cacheDir, "photo-review-route.png").also { target -> val bitmap = Bitmap.createBitmap(12, 12, Bitmap.Config.ARGB_8888) try { bitmap.eraseColor(Color.rgb(79, 130, 167)) FileOutputStream(target).use { check(bitmap.compress(Bitmap.CompressFormat.PNG, 100, it)) } } finally { bitmap.recycle() } } override suspend fun local(key: String, tier: MediaPathTier): LocalMedia = LocalMedia.Present(LocalMediaFile(file), ResolvedMediaTier.Thumb) override suspend fun ensure(key: String): EnsuredMedia = error("Review images must remain local-only") override suspend fun viewed(key: String) = false fun close() { file.delete() } } } private val CLOCK: Clock = Clock.fixed(Instant.parse("2026-01-01T00:00:00Z"), ZoneOffset.UTC) private fun composeMain(block: () -> Unit) = InstrumentationRegistry.getInstrumentation().runOnMainSync(block) private fun sampleMonth() = PhotosMonth( id = "2026-01", title = "January 2026", items = listOf( LibraryMedia( id = "photo:keep", kind = LibraryMediaKind.Photo, key = "media/keep", preview = null, posterKey = null, caption = "Synthetic picture", description = null, takenAt = "2026-01-01T00:00:00Z", sizeBytes = 12, contentType = "image/png", favourite = false, people = emptyList(), projects = emptyList(), durationMs = null, ), ), ) private fun duplicates(): JsonElement = Json.parseToJsonElement( """{"groups":[{"keepId":"photo:keep","copies":[{"id":"duplicate:one","copyId":"photo:copy","distance":1,"method":"phash","state":"open"}]}],"photos":[{"id":"photo:keep","key":"media/keep","preview":null},{"id":"photo:copy","key":"media/copy","preview":null}]}""", ) private fun faces(): JsonElement = Json.parseToJsonElement( """{"faces":[{"id":"face:one","recordId":"photo:keep","suggestedPersonId":"person:one","suggestedName":"Ada","distance":0.1,"x":0,"y":0,"w":1,"h":1}],"photos":[{"id":"photo:keep","key":"media/keep","preview":null}]}""", ) private fun receipt(request: JsonObject, malformed: Boolean): JsonElement { if (malformed) return buildJsonObject { put("answer", buildJsonObject { put("id", "wrong") }) } val args = request["args"]!!.jsonObject return when (request["tool"]!!.jsonPrimitive.content) { "decide_duplicate" -> buildJsonObject { put("answer", buildJsonObject { put("keepId", "photo:keep") put("id", args["id"]!!.jsonPrimitive.content) put("copyId", "photo:copy") put("distance", 1) put("method", "phash") put("state", args["state"]!!.jsonPrimitive.content) put("decidedAt", "2026-01-01T00:00:00Z") }) } "update_face" -> buildJsonObject { put("answer", buildJsonObject { put("photoId", "photo:keep") put("face", buildJsonObject { put("id", "face:one") put("box", buildJsonObject { put("x", 0) put("y", 0) put("width", 1) put("height", 1) }) put("person", args["personId"]?.let { person -> buildJsonObject { put("id", person) put("name", "Ada") } } ?: kotlinx.serialization.json.JsonNull) if (args["dismissSuggestion"]?.jsonPrimitive?.content == "true") put("suggestionDismissedAt", "2026-01-01T00:00:00Z") put("suggestion", kotlinx.serialization.json.JsonNull) put("quality", kotlinx.serialization.json.JsonNull) }) }) } else -> error("Unexpected review tool") } } private fun photoDetail(): JsonElement = Json.parseToJsonElement( """{"photo":{"id":"photo:keep","key":"media/keep","preview":null,"caption":"Synthetic picture","description":null,"takenAt":"2026-01-01T00:00:00Z","sizeBytes":12,"width":12,"height":12,"contentType":"image/png","place":null,"camera":null,"orientation":null,"takenOffset":null,"subtypes":[],"labels":[],"favourite":false,"people":[],"projects":[],"faces":[]},"sightings":[],"albums":[]}""", )