package com.cottondb.android.ui.settings import androidx.compose.ui.graphics.asAndroidBitmap import androidx.compose.ui.test.assertIsNotEnabled import androidx.compose.ui.test.captureToImage import androidx.compose.ui.test.hasSetTextAction import androidx.compose.ui.test.hasText import androidx.compose.ui.test.hasAnyAncestor import androidx.compose.ui.test.isDialog import androidx.compose.ui.test.junit4.createComposeRule import androidx.compose.ui.test.onAllNodesWithText 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.compose.ui.test.performTextReplacement import androidx.test.ext.junit.runners.AndroidJUnit4 import com.cottondb.android.ScreenEvidence import com.cottondb.android.core.FakeCore import com.cottondb.android.design.CottonTheme import com.cottondb.android.settings.devices.DevicesModel import com.cottondb.android.settings.devices.DevicesRepository import java.time.Clock import java.time.Instant import java.time.ZoneId import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import kotlinx.coroutines.SupervisorJob import kotlinx.serialization.json.Json import kotlinx.serialization.json.jsonPrimitive import org.junit.After import org.junit.Assert.assertEquals import org.junit.Assert.assertTrue import org.junit.Before import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith @RunWith(AndroidJUnit4::class) class DevicesScreenTest { @get:Rule val compose = createComposeRule() private lateinit var writerJob: Job private lateinit var writer: CoroutineScope @Before fun startWriter() { writerJob = SupervisorJob() writer = CoroutineScope(writerJob + Dispatchers.Main.immediate) } @After fun closeWriter() { writerJob.cancel() } @Test fun approvingPendingDeviceEchoesItsExactSixDigits() { val core = FakeCore().withSnapshot(pending = pending(digits = "482193")) val model = DevicesModel(DevicesRepository(core)) show(model) await("Joining Slate") ScreenEvidence.capture("devices-list") { compose.onRoot().captureToImage().asAndroidBitmap() } compose.onNodeWithContentDescription("Joining Slate").performClick() await("Approve") ScreenEvidence.capture("device-approval") { compose.onNode(isDialog()).captureToImage().asAndroidBitmap() } compose.onNodeWithText("Approve").performClick() compose.waitUntil(timeoutMillis = 5_000) { core.calls.any { it.method == "devices.approvePending" } } val call = core.calls.single { it.method == "devices.approvePending" } assertEquals("pairing-slate", call.request["pairingId"]!!.jsonPrimitive.content) assertEquals("482193", call.request["digits"]!!.jsonPrimitive.content) } @Test fun pendingDeviceWithoutDigitsCannotBeApproved() { val core = FakeCore().withSnapshot(pending = pending(digits = null)) show(DevicesModel(DevicesRepository(core))) await("Joining Slate") compose.onNodeWithContentDescription("Joining Slate").performClick() compose.waitUntil(timeoutMillis = 5_000) { compose.onAllNodesWithText("Approve").fetchSemanticsNodes().isNotEmpty() } compose.onNodeWithText("Approve").assertIsNotEnabled() assertTrue(core.calls.none { it.method == "devices.approvePending" }) } @Test fun remoteEraseRequiresConfirmationAndSendsAnExplicitEraseChoice() { val core = FakeCore().withSnapshot(approved = devices(remote())) val model = DevicesModel(DevicesRepository(core)) show(model) await("Archive Mac") compose.onNodeWithContentDescription("Archive Mac").performClick() await("Remove and erase") compose.onNodeWithText("Remove and erase").performClick() compose.waitUntil(timeoutMillis = 5_000) { compose.onAllNodesWithText("Remove and erase").fetchSemanticsNodes().isNotEmpty() } compose.onNodeWithText("Remove and erase").performClick() compose.waitUntil(timeoutMillis = 5_000) { core.calls.any { it.method == "devices.revoke" } } val revoke = core.calls.single { it.method == "devices.revoke" } assertEquals("device-archive", revoke.request["deviceId"]!!.jsonPrimitive.content) assertEquals("true", revoke.request["erase"]!!.jsonPrimitive.content) } @Test fun currentDeviceDoesNotOfferRemoval() { val core = FakeCore().withSnapshot(approved = devices(current())) show(DevicesModel(DevicesRepository(core))) await("This synthetic phone") compose.onNodeWithContentDescription("This synthetic phone").performClick() compose.waitUntil(timeoutMillis = 5_000) { compose.onAllNodesWithText("This is the phone you're using").fetchSemanticsNodes().isNotEmpty() } assertTrue(compose.onAllNodesWithText("Remove this device").fetchSemanticsNodes().isEmpty()) assertTrue(compose.onAllNodesWithText("Remove and erase").fetchSemanticsNodes().isEmpty()) } @Test fun failedRenameRetriesTheSameDeviceAndName() { val core = FakeCore().withSnapshot(approved = devices(remote())) core.fail("devices.rename", IllegalStateException("Synthetic rename failure")) val model = DevicesModel(DevicesRepository(core)) show(model) await("Archive Mac") compose.onNodeWithContentDescription("Archive Mac").performClick() compose.onNode(hasSetTextAction() and hasText("Archive Mac")).performTextReplacement("Renamed Archive") compose.onNodeWithText("Rename").performClick() compose.waitUntil(timeoutMillis = 5_000) { compose.onAllNodesWithText("Synthetic rename failure").fetchSemanticsNodes().isNotEmpty() } core.answer("devices.rename", Json.parseToJsonElement("{}")) compose.onNode(hasText("Retry") and hasAnyAncestor(isDialog())).performClick() compose.waitUntil(timeoutMillis = 5_000) { core.calls.count { it.method == "devices.rename" } == 2 } val renames = core.calls.filter { it.method == "devices.rename" } assertEquals(listOf("device-archive", "device-archive"), renames.map { it.request["deviceId"]!!.jsonPrimitive.content }) assertEquals(listOf("Renamed Archive", "Renamed Archive"), renames.map { it.request["name"]!!.jsonPrimitive.content }) } private fun show(model: DevicesModel) { compose.setContent { CottonTheme { DevicesScreen( model = model, writerScope = writer, databaseName = "Synthetic database", clock = fixedClock, onBack = {}, onOpenRejectedWrites = {}, ) } } } private fun await(label: String) { compose.waitUntil(timeoutMillis = 5_000) { compose.onAllNodesWithText(label).fetchSemanticsNodes().isNotEmpty() } } private fun FakeCore.withSnapshot( approved: String = devices(current(), remote()), pending: String = pending(digits = null), ): FakeCore = apply { answer("devices.list", Json.parseToJsonElement(approved)) answer("devices.pending", Json.parseToJsonElement(pending)) answer("devices.approvePending", Json.parseToJsonElement("{}")) answer("devices.revoke", Json.parseToJsonElement("{}")) } private companion object { @Suppress("unused") val fixedClock: Clock = Clock.fixed(Instant.parse("2026-09-22T00:00:00Z"), ZoneId.of("UTC")) fun devices(vararg rows: String) = """{"devices":[${rows.joinToString()}],"thisDevice":"device-current"}""" fun current() = device( id = "device-current", name = "This synthetic phone", platform = "android", ) fun remote() = device( id = "device-archive", name = "Archive Mac", platform = "mac", ) fun device(id: String, name: String, platform: String) = """ {"deviceId":"$id","name":"$name","platform":"$platform","appVersion":"0.1", "lastSeenAt":"2026-09-22T00:00:00Z","revokedAt":null,"approvedBy":null, "revokedBy":null,"serving":false} """.trimIndent() fun pending(digits: String?) = """{"pending":[ {"pairingId":"pairing-slate","name":"Joining Slate","platform":"android","appVersion":"0.1", "createdAt":"2026-09-22T00:00:00Z","expiresAt":"2026-09-22T00:10:00Z", "digits":${digits?.let { "\"$it\"" } ?: "null"}} ]}""".trimIndent() } }