package com.cottondb.android.keyboard import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.platform.app.InstrumentationRegistry import com.cottondb.android.core.CottonCore import java.io.File import java.util.Base64 import java.util.UUID import kotlinx.coroutines.runBlocking import kotlinx.serialization.json.JsonArray import kotlinx.serialization.json.JsonObject import kotlinx.serialization.json.buildJsonObject import kotlinx.serialization.json.jsonArray import kotlinx.serialization.json.jsonObject import kotlinx.serialization.json.jsonPrimitive import kotlinx.serialization.json.long import kotlinx.serialization.json.boolean import kotlinx.serialization.json.put import org.junit.After import org.junit.Assert.assertEquals import org.junit.Assert.assertFalse import org.junit.Assert.assertTrue import org.junit.Test import org.junit.runner.RunWith /** * JNI fixture for the primary-process keyboard bridge. It uses only public core calls and a * synthetic private workspace; database tables are never inspected directly. */ @RunWith(AndroidJUnit4::class) class NativeKeyboardSnapshotBridgeContractTest { private val context = InstrumentationRegistry.getInstrumentation().targetContext private val container = File(context.noBackupFilesDir, "keyboard-bridge-native-${UUID.randomUUID()}") @After fun removeSyntheticContainer() { container.deleteRecursively() } @Test fun typedOutboxBecomesCorpusRowAndStoresTheFlatNativeSnapshot() = runBlocking { val core = opened() try { val channel = Channel(root(typed("typed-1", words = 3))) val bridge = bridge(core, channel) bridge.foreground() val stats = core.call("read.dictationStats").jsonObject assertEquals(1L, stats["count"]!!.jsonPrimitive.long) assertEquals(3L, stats["words"]!!.jsonPrimitive.long) assertTrue(channel.value[KeyboardChannelKeys.OUTBOX]!!.jsonArray.isEmpty()) val snapshot = channel.value[KeyboardChannelKeys.SNAPSHOT]!!.jsonObject assertTrue(snapshot["asOf"]!!.jsonPrimitive.content.isNotBlank()) assertTrue(snapshot["settings"]!!.jsonObject["typedCapture"]!!.jsonPrimitive.boolean) assertTrue(snapshot["takes"] is JsonArray) } finally { core.close() } } @Test fun nativeTypedRefusalLeavesTheExactOutboxEventForRetry() = runBlocking { val core = opened() try { val channel = Channel(root(typed("bad-words", words = -1))) val bridge = bridge(core, channel) bridge.foreground() assertTrue(bridge.state.warning is KeyboardBridgeWarning.NativeFailure) val stored = channel.value[KeyboardChannelKeys.OUTBOX]!!.jsonArray.single().jsonObject assertEquals("bad-words", stored["id"]!!.jsonPrimitive.content) assertFalse(stored.containsKey("claim")) assertEquals(0L, core.call("read.dictationStats").jsonObject["count"]!!.jsonPrimitive.long) } finally { core.close() } } @Test fun nativeTakePendingCarriesThenTakeReceiptClearsWithoutAnotherDictation() = runBlocking { val core = opened() try { val created = core.call("dictation.create", buildJsonObject { put("text", "synthetic deliberate take"); put("source", "take"); put("words", 3) put("spokenAt", "2030-01-01T00:00:00.000Z") }).jsonObject["id"]!!.jsonPrimitive.content val channel = Channel(root(snapshot = standingPending(created))) val bridge = bridge(core, channel) // Rust owns the carry window; the bridge supplies standing raw pending state only. bridge.foreground() assertTrue(channel.value[KeyboardChannelKeys.SNAPSHOT]!!.jsonObject["takes"]!!.jsonArray .single { it.jsonObject["id"]!!.jsonPrimitive.content == created } .jsonObject["pending"]!!.jsonPrimitive.boolean) channel.value = channel.value.withOutbox(JsonArray(listOf(takeInserted("receipt-1", created)))) bridge.foreground() val take = channel.value[KeyboardChannelKeys.SNAPSHOT]!!.jsonObject["takes"]!!.jsonArray .single { it.jsonObject["id"]!!.jsonPrimitive.content == created }.jsonObject assertFalse(take["pending"]!!.jsonPrimitive.boolean) assertTrue(channel.value[KeyboardChannelKeys.OUTBOX]!!.jsonArray.isEmpty()) assertEquals(1L, core.call("read.dictationStats").jsonObject["count"]!!.jsonPrimitive.long) } finally { core.close() } } private suspend fun opened(): CottonCore = CottonCore.open(buildJsonObject { put("containerPath", container.absolutePath); put("appVersion", "0.0.0-instrumented"); put("timeZone", "Etc/UTC") put("deviceSecret", Base64.getUrlEncoder().withoutPadding().encodeToString(ByteArray(32) { 0x4b })) }).also { core -> core.call("workspace.startLocal", buildJsonObject { put("deviceName", "Synthetic keyboard bridge"); put("appVersion", "0.0.0-instrumented") }) } private fun bridge(core: CottonCore, channel: Channel) = KeyboardSnapshotBridge( core, channel, KeyboardBridgeClock { "2030-01-01T00:05:00.000Z" }, { true }, ) private fun root(event: JsonObject? = null, snapshot: JsonObject? = null) = buildJsonObject { put(KeyboardChannelKeys.OUTBOX, JsonArray(listOfNotNull(event))); snapshot?.let { put(KeyboardChannelKeys.SNAPSHOT, it) } } private fun typed(id: String, words: Long) = buildJsonObject { put("id", id); put("kind", "typed"); put("at", "2030-01-01T00:01:00.000Z"); put("text", "synthetic typed words"); put("words", words) } private fun takeInserted(id: String, takeId: String) = buildJsonObject { put("id", id); put("kind", "takeInserted"); put("at", "2030-01-01T00:05:00.000Z"); put("takeId", takeId) } private fun standingPending(id: String) = buildJsonObject { put("asOf", "2030-01-01T00:00:00.000Z"); put("settings", buildJsonObject { put("typedCapture", true) }) put("takes", JsonArray(listOf(buildJsonObject { put("id", id); put("text", "synthetic deliberate take"); put("words", 3); put("createdAt", "2030-01-01T00:00:00.000Z"); put("pending", true) }))) } private class Channel(initial: JsonObject) : KeyboardChannelStore { var value = initial override suspend fun read() = value override suspend fun update(transform: (JsonObject) -> JsonObject): JsonObject = transform(value).also { value = it } } } private fun JsonObject.withOutbox(events: JsonArray) = JsonObject(this + (KeyboardChannelKeys.OUTBOX to events))