Modern Apps git

← Modern-Apps.git

voxels: show real multiplayer connection state and who's here (#ux-audit)

Commit
fc0919d2019cfd33b19d6bcfc66d0eb0b0b91e1c
Author
Vayun Mathur <[email protected]>
When
2026-11-13 01:35 UTC (23 days ago)
Parents
b58c8cd
Symptom: every join flashed a red "Connection lost" banner before the
first connection had even been made; when a session couldn't start at
all (no network, bad invite key, host key unavailable) nothing said
why - the world just never synced; joiners couldn't tell whether the
host was online; players appeared and vanished without a word.

Root cause: the HUD knew one boolean, `netConnected = VoxelsSync.isLive`,
initialised to false (MainActivity), and the multiplayer pump returned
silently from its LaunchedEffect on every setup failure.

Fix:
- The pump moves out of MainActivity into network/MultiplayerPump.kt
  (security logic unchanged: owner-signed ops for clients, roster +
  per-member signature checks on the host, ephemeral presence). It
  now reports a domain NetStatus: Connecting until the first live
  connection, Connected, Reconnecting after a drop, or
  Failed(SERVER_UNREACHABLE | BAD_INVITE | HOST_UNVERIFIED). A client
  that can't fetch the host's key now says so instead of silently
  rejecting every host update.
- New ui/OnlineHud (top-right): "N online", for joiners "Host is
  here" / "Host isn't connected" (owner device in the engine's peer
  list), the connection state with a reason for failures, and
  4-second "Player 1a2b joined/left" notices from diffing peer
  snapshots (pure peerChanges/playerLabel in domain/NetStatus.kt).
- MainActivity shrinks by ~110 lines.

User-visible effect: joining shows "Connecting..." then nothing (all
good); drops show "reconnecting"; failures explain themselves; host
presence and arrivals/departures are visible.

Verification: new NetStatusTest (no "lost" before first connect, peer
diffs, labels) and OnlineHudTest (Compose: connecting text, host
presence, failure reason, peer JSON parsing).

Diff

games/voxels/src/main/java/com/vayunmathur/games/voxels/MainActivity.kt
diff --git a/games/voxels/src/main/java/com/vayunmathur/games/voxels/MainActivity.kt b/games/voxels/src/main/java/com/vayunmathur/games/voxels/MainActivity.ktindex 2e62455487..2d3545849d 100644--- a/games/voxels/src/main/java/com/vayunmathur/games/voxels/MainActivity.kt+++ b/games/voxels/src/main/java/com/vayunmathur/games/voxels/MainActivity.kt@@ -54,6 +54,8 @@ import androidx.core.view.WindowInsetsCompat import androidx.core.view.WindowInsetsControllerCompat import com.vayunmathur.games.voxels.data.GameSettingsStore import com.vayunmathur.games.voxels.domain.BackTarget+import com.vayunmathur.games.voxels.domain.NetStatus+import com.vayunmathur.games.voxels.network.MultiplayerPump import com.vayunmathur.games.voxels.domain.OverlayFlags import com.vayunmathur.games.voxels.domain.backTarget import com.vayunmathur.games.voxels.ui.BossBar@@ -72,14 +74,13 @@ import com.vayunmathur.games.voxels.ui.LoadingOverlay import com.vayunmathur.games.voxels.ui.Joystick import com.vayunmathur.games.voxels.ui.SettingsSheet import com.vayunmathur.games.voxels.ui.StonecutterOverlay+import com.vayunmathur.games.voxels.ui.OnlineHud import com.vayunmathur.games.voxels.ui.TradeOverlay import com.vayunmathur.games.voxels.ui.UseButton import com.vayunmathur.games.voxels.ui.VoxelSurfaceView import com.vayunmathur.games.voxels.ui.VoxelsTheme import com.vayunmathur.games.voxels.platform.VoxelsAchievements import com.vayunmathur.games.voxels.util.VoxelsNative-import com.vayunmathur.games.voxels.network.VoxelsSync-import com.vayunmathur.e2ee.Pqc import com.vayunmathur.library.log.Log import com.vayunmathur.library.ui.AchievementNotification import com.vayunmathur.library.ui.Button@@ -90,12 +91,7 @@ import com.vayunmathur.library.ui.MaterialTheme import com.vayunmathur.library.ui.Text import com.vayunmathur.library.util.GameHubComposeHook import kotlinx.coroutines.delay-import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.isActive-import kotlinx.coroutines.launch-import kotlin.io.encoding.Base64-import org.json.JSONArray-import org.json.JSONObject  class MainActivity : ComponentActivity() {     // Pause-menu state lives on the activity so onStop can pause the game: coming back from Home or@@ -169,7 +165,7 @@ class MainActivity : ComponentActivity() {                 var tradesJson by remember { mutableStateOf("{}") }                 var tradeOpen by remember { mutableStateOf(false) }                 // Online multiplayer HUD state.-                var netConnected by remember { mutableStateOf(false) }+                var netStatus by remember { mutableStateOf<NetStatus>(NetStatus.Connecting) }                 var peersJson by remember { mutableStateOf("[]") }                 LaunchedEffect(Unit) { if (VoxelsNative.isAvailable) try { recipesJson = VoxelsNative.getRecipesJson(); smeltingJson = VoxelsNative.getSmeltingJson(); blessingCatalogJson = VoxelsNative.getBlessingCatalogJson(); cutsJson = VoxelsNative.getCutsJson() } catch (_: Exception) {} }                 // World loading runs on the engine thread; poll it for the loading overlay. The phase@@ -285,126 +281,16 @@ class MainActivity : ComponentActivity() {                     }                 } -                // --- Online multiplayer pump: bridge the Rust net queues to the encrypted relay. ----                // World-log ops are signed (SignedOp{author,sig,ops}) so peers can authenticate them;-                // player transforms ride ephemeral, unsigned presence. Confidentiality comes from the-                // world AES key (only members hold it); the relay only ever sees ciphertext.+                // --- Online multiplayer pump (network/MultiplayerPump.kt): bridges the Rust net+                // queues to the encrypted relay and reports connection state + who is here. ---                 LaunchedEffect(online) {                     if (!online || !VoxelsNative.isAvailable) return@LaunchedEffect-                    if (!VoxelsSync.init(this@MainActivity)) return@LaunchedEffect-                    val pumpScope = this-                    val myId = VoxelsSync.deviceId-                    try { VoxelsNative.nativeSetDevice(myId) } catch (_: Exception) {}-                    val key = runCatching { Base64.decode(worldKeyB64) }.getOrNull() ?: return@LaunchedEffect-                    val channel = "world:$sharedWorldId"-                    // Owner bundle: the host is the owner; a client fetches it once to verify host ops.-                    val ownerBundle: ByteArray? = if (netRole == 1) VoxelsSync.publicBundle else VoxelsSync.getKey(ownerDevice)-                    // Host: the authorized member set (all editors — no viewers) + each member's public-                    // bundle, so every client op is signature-verified, not just role-gated by id.-                    val roster = java.util.Collections.synchronizedSet(HashSet<String>())-                    val bundles = java.util.concurrent.ConcurrentHashMap<String, ByteArray>()-                    roster.add(ownerDevice); roster.add(myId)-                    VoxelsSync.publicBundle.let { bundles[myId] = it; bundles[ownerDevice] = it }-                    suspend fun refreshRoster() {-                        runCatching { VoxelsSync.fetchRoster(sharedWorldId, key, VoxelsSync.publicBundle) }.getOrNull()?.forEach { (id, _) ->-                            roster.add(id)-                            if (!bundles.containsKey(id)) VoxelsSync.getKey(id)?.let { bundles[id] = it }-                        }-                    }-                    if (netRole == 1) refreshRoster()-                    // Verify + gate an incoming signed op, then hand the inner NetMsg to the engine.-                    // Signed-op validation: each early return rejects one distinct-                    // failure (bad author, bad roster, bad signature). Splitting-                    // would scatter a single security check.-                    @Suppress("ReturnCount")-                    fun handleSignedOp(plain: String) {-                        try {-                            val so = JSONObject(plain)-                            val author = so.optString("author")-                            val sig = so.optString("sig")-                            val ops = so.optString("ops")-                            if (author.isEmpty() || ops.isEmpty() || author == myId) return-                            if (netRole == 2) {-                                // Client applies only owner-signed authoritative state.-                                if (author != ownerDevice) return-                                val ob = ownerBundle ?: return-                                val ok = runCatching { Pqc.verify(ob, ops.encodeToByteArray(), Base64.decode(sig)) }.getOrDefault(false)-                                if (!ok) return-                            } else {-                                // Host: author must be a rostered member AND the op must carry a valid-                                // signature from that member's bundle. On a cache miss, fetch it for-                                // next time and drop this op (the client resends as chunks stay dirty).-                                if (!roster.contains(author)) return-                                val ab = bundles[author]-                                if (ab == null) {-                                    pumpScope.launch(Dispatchers.IO) { runCatching { VoxelsSync.getKey(author) }.getOrNull()?.let { bundles[author] = it } }-                                    return-                                }-                                val ok = runCatching { Pqc.verify(ab, ops.encodeToByteArray(), Base64.decode(sig)) }.getOrDefault(false)-                                if (!ok) return-                            }-                            VoxelsNative.netPushInbound(ops)-                        } catch (_: Exception) {}-                    }-                    fun handlePresence(plain: String) {-                        try {-                            val e = JSONObject(plain)-                            if (e.optString("from") == myId) return-                            VoxelsNative.netPushInbound(e.getJSONObject("m").toString())-                        } catch (_: Exception) {}-                    }-                    VoxelsSync.startLive(-                        scope = this,-                        channel = channel,-                        onConnected = {-                            // A client announces itself (signed) so the host streams the world + snapshot.-                            if (netRole == 2) {-                                val joinOps = JSONObject().put("type", "Join").put("device", myId).put("name", worldName).toString()-                                val sig = Base64.encode(VoxelsSync.sign(joinOps.encodeToByteArray()))-                                val signed = JSONObject().put("author", myId).put("sig", sig).put("ops", joinOps).toString()-                                VoxelsSync.liveAppend(channel, key, listOf(signed))-                            }-                        },-                        onMessage = { raw ->-                            val msg = VoxelsSync.parseLive(raw)-                            if (msg != null) when (msg.t) {-                                "actions" -> for (b in msg.actions) {-                                    val plain = VoxelsSync.decrypt(key, b)-                                    if (plain != null) handleSignedOp(plain)-                                }-                                "presence" -> {-                                    val plain = VoxelsSync.decrypt(key, msg.data)-                                    if (plain != null) handlePresence(plain)-                                }-                            }-                        },+                    MultiplayerPump.run(+                        context = this@MainActivity,+                        params = MultiplayerPump.Params(sharedWorldId, worldKeyB64, ownerDevice, netRole, worldName),+                        onStatus = { netStatus = it },+                        onPeers = { peersJson = it },                     )-                    var rosterTick = 0-                    while (isActive) {-                        // Periodically re-read the roster so newly-invited editors are accepted mid-session.-                        rosterTick++-                        if (netRole == 1 && rosterTick % 125 == 0) refreshRoster()-                        val out = try { VoxelsNative.netDrainOutbound() } catch (_: Exception) { "[]" }-                        try {-                            val arr = JSONArray(out)-                            val ops = ArrayList<String>()-                            for (i in 0 until arr.length()) {-                                val o = arr.getJSONObject(i)-                                if (o.optString("type") == "PlayerTransform") {-                                    val env = JSONObject().put("from", myId).put("m", o).toString()-                                    VoxelsSync.sendPresence(channel, key, env)-                                } else {-                                    val opsJson = o.toString()-                                    val sig = Base64.encode(VoxelsSync.sign(opsJson.encodeToByteArray()))-                                    ops.add(JSONObject().put("author", myId).put("sig", sig).put("ops", opsJson).toString())-                                }-                            }-                            if (ops.isNotEmpty()) VoxelsSync.liveAppend(channel, key, ops)-                        } catch (_: Exception) {}-                        netConnected = VoxelsSync.isLive-                        peersJson = try { VoxelsNative.getPeersJson() } catch (_: Exception) { "[]" }-                        delay(80)-                    }                 }                  // "Paused" is real: the engine stops simulating and every held control is released,@@ -616,25 +502,12 @@ class MainActivity : ComponentActivity() {                             }                         } -                        // Online HUD: how many players are here, plus a connection-lost indicator.+                            // Online HUD: players here, host presence, connection state, join/leave notices.                         if (online) {-                            val peerCount = remember(peersJson) { runCatching { JSONArray(peersJson).length() }.getOrDefault(0) }-                            Box(Modifier.align(Alignment.TopEnd).padding(top = 36.dp, end = 12.dp)) {-                                Text(-                                    stringResource(R.string.players_online, peerCount + 1),-                                    color = Color.White,-                                    modifier = Modifier.background(Color(0x66000000)).padding(horizontal = 8.dp, vertical = 4.dp),-                                )-                            }-                            if (!netConnected) {-                                Box(Modifier.align(Alignment.TopCenter).padding(top = 8.dp)) {-                                    Text(-                                        stringResource(R.string.connection_lost),-                                        color = Color.White,-                                        modifier = Modifier.background(Color(0xCCB00020)).padding(horizontal = 12.dp, vertical = 6.dp),-                                    )-                                }-                            }+                            OnlineHud(+                                status = netStatus, peersJson = peersJson, ownerDevice = ownerDevice, isHost = netRole == 1,+                                modifier = Modifier.align(Alignment.TopEnd).padding(top = 36.dp, end = 12.dp),+                            )                         }                     }                     }@@ -732,7 +605,7 @@ class MainActivity : ComponentActivity() {      override fun onDestroy() {         com.vayunmathur.games.voxels.platform.MusicFx.stop()-        VoxelsSync.stopLive()+        com.vayunmathur.games.voxels.network.VoxelsSync.stopLive()         if (VoxelsNative.isAvailable) {             try { VoxelsNative.nativeSetRole(0) } catch (_: Exception) {}             try { VoxelsNative.nativeOnDestroy() } catch (_: Exception) {}
games/voxels/src/main/java/com/vayunmathur/games/voxels/domain/NetStatus.kt
diff --git a/games/voxels/src/main/java/com/vayunmathur/games/voxels/domain/NetStatus.kt b/games/voxels/src/main/java/com/vayunmathur/games/voxels/domain/NetStatus.ktnew file mode 100644index 0000000000..4b072e1fb0--- /dev/null+++ b/games/voxels/src/main/java/com/vayunmathur/games/voxels/domain/NetStatus.kt@@ -0,0 +1,45 @@+package com.vayunmathur.games.voxels.domain++/** Why an online session could not start. */+enum class NetFailure {+    /** The sync identity couldn't be set up / registered (offline, or the relay is unreachable). */+    SERVER_UNREACHABLE,+    /** The world key from the invite is unreadable. */+    BAD_INVITE,+    /** The host's public key couldn't be fetched, so its updates can't be verified. */+    HOST_UNVERIFIED,+}++/** Connection state shown on the online HUD. */+sealed interface NetStatus {+    /** First connection attempt in progress. */+    data object Connecting : NetStatus+    /** Live connection to the world channel. */+    data object Connected : NetStatus+    /** Was connected, lost it, retrying with backoff. */+    data object Reconnecting : NetStatus+    /** Can't start at all; [reason] says why. */+    data class Failed(val reason: NetFailure) : NetStatus+}++/**+ * Live-socket state to HUD state. Before the first successful connection we are "connecting", not+ * "lost" - showing "Connection lost" on every join was the bug this replaces.+ */+fun netStatusOf(live: Boolean, everConnected: Boolean): NetStatus = when {+    live -> NetStatus.Connected+    everConnected -> NetStatus.Reconnecting+    else -> NetStatus.Connecting+}++/** Players who appeared ([joined]) and disappeared ([left]) between two peer snapshots. */+data class PeerChanges(val joined: Set<String>, val left: Set<String>)++/** Diff of two peer-id sets. */+fun peerChanges(before: Set<String>, after: Set<String>): PeerChanges =+    PeerChanges(joined = after - before, left = before - after)++/** Short display name for a device id, matching the join-request naming ("Player 1a2b"). */+fun playerLabel(deviceId: String): String = "Player " + deviceId.takeLast(PLAYER_SUFFIX)++private const val PLAYER_SUFFIX = 4
games/voxels/src/main/java/com/vayunmathur/games/voxels/network/MultiplayerPump.kt
diff --git a/games/voxels/src/main/java/com/vayunmathur/games/voxels/network/MultiplayerPump.kt b/games/voxels/src/main/java/com/vayunmathur/games/voxels/network/MultiplayerPump.ktnew file mode 100644index 0000000000..f836b9cc30--- /dev/null+++ b/games/voxels/src/main/java/com/vayunmathur/games/voxels/network/MultiplayerPump.kt@@ -0,0 +1,199 @@+@file:OptIn(kotlin.io.encoding.ExperimentalEncodingApi::class)++package com.vayunmathur.games.voxels.network++import android.content.Context+import com.vayunmathur.e2ee.Pqc+import com.vayunmathur.games.voxels.domain.NetFailure+import com.vayunmathur.games.voxels.domain.NetStatus+import com.vayunmathur.games.voxels.domain.netStatusOf+import com.vayunmathur.games.voxels.util.VoxelsNative+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.coroutineScope+import kotlinx.coroutines.delay+import kotlinx.coroutines.isActive+import kotlinx.coroutines.launch+import org.json.JSONArray+import org.json.JSONObject+import java.util.Collections+import java.util.concurrent.ConcurrentHashMap+import java.util.concurrent.atomic.AtomicBoolean+import kotlin.io.encoding.Base64++/**+ * Online multiplayer pump: bridges the Rust net queues to the encrypted relay for one session.+ *+ * World-log ops are signed (SignedOp{author,sig,ops}) so peers can authenticate them; player+ * transforms ride ephemeral, unsigned presence. Confidentiality comes from the world AES key (only+ * members hold it); the relay only ever sees ciphertext.+ *+ * Moved out of MainActivity unchanged in its security logic; it now also reports connection state+ * ([NetStatus], including why a session can't start) and the peer list for the HUD.+ */+class MultiplayerPump private constructor(+    private val p: Params,+    private val myId: String,+    private val key: ByteArray,+    private val ownerBundle: ByteArray?,+) {+    /** What MainActivity knows about the session from its launch intent. */+    data class Params(+        val worldId: String,+        val worldKeyB64: String,+        val ownerDevice: String,+        val role: Int,+        val worldName: String,+    )++    private val channel = "world:${p.worldId}"+    private val isHost get() = p.role == ROLE_HOST++    // Host: the authorized member set (all editors — no viewers) + each member's public bundle, so+    // every client op is signature-verified, not just role-gated by id.+    private val roster: MutableSet<String> = Collections.synchronizedSet(HashSet())+    private val bundles = ConcurrentHashMap<String, ByteArray>()++    /** Entry point and session setup. */+    companion object {+        private const val ROLE_HOST = 1+        private const val ROLE_CLIENT = 2+        private const val PUMP_MS = 80L+        // Re-read the roster about every 10 s so newly invited editors are accepted mid-session.+        private const val ROSTER_EVERY = 125++        /** Runs the pump until the calling coroutine is cancelled. */+        suspend fun run(context: Context, params: Params, onStatus: (NetStatus) -> Unit, onPeers: (String) -> Unit) {+            onStatus(NetStatus.Connecting)+            if (!runCatching { VoxelsSync.init(context) }.getOrDefault(false)) {+                onStatus(NetStatus.Failed(NetFailure.SERVER_UNREACHABLE)); return+            }+            val myId = VoxelsSync.deviceId+            try { VoxelsNative.nativeSetDevice(myId) } catch (_: Exception) {}+            val key = runCatching { Base64.decode(params.worldKeyB64) }.getOrNull()+            if (key == null) { onStatus(NetStatus.Failed(NetFailure.BAD_INVITE)); return }+            // Owner bundle: the host is the owner; a client fetches it once to verify host ops.+            val ownerBundle = if (params.role == ROLE_HOST) VoxelsSync.publicBundle+            else runCatching { VoxelsSync.getKey(params.ownerDevice) }.getOrNull()+            if (ownerBundle == null) { onStatus(NetStatus.Failed(NetFailure.HOST_UNVERIFIED)); return }+            MultiplayerPump(params, myId, key, ownerBundle).loop(onStatus, onPeers)+        }+    }++    private suspend fun refreshRoster() {+        val members = runCatching { VoxelsSync.fetchRoster(p.worldId, key, VoxelsSync.publicBundle) }.getOrNull()+        members?.forEach { (id, _) ->+            roster.add(id)+            if (!bundles.containsKey(id)) VoxelsSync.getKey(id)?.let { bundles[id] = it }+        }+    }++    // Verify + gate an incoming signed op, then hand the inner NetMsg to the engine. Each early+    // return rejects one distinct failure (bad author, bad roster, bad signature); splitting would+    // scatter a single security check.+    @Suppress("ReturnCount")+    private fun handleSignedOp(scope: CoroutineScope, plain: String) {+        try {+            val so = JSONObject(plain)+            val author = so.optString("author")+            val sig = so.optString("sig")+            val ops = so.optString("ops")+            if (author.isEmpty() || ops.isEmpty() || author == myId) return+            if (p.role == ROLE_CLIENT) {+                // Client applies only owner-signed authoritative state.+                if (author != p.ownerDevice) return+                val ob = ownerBundle ?: return+                if (!verify(ob, ops, sig)) return+            } else {+                // Host: author must be a rostered member AND the op must carry a valid signature from+                // that member's bundle. On a cache miss, fetch it for next time and drop this op (the+                // client resends as chunks stay dirty).+                if (!roster.contains(author)) return+                val ab = bundles[author]+                if (ab == null) { fetchBundleLater(scope, author); return }+                if (!verify(ab, ops, sig)) return+            }+            VoxelsNative.netPushInbound(ops)+        } catch (_: Exception) {}+    }++    private fun fetchBundleLater(scope: CoroutineScope, author: String) {+        scope.launch(Dispatchers.IO) {+            runCatching { VoxelsSync.getKey(author) }.getOrNull()?.let { bundles[author] = it }+        }+    }++    private fun verify(bundle: ByteArray, ops: String, sig: String): Boolean =+        runCatching { Pqc.verify(bundle, ops.encodeToByteArray(), Base64.decode(sig)) }.getOrDefault(false)++    private fun handlePresence(plain: String) {+        try {+            val e = JSONObject(plain)+            if (e.optString("from") == myId) return+            VoxelsNative.netPushInbound(e.getJSONObject("m").toString())+        } catch (_: Exception) {}+    }++    private suspend fun signed(opsJson: String): String {+        val sig = Base64.encode(VoxelsSync.sign(opsJson.encodeToByteArray()))+        return JSONObject().put("author", myId).put("sig", sig).put("ops", opsJson).toString()+    }++    private fun startLive(scope: CoroutineScope, onConnected: () -> Unit) {+        VoxelsSync.startLive(+            scope = scope,+            channel = channel,+            onConnected = {+                onConnected()+                // A client announces itself (signed) so the host streams the world + snapshot.+                if (!isHost) {+                    val joinOps = JSONObject().put("type", "Join").put("device", myId)+                        .put("name", p.worldName).toString()+                    VoxelsSync.liveAppend(channel, key, listOf(signed(joinOps)))+                }+            },+            onMessage = { raw ->+                val msg = VoxelsSync.parseLive(raw)+                if (msg != null) when (msg.t) {+                    "actions" -> for (b in msg.actions) VoxelsSync.decrypt(key, b)?.let { handleSignedOp(scope, it) }+                    "presence" -> VoxelsSync.decrypt(key, msg.data)?.let { handlePresence(it) }+                }+            },+        )+    }++    // Ships everything the engine queued: transforms as presence, the rest as signed world ops.+    private suspend fun flushOutbound() {+        val out = try { VoxelsNative.netDrainOutbound() } catch (_: Exception) { "[]" }+        try {+            val arr = JSONArray(out)+            val ops = ArrayList<String>()+            for (i in 0 until arr.length()) {+                val o = arr.getJSONObject(i)+                if (o.optString("type") == "PlayerTransform") {+                    VoxelsSync.sendPresence(channel, key, JSONObject().put("from", myId).put("m", o).toString())+                } else {+                    ops.add(signed(o.toString()))+                }+            }+            if (ops.isNotEmpty()) VoxelsSync.liveAppend(channel, key, ops)+        } catch (_: Exception) {}+    }++    private suspend fun loop(onStatus: (NetStatus) -> Unit, onPeers: (String) -> Unit) = coroutineScope {+        roster.add(p.ownerDevice); roster.add(myId)+        VoxelsSync.publicBundle.let { bundles[myId] = it; bundles[p.ownerDevice] = it }+        if (isHost) refreshRoster()+        val everConnected = AtomicBoolean(false)+        startLive(this) { everConnected.set(true) }+        var tick = 0+        while (isActive) {+            tick+++            if (isHost && tick % ROSTER_EVERY == 0) refreshRoster()+            flushOutbound()+            onStatus(netStatusOf(VoxelsSync.isLive, everConnected.get()))+            onPeers(try { VoxelsNative.getPeersJson() } catch (_: Exception) { "[]" })+            delay(PUMP_MS)+        }+    }+}
games/voxels/src/main/java/com/vayunmathur/games/voxels/ui/OnlineHud.kt
diff --git a/games/voxels/src/main/java/com/vayunmathur/games/voxels/ui/OnlineHud.kt b/games/voxels/src/main/java/com/vayunmathur/games/voxels/ui/OnlineHud.ktnew file mode 100644index 0000000000..d30c1de635--- /dev/null+++ b/games/voxels/src/main/java/com/vayunmathur/games/voxels/ui/OnlineHud.kt@@ -0,0 +1,90 @@+package com.vayunmathur.games.voxels.ui++import androidx.compose.foundation.background+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.widthIn+import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.mutableStateListOf+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.unit.dp+import com.vayunmathur.games.voxels.R+import com.vayunmathur.games.voxels.domain.NetFailure+import com.vayunmathur.games.voxels.domain.NetStatus+import com.vayunmathur.games.voxels.domain.peerChanges+import com.vayunmathur.games.voxels.domain.playerLabel+import com.vayunmathur.library.ui.Text+import kotlinx.coroutines.delay+import org.json.JSONArray++private data class Notice(val id: Long, val player: String, val joined: Boolean)++private const val NOTICE_MS = 4000L++/** Device ids in the engine's peer JSON (`[{"device":..}]`). */+internal fun peerIds(peersJson: String): Set<String> = runCatching {+    val arr = JSONArray(peersJson)+    (0 until arr.length()).map { arr.getJSONObject(it).optString("device") }.filter { it.isNotEmpty() }.toSet()+}.getOrDefault(emptySet())++/**+ * Online HUD: how many players are here, whether the host is (for joiners), the connection state+ * (Connecting / Reconnecting / why it failed) and short-lived "X joined" / "X left" notices.+ */+@Composable+fun OnlineHud(status: NetStatus, peersJson: String, ownerDevice: String, isHost: Boolean, modifier: Modifier = Modifier) {+    val peers = remember(peersJson) { peerIds(peersJson) }+    val notices = remember { mutableStateListOf<Notice>() }+    val previous = remember { mutableStateOf<Set<String>?>(null) }+    LaunchedEffect(peers) {+        val before = previous.value+        previous.value = peers+        if (before == null) return@LaunchedEffect+        val c = peerChanges(before, peers)+        val now = System.nanoTime()+        c.joined.forEachIndexed { i, id -> notices += Notice(now + i, playerLabel(id), joined = true) }+        c.left.forEachIndexed { i, id -> notices += Notice(now + 1000 + i, playerLabel(id), joined = false) }+    }+    Column(modifier.widthIn(max = 320.dp), horizontalAlignment = Alignment.End, verticalArrangement = Arrangement.spacedBy(4.dp)) {+        Chip(stringResource(R.string.players_online, peers.size + 1), Color(0x99000000))+        if (!isHost && status == NetStatus.Connected) {+            val here = ownerDevice in peers+            Chip(stringResource(if (here) R.string.host_here else R.string.host_away), if (here) Color(0x992E7D32) else Color(0x99000000))+        }+        when (status) {+            NetStatus.Connected -> Unit+            NetStatus.Connecting -> Chip(stringResource(R.string.online_connecting), Color(0x99000000))+            NetStatus.Reconnecting -> Chip(stringResource(R.string.connection_lost), Color(0xCCB26A00))+            is NetStatus.Failed -> Chip(stringResource(failureText(status.reason)), Color(0xCCB00020))+        }+        for (n in notices) {+            Chip(stringResource(if (n.joined) R.string.player_joined else R.string.player_left, n.player), Color(0x99000000))+            LaunchedEffect(n.id) {+                delay(NOTICE_MS)+                notices.remove(n)+            }+        }+    }+}++private fun failureText(reason: NetFailure): Int = when (reason) {+    NetFailure.SERVER_UNREACHABLE -> R.string.online_failed_server+    NetFailure.BAD_INVITE -> R.string.online_failed_invite+    NetFailure.HOST_UNVERIFIED -> R.string.online_failed_host+}++@Composable+private fun Chip(text: String, background: Color) {+    Text(+        text, color = Color.White,+        modifier = Modifier.background(background, RoundedCornerShape(6.dp)).padding(horizontal = 8.dp, vertical = 4.dp),+    )+}
games/voxels/src/main/res/values/strings.xml
diff --git a/games/voxels/src/main/res/values/strings.xml b/games/voxels/src/main/res/values/strings.xmlindex 4286b051c9..46408c8211 100644--- a/games/voxels/src/main/res/values/strings.xml+++ b/games/voxels/src/main/res/values/strings.xml@@ -95,6 +95,18 @@     <string name="join_request_sent">Requested to join — you\'ll get access once the host approves.</string>     <string name="connection_lost">Connection lost — waiting to reconnect…</string>     <string name="players_online">%1$d online</string>+    <!-- Online HUD while the first connection to a shared world is being made. Sentence fragment -->+    <string name="online_connecting">Connecting…</string>+    <!-- Online HUD for joiners: the host is (not) connected right now. Sentence fragment -->+    <string name="host_here">Host is here</string>+    <string name="host_away">Host isn\'t connected</string>+    <!-- Online HUD notices; %1$s = player name. Sentence fragment -->+    <string name="player_joined">%1$s joined</string>+    <string name="player_left">%1$s left</string>+    <!-- Online HUD: why multiplayer could not start. Sentences -->+    <string name="online_failed_server">Couldn\'t reach the Voxels server — playing offline.</string>+    <string name="online_failed_invite">This world\'s invite is damaged — ask the host to invite you again.</string>+    <string name="online_failed_host">Couldn\'t verify the host, so their changes can\'t be shown.</string>     <!-- Settings sheet title. Noun -->     <string name="settings">Settings</string>     <string name="settings_look_sensitivity">Look sensitivity</string>
games/voxels/src/test/java/com/vayunmathur/games/voxels/domain/NetStatusTest.kt
diff --git a/games/voxels/src/test/java/com/vayunmathur/games/voxels/domain/NetStatusTest.kt b/games/voxels/src/test/java/com/vayunmathur/games/voxels/domain/NetStatusTest.ktnew file mode 100644index 0000000000..9150307859--- /dev/null+++ b/games/voxels/src/test/java/com/vayunmathur/games/voxels/domain/NetStatusTest.kt@@ -0,0 +1,23 @@+package com.vayunmathur.games.voxels.domain++import kotlin.test.Test+import kotlin.test.assertEquals++class NetStatusTest {+    @Test fun `joining shows connecting, not connection lost`() {+        assertEquals(NetStatus.Connecting, netStatusOf(live = false, everConnected = false))+        assertEquals(NetStatus.Connected, netStatusOf(live = true, everConnected = false))+        assertEquals(NetStatus.Reconnecting, netStatusOf(live = false, everConnected = true))+    }++    @Test fun `peer diffs report joins and leaves`() {+        val c = peerChanges(setOf("a", "b"), setOf("b", "c"))+        assertEquals(setOf("c"), c.joined)+        assertEquals(setOf("a"), c.left)+        assertEquals(PeerChanges(emptySet(), emptySet()), peerChanges(setOf("x"), setOf("x")))+    }++    @Test fun `players are labelled by their id suffix`() {+        assertEquals("Player 9f3e", playerLabel("0123-4567-9f3e"))+    }+}
games/voxels/src/test/java/com/vayunmathur/games/voxels/ui/OnlineHudTest.kt
diff --git a/games/voxels/src/test/java/com/vayunmathur/games/voxels/ui/OnlineHudTest.kt b/games/voxels/src/test/java/com/vayunmathur/games/voxels/ui/OnlineHudTest.ktnew file mode 100644index 0000000000..0a96274f2a--- /dev/null+++ b/games/voxels/src/test/java/com/vayunmathur/games/voxels/ui/OnlineHudTest.kt@@ -0,0 +1,38 @@+package com.vayunmathur.games.voxels.ui++import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onNodeWithText+import com.vayunmathur.games.voxels.domain.NetFailure+import com.vayunmathur.games.voxels.domain.NetStatus+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import kotlin.test.Test+import kotlin.test.assertEquals++@RunWith(RobolectricTestRunner::class)+class OnlineHudTest {+    @get:Rule val rule = createComposeRule()++    @Test fun `peer ids are read from the engine json`() {+        assertEquals(setOf("a", "b"), peerIds("""[{"device":"a","x":0},{"device":"b"}]"""))+        assertEquals(emptySet(), peerIds("junk"))+    }++    @Test fun `a fresh join says connecting, not connection lost`() {+        rule.setContent { OnlineHud(NetStatus.Connecting, "[]", ownerDevice = "host", isHost = false) }+        rule.onNodeWithText("Connecting…").assertExists()+        rule.onNodeWithText("Connection lost — waiting to reconnect…").assertDoesNotExist()+    }++    @Test fun `joiners see whether the host is here`() {+        rule.setContent { OnlineHud(NetStatus.Connected, """[{"device":"host"}]""", ownerDevice = "host", isHost = false) }+        rule.onNodeWithText("Host is here").assertExists()+        rule.onNodeWithText("2 online").assertExists()+    }++    @Test fun `failures say why`() {+        rule.setContent { OnlineHud(NetStatus.Failed(NetFailure.BAD_INVITE), "[]", ownerDevice = "h", isHost = false) }+        rule.onNodeWithText("This world's invite is damaged — ask the host to invite you again.").assertExists()+    }+}