kart: host LAN games as an open broadcast, drop the pairing code
- Commit
44434436de1d3e751d489f87ad49d507bb6300c5- Author
- Vayun Mathur <[email protected]>
- When
- 2026-12-05 14:03 UTC (19 hours ago)
- Parents
c72ce94
The just-landed LAN flow made a joining phone type a six-digit pairing code shown on the host. Owner direction is the opposite shape: the host broadcasts itself on the LAN and anybody can read that broadcast and join unilaterally. KartHost now builds its ControllerHost with openJoin = true and advertises a LanGameBeacon on the existing _gamepad._tcp record: host name, game, seated/capacity counts and the track label (the loaded cup name, Sunset Oval before it loads). Every lobby change re-broadcasts, and while racing or when every seat is taken the beacon turns open off, so the game stops looking joinable rather than refusing taps later. Capacity and the race start remain host actions, as before. The pairing-code surface is gone from Kart: KartHost no longer mirrors a code into a flow, KartViewModel exposes no pairing state, the lobby shows the open-LAN line and the driver names instead of digits to type, and the lan_pairing_code string is replaced by lan_open_lobby. KartPairingStore stays as the identity store (the kartTv persisted prefix is untouched, so the existing identity survives) and solo-vs-bots is unchanged: local touch and gamepad input never depended on the LAN host. games/kart/AGENTS.md now describes the open broadcast instead of the pairing code. Verified: :games:kart:lint :games:kart:lintVitalRelease :games:kart:testDevUnitTest pass (env JDK 21 / Android SDK / shared Gradle home, --max-workers=128). Screen and ViewModel tests now assert the open lobby with no code state.
Diff
games/kart/AGENTS.md
diff --git a/games/kart/AGENTS.md b/games/kart/AGENTS.mdindex 0b514e1e82..181dfea98e 100644--- a/games/kart/AGENTS.md+++ b/games/kart/AGENTS.md@@ -11,13 +11,13 @@ _Install: ./install games/kart (release by default)._ - Rust: yes / screenshotTest: yes ## Overview-**Purpose:** 3D kart racer (Sunset Oval) for phones — native Rust engine (Vulkan, with a GLES fallback for devices without Vulkan), kart physics, chase cam, items and AI. Played solo against AI drivers or over LAN: this phone hosts the race, other phones join as extra drivers from the Games Hub app.+**Purpose:** 3D kart racer (Sunset Oval) for phones — native Rust engine (Vulkan, with a GLES fallback for devices without Vulkan), kart physics, chase cam, items and AI. Played solo against AI drivers or over LAN: this phone hosts the race and broadcasts it openly on the Wi-Fi, and other phones join as extra drivers from the Games Hub app with no pairing code. **Game shape:** `Route` (`Lobby` / `Race` / `Results`) → `platform/KartViewModel` → `domain/` race/input rules + `platform/KartHost` (`:sdk:controller` lobby fan-in) → `platform/KartNative` → `src/main/rust/` engine; achievements → `:sdk:games` → hub. Local input (touch + gamepad) is recorded by the ViewModel itself and merged over the host fan-in, so solo races drive even when the LAN host is down. **Entry points:** `Route` → `MainActivity.kt` → `Navigation.kt` → `ui/KartGameScreen.kt` → `platform/KartViewModel.kt` → `platform/KartNative.kt` / `domain/PlaceholderRace.kt`. **Gotchas:** - Native Rust: crate `kart_engine` in `src/main/rust/` (engine/physics/track/mesh/items + `vulkan/` and `gles/` renderers, GLSL `kart.vert`/`kart.frag` compiled at runtime by the GLES path). Phone-only: arm64 like every other app; the GLES renderer is the non-Vulkan fallback. - `platform/KartNative` is the sole `kart_engine` wrapper: every call is gated on `KartNative.isAvailable`; without the `.so` the game runs `domain/PlaceholderRace` — never call native entry points unguarded.-- Controller dep IS present (`:sdk:controller`): `platform/KartHost` advertises `_gamepad._tcp`, accepts phones and fans `ControllerInput` into the race loop (`domain/GameInputLoop`); `platform/GamepadDirect` handles a locally attached gamepad in `MainActivity`. PQC identity stays behind lambdas in `KartHost` — this module never touches the `:library:e2ee-p2p` native library directly. The host's pairing code is mirrored into `KartHost.pairingCodeFlow` and shown in the lobby while a phone pairs — without it, first-time LAN joins cannot complete.+- Controller dep IS present (`:sdk:controller`): `platform/KartHost` broadcasts the open LAN game on `_gamepad._tcp` (a `LanGameBeacon` in the TXT record: host name, game, seated/capacity counts, track, open flag), accepts phones and fans `ControllerInput` into the race loop (`domain/GameInputLoop`); `platform/GamepadDirect` handles a locally attached gamepad in `MainActivity`. PQC identity stays behind lambdas in `KartHost` — this module never touches the `:library:e2ee-p2p` native library directly. LAN joins are open: the inner host runs `openJoin = true`, so any phone that reads the broadcast joins from Games Hub with no pairing code and no approval; the beacon turns closed while racing or full. Solo-vs-bots needs no host at all. - Listing images are hand-captured — Layoutlib can't render the Vulkan surface; `src/screenshotTest` previews cover only the non-surface UI. - `KartDataStore` (`data/`) is the sole prefs owner (cup pointer + lifetime counters); countdown is in-screen state of `Route.Race`, not a destination.
games/kart/src/main/java/com/vayunmathur/games/kart/platform/KartHost.kt
diff --git a/games/kart/src/main/java/com/vayunmathur/games/kart/platform/KartHost.kt b/games/kart/src/main/java/com/vayunmathur/games/kart/platform/KartHost.ktindex 85a34fb639..10d8d91162 100644--- a/games/kart/src/main/java/com/vayunmathur/games/kart/platform/KartHost.kt+++ b/games/kart/src/main/java/com/vayunmathur/games/kart/platform/KartHost.kt@@ -6,9 +6,11 @@ import android.util.Base64 import androidx.core.content.edit import com.vayunmathur.library.log.Log import com.vayunmathur.sdk.controller.ControllerAdvertiser+import com.vayunmathur.sdk.controller.ControllerContract import com.vayunmathur.sdk.controller.ControllerHost import com.vayunmathur.sdk.controller.ControllerInput import com.vayunmathur.sdk.controller.ControllerSocket+import com.vayunmathur.sdk.controller.LanGameBeacon import com.vayunmathur.sdk.controller.LobbyState import java.io.IOException import java.net.ServerSocket@@ -26,19 +28,30 @@ private const val TAG = "KartHost" private const val PREFS = "kart_host" private const val KEY_HOST_ID = "host_id" -/** How often the pairing code is mirrored from the host into [KartHost.pairingCodeFlow]. */-private const val PAIRING_POLL_MS = 250L+/** The one track the engine ships, named in the beacon when no cup label is loaded yet. */+private const val DEFAULT_TRACK = "Sunset Oval" /**- * The LAN lobby owner: advertises `_gamepad._tcp`, accepts phones, and exposes the- * [ControllerHost] fan-in the race loop reads.+ * The LAN lobby owner: broadcasts this phone as an open LAN game, accepts+ * phones, and exposes the [ControllerHost] fan-in the race loop reads.+ *+ * The broadcast is the `_gamepad._tcp` NSD record the controller SDK+ * already advertises, carrying a [LanGameBeacon] in its TXT attributes:+ * host name, game, seated/capacity counts and the track. Anyone on the+ * Wi-Fi who reads it can join unilaterally — the inner host runs with+ * `openJoin = true`, so a connecting phone is paired on the spot with no+ * pairing code shown anywhere and no approval step. While the race is+ * running, or every seat is taken, the beacon turns `open` off, so the+ * game stops looking joinable instead of refusing taps after the fact. * * Key material is injectable: [publicBundle] is the ML-KEM+ML-DSA bundle from `:library:e2ee-p2p` * (`PqcIdentity.publicBundle`), [unsealSecret] opens a sealed session secret with the KEM private- * half. When [pairingStore] is present, device keys and the host id live in the same non-backed-up- * file as the identity, so a restored backup can neither impersonate this phone nor silently- * inherit its paired phones; without it (tests) they fall back to private prefs. Either way the host id- * is a stable id minted once, so re-pairing survives restarts.+ * half. The session channel stays sealed and encrypted exactly as the+ * coded flow left it; only the human code ritual is gone. When+ * [pairingStore] is present, the host id lives in the same non-backed-up+ * file as the identity, so a restored backup cannot silently inherit this+ * phone's identity; without it (tests) they fall back to private prefs.+ * Either way the host id is a stable id minted once. * * PQC stays behind the lambdas deliberately: this module never touches the native library * directly, and tests construct a `KartHost` with fake keys.@@ -52,6 +65,8 @@ class KartHost( private val publicBundle: () -> ByteArray?, private val unsealSecret: (ByteArray) -> ByteArray?, private val pairingStore: KartPairingStore? = null,+ /** The track/mode label for the beacon, e.g. the loaded cup's name. Read at advertise time. */+ private val trackName: () -> String = { DEFAULT_TRACK }, ) { private val prefs: SharedPreferences = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)@@ -81,17 +96,9 @@ class KartHost( private var server: ServerSocket? = null private var started = false - /** The pair code on screen, if a phone is mid-handshake. Null until [start]. */- val pairingCode: String? get() = inner?.pairingCode-- private val _pairingCode = MutableStateFlow<String?>(null)-- /**- * [pairingCode] as a flow, for the lobby UI. The inner host only exposes- * the code as a plain property, so it is polled while the host runs;- * a code that appears between polls shows within a quarter second.- */- val pairingCodeFlow: StateFlow<String?> = _pairingCode.asStateFlow()+ /** Identity of the live broadcast, so [refreshBeacon] can rebuild it. Null until bound. */+ private var broadcastHostId: String? = null+ private var broadcastPort: Int = 0 /** * Resolve the host id, build the [ControllerHost], and start advertising + accepting. Safe to@@ -108,28 +115,62 @@ class KartHost( unsealSecret = unsealSecret, loadDeviceKey = ::loadDeviceKey, saveDeviceKey = ::saveDeviceKey,+ openJoin = true, ) inner = host- scope.launch { host.lobby.collect { _lobby.value = it } }- scope.launch { host.inputs.collect { _inputs.value = it } } scope.launch {- while (true) {- _pairingCode.value = host.pairingCode- kotlinx.coroutines.delay(PAIRING_POLL_MS)+ host.lobby.collect {+ _lobby.value = it+ // The beacon carries the count and the joinability, so every+ // lobby change re-broadcasts: join, leave, race start/end.+ refreshBeacon() } }+ scope.launch { host.inputs.collect { _inputs.value = it } } scope.launch { acceptLoop(hostId, host) } } fun stop() { runCatching { server?.close() } server = null+ broadcastHostId = null+ broadcastPort = 0 advertiser.unadvertise() inner?.close() inner = null scope.cancel() } + /**+ * Re-broadcast the beacon for the current lobby. Called on every lobby+ * change, and by the ViewModel when the track label lands after start.+ * No-ops until the socket is bound.+ */+ fun refreshBeacon() {+ val hostId = broadcastHostId ?: return+ val port = broadcastPort.takeIf { it > 0 } ?: return+ val lobby = latestLobby()+ advertiser.advertise(+ friendlyName = android.os.Build.MODEL ?: "Phone",+ deviceId = hostId,+ port = port,+ gameId = "kart",+ beacon = LanGameBeacon(+ hostId = hostId,+ hostName = android.os.Build.MODEL ?: "Phone",+ gameId = "kart",+ // NSD supplies the endpoint on resolve; the TXT side of the+ // beacon never carries an address.+ hostAddress = "",+ port = port,+ playerCount = lobby.slots.size,+ capacity = ControllerContract.MAX_PLAYERS,+ track = trackName(),+ open = !lobby.racing && lobby.slots.size < ControllerContract.MAX_PLAYERS,+ ),+ )+ }+ private fun acceptLoop(hostId: String, host: ControllerHost) { val server = try { ServerSocket(0).also { this.server = it }@@ -137,12 +178,9 @@ class KartHost( Log.status(TAG, "cannot bind a lobby port", e) return }- advertiser.advertise(- friendlyName = android.os.Build.MODEL ?: "Phone",- deviceId = hostId,- port = server.localPort,- gameId = "kart",- )+ broadcastHostId = hostId+ broadcastPort = server.localPort+ refreshBeacon() Log.status(TAG, "lobby open on port ${server.localPort}") while (true) { val accepted = try {
games/kart/src/main/java/com/vayunmathur/games/kart/platform/KartPairingStore.kt
diff --git a/games/kart/src/main/java/com/vayunmathur/games/kart/platform/KartPairingStore.kt b/games/kart/src/main/java/com/vayunmathur/games/kart/platform/KartPairingStore.ktindex 30f01510ba..e146056fd4 100644--- a/games/kart/src/main/java/com/vayunmathur/games/kart/platform/KartPairingStore.kt+++ b/games/kart/src/main/java/com/vayunmathur/games/kart/platform/KartPairingStore.kt@@ -12,7 +12,10 @@ import kotlinx.coroutines.flow.map private val Context.kartIdentityStore by preferencesDataStore(name = "kart_identity") /**- * The phone's long-term secrets: its own ML-KEM identity, and one device key per paired phone.+ * The phone's long-term identity store: its own ML-KEM identity and stable+ * host id, plus the remembered device keys the coded controller flow used.+ * LAN play is open now (no pairing), so the device keys are only ever read+ * back by the generic coded path, never written by a Kart join. * * Follows the cast/tv `PairingStore` shape (an [E2eeKeyStore] for * `PqcIdentity.loadOrCreate`, plus remembered device keys), with one deliberate
games/kart/src/main/java/com/vayunmathur/games/kart/platform/KartViewModel.kt
diff --git a/games/kart/src/main/java/com/vayunmathur/games/kart/platform/KartViewModel.kt b/games/kart/src/main/java/com/vayunmathur/games/kart/platform/KartViewModel.ktindex a1ee7f09ac..8635f5872b 100644--- a/games/kart/src/main/java/com/vayunmathur/games/kart/platform/KartViewModel.kt+++ b/games/kart/src/main/java/com/vayunmathur/games/kart/platform/KartViewModel.kt@@ -49,9 +49,10 @@ class KartViewModel(application: Application) : AndroidViewModel(application), * The identity loads off the main thread (keygen on first run touches the * native PQC library): until it lands, [KartHost] refuses handshakes * cleanly — the same posture the `{ null }` scaffold had, but only for- * the cold-start window rather than forever. The device-key persistence- * lives in [KartPairingStore] alongside the identity, outside the backup- * set, so a remembered phone re-pairs silently across restarts.+ * the cold-start window rather than forever. The identity lives in+ * [KartPairingStore] outside the backup set. LAN joins are open — no+ * pairing code is ever shown — but each session's channel is still+ * sealed to this identity, so the broadcast stays the only public part. */ private val pairingStore = KartPairingStore(application) @@ -68,11 +69,10 @@ class KartViewModel(application: Application) : AndroidViewModel(application), ?.takeIf { it.size == com.vayunmathur.sdk.controller.ControllerKeys.SECRET_BYTES } }, pairingStore = pairingStore,+ // The beacon names the cup on offer once it has loaded.+ trackName = { _uiState.value.cup?.name ?: "Sunset Oval" }, ) - /** LAN pair code to show while another phone is joining; null when nobody is pairing. */- val pairingCode: StateFlow<String?> = kartHost.pairingCodeFlow- private val _racePhase = MutableStateFlow<RacePhase>(RacePhase.Lobby(kartHost.lobby.value)) /** Lobby → countdown → race → results. The garage reads this alongside [uiState]. */ val racePhase: StateFlow<RacePhase> = _racePhase.asStateFlow()@@ -145,6 +145,8 @@ class KartViewModel(application: Application) : AndroidViewModel(application), bestLapMs = session.bestLap, ), )+ // The cup name is the beacon's track label; refresh it now it exists.+ kartHost.refreshBeacon() } override fun startRace() {
games/kart/src/main/java/com/vayunmathur/games/kart/ui/KartGamePage.kt
diff --git a/games/kart/src/main/java/com/vayunmathur/games/kart/ui/KartGamePage.kt b/games/kart/src/main/java/com/vayunmathur/games/kart/ui/KartGamePage.ktindex 76378c3f48..a77971f608 100644--- a/games/kart/src/main/java/com/vayunmathur/games/kart/ui/KartGamePage.kt+++ b/games/kart/src/main/java/com/vayunmathur/games/kart/ui/KartGamePage.kt@@ -16,11 +16,9 @@ fun KartGamePage( ) { val uiState by viewModel.uiState.collectAsState() val racePhase by viewModel.racePhase.collectAsState()- val pairingCode by viewModel.pairingCode.collectAsState() KartGameScreen( state = uiState, phase = racePhase, actions = viewModel,- pairingCode = pairingCode, ) }
games/kart/src/main/java/com/vayunmathur/games/kart/ui/KartGameScreen.kt
diff --git a/games/kart/src/main/java/com/vayunmathur/games/kart/ui/KartGameScreen.kt b/games/kart/src/main/java/com/vayunmathur/games/kart/ui/KartGameScreen.ktindex 08df03ac79..947bf1e313 100644--- a/games/kart/src/main/java/com/vayunmathur/games/kart/ui/KartGameScreen.kt+++ b/games/kart/src/main/java/com/vayunmathur/games/kart/ui/KartGameScreen.kt@@ -48,7 +48,6 @@ fun KartGameScreen( state: KartUiState, phase: RacePhase, actions: KartGameActions,- pairingCode: String? = null, ) { AppScaffold( title = state.cup?.let { stringResource(R.string.cup_title, it.name) }@@ -71,7 +70,7 @@ fun KartGameScreen( verticalArrangement = Arrangement.spacedBy(Spacing.md), ) { when (val p = phase) {- is RacePhase.Lobby -> LobbyBody(state, p, actions, pairingCode)+ is RacePhase.Lobby -> LobbyBody(state, p, actions) is RacePhase.Countdown -> CountdownBody(p) is RacePhase.Racing -> RacingBody(p, actions) is RacePhase.Results -> ResultsBody(p, actions)@@ -85,7 +84,6 @@ private fun LobbyBody( state: KartUiState, phase: RacePhase.Lobby, actions: KartGameActions,- pairingCode: String?, ) { val cup = state.cup if (cup == null) {@@ -132,14 +130,14 @@ private fun LobbyBody( textAlign = TextAlign.Center, ) }- if (pairingCode != null) {- Text(- stringResource(R.string.lan_pairing_code, pairingCode),- style = MaterialTheme.typography.titleMedium,- color = MaterialTheme.colorScheme.primary,- textAlign = TextAlign.Center,- )- }+ // This lobby is an open LAN broadcast: anyone nearby can join from+ // Games Hub with no code and no approval on this phone.+ Text(+ stringResource(R.string.lan_open_lobby),+ style = MaterialTheme.typography.bodyMedium,+ color = MaterialTheme.colorScheme.primary,+ textAlign = TextAlign.Center,+ ) Button( onClick = { actions.startRace() }, modifier = Modifier.fillMaxWidth(),
games/kart/src/main/res/values/strings.xml
diff --git a/games/kart/src/main/res/values/strings.xml b/games/kart/src/main/res/values/strings.xmlindex cf7148eb60..c00d5b594f 100644--- a/games/kart/src/main/res/values/strings.xml+++ b/games/kart/src/main/res/values/strings.xml@@ -23,8 +23,8 @@ <string name="how_to_play">Drive with the touch controls or a gamepad. Friends on the same Wi-Fi can join this lobby from the Games Hub app.</string> <!-- KartGameScreen: Drivers currently seated in the LAN lobby. %1$s = comma-joined names --> <string name="lobby_drivers">In the lobby: <xliff:g id="names" example="You, Pixel 9">%1$s</xliff:g></string>- <!-- KartGameScreen: Pair code a joining phone must type, shown while it pairs. %1$s = six digits -->- <string name="lan_pairing_code">LAN pairing code: <xliff:g id="code" example="482916">%1$s</xliff:g> — type it on the joining phone</string>+ <!-- KartGameScreen: This lobby is broadcast openly on the LAN; anyone nearby can join, no code. Sentence -->+ <string name="lan_open_lobby">Open LAN game — anyone on this Wi-Fi can join from Games Hub. No code needed.</string> <!-- KartGameScreen: Seats taken in the lobby. %1$d = seat count, e.g. 2 --> <plurals name="lobby_seats"> <item quantity="one"><xliff:g id="count" example="1">%1$d</xliff:g> driver in the lobby</item>
games/kart/src/test/java/com/vayunmathur/games/kart/platform/KartHostAndNativeTest.kt
diff --git a/games/kart/src/test/java/com/vayunmathur/games/kart/platform/KartHostAndNativeTest.kt b/games/kart/src/test/java/com/vayunmathur/games/kart/platform/KartHostAndNativeTest.ktindex bfd78813c2..2cf87b79ed 100644--- a/games/kart/src/test/java/com/vayunmathur/games/kart/platform/KartHostAndNativeTest.kt+++ b/games/kart/src/test/java/com/vayunmathur/games/kart/platform/KartHostAndNativeTest.kt@@ -24,8 +24,6 @@ class KartHostAndNativeTest { assertTrue(host.lobby.value.slots.isEmpty()) assertTrue(host.inputs.value.isEmpty()) assertNull(host.host)- assertNull(host.pairingCode)- assertNull(host.pairingCodeFlow.value) host.start() // Idempotent: a second start is a no-op, not a second lobby. host.start()
games/kart/src/test/java/com/vayunmathur/games/kart/platform/KartViewModelTest.kt
diff --git a/games/kart/src/test/java/com/vayunmathur/games/kart/platform/KartViewModelTest.kt b/games/kart/src/test/java/com/vayunmathur/games/kart/platform/KartViewModelTest.ktindex e4a24f3475..1b3d02c8fa 100644--- a/games/kart/src/test/java/com/vayunmathur/games/kart/platform/KartViewModelTest.kt+++ b/games/kart/src/test/java/com/vayunmathur/games/kart/platform/KartViewModelTest.kt@@ -159,11 +159,12 @@ class KartViewModelTest { } } - @Test fun pairingCodeIsQuietUntilSomeoneJoins() {+ @Test fun lobbyStartsOpenWithNoPairingStep() { val vm = KartViewModel(app) await("cup loads") { vm.uiState.value.cup != null }- // Nobody is mid-handshake, so the lobby shows no code to type anywhere.- assertEquals(null, vm.pairingCode.value)+ // The LAN lobby is an open broadcast from the start: it is a Lobby+ // phase anyone nearby can join, with no code state anywhere.+ assertTrue(vm.racePhase.value is RacePhase.Lobby) } @Test fun secondViewModelSeesPersistedCupState() {
games/kart/src/test/java/com/vayunmathur/games/kart/ui/KartGameScreenTest.kt
diff --git a/games/kart/src/test/java/com/vayunmathur/games/kart/ui/KartGameScreenTest.kt b/games/kart/src/test/java/com/vayunmathur/games/kart/ui/KartGameScreenTest.ktindex 9645396733..80e51dff04 100644--- a/games/kart/src/test/java/com/vayunmathur/games/kart/ui/KartGameScreenTest.kt+++ b/games/kart/src/test/java/com/vayunmathur/games/kart/ui/KartGameScreenTest.kt@@ -69,7 +69,7 @@ class KartGameScreenTest { assertEquals(0, actions.backs) } - @Test fun lobbyShowsPairingCodeAndDriverNames() {+ @Test fun lobbyShowsOpenLanAndDriverNames() { val lobby = LobbyState( gameId = "kart", slots = listOf(@@ -82,24 +82,13 @@ class KartGameScreenTest { KartUiState(cup = CUPS[0], progress = KartProgress()), RacePhase.Lobby(lobby), KartGameActions.Noop,- pairingCode = "482916", ) }- rule.onNodeWithText(str(R.string.lan_pairing_code, "482916")).assertIsDisplayed()+ // Open broadcast, no pairing code anywhere to type.+ rule.onNodeWithText(str(R.string.lan_open_lobby)).assertIsDisplayed() rule.onNodeWithText(str(R.string.lobby_drivers, "You, Pixel 9")).assertIsDisplayed() } - @Test fun lobbyWithoutPairingHidesCodeRow() {- rule.setContent {- KartGameScreen(- KartUiState(cup = CUPS[0], progress = KartProgress()),- RacePhase.Lobby(LobbyState(gameId = "kart")),- KartGameActions.Noop,- )- }- rule.onNodeWithText(str(R.string.lan_pairing_code, "482916")).assertDoesNotExist()- }- @Test fun racingShowsLanDriverNames() { val phase = RacePhase.Racing( order = listOf("p1", "p2", "ai-0"),