Modern Apps git

← Modern-Apps.git

voxels: add cov-x4 sync, pump, HUD and activity tests

Commit
e6d28e74f8b943ca5416c81fe6cb6ab67832d08c
Author
Vayun Mathur <[email protected]>
When
2026-11-16 14:07 UTC (20 days ago)
Parents
e106818
Coverage for games/voxels only (test code, no production changes):
VoxelsSync AES decrypt round-trips, protocol shapes, real-identity
sign/verify/seal/unseal and read-only relay pulls under Robolectric;
MultiplayerPump signed-op/presence gating via its private constructor
with a generated ML-DSA peer, plus companion host/client loop starts;
JoinRequests pending/deny/refresh/approve-owned branches; Compose
interactions for inventory, health, settings sliders/switches,
joysticks, furnace/trade/chest and OnlineHud peer changes; real
MainActivity/MenuActivity HUD, pause menu, creator and lifecycle flows.

Measured via :games:voxels:createMergedCoverageReport (report.xml):
instructions 33849 covered / 11425 missed before, 38024 / 7250 after
(+4175 covered).

Skipped as unreachable without the Rust engine or a relay write:
VoxelSurfaceView/GL rendering, VoxelsSync append/record write paths
(read-only pulls exercised instead), and MainActivity action-result
branches gated on engine output. No dead code found to delete.

Verified without ignore-failures:
./gradlew :games:voxels:testDevUnitTest :games:voxels:detekt :games:voxels:lint (green)

Diff

games/voxels/src/test/java/com/vayunmathur/games/voxels/VoxelsCovX4ActivityTest.kt
diff --git a/games/voxels/src/test/java/com/vayunmathur/games/voxels/VoxelsCovX4ActivityTest.kt b/games/voxels/src/test/java/com/vayunmathur/games/voxels/VoxelsCovX4ActivityTest.ktnew file mode 100644index 0000000000..32cc24a55d--- /dev/null+++ b/games/voxels/src/test/java/com/vayunmathur/games/voxels/VoxelsCovX4ActivityTest.kt@@ -0,0 +1,179 @@+package com.vayunmathur.games.voxels++import android.content.ClipData+import android.content.ClipboardManager+import android.content.Context+import android.content.Intent+import android.net.Uri+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.games.voxels.data.WorldInfo+import com.vayunmathur.games.voxels.data.WorldMeta+import com.vayunmathur.games.voxels.data.WorldMode+import com.vayunmathur.games.voxels.platform.MenuActivity+import com.vayunmathur.games.voxels.platform.MusicFx+import java.io.File+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNull+import kotlin.test.assertTrue+import org.junit.Test+import org.junit.runner.RunWith+import org.robolectric.Robolectric+import org.robolectric.RobolectricTestRunner+import org.robolectric.Shadows+import org.robolectric.annotation.Config+import org.robolectric.annotation.GraphicsMode+import org.robolectric.shadows.ShadowLooper++/** Cov-x4: MenuActivity join-link/clipboard/play glue and MainActivity launch variants. */+@RunWith(RobolectricTestRunner::class)+@GraphicsMode(GraphicsMode.Mode.NATIVE)+@Config(sdk = [34])+class VoxelsCovX4ActivityTest {+    private val ctx get() = ApplicationProvider.getApplicationContext<Context>()++    private fun menuActivity(intent: Intent? = null) =+        Robolectric.buildActivity(MenuActivity::class.java, intent ?: Intent(ctx, MenuActivity::class.java))++    private fun parse(activity: MenuActivity, intent: Intent?): Pair<String, String>? {+        val m = MenuActivity::class.java.getDeclaredMethod("parseJoinLink", Intent::class.java)+            .apply { isAccessible = true }+        @Suppress("UNCHECKED_CAST")+        return m.invoke(activity, intent) as Pair<String, String>?+    }++    private fun play(activity: MenuActivity, world: WorldInfo) {+        val m = MenuActivity::class.java.getDeclaredMethod("play", WorldInfo::class.java)+            .apply { isAccessible = true }+        m.invoke(activity, world)+    }++    private fun copy(activity: MenuActivity, text: String) {+        val m = MenuActivity::class.java.getDeclaredMethod("copyToClipboard", String::class.java)+            .apply { isAccessible = true }+        m.invoke(activity, text)+    }++    private fun world(online: Boolean, role: String) = WorldInfo(+        id = "w_1", dir = File(ctx.filesDir, "worlds/w_1").absolutePath,+        meta = WorldMeta(+            name = "W", seed = 42, created = 1, lastPlayed = 2, online = online,+            worldId = "shared-1", ownerDeviceId = "owner-9", role = role, keyB64 = "a2V5",+            mode = WorldMode.SURVIVAL,+        ),+    )++    @Test fun joinLinkParsingAcceptsOnlyWellFormedVoxelsLinks() {+        val controller = menuActivity().setup()+        val a = controller.get()+        assertEquals("world123" to "dev9", parse(a, Intent(Intent.ACTION_VIEW, Uri.parse("voxels://join/world123?owner=dev9"))))+        assertEquals("w" to "o", parse(a, Intent(Intent.ACTION_VIEW, Uri.parse("voxels://join/w?owner=o&x=1"))))+        assertNull(parse(a, null))+        assertNull(parse(a, Intent()))+        assertNull(parse(a, Intent(Intent.ACTION_VIEW, Uri.parse("https://join/world123?owner=dev9"))))+        assertNull(parse(a, Intent(Intent.ACTION_VIEW, Uri.parse("voxels://play/world123?owner=dev9"))))+        assertNull(parse(a, Intent(Intent.ACTION_VIEW, Uri.parse("voxels://join/world123"))))+        assertNull(parse(a, Intent(Intent.ACTION_VIEW, Uri.parse("voxels://join/world123?owner="))))+        assertNull(parse(a, Intent(Intent.ACTION_VIEW, Uri.parse("voxels://join/?owner=dev9"))))+        assertNull(parse(a, Intent(Intent.ACTION_VIEW, Uri.parse("voxels://join?owner=dev9"))))+        controller.pause().stop().destroy()+    }++    @Test fun clipboardCopyStoresDeviceIdAndIgnoresEmpty() {+        val controller = menuActivity().setup()+        val a = controller.get()+        val cm = ctx.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager+        cm.setPrimaryClip(ClipData.newPlainText("seed", "before"))+        copy(a, "")+        assertEquals("before", cm.primaryClip?.getItemAt(0)?.text)+        copy(a, "device-42")+        assertEquals("device-42", cm.primaryClip?.getItemAt(0)?.text)+        controller.pause().stop().destroy()+    }++    @Test fun playBuildsOfflineAndOnlineIntents() {+        val controller = menuActivity().setup()+        val a = controller.get()+        Shadows.shadowOf(a).clearNextStartedActivities()+        play(a, world(online = false, role = ""))+        var next = Shadows.shadowOf(a).nextStartedActivity+        assertEquals("W", next.getStringExtra("world_name"))+        assertEquals(42, next.getIntExtra("world_seed", -1))+        assertEquals(WorldMode.SURVIVAL, next.getStringExtra("world_mode"))+        assertFalse(next.getBooleanExtra("online", false))+        play(a, world(online = true, role = "owner"))+        next = Shadows.shadowOf(a).nextStartedActivity+        assertTrue(next.getBooleanExtra("online", false))+        assertEquals("shared-1", next.getStringExtra("world_id"))+        assertEquals("a2V5", next.getStringExtra("world_key"))+        assertEquals("owner-9", next.getStringExtra("owner_device"))+        assertEquals(1, next.getIntExtra("net_role", -1)) // owner hosts+        play(a, world(online = true, role = "editor"))+        next = Shadows.shadowOf(a).nextStartedActivity+        assertEquals(2, next.getIntExtra("net_role", -1)) // everyone else joins as a client+        controller.pause().stop().destroy()+    }++    @Test fun menuActivityResumePauseCyclesAndNewIntents() {+        val controller = menuActivity().setup()+        ShadowLooper.idleMainLooper()+        controller.resume().pause().resume()+        ShadowLooper.idleMainLooper()+        controller.newIntent(Intent(Intent.ACTION_VIEW, Uri.parse("voxels://join/warm?owner=o1")))+        ShadowLooper.idleMainLooper()+        controller.newIntent(Intent(Intent.ACTION_VIEW, Uri.parse("voxels://join/warm")))+        controller.pause().stop().destroy()+    }++    @Test fun mainActivityLaunchVariantsAndLifecycle() {+        fun launch(extras: Intent.() -> Unit) {+            val dir = File(ctx.filesDir, "worlds/w_covx4").apply { mkdirs() }+            val intent = Intent(ctx, MainActivity::class.java).apply {+                putExtra("world_dir", dir.absolutePath)+                extras()+            }+            val c = Robolectric.buildActivity(MainActivity::class.java, intent).setup()+            ShadowLooper.idleMainLooper()+            c.get().onWindowFocusChanged(true)+            c.get().onWindowFocusChanged(false)+            c.pause().stop().start().resume() // onStop pauses the game; returning shows the pause state+            ShadowLooper.idleMainLooper()+            c.pause().stop().destroy()+        }+        launch { putExtra("world_seed", 1); putExtra("world_mode", WorldMode.SURVIVAL); putExtra("world_name", "S") }+        launch { putExtra("world_seed", -5); putExtra("world_mode", WorldMode.CREATIVE) }+        launch { /* all defaults */ }+        launch {+            putExtra("online", true); putExtra("net_role", 1); putExtra("world_id", "wid")+            putExtra("world_key", "a2V5"); putExtra("owner_device", "owner"); putExtra("world_name", "Host")+        }+        launch {+            putExtra("online", true); putExtra("net_role", 2); putExtra("world_id", "wid2")+            putExtra("world_key", ""); putExtra("owner_device", ""); putExtra("world_name", "")+        }+    }++    @Test fun mainActivityDirectLaunchUsesDefaultWorld() {+        val c = Robolectric.buildActivity(MainActivity::class.java, Intent(ctx, MainActivity::class.java)).setup()+        ShadowLooper.idleMainLooper()+        assertTrue(File(ctx.filesDir, "worlds/default").exists())+        c.pause().stop().destroy()+    }++    @Test fun musicFxForegroundBackgroundAndDiscCycle() {+        MusicFx.stop()+        MusicFx.onForeground(ctx)+        ShadowLooper.idleMainLooper()+        MusicFx.setVolume(0.25f)+        MusicFx.onBackground()+        MusicFx.onForeground(ctx)+        MusicFx.toggle(ctx, "golden.ogg")+        MusicFx.toggle(ctx, "lullaby.ogg") // a different disc takes over+        MusicFx.toggle(ctx, null) // null resumes ambient+        MusicFx.toggle(ctx, "golden.ogg")+        MusicFx.toggle(ctx, "golden.ogg") // same disc stops it+        MusicFx.stop()+        MusicFx.stop() // stopping twice is safe+        MusicFx.onBackground()+    }+}
games/voxels/src/test/java/com/vayunmathur/games/voxels/VoxelsCovX4MainUiTest.kt
diff --git a/games/voxels/src/test/java/com/vayunmathur/games/voxels/VoxelsCovX4MainUiTest.kt b/games/voxels/src/test/java/com/vayunmathur/games/voxels/VoxelsCovX4MainUiTest.ktnew file mode 100644index 0000000000..509fb0aa91--- /dev/null+++ b/games/voxels/src/test/java/com/vayunmathur/games/voxels/VoxelsCovX4MainUiTest.kt@@ -0,0 +1,86 @@+package com.vayunmathur.games.voxels++import androidx.compose.ui.geometry.Offset+import androidx.compose.ui.test.isToggleable+import androidx.compose.ui.test.hasClickAction+import androidx.compose.ui.test.junit4.createAndroidComposeRule+import androidx.compose.ui.test.onAllNodesWithText+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.onRoot+import androidx.compose.ui.test.click+import androidx.compose.ui.test.performClick+import androidx.compose.ui.test.performTouchInput+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue+import org.junit.Rule+import org.junit.Test+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config+import org.robolectric.annotation.GraphicsMode++/** Cov-x4: in-game HUD interactions in the real MainActivity (engine absent on the JVM). */+@RunWith(RobolectricTestRunner::class)+@GraphicsMode(GraphicsMode.Mode.NATIVE)+@Config(sdk = [34])+class VoxelsCovX4MainUiTest {+    @get:Rule val rule = createAndroidComposeRule<MainActivity>()++    private fun exists(text: String) =+        rule.onAllNodesWithText(text, substring = true).fetchSemanticsNodes().isNotEmpty()++    private fun pressBack() {+        rule.runOnUiThread { rule.activity.onBackPressedDispatcher.onBackPressed() }+        rule.waitForIdle()+    }++    @Test fun hudHoldButtonsPressAndRelease() {+        rule.waitForIdle()+        assertTrue(exists("Use"))+        for (label in listOf("Use", "Jump", "Fly", "Sneak")) {+            if (exists(label)) {+                rule.onNodeWithText(label).performTouchInput { down(center); advanceEventTime(120); up() }+                rule.waitForIdle()+            }+        }+        // After Fly toggles, the vertical button relabels; sneak state resets with flight.+        if (exists("Land")) {+            rule.onNodeWithText("Land").performTouchInput { down(center); up() }+            rule.waitForIdle()+        }+        if (exists("Up")) {+            rule.onNodeWithText("Up").performTouchInput { down(center); up() }+            rule.onNodeWithText("Down").performTouchInput { down(center); up() }+            rule.waitForIdle()+        }+    }++    @Test fun backOpensPauseMenuAndResumeClosesIt() {+        rule.waitForIdle()+        assertFalse(exists("Resume"))+        pressBack()+        assertTrue(exists("Paused"))+        assertTrue(exists("Resume"))+        rule.onNodeWithText("Resume").performClick()+        rule.waitForIdle()+        assertFalse(exists("Resume"))+    }++    @Test fun backThenSaveAndQuitFinishesActivity() {+        rule.waitForIdle()+        pressBack()+        assertTrue(exists("Save & Quit to Menu"))+        rule.onNodeWithText("Save & Quit to Menu").performClick()+        rule.waitForIdle()+        assertTrue(rule.activity.isFinishing)+    }++    @Test fun topLeftIconButtonsArePresent() {+        rule.waitForIdle()+        // Pause, settings and the hotbar inventory button are the activity's click-action nodes.+        val clickables = rule.onAllNodes(hasClickAction()).fetchSemanticsNodes()+        assertEquals(3, clickables.size)+        assertTrue(clickables.any { it.boundsInRoot.top < 100f })+    }+}
games/voxels/src/test/java/com/vayunmathur/games/voxels/VoxelsCovX4MenuUiTest.kt
diff --git a/games/voxels/src/test/java/com/vayunmathur/games/voxels/VoxelsCovX4MenuUiTest.kt b/games/voxels/src/test/java/com/vayunmathur/games/voxels/VoxelsCovX4MenuUiTest.ktnew file mode 100644index 0000000000..9011229479--- /dev/null+++ b/games/voxels/src/test/java/com/vayunmathur/games/voxels/VoxelsCovX4MenuUiTest.kt@@ -0,0 +1,93 @@+package com.vayunmathur.games.voxels++import android.content.Intent+import androidx.compose.ui.test.hasClickAction+import androidx.compose.ui.test.hasText+import androidx.compose.ui.test.junit4.createAndroidComposeRule+import androidx.compose.ui.test.onAllNodesWithText+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.performClick+import androidx.compose.ui.test.performTextInput+import com.vayunmathur.games.voxels.platform.MenuActivity+import kotlin.test.assertEquals+import kotlin.test.assertTrue+import org.junit.Rule+import org.junit.Test+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.Shadows+import org.robolectric.annotation.Config+import org.robolectric.annotation.GraphicsMode++/** Cov-x4: the real MenuActivity — creator flow, refresh/copy and online hosting. */+@RunWith(RobolectricTestRunner::class)+@GraphicsMode(GraphicsMode.Mode.NATIVE)+@Config(sdk = [34])+class VoxelsCovX4MenuUiTest {+    @get:Rule val rule = createAndroidComposeRule<MenuActivity>()++    private fun exists(text: String) =+        rule.onAllNodesWithText(text, substring = true).fetchSemanticsNodes().isNotEmpty()++    @Test fun creatorFlowCreatesAndPlaysWorld() {+        rule.waitForIdle()+        Shadows.shadowOf(rule.activity).clearNextStartedActivities()+        rule.onNode(hasText("Create New World") and hasClickAction()).performClick()+        rule.waitForIdle()+        rule.onNodeWithText("World name", substring = true).performTextInput("X4 World")+        rule.waitForIdle()+        rule.onNode(hasText("Create & Play") and hasClickAction()).performClick()+        rule.waitForIdle()+        val next = Shadows.shadowOf(rule.activity).nextStartedActivity+        assertEquals(MainActivity::class.java.name, next?.component?.className)+        assertEquals("X4 World", next?.getStringExtra("world_name"))+    }++    @Test fun creatorBackReturnsToMenu() {+        rule.waitForIdle()+        rule.onNode(hasText("Create New World") and hasClickAction()).performClick()+        rule.waitForIdle()+        rule.onAllNodesWithText("Cancel", substring = true)[0].performClick()+        rule.waitForIdle()+        assertTrue(exists("Create New World"))+    }++    @Test fun refreshAndCopyDeviceId() {+        rule.waitForIdle()+        // Provisioning runs in a background effect; give the main looper a chance to show the id.+        Thread.sleep(500)+        rule.waitForIdle()+        if (exists("Refresh")) {+            rule.onNode(hasText("Refresh") and hasClickAction()).performClick()+            rule.waitForIdle()+        }+        if (exists("Copy")) {+            val copy = rule.onAllNodesWithText("Copy", substring = true)+            if (copy.fetchSemanticsNodes().isNotEmpty()) {+                runCatching { copy[0].performClick() }+                rule.waitForIdle()+            }+        }+        assertTrue(exists("Voxels") || exists("Select a world") || exists("world"))+    }++    @Test fun hostOnlineStartsWorldWhenOnline() {+        rule.waitForIdle()+        Thread.sleep(500)+        rule.waitForIdle()+        Shadows.shadowOf(rule.activity).clearNextStartedActivities()+        val host = rule.onAllNodesWithText("Host Online", substring = true)+        if (host.fetchSemanticsNodes().isNotEmpty()) {+            runCatching { host[0].performClick() }+            rule.waitForIdle()+            Thread.sleep(500)+            rule.waitForIdle()+        }+        // Hosting requires connectivity; offline the button is disabled and nothing starts.+        val next: Intent? = Shadows.shadowOf(rule.activity).peekNextStartedActivity()+        if (next != null) {+            assertEquals(MainActivity::class.java.name, next.component?.className)+            assertTrue(next.getBooleanExtra("online", false))+        }+    }+}
games/voxels/src/test/java/com/vayunmathur/games/voxels/network/VoxelsCovX4PumpTest.kt
diff --git a/games/voxels/src/test/java/com/vayunmathur/games/voxels/network/VoxelsCovX4PumpTest.kt b/games/voxels/src/test/java/com/vayunmathur/games/voxels/network/VoxelsCovX4PumpTest.ktnew file mode 100644index 0000000000..3ed1137d1a--- /dev/null+++ b/games/voxels/src/test/java/com/vayunmathur/games/voxels/network/VoxelsCovX4PumpTest.kt@@ -0,0 +1,264 @@+package com.vayunmathur.games.voxels.network++import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.e2ee.Pqc+import kotlin.io.encoding.Base64+import kotlin.io.encoding.ExperimentalEncodingApi+import com.vayunmathur.games.voxels.data.WorldManager+import com.vayunmathur.games.voxels.domain.NetFailure+import com.vayunmathur.games.voxels.domain.NetStatus+import java.lang.reflect.InvocationTargetException+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue+import kotlin.test.fail+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.delay+import kotlinx.coroutines.launch+import kotlinx.coroutines.runBlocking+import org.junit.Test+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config+import org.robolectric.annotation.GraphicsMode++/**+ * Cov-x4: MultiplayerPump gating (via its private constructor) and JoinRequests persistence.+ * Signed ops that would be accepted reach the native engine and are deliberately not exercised+ * past the gate: every case below is rejected before `netPushInbound`, which is the gate's job.+ */+@RunWith(RobolectricTestRunner::class)+@GraphicsMode(GraphicsMode.Mode.NATIVE)+@Config(sdk = [34])+@OptIn(ExperimentalEncodingApi::class)+class VoxelsCovX4PumpTest {+    private val ctx get() = ApplicationProvider.getApplicationContext<android.content.Context>()+    private val scope = CoroutineScope(Dispatchers.Unconfined)++    private fun pump(role: Int, ownerBundle: ByteArray? = byteArrayOf(1, 2, 3)): Any {+        val params = MultiplayerPump.Params("wid", "a2V5", "owner-dev", role, "World")+        val ctor = MultiplayerPump::class.java.getDeclaredConstructor(+            MultiplayerPump.Params::class.java, String::class.java,+            ByteArray::class.java, ByteArray::class.java,+        ).apply { isAccessible = true }+        return ctor.newInstance(params, "me-dev", ByteArray(32) { 7 }, ownerBundle)+    }++    private fun invoke(target: Any, name: String, types: Array<Class<*>>, vararg args: Any?) {+        val m = MultiplayerPump::class.java.getDeclaredMethod(name, *types).apply { isAccessible = true }+        try {+            m.invoke(target, *args)+        } catch (e: InvocationTargetException) {+            throw e.targetException+        }+    }++    @Suppress("UNCHECKED_CAST")+    private fun mutableField(target: Any, name: String): MutableCollection<String> {+        val f = MultiplayerPump::class.java.getDeclaredField(name).apply { isAccessible = true }+        return f.get(target) as MutableCollection<String>+    }++    @Suppress("UNCHECKED_CAST")+    private fun bundleField(target: Any): MutableMap<String, ByteArray> {+        val f = MultiplayerPump::class.java.getDeclaredField("bundles").apply { isAccessible = true }+        return f.get(target) as MutableMap<String, ByteArray>+    }++    private fun signedOp(author: String, ops: String = """{"type":"Place"}""", sig: String = "AAAA") =+        """{"author":"$author","sig":"$sig","ops":${org.json.JSONObject.quote(ops)}}"""++    @Test fun clientRejectsSelfEmptyAndNonOwnerOps() {+        val p = pump(role = 2)+        val sig = arrayOf(CoroutineScope::class.java, String::class.java)+        invoke(p, "handleSignedOp", sig, scope, signedOp("me-dev")) // self+        invoke(p, "handleSignedOp", sig, scope, signedOp("")) // empty author+        invoke(p, "handleSignedOp", sig, scope, """{"author":"peer","sig":"AAAA","ops":""}""") // empty ops+        invoke(p, "handleSignedOp", sig, scope, signedOp("peer")) // not the owner on a client+        invoke(p, "handleSignedOp", sig, scope, "not json")+        invoke(p, "handleSignedOp", sig, scope, "{}")+        // Owner-authored but the signature cannot verify against a garbage bundle.+        invoke(p, "handleSignedOp", sig, scope, signedOp("owner-dev"))+    }++    @Test fun clientWithoutOwnerBundleRejectsOwnerOps() {+        val p = pump(role = 2, ownerBundle = null)+        invoke(p, "handleSignedOp", arrayOf(CoroutineScope::class.java, String::class.java), scope, signedOp("owner-dev"))+    }++    @Test fun hostRejectsNonRosterAndUnverifiableOps() {+        val p = pump(role = 1)+        val sig = arrayOf(CoroutineScope::class.java, String::class.java)+        invoke(p, "handleSignedOp", sig, scope, signedOp("stranger")) // not in roster+        mutableField(p, "roster").add("peer")+        // Rostered but no cached bundle: the op is dropped and a fetch is scheduled.+        invoke(p, "handleSignedOp", sig, scope, signedOp("peer"))+        bundleField(p)["peer"] = byteArrayOf(9, 9, 9)+        // Rostered with a bundle, but the signature does not verify.+        invoke(p, "handleSignedOp", sig, scope, signedOp("peer"))+        invoke(p, "handleSignedOp", sig, scope, signedOp("peer", sig = "!!!"))+    }++    @Test fun presenceRejectsSelfAndMalformed() {+        val p = pump(role = 1)+        val sig = arrayOf<Class<*>>(String::class.java)+        invoke(p, "handlePresence", sig, """{"from":"me-dev","m":{"x":1}}""")+        invoke(p, "handlePresence", sig, "not json")+        invoke(p, "handlePresence", sig, "{}")+        invoke(p, "handlePresence", sig, """{"from":"peer"}""") // no transform object+        invoke(p, "handlePresence", sig, """{"from":"peer","m":"not-an-object"}""")+    }++    @Test fun verifyRejectsGarbageSignatures() {+        val p = pump(role = 1)+        val m = MultiplayerPump::class.java.getDeclaredMethod(+            "verify", ByteArray::class.java, String::class.java, String::class.java,+        ).apply { isAccessible = true }+        assertEquals(false, m.invoke(p, byteArrayOf(1, 2), "ops", "AAAA"))+        assertEquals(false, m.invoke(p, byteArrayOf(1, 2), "ops", "!!!not-base64!!!"))+        assertEquals(false, m.invoke(p, ByteArray(0), "", ""))+    }++    @Test fun pumpStartsWithEmptyRosterAndBundles() {+        val p = pump(role = 1)+        // A freshly built pump trusts nobody yet: the loop is what seeds owner + self.+        assertTrue(mutableField(p, "roster").isEmpty())+        assertTrue(bundleField(p).isEmpty())+        assertFalse(VoxelsSync.isLive)+    }++    @Test fun companionRunReportsUnreachableWithoutIdentity() = runBlocking {+        val statuses = mutableListOf<NetStatus>()+        MultiplayerPump.run(+            ctx, MultiplayerPump.Params("wid", "not-base64!!", "owner", 2, "W"),+            onStatus = { statuses += it }, onPeers = {},+        )+        // Identity setup fails on the JVM (no native PQC), so the session cannot start:+        // Connecting first, then the unreachable-server failure, never Connected.+        assertEquals(NetStatus.Connecting, statuses.first())+        assertTrue(statuses.any { it is NetStatus.Failed }, "statuses=$statuses")+        assertFalse(statuses.contains(NetStatus.Connected))+    }++    @Test fun paramsEqualityAndCopy() {+        val a = MultiplayerPump.Params("w", "k", "o", 1, "Name")+        assertEquals(a, a.copy())+        assertEquals("w", a.copy(worldId = "w").worldId)+        assertFalse(a == a.copy(role = 2))+        assertTrue(a.toString().contains("worldId=w"))+    }++    @Test fun hostAcceptsValidMemberSignatureUpToEngineGate() {+        // A real second identity: ML-DSA keypair generated here, signed op verified by the pump.+        val (kemPub, _) = Pqc.generateKem()+        val (dsaPub, dsaPriv) = Pqc.generateDsa()+        val bundle = Pqc.bundle(kemPub, dsaPub)+        val ops = """{"type":"Place","x":1}"""+        val sig = Base64.encode(Pqc.signWith(dsaPriv, ops.encodeToByteArray()))+        val p = pump(role = 1)+        mutableField(p, "roster").add("peer-x")+        bundleField(p)["peer-x"] = bundle+        // Verification passes, so the gate hands the op to the engine — absent on the JVM.+        val thrown = runCatching {+            invoke(p, "handleSignedOp", arrayOf(CoroutineScope::class.java, String::class.java), scope, signedOp("peer-x", ops, sig))+        }.exceptionOrNull()+        assertTrue(thrown == null || thrown is UnsatisfiedLinkError, "thrown=$thrown")+        // The same op with a forged signature is rejected before the engine.+        val badSig = Base64.encode(Pqc.signWith(dsaPriv, "other".encodeToByteArray()))+        invoke(p, "handleSignedOp", arrayOf(CoroutineScope::class.java, String::class.java), scope, signedOp("peer-x", ops, badSig))+    }++    @Test fun clientAcceptsValidOwnerSignatureUpToEngineGate() {+        val (kemPub, _) = Pqc.generateKem()+        val (dsaPub, dsaPriv) = Pqc.generateDsa()+        val bundle = Pqc.bundle(kemPub, dsaPub)+        val ops = """{"type":"Snapshot"}"""+        val sig = Base64.encode(Pqc.signWith(dsaPriv, ops.encodeToByteArray()))+        val p = pump(role = 2, ownerBundle = bundle)+        val thrown = runCatching {+            invoke(p, "handleSignedOp", arrayOf(CoroutineScope::class.java, String::class.java), scope, signedOp("owner-dev", ops, sig))+        }.exceptionOrNull()+        assertTrue(thrown == null || thrown is UnsatisfiedLinkError, "thrown=$thrown")+        // Valid presence from a peer also reaches the engine gate.+        val thrown2 = runCatching {+            invoke(p, "handlePresence", arrayOf<Class<*>>(String::class.java), """{"from":"peer","m":{"type":"PlayerTransform"}}""")+        }.exceptionOrNull()+        assertTrue(thrown2 == null || thrown2 is UnsatisfiedLinkError, "thrown=$thrown2")+    }++    @Test fun companionLoopStartsAndReportsConnecting() = runBlocking {+        assertTrue(VoxelsSync.init(ctx))+        val statuses = mutableListOf<NetStatus>()+        val scope2 = CoroutineScope(kotlinx.coroutines.SupervisorJob() + Dispatchers.Default)+        val job = scope2.launch {+            MultiplayerPump.run(+                ctx,+                MultiplayerPump.Params(+                    "x4-loop-world", Base64.encode(VoxelsSync.newWorldKey()),+                    VoxelsSync.deviceId, 1, "Loop World",+                ),+                onStatus = { statuses += it }, onPeers = {},+            )+        }+        delay(1500)+        job.cancel()+        VoxelsSync.stopLive()+        assertEquals(NetStatus.Connecting, statuses.first())+        Unit+    }+++    @Test fun companionLoopClientFetchesOwnerBundle() = runBlocking {+        assertTrue(VoxelsSync.init(ctx))+        val statuses = mutableListOf<NetStatus>()+        val scope2 = CoroutineScope(kotlinx.coroutines.SupervisorJob() + Dispatchers.Default)+        val job = scope2.launch {+            MultiplayerPump.run(+                ctx,+                MultiplayerPump.Params(+                    "x4-loop-world-client", Base64.encode(VoxelsSync.newWorldKey()),+                    VoxelsSync.deviceId, 2, "Client World",+                ),+                onStatus = { statuses += it }, onPeers = {},+            )+        }+        delay(1200)+        job.cancel()+        VoxelsSync.stopLive()+        assertEquals(NetStatus.Connecting, statuses.first())+        Unit+    }++    // --- JoinRequests ---++    private fun req(world: String, who: String, name: String = "") =+        VoxelsSync.JoinRequest(worldId = world, requesterId = who, name = name)++    @Test fun pendingFiltersDuplicatesHandledAndForeign() {+        assertEquals("w1|dev9", JoinRequests.handledKey(req("w1", "dev9")))+        assertTrue(JoinRequests.pending(emptyList(), setOf("w1"), emptySet()).isEmpty())+        assertTrue(JoinRequests.pending(listOf(req("w1", "a")), emptySet(), emptySet()).isEmpty())+        assertTrue(JoinRequests.pending(listOf(req("w1", "a")), setOf("w1"), setOf("w1|a")).isEmpty())+        val kept = JoinRequests.pending(+            listOf(req("w2", "x"), req("w1", "b", "Bob"), req("w1", "b", "Bob2"), req("w1", "a")),+            owned = setOf("w1", "w2"), handled = emptySet(),+        )+        // First occurrence wins for a duplicate requester+world pair.+        assertEquals(listOf("", "Bob", ""), kept.map { it.name })+        assertEquals(listOf("x", "b", "a"), kept.map { it.requesterId })+    }++    @Test fun denyPersistsHandledKeyAndRefreshDegradesOffline() = runBlocking {+        val r = req("world-deny", "dev-deny")+        JoinRequests.deny(ctx, r)+        assertTrue(JoinRequests.handledKey(r) in WorldManager.handledRequests(ctx))+        JoinRequests.deny(ctx, r) // idempotent+        assertEquals(1, WorldManager.handledRequests(ctx).count { it == JoinRequests.handledKey(r) })+        // Without a sync identity the inbox refresh yields no requests instead of throwing.+        assertEquals(emptyList(), JoinRequests.refresh(ctx, acceptInvites = true))+        assertEquals(emptyList(), JoinRequests.refresh(ctx, acceptInvites = false))+        // Approving a world this device does not own fails cleanly.+        assertFalse(JoinRequests.approve(ctx, req("no-such-world", "dev-x")))+    }+}
games/voxels/src/test/java/com/vayunmathur/games/voxels/network/VoxelsCovX4SyncRoboTest.kt
diff --git a/games/voxels/src/test/java/com/vayunmathur/games/voxels/network/VoxelsCovX4SyncRoboTest.kt b/games/voxels/src/test/java/com/vayunmathur/games/voxels/network/VoxelsCovX4SyncRoboTest.ktnew file mode 100644index 0000000000..bb627ab059--- /dev/null+++ b/games/voxels/src/test/java/com/vayunmathur/games/voxels/network/VoxelsCovX4SyncRoboTest.kt@@ -0,0 +1,131 @@+package com.vayunmathur.games.voxels.network++import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.games.voxels.data.WorldManager+import kotlin.io.encoding.Base64+import kotlin.io.encoding.ExperimentalEncodingApi+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue+import kotlin.test.fail+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.delay+import kotlinx.coroutines.runBlocking+import org.junit.Test+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config+import org.robolectric.annotation.GraphicsMode++/**+ * Cov-x4: VoxelsSync with a real identity (native PQC loads on the host JVM).+ * Read-only relay paths only: no world/members appends are exercised, so nothing is+ * written to shared relay channels beyond the device registration `init` itself performs.+ */+@RunWith(RobolectricTestRunner::class)+@GraphicsMode(GraphicsMode.Mode.NATIVE)+@Config(sdk = [34])+@OptIn(ExperimentalEncodingApi::class)+class VoxelsCovX4SyncRoboTest {+    private val ctx get() = ApplicationProvider.getApplicationContext<android.content.Context>()++    @Test fun initIsIdempotentAndIdentityCryptoRoundTrips() = runBlocking {+        assertTrue(VoxelsSync.init(ctx))+        val id = VoxelsSync.deviceId+        assertTrue(id.isNotBlank())+        assertTrue(VoxelsSync.init(ctx)) // second call is a no-op success+        assertEquals(id, VoxelsSync.deviceId)+        val bundle = VoxelsSync.publicBundle+        assertTrue(bundle.size > 100)+        // Sign/verify: valid signature passes, tampered data and garbage bundles fail.+        val data = "signed ops".encodeToByteArray()+        val sig = VoxelsSync.sign(data)+        assertTrue(VoxelsSync.verify(bundle, data, sig))+        assertFalse(VoxelsSync.verify(bundle, "other".encodeToByteArray(), sig))+        assertFalse(VoxelsSync.verify(byteArrayOf(1, 2, 3), data, sig))+        val tampered = sig.copyOf(); tampered[0] = (tampered[0].toInt() xor 1).toByte()+        assertFalse(VoxelsSync.verify(bundle, data, tampered))+        // Seal to ourselves and unseal; garbage ciphertext must not decode silently.+        val sealed = VoxelsSync.seal(bundle, "invite payload".encodeToByteArray())+        assertEquals("invite payload", VoxelsSync.unseal(sealed).decodeToString())+        try {+            VoxelsSync.unseal(byteArrayOf(1, 2, 3))+            fail("unsealing garbage should throw")+        } catch (e: Exception) {+            assertTrue(e.message != null || e is RuntimeException)+        }+        // Safety code against our own bundle is a stable, non-empty string.+        val code = VoxelsSync.securityCode(bundle)+        assertNotNull(code)+        assertEquals(code, VoxelsSync.securityCode(bundle))+        assertTrue(code.isNotBlank())+    }++    @Test fun relayReadsForMissingPeersAndEmptyChannels() = runBlocking {+        assertTrue(VoxelsSync.init(ctx))+        assertNull(VoxelsSync.getKey("no-such-device-x4-zzz"))+        // Our own registered bundle is fetchable and identical to the local one.+        val own = VoxelsSync.getKey(VoxelsSync.deviceId)+        assertNotNull(own)+        assertTrue(own.contentEquals(VoxelsSync.publicBundle))+        val key = VoxelsSync.newWorldKey()+        val ops = VoxelsSync.pullWorldOps("x4-empty-${VoxelsSync.newWorldId()}", key, 0)+        assertTrue(ops.items.isEmpty())+        assertTrue(VoxelsSync.pullMembers("x4-empty-${VoxelsSync.newWorldId()}", key).isEmpty())+        assertTrue(VoxelsSync.fetchRoster("x4-empty-${VoxelsSync.newWorldId()}", key, VoxelsSync.publicBundle).isEmpty())+        val inbox = VoxelsSync.pullInbox(0)+        assertTrue(inbox.seq >= 0)+        val invites = VoxelsSync.pullInvites(0)+        assertEquals(inbox.seq, invites.seq)+        assertTrue(VoxelsSync.pullRaw("x4-empty-${VoxelsSync.newWorldId()}", 0).isEmpty())+        // Invites/requests addressed to devices the relay does not know cannot be sent.+        assertFalse(+            VoxelsSync.sendInvite(+                "no-such-device-x4-zzz", "wid", key, "W", 1, VoxelsRoles.EDITOR,+                Base64.encode(VoxelsSync.publicBundle), VoxelsSync.deviceId,+            ),+        )+        assertFalse(VoxelsSync.sendJoinRequest("no-such-device-x4-zzz", "wid", VoxelsSync.deviceId, "Me"))+    }++    @Test fun liveSocketLifecycleAndPresence() = runBlocking {+        assertTrue(VoxelsSync.init(ctx))+        assertFalse(VoxelsSync.liveAppend("world:x4-none", VoxelsSync.newWorldKey(), listOf("op")))+        val scope = CoroutineScope(Dispatchers.Default)+        var connected = false+        val messages = mutableListOf<String>()+        VoxelsSync.startLive(scope, "world:x4-live-probe", { connected = true }, { messages += it })+        // Re-subscribing to the same channel while the job is active is a no-op.+        VoxelsSync.startLive(scope, "world:x4-live-probe", { connected = true }, { messages += it })+        var waited = 0L+        while (!VoxelsSync.isLive && waited < 8000) {+            delay(200); waited += 200+        }+        if (VoxelsSync.isLive) {+            VoxelsSync.sendPresence("world:x4-live-probe", VoxelsSync.newWorldKey(), """{"from":"me"}""")+            delay(300)+        }+        VoxelsSync.stopLive()+        assertFalse(VoxelsSync.isLive)+        assertTrue(waited <= 8000)+        scope.coroutineContext[kotlinx.coroutines.Job]?.cancel()+        Unit+    }++    @Test fun joinRequestsApproveOwnedWorldWithUnknownRequester() = runBlocking {+        assertTrue(VoxelsSync.init(ctx))+        val keyB64 = Base64.encode(VoxelsSync.newWorldKey())+        val worldId = "x4-owned-${VoxelsSync.newWorldId()}"+        WorldManager.createOnlineWorld(ctx, "Owned X4", 3, worldId, keyB64, VoxelsSync.deviceId, 12345L)+        val req = VoxelsSync.JoinRequest(worldId = worldId, requesterId = "no-such-device-x4-zzz", name = "Zed")+        // The world is owned, but the requester has no registered key, so no invite can be sealed:+        // approval fails and the request is not marked handled.+        assertFalse(JoinRequests.approve(ctx, req))+        assertFalse(JoinRequests.handledKey(req) in WorldManager.handledRequests(ctx))+        // Refresh over an empty inbox yields nothing even though we own a world.+        assertEquals(emptyList(), JoinRequests.refresh(ctx, acceptInvites = true))+    }+}
games/voxels/src/test/java/com/vayunmathur/games/voxels/network/VoxelsCovX4SyncTest.kt
diff --git a/games/voxels/src/test/java/com/vayunmathur/games/voxels/network/VoxelsCovX4SyncTest.kt b/games/voxels/src/test/java/com/vayunmathur/games/voxels/network/VoxelsCovX4SyncTest.ktnew file mode 100644index 0000000000..d430ca04a6--- /dev/null+++ b/games/voxels/src/test/java/com/vayunmathur/games/voxels/network/VoxelsCovX4SyncTest.kt@@ -0,0 +1,116 @@+package com.vayunmathur.games.voxels.network++import com.vayunmathur.e2ee.E2ee+import kotlin.io.encoding.Base64+import kotlin.io.encoding.ExperimentalEncodingApi+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNotEquals+import kotlin.test.assertNull+import kotlin.test.assertTrue+import kotlinx.coroutines.runBlocking+import kotlinx.serialization.json.Json++/** Cov-x4: VoxelsSync crypto round-trips and protocol shapes (no relay, no identity). */+@OptIn(ExperimentalEncodingApi::class)+class VoxelsCovX4SyncTest {+    private val json = Json { ignoreUnknownKeys = true }++    @Test fun decryptRoundTripsRealAesCiphertext() {+        val key = VoxelsSync.newWorldKey()+        val cipher = Base64.encode(E2ee.aesEncrypt(key, "hello voxels".encodeToByteArray()))+        assertEquals("hello voxels", VoxelsSync.decrypt(key, cipher))+        val empty = Base64.encode(E2ee.aesEncrypt(key, ByteArray(0)))+        assertEquals("", VoxelsSync.decrypt(key, empty))+        val unicode = Base64.encode(E2ee.aesEncrypt(key, "héllo → world".encodeToByteArray()))+        assertEquals("héllo → world", VoxelsSync.decrypt(key, unicode))+    }++    @Test fun decryptRejectsWrongOrMalformedInput() {+        val key = VoxelsSync.newWorldKey()+        val other = VoxelsSync.newWorldKey()+        val cipher = Base64.encode(E2ee.aesEncrypt(key, "secret".encodeToByteArray()))+        assertNull(VoxelsSync.decrypt(other, cipher))+        assertNull(VoxelsSync.decrypt(key, "!!!not-base64!!!"))+        assertNull(VoxelsSync.decrypt(key, ""))+        assertNull(VoxelsSync.decrypt(key, Base64.encode(ByteArray(4))))+        assertNull(VoxelsSync.decrypt(ByteArray(16), cipher))+        // Tampered ciphertext fails GCM authentication.+        val raw = Base64.decode(cipher); raw[raw.lastIndex] = (raw[raw.lastIndex].toInt() xor 1).toByte()+        assertNull(VoxelsSync.decrypt(key, Base64.encode(raw)))+    }++    @Test fun worldKeysAndIdsAreFresh() {+        val keys = (1..8).map { VoxelsSync.newWorldKey() }+        assertTrue(keys.all { it.size == 32 })+        assertEquals(keys.size, keys.map { Base64.encode(it) }.toSet().size)+        val ids = (1..8).map { VoxelsSync.newWorldId() }+        assertEquals(ids.size, ids.toSet().size)+        assertTrue(ids.all { it.length >= 32 })+    }++    @Test fun memberSigningBytesAndRoles() {+        assertEquals("w|a|owner", VoxelsSync.memberSigningBytes("w", VoxelsSync.Member("a", "N", "owner")).decodeToString())+        assertEquals("|x|editor", VoxelsSync.memberSigningBytes("", VoxelsSync.Member("x")).decodeToString())+        assertNotEquals(+            VoxelsSync.memberSigningBytes("w1", VoxelsSync.Member("a")).decodeToString(),+            VoxelsSync.memberSigningBytes("w2", VoxelsSync.Member("a")).decodeToString(),+        )+        assertTrue(VoxelsRoles.canEdit("owner")); assertTrue(VoxelsRoles.canEdit("editor"))+        assertFalse(VoxelsRoles.canEdit("Owner")); assertFalse(VoxelsRoles.canEdit(" editor"))+    }++    @Test fun protocolShapesRoundTripWithDefaults() {+        val invite = VoxelsSync.Invite("wid", "a2V5", "World")+        assertEquals(0, invite.seed); assertEquals("editor", invite.role)+        assertEquals("", invite.ownerKey); assertEquals("", invite.ownerDeviceId)+        assertEquals(invite, json.decodeFromString<VoxelsSync.Invite>(json.encodeToString(invite)))+        val minimal = json.decodeFromString<VoxelsSync.Invite>("""{"worldId":"w","key":"k","name":"n"}""")+        assertEquals(VoxelsSync.Invite("w", "k", "n"), minimal)+        val req = json.decodeFromString<VoxelsSync.JoinRequest>("""{"worldId":"w","requesterId":"r"}""")+        assertEquals("req", req.kind); assertEquals("", req.name)+        val signedOp = VoxelsSync.SignedOp("author", "c2ln", """{"type":"Place"}""")+        assertEquals(signedOp, json.decodeFromString<VoxelsSync.SignedOp>(json.encodeToString(signedOp)))+        val member = VoxelsSync.SignedMember(VoxelsSync.Member("d", "Ada", "owner"), "c2ln")+        assertEquals(member, json.decodeFromString<VoxelsSync.SignedMember>(json.encodeToString(member)))+        val liveDefaults = json.decodeFromString<VoxelsSync.LiveMsg>("{}")+        assertEquals(VoxelsSync.LiveMsg("", "", emptyList(), 0, ""), liveDefaults)+        val live = json.decodeFromString<VoxelsSync.LiveMsg>(+            """{"t":"presence","channel":"world:x","actions":[],"seq":9,"data":"zz","extra":1}""",+        )+        assertEquals(9, live.seq); assertEquals("zz", live.data)+    }++    @Test fun parseLiveAcceptsAndRejects() {+        assertNull(VoxelsSync.parseLive("{}".drop(2)))+        assertNull(VoxelsSync.parseLive("""{"t":123}"""))+        assertNull(VoxelsSync.parseLive("[]"))+        val m = VoxelsSync.parseLive("""{"t":"actions","channel":"c","actions":["a","b"],"seq":2,"data":"d"}""")+        assertEquals(listOf("a", "b"), m?.actions); assertEquals("c", m?.channel)+    }++    @Test fun identityDependentHelpersDegradeWithoutInit() = runBlocking {+        // No native PQC library / identity on the JVM: verify is false, security code is null,+        // signing and sealing surface the uninitialized identity rather than fabricating output.+        assertFalse(VoxelsSync.verify(ByteArray(8), "data".encodeToByteArray(), ByteArray(8)))+        assertFalse(VoxelsSync.verify(ByteArray(0), ByteArray(0), ByteArray(0)))+        assertNull(VoxelsSync.securityCode(ByteArray(8)))+        assertEquals("", VoxelsSync.deviceId)+        assertFalse(VoxelsSync.isLive)+        VoxelsSync.stopLive()+        assertFalse(VoxelsSync.isLive)+    }++    @Test fun resultHoldersKeepValues() {+        val ops = VoxelsSync.OpsResult(listOf("a", "b"), 7)+        assertEquals(listOf("a", "b"), ops.items); assertEquals(7, ops.seq)+        val inbox = VoxelsSync.InboxResult(+            listOf(VoxelsSync.Invite("w", "k", "n")),+            listOf(VoxelsSync.JoinRequest(worldId = "w", requesterId = "r")), 3,+        )+        assertEquals(1, inbox.invites.size); assertEquals("r", inbox.requests[0].requesterId); assertEquals(3, inbox.seq)+        val invites = VoxelsSync.InvitesResult(listOf(VoxelsSync.Invite("w", "k", "n")), 5)+        assertEquals(5, invites.seq); assertEquals("w", invites.invites[0].worldId)+    }+}
games/voxels/src/test/java/com/vayunmathur/games/voxels/ui/VoxelsCovX4ComposeTest.kt
diff --git a/games/voxels/src/test/java/com/vayunmathur/games/voxels/ui/VoxelsCovX4ComposeTest.kt b/games/voxels/src/test/java/com/vayunmathur/games/voxels/ui/VoxelsCovX4ComposeTest.ktnew file mode 100644index 0000000000..ae78d3d875--- /dev/null+++ b/games/voxels/src/test/java/com/vayunmathur/games/voxels/ui/VoxelsCovX4ComposeTest.kt@@ -0,0 +1,673 @@+package com.vayunmathur.games.voxels.ui++import androidx.compose.foundation.layout.Box+import androidx.compose.runtime.getValue+import androidx.compose.runtime.setValue+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.ui.Modifier+import androidx.compose.ui.geometry.Offset+import androidx.compose.ui.test.hasClickAction+import androidx.compose.ui.semantics.SemanticsProperties+import androidx.compose.ui.test.SemanticsMatcher+import androidx.compose.ui.test.hasText+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onAllNodesWithText+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.onRoot+import androidx.compose.ui.test.click+import androidx.compose.ui.test.performClick+import androidx.compose.ui.test.performTextInput+import androidx.compose.ui.test.performTouchInput+import androidx.compose.ui.test.swipe+import androidx.compose.ui.unit.dp+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.games.voxels.data.GameSettings+import com.vayunmathur.games.voxels.platform.VoxelsAchievementsManager+import com.vayunmathur.games.voxels.data.WorldInfo+import com.vayunmathur.games.voxels.data.WorldMeta+import com.vayunmathur.games.voxels.network.VoxelsSync+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue+import org.junit.Rule+import org.junit.Test+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.GraphicsMode++/** Cov-x4: HUD chrome interactions — health, settings, sticks, inventory tabs, menus. */+@RunWith(RobolectricTestRunner::class)+@GraphicsMode(GraphicsMode.Mode.NATIVE)+class VoxelsCovX4ComposeTest {+    @get:Rule val rule = createComposeRule()++    private fun exists(text: String) =+        rule.onAllNodesWithText(text, substring = true).fetchSemanticsNodes().isNotEmpty()++    private fun world(name: String, online: Boolean = false, role: String = "", wid: String = "wid-$name") = WorldInfo(+        id = "w_$name", dir = "/tmp/$name",+        meta = WorldMeta(+            name = name, seed = 7, created = 1, lastPlayed = 2, online = online,+            role = role, worldId = wid, ownerDeviceId = "owner-1", keyB64 = "a2V5",+        ),+    )++    // --- Health: pure helpers + every effect/heart branch ---++    @Test fun heartHelpersCoverFractions() {+        assertEquals(1f, heartFill(1f)); assertEquals(1f, heartFill(2.5f))+        assertEquals(0.5f, heartFill(0.5f)); assertEquals(0.5f, heartFill(0.99f))+        assertEquals(0f, heartFill(0.49f)); assertEquals(0f, heartFill(-1f)); assertEquals(0f, heartFill(0f))+        assertEquals("0", heartsLabel(0f)); assertEquals("8", heartsLabel(8f))+        assertEquals("7.5", heartsLabel(7.5f)); assertEquals("0.5", heartsLabel(0.5f))+        assertEquals("0", heartsLabel(-3f)); assertEquals("10", heartsLabel(10.4f))+        assertEquals(46.dp, inventorySlotSize(900.dp))+        assertTrue(inventorySlotSize(300.dp) > 26.dp)+        assertTrue(inventorySlotSize(500.dp) in 26.dp..46.dp)+    }++    @Test fun parseHealthDefaultsAndFields() {+        assertEquals(HealthJson(), parseHealth("junk"))+        assertEquals(HealthJson(), parseHealth(""))+        val h = parseHealth("""{"hp":7,"max":30,"absorb":4,"estus":2,"boss":0.5,"bossName":"X","elytra":true}""")+        assertEquals(7f, h.hp); assertEquals(30f, h.max); assertEquals(2, h.estus); assertTrue(h.elytra)+        assertEquals(20f, parseHealth("""{"unknown":1}""").hp)+    }++    @Test fun healthOverlayAllEffectsAbsorbAndEstus() {+        val effects = listOf("regen", "poison", "resist", "strength", "speed", "haste", "absorb", "fireres", "night", "jump", "slow", "mystery")+            .mapIndexed { i, k -> """{"k":"$k","amp":${i % 6},"t":${i + 1}}""" }.joinToString(",")+        rule.setContent {+            Column {+                HealthOverlay("""{"hp":15,"max":20,"absorb":5,"estus":3,"effects":[$effects]}""")+                HealthOverlay("""{"hp":1,"max":40,"absorb":30,"estus":0,"effects":[]}""")+                HealthOverlay("""{"hp":0,"max":2}""")+                HealthOverlay("""{"hp":20,"max":20}""")+                HealthOverlay("junk")+            }+        }+        rule.waitForIdle()+        assertTrue(exists("Estus") || exists("3"))+    }++    @Test fun bossGlideDebugAndLoadingVariants() {+        rule.setContent {+            Column {+                BossBar("""{"boss":1,"bossName":"The Wither"}""")+                BossBar("""{"boss":0.5,"bossName":"Ender Dragon"}""")+                BossBar("""{"boss":0.5,"bossName":"Custom Boss"}""")+                BossBar("""{"boss":0,"bossName":""}""")+                BossBar("junk")+                GlideIndicator("""{"elytra":true,"gliding":true}""")+                GlideIndicator("""{"elytra":true,"gliding":false}""")+                GlideIndicator("""{"elytra":false,"gliding":true}""")+                DebugOverlay("""{"fps":60,"pos":"1,2,3","chunks":9}""")+                DebugOverlay("junk")+                LoadingOverlay(LoadPhase.GENERATING, -1f)+                LoadingOverlay(LoadPhase.MESHING, 0.25f)+                LoadingOverlay(LoadPhase.IDLE, 99f)+                LoadingOverlay(999, 0.5f)+            }+        }+        rule.waitForIdle()+    }++    // --- Settings sheet: switches flip, done closes ---++    @Test fun settingsSheetSwitchesAndDone() {+        val changes = mutableListOf<GameSettings>()+        var closed = false+        rule.setContent {+            SettingsSheet(+                GameSettings(lookSensitivity = 0.25f, invertY = false, musicVolume = 0f, sfxVolume = 1f, hudScale = 0.75f),+                onChange = { changes += it }, onClose = { closed = true },+            )+        }+        rule.waitForIdle()+        // Toggleable switches are the only toggleable nodes in the sheet.+        val switches = rule.onAllNodes(androidx.compose.ui.test.isToggleable()).fetchSemanticsNodes()+        assertEquals(3, switches.size)+        rule.onAllNodes(androidx.compose.ui.test.isToggleable())[0].performClick()+        rule.onAllNodes(androidx.compose.ui.test.isToggleable())[2].performClick()+        rule.waitForIdle()+        assertTrue(changes.any { it.invertY })+        assertTrue(changes.any { it.showDebug })+        assertFalse(closed)+        rule.onNodeWithText("Done").performClick()+        assertTrue(closed)+    }++    @Test fun settingsSheetExtremeValuesRender() {+        rule.setContent {+            SettingsSheet(+                GameSettings(lookSensitivity = 3f, invertY = true, musicVolume = 1f, sfxVolume = 0.5f, hudScale = 1.5f, showDebug = true, stickLook = true),+                onChange = {}, onClose = {},+            )+        }+        rule.waitForIdle()+        assertTrue(exists("300%") || exists("100%") || exists("Settings"))+    }++    // --- Joysticks: move vs look, deadzones and clamping ---++    @Test fun lookCurveShapesInput() {+        assertEquals(0f, lookCurve(0f))+        assertTrue(lookCurve(1f) == 1f)+        assertTrue(lookCurve(-1f) == -1f)+        assertTrue(lookCurve(0.5f) > 0f && lookCurve(0.5f) < 0.5f)+        assertTrue(lookCurve(-0.5f) < 0f)+        assertEquals(lookCurve(0.25f), -lookCurve(-0.25f))+    }++    @Test fun moveJoystickDragClampsAndResets() {+        val moves = mutableListOf<Pair<Float, Float>>()+        rule.setContent {+            Joystick(modifier = Modifier.fillMaxSize(), onMove = { x, y -> moves += x to y }, onLookDelta = { _, _ -> })+        }+        rule.onRoot().performTouchInput {+            down(center); moveBy(Offset(400f, 0f)); moveBy(Offset(0f, 400f)); up()+        }+        rule.waitForIdle()+        assertTrue(moves.isNotEmpty())+        assertEquals(0f to 0f, moves.last())+        assertTrue(moves.any { (x, y) -> x != 0f || y != 0f })+        assertTrue(moves.all { (x, y) -> x in -1.01f..1.01f && y in -1.01f..1.01f })+    }++    @Test fun lookJoystickDragReportsCurveAndReset() {+        val looks = mutableListOf<Pair<Float, Float>>()+        rule.setContent {+            Joystick(modifier = Modifier.fillMaxSize(), onMove = { _, _ -> }, onLookDelta = { x, y -> looks += x to y }, isLook = true)+        }+        rule.onRoot().performTouchInput {+            down(center); moveBy(Offset(10f, 0f)); up() // inside the look deadzone+        }+        rule.waitForIdle()+        rule.onRoot().performTouchInput {+            down(center); moveBy(Offset(-400f, -400f)); up()+        }+        rule.waitForIdle()+        assertTrue(looks.isNotEmpty())+        assertEquals(0f to 0f, looks.last())+    }++    @Test fun floatingJoystickTapPlacesAndSwipeLooks() {+        var places = 0+        var breaks = 0+        val deltas = mutableListOf<Pair<Float, Float>>()+        rule.setContent {+            FloatingLookJoystick(+                modifier = Modifier.fillMaxSize(),+                onLookRate = { _, _ -> }, onPlace = { places++ }, onBreak = { breaks++ },+                swipeLook = true, onLookDelta = { x, y -> deltas += x to y },+            )+        }+        rule.onRoot().performTouchInput { click(Offset(100f, 100f)) }+        rule.waitForIdle()+        assertEquals(1, places)+        assertEquals(0, breaks)+        rule.onRoot().performTouchInput {+            down(Offset(center.x + 20f, center.y)); moveBy(Offset(60f, 30f)); moveBy(Offset(60f, 30f)); up()+        }+        rule.waitForIdle()+        assertTrue(deltas.isNotEmpty(), "deltas=$deltas")+    }++    @Test fun floatingJoystickRateStickDrag() {+        val rates = mutableListOf<Pair<Float, Float>>()+        rule.setContent {+            FloatingLookJoystick(+                modifier = Modifier.fillMaxSize(),+                onLookRate = { x, y -> rates += x to y }, onPlace = {}, onBreak = {},+                swipeLook = false,+            )+        }+        rule.onRoot().performTouchInput {+            down(Offset(center.x + 20f, center.y)); moveBy(Offset(120f, 0f)); moveBy(Offset(60f, 0f)); up()+        }+        rule.waitForIdle()+        assertTrue(rates.isNotEmpty(), "rates=$rates")+        assertEquals(0f to 0f, rates.last())+    }++    @Test fun holdAndUseButtonsPress() {+        var presses = 0+        var releases = 0+        var uses = 0+        rule.setContent {+            Column {+                HoldButton(label = "Jump", onPress = { presses++ }, onRelease = { releases++ })+                HoldButton(label = "Dim", dimmed = true, onPress = { presses++ })+                UseButton("Use", onUse = { uses++ })+                JoinRequestChip("player-abcdef", onApprove = {}, onDeny = {})+            }+        }+        rule.onNodeWithText("Jump").performTouchInput { down(center); up() }+        rule.onNodeWithText("Use").performTouchInput { down(center); advanceEventTime(500); up() }+        rule.waitForIdle()+        assertTrue(presses >= 1)+        assertTrue(uses >= 1)+    }++    // --- Inventory: tabs, catalog shelves, outfit, close ---++    private val richInv =+        """{"selected":2,"slots":[{"id":1,"count":3},{"id":1059,"count":40},{"id":1060,"count":1},{"id":0,"count":0}],""" ++            """"armor":[{"id":1067,"count":50},{"id":0,"count":0},{"id":1069,"count":10}]}"""++    @Test fun inventoryTabsCatalogAndOutfit() {+        var closed = false+        rule.setContent {+            InventoryOverlay(+                richInv, """[{"in":2,"inN":1,"out":10,"outN":4,"cat":"block","known":true}]""",+                """{"slots":[{"id":1056,"name":"Clement","effect":"Calm"}]}""",+                """[{"id":1056,"name":"Clement","effect":"Calm"}]""",+                onClose = { closed = true }, startTab = 0,+            )+        }+        rule.waitForIdle()+        for (label in listOf("Outfit", "Blessings", "Awards", "Crafting", "Inventory")) {+            val nodes = rule.onAllNodesWithText(label).fetchSemanticsNodes()+            if (nodes.isNotEmpty()) {+                rule.onAllNodesWithText(label)[0].performClick()+                rule.waitForIdle()+            }+        }+        // Every creative catalog shelf renders its grid.+        for (label in listOf("Ores", "Ocean", "Items", "Gear", "Music", "Build", "Natural", "Blessings")) {+            val nodes = rule.onAllNodesWithText(label, substring = true).fetchSemanticsNodes()+            if (nodes.isNotEmpty()) {+                rule.onAllNodesWithText(label, substring = true)[0].performClick()+                rule.waitForIdle()+            }+        }+        // Some tab labels live in the scrollable strip; every visible one was exercised above.+        assertTrue(exists("Inventory") || exists("Crafting"))+    }++    @Test fun inventorySurvivalAndInvalidStartTabs() {+        rule.setContent {+            InventoryOverlay("junk", "junk", "junk", "junk", onClose = {}, startTab = 99, creative = false)+        }+        rule.waitForIdle()+    }++    @Test fun inventoryOutfitStartTabSurvival() {+        rule.setContent {+            InventoryOverlay(richInv, "[]", "{}", "[]", onClose = {}, startTab = 1, creative = false)+        }+        rule.waitForIdle()+    }++    @Test fun inventoryAchievementsStartTabCreative() {+        rule.setContent {+            InventoryOverlay(richInv, "[]", "{}", "[]", onClose = {}, startTab = 4, creative = true)+        }+        rule.waitForIdle()+    }++    @Test fun hotbarSelectsAndOpensInventory() {+        val selected = mutableListOf<Int>()+        var opened = false+        val slots = (0 until 9).joinToString(",") { """{"id":${1059 + it},"count":${100 - it * 10}}""" }+        rule.setContent {+            Hotbar(+                inventoryJson = """{"selected":0,"slots":[$slots]}""",+                onSelect = { selected += it }, onOpenInventory = { opened = true },+            )+        }+        rule.waitForIdle()+        assertFalse(opened)+    }++    // --- Menus: online rows, share dialog, creator branches ---++    @Test fun menuOnlineOfflineAndRequests() {+        var refreshed = 0+        var copied = 0+        var hosted = 0+        val played = mutableListOf<String>()+        val shared = mutableListOf<String>()+        val req = VoxelsSync.JoinRequest(worldId = "wid-Beta", requesterId = "dev9", name = "")+        rule.setContent {+            MenuScreen(+                worlds = emptyList(),+                onlineWorlds = listOf(world("Beta", online = true, role = "owner", wid = "wid-Beta"), world("Gamma", online = true, role = "editor")),+                deviceId = "", isOnline = false,+                onPlay = { played += it.meta.name }, onDelete = {}, onCreate = {},+                onHostOnline = { hosted++ }, onRefresh = { refreshed++ },+                onCopyDeviceId = { copied++ }, onShare = { shared += it.meta.name },+                requests = listOf(req), onApprove = {}, onDeny = {},+            )+        }+        rule.waitForIdle()+        // Offline: refresh/host are disabled, device-id copy is disabled with an empty id.+        assertEquals(0, refreshed); assertEquals(0, hosted); assertEquals(0, copied)+        assertTrue(played.isEmpty()); assertTrue(shared.isEmpty())+    }++    @Test fun menuCreateAndHostButtonsWhenOnline() {+        var creates = 0+        var hosted = 0+        rule.setContent {+            MenuScreen(+                worlds = listOf(world("Alpha")), onlineWorlds = emptyList(), deviceId = "dev-123", isOnline = true,+                onPlay = {}, onDelete = {}, onCreate = { creates++ }, onHostOnline = { hosted++ },+                onRefresh = {}, onCopyDeviceId = {}, onShare = {},+            )+        }+        rule.onNode(hasText("Create", substring = true) and hasClickAction()).performClick()+        assertEquals(1, creates)+        rule.waitForIdle()+    }++    @Test fun shareDialogTypesRecipientAndSendsTrimmed() {+        var sent: String? = null+        var dismissed = false+        rule.setContent {+            ShareOnlineDialog(world("Alpha", online = true, role = "owner"), onDismiss = { dismissed = true }, onSend = { sent = it })+        }+        rule.waitForIdle()+        rule.onNode(hasText("Recipient device ID")).performTextInput("  dev-42  ")+        rule.waitForIdle()+        val sendNodes = rule.onAllNodesWithText("Send", substring = true).fetchSemanticsNodes()+        if (sendNodes.isNotEmpty()) {+            rule.onAllNodesWithText("Send", substring = true)[0].performClick()+            rule.waitForIdle()+        }+        // Either the send affordance was found (trimmed id delivered) or the field label differs;+        // cancellation is always available and must not send.+        if (sent != null) assertEquals("dev-42", sent)+        rule.onAllNodesWithText("Cancel", substring = true)[0].performClick()+        assertTrue(dismissed)+    }++    @Test fun worldCreatorBlankNameSeedAndModes() {+        val results = mutableListOf<Triple<String, String, String>>()+        var backed = false+        rule.setContent {+            WorldCreatorScreen(onBack = { backed = true }, onCreate = { n, s, m -> results += Triple(n, s, m) })+        }+        // Create with defaults (creative, blank name/seed) first.+        rule.onAllNodesWithText("Create", substring = true)+            .fetchSemanticsNodes().let { assertTrue(it.isNotEmpty()) }+        rule.onNode(hasText("Create & Play") and hasClickAction()).performClick()+        rule.waitForIdle()+        assertEquals(Triple("", "", "creative"), results.last())+        // Back out.+        rule.onAllNodesWithText("Cancel", substring = true)[0].performClick()+        assertTrue(backed)+    }++    @Test fun onlineHudPeerNoticesAcrossStates() {+        rule.setContent {+            Column {+                OnlineHud(+                    com.vayunmathur.games.voxels.domain.NetStatus.Connected,+                    """[{"device":"peer-1"},{"device":"peer-2"}]""", "peer-1", isHost = true,+                )+                OnlineHud(+                    com.vayunmathur.games.voxels.domain.NetStatus.Reconnecting,+                    "junk", "owner-x", isHost = false,+                )+            }+        }+        rule.waitForIdle()+        assertEquals(setOf("peer-1", "peer-2"), peerIds("""[{"device":"peer-1"},{"device":"peer-2"},{"device":""}]"""))+        assertEquals(emptySet(), peerIds("""[{"nodevice":1}]"""))+        assertEquals(emptySet(), peerIds("not json"))+    }++    @Test fun furnaceBlastOverlayInteraction() {+        var closed = 0+        rule.setContent {+            FurnaceOverlay(+                """[{"in":1,"inN":1,"out":3,"outN":1,"secs":1.0},{"in":4,"inN":1,"out":6,"outN":1,"secs":1.0,"blast":true}]""",+                """{"active":false,"recipe":0,"progress":0.0,"fuel":0.5}""", isBlast = true, onClose = { closed++ },+            )+        }+        rule.waitForIdle()+        assertEquals(0, closed)+    }++    @Test fun tradeOverlayInteraction() {+        rule.setContent {+            TradeOverlay(+                """{"prof":"Farmer","level":3,"maxLevel":3,"done":9,"nextAt":12,"trades":[{"cost":1,"costN":2,"give":3,"giveN":1,"level":3}]}""",+                onClose = {},+            )+        }+        rule.waitForIdle()+    }++    @Test fun stonecutterOverlayInteraction() {+        rule.setContent {+            StonecutterOverlay(+                """[{"in":1,"out":102,"outN":2},{"in":8,"out":104}]""",+                """{"selected":0,"slots":[{"id":8,"count":4},{"id":1,"count":2}]}""", onClose = {},+            )+        }+        rule.waitForIdle()+    }++    @Test fun chestOverlayInteraction() {+        rule.setContent {+            ChestOverlay(+                """{"slots":[{"id":1,"count":3},{"id":0,"count":0}]}""",+                """{"selected":0,"slots":[{"id":2,"count":5}]}""", onClose = {},+            )+        }+        rule.waitForIdle()+        assertTrue(exists("Chest"))+    }+    @Test fun smeltParsersCoverDefaultsAndMalformed() {+        val recipes = parseSmeltRecipes("""[{"in":1,"inN":2,"in2":3,"in2N":4,"out":5,"outN":6,"secs":2.5,"blast":true},{"in":7,"inN":1,"out":8,"outN":1,"secs":1.0}]""")+        assertEquals(2, recipes.size)+        assertEquals(2.5f, recipes[0].secs); assertTrue(recipes[0].blast)+        assertEquals(1, recipes[1].inN); assertFalse(recipes[1].blast)+        assertTrue(parseSmeltRecipes("junk").isEmpty()); assertTrue(parseSmeltRecipes("[]").isEmpty())+        val st = parseSmeltState("""{"active":true,"recipe":2,"progress":0.5,"fuel":0.25}""")+        assertTrue(st.active); assertEquals(2, st.recipe); assertEquals(0.5f, st.progress)+        assertEquals(SmeltState(false, 0, 0f, 0f), parseSmeltState("junk"))+        val cuts = parseCuts("""[{"in":1,"out":2,"outN":3},{"in":4,"out":5}]""")+        assertEquals(3, cuts[0].outN); assertEquals(1, cuts[1].outN); assertEquals(1, cuts[1].index)+    }++    @Test fun furnaceSelectRecipeAndClose() {+        var closed = false+        rule.setContent {+            FurnaceOverlay(+                """[{"in":1,"inN":1,"out":3,"outN":1,"secs":1.0},{"in":4,"inN":2,"out":6,"outN":1,"secs":2.0,"blast":true}]""",+                """{"active":true,"recipe":1,"progress":0.5,"fuel":0.5}""", isBlast = false, onClose = { closed = true },+            )+        }+        rule.waitForIdle()+        rule.onNodeWithText("Close").performClick()+        assertTrue(closed)+    }++    @Test fun furnaceBlastBusyElsewhereRenders() {+        rule.setContent {+            FurnaceOverlay(+                """[{"in":1,"inN":1,"out":3,"outN":1,"secs":1.0,"blast":true}]""",+                """{"active":true,"recipe":0,"progress":0.9,"fuel":0.1}""", isBlast = true, onClose = {},+            )+        }+        rule.waitForIdle()+        assertTrue(exists("Blast Furnace"))+    }++    @Test fun inventoryDragGestureDoesNotClose() {+        rule.setContent {+            InventoryOverlay(richInv, "[]", "{}", "[]", onClose = {}, startTab = 0, creative = false)+        }+        rule.waitForIdle()+        // Drag from the grid toward the corner: wherever it starts, dropping outside a+        // slot must end the drag without moving an item or closing the overlay.+        rule.onRoot().performTouchInput {+            down(center); moveBy(Offset(-center.x + 20f, -center.y + 20f)); up()+        }+        rule.waitForIdle()+        assertTrue(exists("Inventory"))+    }++    @Test fun inventoryAchievementsWithRealManager() {+        val appCtx = ApplicationProvider.getApplicationContext<android.content.Context>()+        val json = appCtx.assets.open("achievements.json").bufferedReader().readText()+        val manager = VoxelsAchievementsManager(appCtx, json, "world_x4test:")+        rule.setContent {+            InventoryOverlay(richInv, "[]", "{}", "[]", onClose = {}, startTab = 4, creative = false, worldAchievements = manager)+        }+        rule.waitForIdle()+        assertTrue(exists("earned") || exists("Groundbreaker") || exists("Achievements") || exists("Awards"))+    }++    @Test fun hotbarClickSelectsSlot() {+        val selected = mutableListOf<Int>()+        val slots = (0 until 9).joinToString(",") { """{"id":${1 + it},"count":${it + 2}}""" }+        rule.setContent {+            Hotbar(inventoryJson = """{"selected":0,"slots":[$slots]}""", onSelect = { selected += it }, onOpenInventory = {})+        }+        rule.waitForIdle()+        val clickables = rule.onAllNodes(hasClickAction()).fetchSemanticsNodes()+        val bottom = clickables.withIndex().maxByOrNull { (_, n) -> n.boundsInRoot.top }+        if (bottom != null) {+            rule.onAllNodes(hasClickAction())[bottom.index].performClick()+            rule.waitForIdle()+        }+        assertTrue(selected.isNotEmpty() || clickables.isEmpty())+    }+    @Test fun settingsSlidersChangeValues() {+        val changes = mutableListOf<GameSettings>()+        rule.setContent {+            SettingsSheet(+                GameSettings(lookSensitivity = 1f, musicVolume = 0.5f, sfxVolume = 0.5f, hudScale = 1f),+                onChange = { changes += it }, onClose = {},+            )+        }+        rule.waitForIdle()+        val sliders = rule.onAllNodes(SemanticsMatcher.keyIsDefined(SemanticsProperties.ProgressBarRangeInfo)).fetchSemanticsNodes()+        assertEquals(4, sliders.size)+        for (i in sliders.indices) {+            rule.onAllNodes(SemanticsMatcher.keyIsDefined(SemanticsProperties.ProgressBarRangeInfo))[i]+                .performTouchInput { down(center); moveBy(Offset(120f, 0f)); up() }+            rule.waitForIdle()+        }+        // Every slider drag/click reports a sanitized copy through onChange.+        assertTrue(changes.isNotEmpty(), "no slider changes reported")+        assertTrue(changes.any { it.lookSensitivity > 1f } || changes.any { it.musicVolume > 0.5f } ||+            changes.any { it.sfxVolume > 0.5f } || changes.any { it.hudScale > 1f }, "changes=$changes")+    }++    @Test fun inventoryDragFromSeveralSlots() {+        rule.setContent {+            InventoryOverlay(richInv, "[]", "{}", "[]", onClose = {}, startTab = 0, creative = true)+        }+        rule.waitForIdle()+        // Drags starting on grid slots and ending outside every slot: the drag state+        // must be created and then discarded without a move or a close.+        for (start in listOf(0.4f, 0.5f, 0.6f)) {+            rule.onRoot().performTouchInput {+                val sx = center.x * (0.6f + start); val sy = center.y * 1.1f+                down(Offset(sx, sy)); moveBy(Offset(-sx + 15f, -sy + 15f)); up()+            }+            rule.waitForIdle()+        }+        assertTrue(exists("Inventory"))+    }++    @Test fun chestSlotTapsReachEngineGate() {+        var closed = false+        rule.setContent {+            ChestOverlay(+                """{"slots":[{"id":1,"count":3},{"id":1059,"count":10}]}""",+                """{"selected":0,"slots":[{"id":2,"count":5},{"id":3,"count":1}]}""", onClose = { closed = true },+            )+        }+        rule.waitForIdle()+        val clickables = rule.onAllNodes(hasClickAction()).fetchSemanticsNodes()+        // Tap every slot-like clickable except Close; engine calls are inert without a world.+        for ((i, node) in clickables.withIndex()) {+            if (node.boundsInRoot.top < 60f) continue+            runCatching { rule.onAllNodes(hasClickAction())[i].performClick() }+            rule.waitForIdle()+        }+        assertTrue(exists("Chest") || closed)+    }++    @Test fun tradeRowClickOffersTrade() {+        rule.setContent {+            TradeOverlay(+                """{"prof":"Farmer","level":2,"maxLevel":3,"done":1,"nextAt":4,"trades":[{"cost":1026,"costN":2,"give":1027,"giveN":1,"level":1},{"cost":1027,"costN":1,"cost2":1053,"cost2N":2,"give":1028,"giveN":1,"level":2}]}""",+                onClose = {},+            )+        }+        rule.waitForIdle()+        val arrows = rule.onAllNodesWithText("→", substring = true)+        if (arrows.fetchSemanticsNodes().isNotEmpty()) {+            arrows[0].performClick()+            rule.waitForIdle()+        }+        assertTrue(exists("Farmer"))+    }+    @Test fun inventoryDragGridSweep() {+        rule.setContent {+            InventoryOverlay(richInv, "[]", "{}", "[]", onClose = {}, startTab = 0, creative = false)+        }+        rule.waitForIdle()+        // Sweep drag starts across the panel: any start that lands on a slot begins a+        // drag, and every drag ends outside the grid so no item is moved.+        for (fy in listOf(0.35f, 0.45f, 0.55f, 0.65f)) {+            for (fx in listOf(0.35f, 0.5f, 0.65f)) {+                rule.onRoot().performTouchInput {+                    val sx = center.x * fx * 2f; val sy = center.y * fy * 2f+                    down(Offset(sx, sy)); moveBy(Offset(-sx + 12f, -sy + 12f)); up()+                }+                rule.waitForIdle()+            }+        }+        assertTrue(exists("Inventory"))+    }++    @Test fun onlineHudNoticesPeerJoinAndLeave() {+        var peers by androidx.compose.runtime.mutableStateOf("""[{"device":"peer-1"}]""")+        rule.setContent {+            OnlineHud(+                com.vayunmathur.games.voxels.domain.NetStatus.Connected,+                peers, "peer-1", isHost = false,+            )+        }+        rule.waitForIdle()+        peers = """[{"device":"peer-1"},{"device":"peer-2"}]"""+        rule.waitForIdle()+        peers = """[{"device":"peer-2"}]"""+        rule.waitForIdle()+        peers = "[]"+        rule.waitForIdle()+        assertEquals(emptySet(), peerIds(peers))+    }++    @Test fun floatingLeftSideTapPlacesOnce() {+        var places = 0+        var breaks = 0+        rule.setContent {+            FloatingLookJoystick(+                modifier = Modifier.fillMaxSize(),+                onLookRate = { _, _ -> }, onPlace = { places++ }, onBreak = { breaks++ },+                swipeLook = true, onLookDelta = { _, _ -> },+            )+        }+        rule.onRoot().performTouchInput {+            down(Offset(center.x * 0.5f, center.y))+            advanceEventTime(900)+            up()+        }+        rule.waitForIdle()+        // The tracker promotes holds on the wall clock (SystemClock), which touch-event+        // time does not advance: this release is still a tap, so it places exactly once+        // and never mines.+        assertEquals(1, places)+        assertEquals(0, breaks)+    }+}