package com.cottondb.android.ui import androidx.compose.ui.graphics.asAndroidBitmap import androidx.compose.ui.test.captureToImage import androidx.compose.ui.test.onRoot import com.cottondb.android.ScreenEvidence import androidx.compose.ui.test.junit4.createComposeRule import androidx.compose.ui.test.onNodeWithContentDescription import androidx.compose.ui.test.onNodeWithText import androidx.compose.ui.test.onAllNodesWithText import androidx.compose.ui.test.performClick import androidx.compose.ui.test.performTextInput import androidx.compose.ui.test.assertIsNotEnabled import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.platform.app.InstrumentationRegistry import com.cottondb.android.capture.CaptureModel import com.cottondb.android.capture.CaptureRepository import com.cottondb.android.capture.CaptureStart import com.cottondb.android.capture.CaptureState import com.cottondb.android.core.CoreException import com.cottondb.android.core.CottonCalling import com.cottondb.android.core.CottonCore import com.cottondb.android.core.CottonEvent import com.cottondb.android.core.MalformedCoreEventException import com.cottondb.android.day.thoughts.ThoughtRepository import com.cottondb.android.design.CottonTheme import com.cottondb.android.ui.capture.CaptureOverlay import java.io.File import java.util.Base64 import java.util.UUID import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.cancel import kotlinx.coroutines.runBlocking import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.SharedFlow import kotlinx.serialization.json.JsonElement import kotlinx.serialization.json.JsonObject import kotlinx.serialization.json.JsonPrimitive import kotlinx.serialization.json.buildJsonObject import kotlinx.serialization.json.put import org.junit.After import org.junit.Assert.assertEquals import org.junit.Assert.assertTrue import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith /** Compose capture behavior over a real, isolated JNI workspace. */ @RunWith(AndroidJUnit4::class) class CaptureScreenTest { @get:Rule val compose = createComposeRule() private val context = InstrumentationRegistry.getInstrumentation().targetContext private val container = File(context.noBackupFilesDir, "capture-ui-test-${UUID.randomUUID()}") @After fun removeSyntheticContainer() { container.deleteRecursively() } @Test fun typedCaptureSavesThroughTheRealJniCore() = runBlocking { val core = openedCore("Android capture UI test") val writerScope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate) try { val model = CaptureModel(CaptureRepository(core)) var kept: String? = null compose.setContent { CottonTheme { CaptureOverlay( model = model, start = CaptureStart.Typing, writerScope = writerScope, requestMicrophone = { error("Typing must not ask for microphone permission.") }, onKept = { kept = it }, onClose = {}, ) } } compose.onNodeWithContentDescription("Anything on your mind?") .performTextInput("JNI Compose capture") compose.onNodeWithContentDescription("Capture this thought").performClick() compose.waitUntil(timeoutMillis = 5_000) { kept != null } val thought = ThoughtRepository(core).read().thoughts.single { it.id == kept } assertEquals("JNI Compose capture", thought.rawText) } finally { writerScope.cancel() core.close() } } @Test fun closeDiscardsTheTypedDraftWithoutCreatingACapture() = runBlocking { val core = openedCore("Android cancelled capture UI test") val writerScope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate) try { val model = CaptureModel(CaptureRepository(core)) var closes = 0 compose.setContent { CottonTheme { CaptureOverlay( model = model, start = CaptureStart.Typing, writerScope = writerScope, requestMicrophone = { error("Typing must not ask for microphone permission.") }, onKept = {}, onClose = { closes += 1 }, ) } } compose.onNodeWithContentDescription("Anything on your mind?") .performTextInput("draft that must stay local") compose.onNodeWithContentDescription("Close and discard this capture").performClick() compose.waitUntil(timeoutMillis = 2_000) { closes == 1 } assertTrue(ThoughtRepository(core).read().thoughts.isEmpty()) } finally { writerScope.cancel() core.close() } } @Test fun deniedMicrophoneKeepsTheOverlayAndNamesTheRequiredPermission() = runBlocking { val core = openedCore("Android capture permission UI test") val writerScope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate) try { val model = CaptureModel(CaptureRepository(core)) compose.setContent { CottonTheme { CaptureOverlay( model = model, start = CaptureStart.Listening, writerScope = writerScope, requestMicrophone = { result -> result(false) }, onKept = {}, onClose = {}, ) } } val message = "Dictation needs microphone access — you can turn it on in Settings." compose.waitUntil(timeoutMillis = 2_000) { compose.onAllNodesWithText(message).fetchSemanticsNodes().isNotEmpty() } compose.onNodeWithText(message).assertExists() compose.onNodeWithText("Keep editing").performClick() compose.onNodeWithContentDescription("Anything on your mind?").assertExists() assertTrue(ThoughtRepository(core).read().thoughts.isEmpty()) } finally { writerScope.cancel() core.close() } } @Test fun malformedCreateFreezesTheDraftWithoutASecondSendOrListenAndCanClose() = runBlocking { val core = FakeCaptureCore(JsonPrimitive("not a receipt")) val writerScope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate) try { val model = CaptureModel(CaptureRepository(core)) var microphoneRequests = 0 var closes = 0 compose.setContent { CottonTheme { CaptureOverlay( model = model, start = CaptureStart.Typing, writerScope = writerScope, requestMicrophone = { microphoneRequests += 1 }, onKept = {}, onClose = { closes += 1 }, ) } } compose.onNodeWithContentDescription("Anything on your mind?") .performTextInput("draft whose receipt is malformed") compose.onNodeWithContentDescription("Capture this thought").performClick() val warning = "The capture may have been saved, so it will not be sent again." compose.waitUntil(2_000) { compose.onAllNodesWithText(warning).fetchSemanticsNodes().isNotEmpty() } ScreenEvidence.capture("capture-unconfirmed") { compose.onRoot().captureToImage().asAndroidBitmap() } assertEquals(1, core.calls) assertEquals( "draft whose receipt is malformed", (model.state.value as CaptureState.Error).draft, ) compose.onNodeWithContentDescription("Speak a thought").assertIsNotEnabled() compose.onNodeWithContentDescription("Capture this thought").assertIsNotEnabled() assertTrue(compose.onAllNodesWithText("Keep editing").fetchSemanticsNodes().isEmpty()) assertEquals(0, microphoneRequests) compose.onNodeWithContentDescription("Close capture").performClick() compose.waitUntil(2_000) { closes == 1 } assertEquals(1, core.calls) assertEquals(0, microphoneRequests) } finally { writerScope.cancel() } } @Test fun knownRefusalKeepsTheRetryableEditingDialog() = runBlocking { val core = FakeCaptureCore( CoreException("capture_refused", "Synthetic refusal", null), buildJsonObject { put("id", "capture-1") }, ) val writerScope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate) try { val model = CaptureModel(CaptureRepository(core)) var kept: String? = null compose.setContent { CottonTheme { CaptureOverlay( model = model, start = CaptureStart.Typing, writerScope = writerScope, requestMicrophone = { error("Typing must not request a microphone.") }, onKept = { kept = it }, onClose = {}, ) } } compose.onNodeWithContentDescription("Anything on your mind?").performTextInput("retryable draft") compose.onNodeWithContentDescription("Capture this thought").performClick() compose.waitUntil(2_000) { compose.onAllNodesWithText("Synthetic refusal").fetchSemanticsNodes().isNotEmpty() } compose.onNodeWithText("Keep editing").performClick() compose.onNodeWithContentDescription("Capture this thought").performClick() compose.waitUntil(2_000) { kept == "capture-1" } assertEquals(2, core.calls) } finally { writerScope.cancel() } } private suspend fun openedCore(deviceName: String): CottonCore { val core = CottonCore.open(buildJsonObject { put("containerPath", container.absolutePath) put("appVersion", "0.0.0-instrumented") put("timeZone", "Etc/UTC") put("deviceSecret", SYNTHETIC_DEVICE_SEED) }) core.call("workspace.startLocal", buildJsonObject { put("deviceName", deviceName) put("appVersion", "0.0.0-instrumented") }) return core } private companion object { val SYNTHETIC_DEVICE_SEED: String = Base64.getUrlEncoder().withoutPadding() .encodeToString(ByteArray(32) { 0x63 }) } } private class FakeCaptureCore(vararg replies: Any) : CottonCalling { override val events: SharedFlow = MutableSharedFlow() override val eventErrors: SharedFlow = MutableSharedFlow() private val replies = ArrayDeque(replies.toList()) var calls = 0 private set override suspend fun call(method: String, request: JsonObject): JsonElement { check(method == "capture.create") calls += 1 return when (val reply = replies.removeFirst()) { is Throwable -> throw reply is JsonElement -> reply else -> error("Unsupported fake reply: ${reply::class}") } } override suspend fun close() = Unit }