Cotton code
440 lines · 17.8 KB · KotlinRaw
package com.cottondb.android.ui.photosimport android.graphics.Bitmapimport android.graphics.Colorimport androidx.compose.runtime.keyimport androidx.compose.runtime.mutableLongStateOfimport androidx.compose.runtime.mutableStateOfimport androidx.compose.ui.test.assertIsNotEnabledimport androidx.compose.ui.test.captureToImageimport androidx.compose.ui.test.junit4.createComposeRuleimport androidx.compose.ui.test.onAllNodesWithContentDescriptionimport androidx.compose.ui.test.onNodeWithContentDescriptionimport androidx.compose.ui.test.onNodeWithTextimport androidx.compose.ui.test.onRootimport androidx.compose.ui.test.performClickimport androidx.test.ext.junit.runners.AndroidJUnit4import androidx.test.platform.app.InstrumentationRegistryimport androidx.compose.ui.graphics.asAndroidBitmapimport com.cottondb.android.FeatureModelsimport com.cottondb.android.PasswordModelsimport com.cottondb.android.PhotosModelsimport com.cottondb.android.ScreenEvidenceimport com.cottondb.android.boot.BootReadimport com.cottondb.android.core.CoreExceptionimport com.cottondb.android.core.CottonCallingimport com.cottondb.android.core.CottonEventimport com.cottondb.android.core.MalformedCoreEventExceptionimport com.cottondb.android.design.CottonThemeimport com.cottondb.android.home.HomeStateimport com.cottondb.android.media.EnsuredMediaimport com.cottondb.android.media.LocalMediaimport com.cottondb.android.media.LocalMediaFileimport com.cottondb.android.media.MediaPathTierimport com.cottondb.android.media.MediaSourceimport com.cottondb.android.media.ResolvedMediaTierimport com.cottondb.android.navigation.Routeimport com.cottondb.android.traffic.photos.LibraryMediaimport com.cottondb.android.traffic.photos.LibraryMediaKindimport com.cottondb.android.traffic.photos.PhotosMonthimport java.io.Fileimport java.io.FileOutputStreamimport java.time.Clockimport java.time.Instantimport java.time.ZoneOffsetimport java.util.concurrent.CopyOnWriteArrayListimport java.util.concurrent.atomic.AtomicIntegerimport kotlinx.coroutines.CoroutineScopeimport kotlinx.coroutines.Dispatchersimport kotlinx.coroutines.SupervisorJobimport kotlinx.coroutines.cancelimport kotlinx.coroutines.flow.MutableSharedFlowimport kotlinx.coroutines.flow.SharedFlowimport kotlinx.serialization.json.Jsonimport kotlinx.serialization.json.JsonElementimport kotlinx.serialization.json.JsonObjectimport kotlinx.serialization.json.buildJsonObjectimport kotlinx.serialization.json.jsonObjectimport kotlinx.serialization.json.jsonPrimitiveimport kotlinx.serialization.json.putimport org.junit.Afterimport org.junit.Assert.assertEqualsimport org.junit.Assert.assertFalseimport org.junit.Assert.assertNullimport org.junit.Ruleimport org.junit.Testimport 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<Route>()        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<String>()                    override fun save(recents: List<String>) = 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<CottonEvent> = MutableSharedFlow()        override val eventErrors: SharedFlow<MalformedCoreEventException> = MutableSharedFlow()        val duplicateReads = AtomicInteger()        val faceReads = AtomicInteger()        val photoReads = AtomicInteger()        val writes = AtomicInteger()        val tools = CopyOnWriteArrayList<String>()        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":[]}""",)