package com.cottondb.android.ui.navigation import androidx.activity.compose.setContent import kotlinx.coroutines.runBlocking import kotlinx.coroutines.withContext import android.Manifest import android.content.ClipboardManager import androidx.compose.ui.test.junit4.createAndroidComposeRule import androidx.compose.ui.test.onNodeWithContentDescription import androidx.compose.ui.test.onNodeWithText import androidx.compose.ui.test.performClick import androidx.test.ext.junit.runners.AndroidJUnit4 import com.cottondb.android.TakeModels import com.cottondb.android.capture.CaptureSpeechEvent 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.platform.PermissionHarnessActivity import com.cottondb.android.take.TakePhase import com.cottondb.android.take.TakeHandback import com.cottondb.android.take.TakeHandbackOutcome import com.cottondb.android.take.TakeVoice 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 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 @RunWith(AndroidJUnit4::class) class TakeHostTest { @get:Rule val compose = createAndroidComposeRule() private val instrumentation get() = androidx.test.platform.app.InstrumentationRegistry.getInstrumentation() private val context get() = instrumentation.targetContext private var fixture: Fixture? = null @After fun closeFixture() { instrumentation.runOnMainSync { fixture?.close() } } @Test fun grantedMicrophoneStartsOnceFinalWritesOnceAndCopyShowsFeedback() { grantMicrophonePermission() val host = mount("granted-visit") compose.waitUntil(5_000) { host.voice.starts.get() == 1 } instrumentation.runOnMainSync { host.voice.final("synthetic final take") } compose.waitUntil(5_000) { host.core.dictations.get() == 1 } compose.onNodeWithContentDescription("Copy").performClick() compose.onNodeWithText("Copied.").assertExists() val clipboard = context.getSystemService(ClipboardManager::class.java) assertEquals("synthetic final take", clipboard.primaryClip?.getItemAt(0)?.text) assertEquals(1, host.core.dictations.get()) } @Test fun recreationKeepsTheRetainedVisitAndDoesNotStartRecognitionAgain() { grantMicrophonePermission() val host = mount("recreate-visit") compose.waitUntil(5_000) { host.voice.starts.get() == 1 } compose.activityRule.scenario.recreate() compose.activityRule.scenario.onActivity { activity -> activity.setContent { CottonTheme { TakeHost(host.models, "recreate-visit", {}, { host.voiceFactoryCalls.incrementAndGet(); host.voice }) } } } compose.onNodeWithContentDescription("Done").assertExists() assertEquals(1, host.voiceFactoryCalls.get()) assertEquals(1, host.core.reads.get()) assertEquals(1, host.voice.starts.get()) } @Test fun discardInvokesBackAndReleasesTheListeningVoice() { grantMicrophonePermission() val host = mount("discard-visit") compose.waitUntil(5_000) { host.voice.starts.get() == 1 } compose.onNodeWithContentDescription("Discard").performClick() assertEquals(1, host.back.get()) assertTrue(host.voice.cancelled.get() > 0) instrumentation.runOnMainSync { assertEquals(TakePhase.Unavailable, host.models.take("discard-visit") { host.voice }.state.value.phase) } } @Test fun microphoneDeniedBoundaryDoesNotStartVoiceAndExplicitRetryStartsAfterGrant() { // Android can kill this instrumentation process when its own permission is revoked. // Exercise denial at the model boundary; PermissionHarnessActivityTest covers the real // ActivityResult denial callback independently. val host = Fixture() fixture = host val model = host.models.take("denied-visit") { host.voice } instrumentation.runOnMainSync { model.microphoneDenied() } assertEquals(TakePhase.Unavailable, model.state.value.phase) assertEquals(0, host.voice.starts.get()) grantMicrophonePermission() runBlocking { withContext(Dispatchers.Main) { model.retry()?.join() } } compose.waitUntil(5_000) { host.voice.starts.get() == 1 } assertEquals(1, host.core.reads.get()) } @Test fun publishedHandbackShowsReturnOnlyAfterTheFinalTakeIsPublished() { grantMicrophonePermission() val published = AtomicInteger() val returned = AtomicInteger() val host = Fixture(TakeHandback { _, _, _ -> published.incrementAndGet(); TakeHandbackOutcome.Published }) fixture = host compose.setContent { CottonTheme { TakeHost(host.models, "keyboard-return", {}, { host.voice }, { returned.incrementAndGet() }) } } compose.waitUntil(5_000) { host.voice.starts.get() == 1 } compose.onNodeWithContentDescription("Done").performClick() instrumentation.runOnMainSync { host.voice.final("synthetic return") } compose.waitUntil(5_000) { published.get() == 1 } compose.onNodeWithContentDescription("Return to keyboard").performClick() assertEquals(1, returned.get()) } @Test fun failedHandbackLeavesCopyVisibleWithoutReturn() { grantMicrophonePermission() val host = Fixture(TakeHandback { _, _, _ -> TakeHandbackOutcome.Failed("Keyboard unavailable; you can still copy this take.") }) fixture = host compose.setContent { CottonTheme { TakeHost(host.models, "keyboard-failed", {}, { host.voice }, {}) } } compose.waitUntil(5_000) { host.voice.starts.get() == 1 } compose.onNodeWithContentDescription("Done").performClick() instrumentation.runOnMainSync { host.voice.final("synthetic copy") } compose.waitUntil(5_000) { host.core.dictations.get() == 1 } compose.onNodeWithContentDescription("Copy").assertExists() compose.onNodeWithText("Keyboard unavailable; you can still copy this take.").assertExists() compose.onNodeWithContentDescription("Return to keyboard").assertDoesNotExist() } private fun mount(visit: String): Fixture { val host = Fixture() fixture = host compose.setContent { CottonTheme { TakeHost( models = host.models, visit = visit, onBack = { host.back.incrementAndGet() }, voiceFactory = { host.voiceFactoryCalls.incrementAndGet() host.voice }, ) } } return host } private fun grantMicrophonePermission() { shell("pm grant ${context.packageName} ${Manifest.permission.RECORD_AUDIO}") assertTrue(context.checkSelfPermission(Manifest.permission.RECORD_AUDIO) == android.content.pm.PackageManager.PERMISSION_GRANTED) } private fun shell(command: String) { android.os.ParcelFileDescriptor.AutoCloseInputStream(instrumentation.uiAutomation.executeShellCommand(command)).use { it.readBytes() } } private class Fixture(handback: TakeHandback? = null) { private val job = SupervisorJob() private val scope = CoroutineScope(job + Dispatchers.Main.immediate) val core = TakeCore() val voice = TakeVoiceFake() val voiceFactoryCalls = AtomicInteger() val back = AtomicInteger() val models = TakeModels(core, scope, scope, monotonicMillis = { 1_000L }, handback = handback) fun close() { models.retain(emptySet()) scope.cancel() } } private class TakeVoiceFake : TakeVoice { val starts = AtomicInteger() val cancelled = AtomicInteger() private var listener: ((CaptureSpeechEvent) -> Unit)? = null override fun start(biasTerms: List, listener: (CaptureSpeechEvent) -> Unit) { starts.incrementAndGet() this.listener = listener } override fun finish() = Unit override fun cancel() { cancelled.incrementAndGet() } fun final(text: String) { listener?.invoke(CaptureSpeechEvent.Final(text)) } } private class TakeCore : CottonCalling { override val events: SharedFlow = MutableSharedFlow() override val eventErrors: SharedFlow = MutableSharedFlow() val reads = AtomicInteger() val dictations = AtomicInteger() override suspend fun call(method: String, request: JsonObject): JsonElement = when (method) { "read.take" -> { reads.incrementAndGet() Json.parseToJsonElement( """{"corpusCount":0,"vocabularyTerms":["Cotton"],"biasTerms":["Cotton"]}""", ) } "dictation.create" -> { dictations.incrementAndGet() Json.parseToJsonElement("""{"id":"synthetic-take"}""") } else -> error("Unexpected Take host core method: $method") } override suspend fun close() = Unit } }