voxels: poll join requests in the menu; in-game host prompt (#ux-audit)
- Commit
fbbd8fde166726dba5620b7decb6c67edd3474b8- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-13 01:36 UTC (23 days ago)
- Parents
fc0919d
Symptom: a friend tapping a join link sent a request the host only saw if they happened to open the world menu (or pressed Refresh) after it arrived. A host who was already playing never found out, so joining meant coordinating out of band and asking the host to quit to the menu. Root cause: MenuActivity pulled the inbox once on start and on manual Refresh; nothing pulled it while playing. Fix: - New network/JoinRequests: refresh() (pull inbox, optionally fold in invites, return pending requests for owned worlds), the pure pending() filter (owned world, not yet handled, one per requester+world), approve() (sealed invite + roster record, marks handled) and deny(). MenuActivity's inline copies of that logic now call it. - The menu re-pulls the inbox every 20 s while it is resumed and the device is online (new menuResumed flag from onResume/onPause), so invites and requests appear by themselves. - In game, the host of an online world polls for requests to that world every 20 s and shows a JoinRequestChip under the online HUD: "<player> wants to join" with Deny / Approve. Approving sends the invite; the running session's roster refresh (every ~10 s) then accepts the newcomer's signed ops. User-visible effect: join requests show up within ~20 s in the menu and can be approved without leaving the world. Verification: new JoinRequestsTest for the pending() filter.
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 2d3545849d..1a82963e72 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@@ -38,6 +38,7 @@ import androidx.compose.runtime.mutableFloatStateOf import androidx.compose.runtime.mutableIntStateOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember+import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.setValue import androidx.compose.ui.input.pointer.pointerInput import androidx.compose.ui.Alignment@@ -55,7 +56,9 @@ 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.JoinRequests import com.vayunmathur.games.voxels.network.MultiplayerPump+import com.vayunmathur.games.voxels.network.VoxelsSync import com.vayunmathur.games.voxels.domain.OverlayFlags import com.vayunmathur.games.voxels.domain.backTarget import com.vayunmathur.games.voxels.ui.BossBar@@ -74,6 +77,7 @@ 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.JoinRequestChip import com.vayunmathur.games.voxels.ui.OnlineHud import com.vayunmathur.games.voxels.ui.TradeOverlay import com.vayunmathur.games.voxels.ui.UseButton@@ -92,6 +96,7 @@ import com.vayunmathur.library.ui.Text import com.vayunmathur.library.util.GameHubComposeHook import kotlinx.coroutines.delay import kotlinx.coroutines.isActive+import kotlinx.coroutines.launch class MainActivity : ComponentActivity() { // Pause-menu state lives on the activity so onStop can pause the game: coming back from Home or@@ -281,6 +286,19 @@ class MainActivity : ComponentActivity() { } } + // Host only: poll for join requests to this world while playing, so the host can let a+ // friend in without quitting to the menu.+ val scope = rememberCoroutineScope()+ var joinRequests by remember { mutableStateOf<List<VoxelsSync.JoinRequest>>(emptyList()) }+ LaunchedEffect(online, netRole) {+ if (!online || netRole != 1) return@LaunchedEffect+ while (isActive) {+ joinRequests = JoinRequests.refresh(this@MainActivity, acceptInvites = false)+ .filter { it.worldId == sharedWorldId }+ delay(JoinRequests.POLL_MS)+ }+ }+ // --- Online multiplayer pump (network/MultiplayerPump.kt): bridges the Rust net // queues to the encrypted relay and reports connection state + who is here. --- LaunchedEffect(online) {@@ -502,12 +520,28 @@ class MainActivity : ComponentActivity() { } } - // Online HUD: players here, host presence, connection state, join/leave notices.+ // Online HUD: players here, host presence, connection state, join/leave notices,+ // and for the host, anyone asking to join right now. if (online) {- OnlineHud(- status = netStatus, peersJson = peersJson, ownerDevice = ownerDevice, isHost = netRole == 1,- modifier = Modifier.align(Alignment.TopEnd).padding(top = 36.dp, end = 12.dp),- )+ Column(+ Modifier.align(Alignment.TopEnd).padding(top = 36.dp, end = 12.dp),+ horizontalAlignment = Alignment.End, verticalArrangement = Arrangement.spacedBy(6.dp),+ ) {+ OnlineHud(status = netStatus, peersJson = peersJson, ownerDevice = ownerDevice, isHost = netRole == 1)+ joinRequests.firstOrNull()?.let { req ->+ JoinRequestChip(+ player = req.name.ifBlank { req.requesterId.take(8) },+ onApprove = {+ joinRequests = joinRequests - req+ scope.launch { JoinRequests.approve(this@MainActivity, req) }+ },+ onDeny = {+ joinRequests = joinRequests - req+ JoinRequests.deny(this@MainActivity, req)+ },+ )+ }+ } } } }@@ -605,7 +639,7 @@ class MainActivity : ComponentActivity() { override fun onDestroy() { com.vayunmathur.games.voxels.platform.MusicFx.stop()- com.vayunmathur.games.voxels.network.VoxelsSync.stopLive()+ 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/network/JoinRequests.kt
diff --git a/games/voxels/src/main/java/com/vayunmathur/games/voxels/network/JoinRequests.kt b/games/voxels/src/main/java/com/vayunmathur/games/voxels/network/JoinRequests.ktnew file mode 100644index 0000000000..4b080ebdaf--- /dev/null+++ b/games/voxels/src/main/java/com/vayunmathur/games/voxels/network/JoinRequests.kt@@ -0,0 +1,82 @@+@file:OptIn(kotlin.io.encoding.ExperimentalEncodingApi::class)++package com.vayunmathur.games.voxels.network++import android.content.Context+import com.vayunmathur.games.voxels.data.WorldManager+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.withContext+import kotlin.io.encoding.Base64++/**+ * Join requests for worlds this device owns: fetching the pending ones and approving or denying+ * them. Shared by the world menu (which polls while it's on screen) and the in-game host chip.+ */+object JoinRequests {+ /** How often the menu and the in-game host poll the inbox. */+ const val POLL_MS = 20_000L++ /** Persistent key marking a request as handled (the inbox is always pulled from 0). */+ fun handledKey(r: VoxelsSync.JoinRequest): String = "${r.worldId}|${r.requesterId}"++ /** Requests for [owned] worlds that haven't been approved/denied yet, one per requester+world. */+ fun pending(+ requests: List<VoxelsSync.JoinRequest>,+ owned: Set<String>,+ handled: Set<String>,+ ): List<VoxelsSync.JoinRequest> = requests+ .filter { it.worldId in owned && handledKey(it) !in handled }+ .distinctBy { handledKey(it) }++ /**+ * Pulls the inbox. Invites are folded into the shared-world list (when [acceptInvites]); returns+ * the pending requests for worlds this device owns. Empty on any failure.+ */+ suspend fun refresh(ctx: Context, acceptInvites: Boolean): List<VoxelsSync.JoinRequest> =+ withContext(Dispatchers.IO) {+ runCatching {+ if (!VoxelsSync.init(ctx)) return@runCatching emptyList()+ val res = VoxelsSync.pullInbox(0)+ if (acceptInvites) {+ for (inv in res.invites) {+ WorldManager.upsertSharedWorld(+ ctx, inv.name, inv.seed, inv.worldId,+ inv.key, inv.ownerDeviceId, inv.role, System.currentTimeMillis(),+ )+ }+ }+ val owned = WorldManager.onlineWorlds(ctx)+ .filter { it.meta.role == VoxelsRoles.OWNER }.map { it.meta.worldId }.toSet()+ pending(res.requests, owned, WorldManager.handledRequests(ctx))+ }.getOrDefault(emptyList())+ }++ /** Sends the requester a sealed invite and records them as an editor. True if the invite went out. */+ suspend fun approve(ctx: Context, req: VoxelsSync.JoinRequest): Boolean = withContext(Dispatchers.IO) {+ val ok = runCatching {+ VoxelsSync.init(ctx)+ val world = WorldManager.onlineWorlds(ctx)+ .firstOrNull { it.meta.worldId == req.worldId && it.meta.role == VoxelsRoles.OWNER }+ ?: return@runCatching false+ val key = Base64.decode(world.meta.keyB64)+ val sent = VoxelsSync.sendInvite(+ req.requesterId, world.meta.worldId, key,+ world.meta.name, world.meta.seed, VoxelsRoles.EDITOR,+ Base64.encode(VoxelsSync.publicBundle), world.meta.ownerDeviceId,+ )+ if (sent) VoxelsSync.recordMembers(+ world.meta.worldId, key,+ listOf(+ VoxelsSync.Member(world.meta.ownerDeviceId, "", VoxelsRoles.OWNER),+ VoxelsSync.Member(req.requesterId, req.name, VoxelsRoles.EDITOR),+ ),+ )+ sent+ }.getOrDefault(false)+ if (ok) WorldManager.markRequestHandled(ctx, handledKey(req))+ ok+ }++ /** Declines a request; it won't be shown again. */+ fun deny(ctx: Context, req: VoxelsSync.JoinRequest) = WorldManager.markRequestHandled(ctx, handledKey(req))+}
games/voxels/src/main/java/com/vayunmathur/games/voxels/platform/MenuActivity.kt
diff --git a/games/voxels/src/main/java/com/vayunmathur/games/voxels/platform/MenuActivity.kt b/games/voxels/src/main/java/com/vayunmathur/games/voxels/platform/MenuActivity.ktindex 1693d9b8a6..b0361a1a4d 100644--- a/games/voxels/src/main/java/com/vayunmathur/games/voxels/platform/MenuActivity.kt+++ b/games/voxels/src/main/java/com/vayunmathur/games/voxels/platform/MenuActivity.kt@@ -31,11 +31,13 @@ import com.vayunmathur.library.ui.DynamicTheme import com.vayunmathur.library.ui.Surface import com.vayunmathur.library.util.AppMessages import com.vayunmathur.library.util.rememberIsOnline+import com.vayunmathur.games.voxels.network.JoinRequests import com.vayunmathur.games.voxels.network.VoxelsRoles import com.vayunmathur.games.voxels.network.VoxelsSync import com.vayunmathur.games.voxels.data.WorldInfo import com.vayunmathur.games.voxels.data.WorldManager import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.delay import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import kotlin.io.encoding.Base64@@ -48,6 +50,8 @@ class MenuActivity : ComponentActivity() { // Bumped on each onResume so the world list reloads when returning from the game // (keeps last-played ordering fresh). private var resumeTick by mutableStateOf(0)+ // True while the menu is in the foreground; drives the inbox poll.+ private var menuResumed by mutableStateOf(false) /** * Pending `voxels://join/<worldId>?owner=<id>` link (worldId to ownerId), set on cold start and@@ -58,6 +62,12 @@ class MenuActivity : ComponentActivity() { override fun onResume() { super.onResume() resumeTick+++ menuResumed = true+ }++ override fun onPause() {+ menuResumed = false+ super.onPause() } override fun onNewIntent(intent: Intent) {@@ -105,27 +115,17 @@ class MenuActivity : ComponentActivity() { // Pulls the inbox (from 0): folds invites into the shared-world list and surfaces // join requests for worlds this device owns (minus already-approved/denied ones). val refreshInbox: suspend () -> Unit = {- val pending = withContext(Dispatchers.IO) {- runCatching {- VoxelsSync.init(ctx)- val res = VoxelsSync.pullInbox(0)- for (inv in res.invites) {- WorldManager.upsertSharedWorld(- ctx, inv.name, inv.seed, inv.worldId,- inv.key, inv.ownerDeviceId, inv.role, System.currentTimeMillis(),- )- }- val owned = WorldManager.onlineWorlds(ctx)- .filter { it.meta.role == VoxelsRoles.OWNER }.map { it.meta.worldId }.toSet()- val handled = WorldManager.handledRequests(ctx)- res.requests- .filter { it.worldId in owned && "${it.worldId}|${it.requesterId}" !in handled }- .distinctBy { "${it.worldId}|${it.requesterId}" }- }.getOrDefault(emptyList())- }- requests = pending+ requests = JoinRequests.refresh(ctx, acceptInvites = true) reload() }+ // Keep pulling while the menu is on screen, so new invites and join requests show up+ // without pressing Refresh.+ LaunchedEffect(menuResumed, online) {+ while (menuResumed && online) {+ delay(JoinRequests.POLL_MS)+ runCatching { refreshInbox() }+ }+ } LaunchedEffect(resumeTick) { worlds = localWorlds()@@ -203,35 +203,13 @@ class MenuActivity : ComponentActivity() { requests = requests, onApprove = { req -> scope.launch {- val ok = withContext(Dispatchers.IO) {- runCatching {- VoxelsSync.init(ctx)- val world = WorldManager.onlineWorlds(ctx)- .firstOrNull { it.meta.worldId == req.worldId && it.meta.role == VoxelsRoles.OWNER }- ?: return@runCatching false- val key = Base64.decode(world.meta.keyB64)- val sent = VoxelsSync.sendInvite(- req.requesterId, world.meta.worldId, key,- world.meta.name, world.meta.seed, VoxelsRoles.EDITOR,- Base64.encode(VoxelsSync.publicBundle), world.meta.ownerDeviceId,- )- if (sent) VoxelsSync.recordMembers(- world.meta.worldId, key,- listOf(- VoxelsSync.Member(world.meta.ownerDeviceId, "", VoxelsRoles.OWNER),- VoxelsSync.Member(req.requesterId, req.name, VoxelsRoles.EDITOR),- ),- )- sent- }.getOrDefault(false)- }- if (ok) WorldManager.markRequestHandled(ctx, "${req.worldId}|${req.requesterId}")+ val ok = JoinRequests.approve(ctx, req) requests = requests.filterNot { it.worldId == req.worldId && it.requesterId == req.requesterId } toast(getString(if (ok) R.string.invite_sent else R.string.invite_failed)) } }, onDeny = { req ->- WorldManager.markRequestHandled(ctx, "${req.worldId}|${req.requesterId}")+ JoinRequests.deny(ctx, req) requests = requests.filterNot { it.worldId == req.worldId && it.requesterId == req.requesterId } }, )
games/voxels/src/main/java/com/vayunmathur/games/voxels/ui/JoinRequestChip.kt
diff --git a/games/voxels/src/main/java/com/vayunmathur/games/voxels/ui/JoinRequestChip.kt b/games/voxels/src/main/java/com/vayunmathur/games/voxels/ui/JoinRequestChip.ktnew file mode 100644index 0000000000..ca5f17cd9c--- /dev/null+++ b/games/voxels/src/main/java/com/vayunmathur/games/voxels/ui/JoinRequestChip.kt@@ -0,0 +1,33 @@+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.Row+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.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.library.ui.Button+import com.vayunmathur.library.ui.OutlinedButton+import com.vayunmathur.library.ui.Text++/** In-game prompt for the host: "<player> wants to join" with Approve / Deny. */+@Composable+fun JoinRequestChip(player: String, onApprove: () -> Unit, onDeny: () -> Unit, modifier: Modifier = Modifier) {+ Column(+ modifier.widthIn(max = 320.dp).background(Color(0xCC1A1E1A), RoundedCornerShape(10.dp)).padding(10.dp),+ verticalArrangement = Arrangement.spacedBy(6.dp),+ ) {+ Text(stringResource(R.string.player_wants_to_join, player), color = Color.White)+ Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {+ OutlinedButton(onClick = onDeny) { Text(stringResource(R.string.deny)) }+ Button(onClick = onApprove) { Text(stringResource(R.string.approve)) }+ }+ }+}
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 46408c8211..85e4dc2cdc 100644--- a/games/voxels/src/main/res/values/strings.xml+++ b/games/voxels/src/main/res/values/strings.xml@@ -101,6 +101,8 @@ <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 -->+ <!-- In-game host prompt; %1$s = requesting player. Sentence -->+ <string name="player_wants_to_join">%1$s wants to join</string> <string name="player_joined">%1$s joined</string> <string name="player_left">%1$s left</string> <!-- Online HUD: why multiplayer could not start. Sentences -->
games/voxels/src/test/java/com/vayunmathur/games/voxels/network/JoinRequestsTest.kt
diff --git a/games/voxels/src/test/java/com/vayunmathur/games/voxels/network/JoinRequestsTest.kt b/games/voxels/src/test/java/com/vayunmathur/games/voxels/network/JoinRequestsTest.ktnew file mode 100644index 0000000000..17c93be370--- /dev/null+++ b/games/voxels/src/test/java/com/vayunmathur/games/voxels/network/JoinRequestsTest.kt@@ -0,0 +1,14 @@+package com.vayunmathur.games.voxels.network++import kotlin.test.Test+import kotlin.test.assertEquals++class JoinRequestsTest {+ private fun req(world: String, who: String) = VoxelsSync.JoinRequest(worldId = world, requesterId = who)++ @Test fun `only unhandled requests for owned worlds, once each`() {+ val all = listOf(req("w1", "a"), req("w1", "a"), req("w2", "b"), req("w1", "c"))+ val pending = JoinRequests.pending(all, owned = setOf("w1"), handled = setOf("w1|c"))+ assertEquals(listOf(req("w1", "a")), pending)+ }+}