Modern Apps git

← Modern-Apps.git

controller: add open LAN beacon and code-free join

Commit
c72ce947d78835065b7bd72408278a2f03eb762f
Author
Vayun Mathur <[email protected]>
When
2026-12-05 14:03 UTC (23 hours ago)
Parents
d82a5ff
Kart LAN play should work like a Minecraft LAN world: the host
broadcasts itself and anyone who can read the broadcast joins
unilaterally, with no pairing code and no host approval.

The broadcast mechanism is the _gamepad._tcp NSD record this SDK
already advertises and browses, chosen over a raw UDP beacon
because NSD already works phone-to-phone on one Wi-Fi network,
supplies the session endpoint (host and port) on resolve, and
needs no new socket, multicast lock or permission. The new
LanGameBeacon is the TXT side of that record: host display name,
game, seated and capacity counts, track/mode label and an open
flag, with a pure encode/decode round trip. Missing or garbage
TXT decodes closed, never open, so older coded hosts cannot be
mistaken for open ones. A LanBeaconTracker keeps the live list:
sightings refresh, and games whose beacons stop age out after a
TTL instead of sitting in the list forever; discovery prune
ticks while browsing so silent hosts expire too.

ControllerHost gains opt-in openJoin: after the sealed-secret
negotiation (the channel stays encrypted exactly as before) it
sends PAIR_REQUIRED(code=false) and PAIR_OK immediately, and
the next message is the JOIN. ControllerClient, when the tapped
host advertised openJoin, reads that PAIR_OK and lands in PAIRED
with no AWAITING_CODE stop and no persisted device key. Hosts
that never opt in run the existing six-digit flow unchanged,
and full or racing lobbies still refuse joins in admitPlayer.

Test-first: LanBeaconTest covers the TXT round trip, instance
name fallback, unusable endpoints, garbage numbers, full/closed
joinability and tracker expiry/refresh/forget;
ControllerOpenJoinTest covers an open host seating and feeding
input to a phone with no code anywhere, an open host refusing
while racing, and a coded host still stopping at the code.

Verified: :sdk:controller:testDebugUnitTest and
:sdk:controller:lint pass; the new LanBeacon.kt is
ktlint-clean (the module's other ktlint findings predate this
change and fail identically on origin/main).

Diff

sdk/controller/AGENTS.md
diff --git a/sdk/controller/AGENTS.md b/sdk/controller/AGENTS.mdindex e08740f62f..8ed0e34fac 100644--- a/sdk/controller/AGENTS.md+++ b/sdk/controller/AGENTS.md@@ -30,9 +30,10 @@ baked in so only `ControllerSocket` changes underneath. - com/vayunmathur/sdk/controller/ControllerSocket.kt — TCP socket, both ends - com/vayunmathur/sdk/controller/ControllerDiscovery.kt — mDNS browse (phone side) - com/vayunmathur/sdk/controller/ControllerAdvertiser.kt — mDNS register (TV side)-- com/vayunmathur/sdk/controller/ControllerHost.kt — N player slots, replay window, rate limit+- com/vayunmathur/sdk/controller/LanBeacon.kt — open-LAN beacon (TXT encode/decode) + last-seen expiry tracker+- com/vayunmathur/sdk/controller/ControllerHost.kt — N player slots, replay window, rate limit; `openJoin` hosts pair on connect with no code - com/vayunmathur/sdk/controller/ControllerInputGate.kt — per-player replay + rate-limit policy (JVM-testable)-- com/vayunmathur/sdk/controller/ControllerClient.kt — connect/pair/join/input emit+- com/vayunmathur/sdk/controller/ControllerClient.kt — connect/pair/join/input emit; open beacons skip the code state  ## Verify (this module only) ```
sdk/controller/src/main/java/com/vayunmathur/sdk/controller/ControllerAdvertiser.kt
diff --git a/sdk/controller/src/main/java/com/vayunmathur/sdk/controller/ControllerAdvertiser.kt b/sdk/controller/src/main/java/com/vayunmathur/sdk/controller/ControllerAdvertiser.ktindex 16928826d8..9b6fe23ff3 100644--- a/sdk/controller/src/main/java/com/vayunmathur/sdk/controller/ControllerAdvertiser.kt+++ b/sdk/controller/src/main/java/com/vayunmathur/sdk/controller/ControllerAdvertiser.kt@@ -75,14 +75,25 @@ class ControllerAdvertiser(context: Context) {     /**      * Advertise [friendlyName] on [port]. Safe to call repeatedly; re-advertising replaces the prior      * registration rather than stacking a second one.+     *+     * [beacon], when present, is the open-LAN broadcast: its TXT attributes+     * ride along so browsers see the game's name, how full the lobby is and+     * whether it takes unilateral joins. Calling again with a fresh beacon+     * (a driver joined, the race started) is how the broadcast stays true.      */-    fun advertise(friendlyName: String, deviceId: String, port: Int, gameId: String) {+    fun advertise(+        friendlyName: String,+        deviceId: String,+        port: Int,+        gameId: String,+        beacon: LanGameBeacon? = null,+    ) {         val manager = nsdManager ?: run {             Log.status(TAG, "NsdManager unavailable - this TV cannot announce itself")             return         }         unadvertise()-        register(manager, friendlyName, deviceId, port, gameId, attempt = 1)+        register(manager, friendlyName, deviceId, port, gameId, attempt = 1, beacon = beacon)     }      /**@@ -97,6 +108,7 @@ class ControllerAdvertiser(context: Context) {         port: Int,         gameId: String,         attempt: Int,+        beacon: LanGameBeacon? = null,     ) {         val issuedAt = generation         val instanceName = instanceLabel(friendlyName, attempt)@@ -108,6 +120,14 @@ class ControllerAdvertiser(context: Context) {             setAttribute(TXT_PROTOCOL_VERSION, ControllerContract.CONTROLLER_PROTOCOL_VERSION.toString())             setAttribute(TXT_ID, deviceId)             setAttribute(TXT_GAME_ID, gameId)+            // The open-LAN beacon rides the same record: browsers read the+            // lobby's fullness and joinability before connecting to anything.+            beacon?.let {+                setAttribute(LanGameBeacon.TXT_PLAYERS, it.playerCount.toString())+                setAttribute(LanGameBeacon.TXT_CAPACITY, it.capacity.toString())+                setAttribute(LanGameBeacon.TXT_TRACK, it.track)+                setAttribute(LanGameBeacon.TXT_OPEN, if (it.open) "1" else "0")+            }         }         val registration = object : NsdManager.RegistrationListener {             override fun onServiceRegistered(info: NsdServiceInfo) {@@ -134,7 +154,7 @@ class ControllerAdvertiser(context: Context) {                 }                 val next = instanceLabel(friendlyName, attempt + 1)                 Log.status(TAG, "registration failed: $errorCode for '$instanceName', retrying as '$next'")-                register(manager, friendlyName, deviceId, port, gameId, attempt + 1)+                register(manager, friendlyName, deviceId, port, gameId, attempt + 1, beacon = beacon)             }              override fun onServiceUnregistered(serviceInfo: NsdServiceInfo) = Unit
sdk/controller/src/main/java/com/vayunmathur/sdk/controller/ControllerClient.kt
diff --git a/sdk/controller/src/main/java/com/vayunmathur/sdk/controller/ControllerClient.kt b/sdk/controller/src/main/java/com/vayunmathur/sdk/controller/ControllerClient.ktindex 1b181a33ad..c18ce044cf 100644--- a/sdk/controller/src/main/java/com/vayunmathur/sdk/controller/ControllerClient.kt+++ b/sdk/controller/src/main/java/com/vayunmathur/sdk/controller/ControllerClient.kt@@ -132,6 +132,8 @@ class ControllerClient(     private var pendingTranscript: ControllerTranscript? = null     private var pendingHostId: String? = null     private var pendingWantsCode = false+    /** True when the tapped beacon advertised an open lobby: pair without any code. */+    private var pendingOpenJoin = false      private fun runHandshake(host: ControllerHostInfo) {         _state.value = ClientState.CONNECTING@@ -147,13 +149,27 @@ class ControllerClient(         val transcript = ControllerTranscript()         pendingTranscript = transcript         pendingHostId = host.id+        pendingOpenJoin = host.openJoin         val remembered = loadDeviceKey(host.id)         val keys = negotiateSecret(socket, transcript, remembered) ?: return         pendingKeys = keys-        if (!pendingWantsCode && remembered != null) {-            proveRemembered(socket, keys, transcript, remembered)+        when {+            // Open LAN beacon: the host pairs on connect, so the next frame+            // is PAIR_OK and there is never a code to type.+            pendingOpenJoin -> proveOpen(socket)+            !pendingWantsCode && remembered != null ->+                proveRemembered(socket, keys, transcript, remembered)+            else -> _state.value = ClientState.AWAITING_CODE+        }+    }++    /** Read the open host's immediate PAIR_OK. No proof is sent and no key is persisted. */+    private fun proveOpen(socket: ControllerSocket) {+        val answer = socket.receive() ?: return failed(socket)+        if (answer.message is ControllerPairOk) {+            _state.value = ClientState.PAIRED         } else {-            _state.value = ClientState.AWAITING_CODE+            failed(socket)         }     } 
sdk/controller/src/main/java/com/vayunmathur/sdk/controller/ControllerDiscovery.kt
diff --git a/sdk/controller/src/main/java/com/vayunmathur/sdk/controller/ControllerDiscovery.kt b/sdk/controller/src/main/java/com/vayunmathur/sdk/controller/ControllerDiscovery.ktindex a064d5abe7..3324b7d0de 100644--- a/sdk/controller/src/main/java/com/vayunmathur/sdk/controller/ControllerDiscovery.kt+++ b/sdk/controller/src/main/java/com/vayunmathur/sdk/controller/ControllerDiscovery.kt@@ -11,20 +11,15 @@ import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.callbackFlow import kotlinx.coroutines.flow.update+import kotlinx.coroutines.launch  private const val TAG = "ControllerDiscovery" -/** Friendly name, e.g. "Living Room TV". */-private const val TXT_FRIENDLY_NAME = "fn"--/** The protocol version the host speaks. */+/** The protocol version the host speaks. The remaining TXT keys live on [LanGameBeacon]. */ private const val TXT_PROTOCOL_VERSION = "pv" -/** The host's own stable id. Stable across renames, unlike the instance name. */-private const val TXT_ID = "id"--/** The game this lobby is for, e.g. "kart" - informational, so a phone can label what it found. */-private const val TXT_GAME_ID = "gameId"+/** How often the browse prunes games whose beacons have stopped. */+private const val PRUNE_INTERVAL_MS = 5_000L  /** One TV hosting a controller lobby, as resolved from mDNS. */ data class ControllerHostInfo(@@ -35,7 +30,36 @@ data class ControllerHostInfo(     val port: Int,     val protocolVersion: Int,     val gameId: String,-)+    /** Drivers already seated, from the host's beacon. 0 when the host does not broadcast it. */+    val playerCount: Int = 0,+    /** Seats the host offers, from the host's beacon. 0 when the host does not broadcast it. */+    val capacity: Int = 0,+    /** Track/mode being played, from the host's beacon, when the game labels it. */+    val track: String = "",+    /**+     * True when this host takes unilateral joins: tapping it connects and+     * seats the phone with no pairing code and no host approval. Only hosts+     * that broadcast `open = 1` (open LAN games) set it; coded hosts keep+     * the pairing flow.+     */+    val openJoin: Boolean = false,+) {+    /** True when every seat is taken. An unknown capacity (0) is never "full". */+    val isFull: Boolean get() = capacity > 0 && playerCount >= capacity++    /** This host as the [LanGameBeacon] its advertisement decodes to. */+    fun toBeacon(): LanGameBeacon = LanGameBeacon(+        hostId = id,+        hostName = friendlyName,+        gameId = gameId,+        hostAddress = host,+        port = port,+        playerCount = playerCount,+        capacity = capacity,+        track = track,+        open = openJoin,+    )+}  /**  * mDNS discovery of controller hosts on the LAN.@@ -57,6 +81,22 @@ class ControllerDiscovery(context: Context) {     private val _hosts = MutableStateFlow<List<ControllerHostInfo>>(emptyList())     val hosts: StateFlow<List<ControllerHostInfo>> = _hosts.asStateFlow() +    /**+     * Last-seen bookkeeping behind [hosts]. NSD's service-lost only fires+     * for a clean unregistration; a host that leaves Wi-Fi range just goes+     * silent, so sightings feed the tracker and a prune tick drops games+     * whose beacons stopped (see [LanBeaconTracker]).+     */+    private val tracker = LanBeaconTracker()++    private fun nowMs(): Long = android.os.SystemClock.uptimeMillis()++    /** Drop hosts the tracker has aged out. Called on the browse's prune tick. */+    private fun pruneExpired() {+        val liveIds = tracker.live(nowMs()).map { it.hostId }.toSet()+        _hosts.update { hosts -> hosts.filter { it.id in liveIds } }+    }+     /** True when the platform refused the browse, not when the network is simply empty. */     private val _localNetworkBlocked = MutableStateFlow(false)     val localNetworkBlocked: StateFlow<Boolean> = _localNetworkBlocked.asStateFlow()@@ -87,6 +127,7 @@ class ControllerDiscovery(context: Context) {                          override fun onServiceResolved(info: NsdServiceInfo) {                             val host = toHostInfo(info) ?: return+                            tracker.observe(host.toBeacon(), nowMs())                             trySend(host)                             // update, not value =: resolve callbacks arrive on several threads                             // and a read-modify-write would drop hosts found at once.@@ -104,6 +145,8 @@ class ControllerDiscovery(context: Context) {                 // Only the instance name is available here, so match on it rather than on the                 // UUID; the two are one-to-one for the lifetime of a registration.                 val name = service.serviceName ?: return+                val lostIds = _hosts.value.filter { it.instanceName == name }.map { it.id }+                lostIds.forEach { tracker.forget(it) }                 _hosts.update { hosts -> hosts.filterNot { it.instanceName == name } }             } @@ -144,6 +187,15 @@ class ControllerDiscovery(context: Context) {             close(e)             return@callbackFlow         }+        // Games whose beacons stopped age out even when nothing else happens+        // on the browse: without this tick a dead host would only be pruned+        // when the next unrelated sighting arrived.+        launch {+            while (true) {+                kotlinx.coroutines.delay(PRUNE_INTERVAL_MS)+                pruneExpired()+            }+        }         awaitClose {             try {                 discoveryListener?.let { manager.stopServiceDiscovery(it) }@@ -155,6 +207,7 @@ class ControllerDiscovery(context: Context) {     }      fun clear() {+        tracker.clear()         _hosts.value = emptyList()     } @@ -174,14 +227,29 @@ class ControllerDiscovery(context: Context) {         val host = info.host?.hostAddress ?: return null         val instance = info.serviceName ?: return null         val port = info.port.takeIf { it > 0 } ?: return null+        val beacon = LanGameBeacon.fromTxtAttributes(+            attributes = LanGameBeacon.run {+                listOf(+                    TXT_FRIENDLY_NAME, TXT_PROTOCOL_VERSION, TXT_ID, TXT_GAME_ID,+                    TXT_PLAYERS, TXT_CAPACITY, TXT_TRACK, TXT_OPEN,+                ).associateWith { textAttribute(info, it) }+            },+            hostAddress = host,+            port = port,+            instanceName = instance,+        ) ?: return null         return ControllerHostInfo(-            id = textAttribute(info, TXT_ID) ?: instance,+            id = beacon.hostId,             instanceName = instance,-            friendlyName = textAttribute(info, TXT_FRIENDLY_NAME) ?: instance,+            friendlyName = beacon.hostName,             host = host,             port = port,             protocolVersion = textAttribute(info, TXT_PROTOCOL_VERSION)?.toIntOrNull() ?: 0,-            gameId = textAttribute(info, TXT_GAME_ID).orEmpty(),+            gameId = beacon.gameId,+            playerCount = beacon.playerCount,+            capacity = beacon.capacity,+            track = beacon.track,+            openJoin = beacon.open,         )     } 
sdk/controller/src/main/java/com/vayunmathur/sdk/controller/ControllerHost.kt
diff --git a/sdk/controller/src/main/java/com/vayunmathur/sdk/controller/ControllerHost.kt b/sdk/controller/src/main/java/com/vayunmathur/sdk/controller/ControllerHost.ktindex 52d10be8ba..56becfb39c 100644--- a/sdk/controller/src/main/java/com/vayunmathur/sdk/controller/ControllerHost.kt+++ b/sdk/controller/src/main/java/com/vayunmathur/sdk/controller/ControllerHost.kt@@ -57,6 +57,14 @@ class ControllerHost(     private val unsealSecret: (sealed: ByteArray) -> ByteArray?,     private val loadDeviceKey: (senderId: String) -> ByteArray?,     private val saveDeviceKey: (senderId: String, key: ByteArray) -> Unit,+    /**+     * True for an open LAN lobby: any phone that connects is paired+     * immediately — no code on screen, no proof, no approval step. The+     * session secret is still sealed and the channel still encrypted; only+     * the human ritual is gone. Full and racing lobbies still refuse joins+     * in [admitPlayer]. Defaults to the coded flow every existing host uses.+     */+    private val openJoin: Boolean = false, ) {      private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)@@ -217,6 +225,18 @@ class ControllerHost(         keys: ControllerKeys,         transcript: ControllerTranscript,     ) {+        if (openJoin) {+            // Open LAN: tell the phone no code is coming, then pair it on the+            // spot. The phone's next message is its JOIN — see runJoined.+            if (socket.send(ControllerPairRequired(code = false)) == null ||+                socket.send(ControllerPairOk(deviceKey = null)) == null+            ) {+                socket.close()+                return+            }+            runJoined(socket, hello, keys, deviceKey = null)+            return+        }         val remembered = loadDeviceKey(hello.senderId)         var wantsCode = remembered == null || !hello.paired         val gate = ControllerPairingGate()
sdk/controller/src/main/java/com/vayunmathur/sdk/controller/LanBeacon.kt
diff --git a/sdk/controller/src/main/java/com/vayunmathur/sdk/controller/LanBeacon.kt b/sdk/controller/src/main/java/com/vayunmathur/sdk/controller/LanBeacon.ktnew file mode 100644index 0000000000..486c6a5f6f--- /dev/null+++ b/sdk/controller/src/main/java/com/vayunmathur/sdk/controller/LanBeacon.kt@@ -0,0 +1,171 @@+package com.vayunmathur.sdk.controller++/**+ * One open LAN game, as broadcast on the local network.+ *+ * This is the whole join contract: anyone who can read the broadcast can+ * join, with no pairing code and no host approval (the Minecraft LAN shape).+ * It carries only what a joiner needs to decide and connect — who is+ * hosting, which game, where the session endpoint is, how full the lobby+ * is, and what is being played. Nothing secret ever goes in a beacon: the+ * broadcast is readable by the whole LAN by design.+ *+ * On the wire the beacon is the TXT record of the `_gamepad._tcp` NSD+ * service the codebase already advertises ([ControllerAdvertiser]) and+ * browses ([ControllerDiscovery]): NSD supplies the endpoint (host + port)+ * on resolve, the TXT attributes below supply the rest. Encoding and+ * decoding are pure so the round trip is a plain JVM test.+ */+data class LanGameBeacon(+    /** The host's stable id (TXT `id`), so re-announcements replace, never duplicate. */+    val hostId: String,+    /** The host's display name (TXT `fn`), e.g. the phone model or a chosen lobby name. */+    val hostName: String,+    /** Which game this lobby is for (TXT `gameId`), e.g. "kart". */+    val gameId: String,+    /** The session endpoint's address, from the NSD resolve. Never in TXT. */+    val hostAddress: String,+    /** The session endpoint's port, from the NSD resolve. Never in TXT. */+    val port: Int,+    /** Drivers already seated (TXT `players`). */+    val playerCount: Int,+    /** Seats the host offers (TXT `capacity`); [ControllerContract.MAX_PLAYERS] unless a game caps lower. */+    val capacity: Int,+    /** Track/mode being played (TXT `track`), when the game has a cheap label for it. */+    val track: String,+    /**+     * True while the lobby takes unilateral joins (TXT `open`). A full or+     * racing lobby broadcasts `open = false`, so it stops looking joinable+     * instead of accepting taps it would refuse.+     */+    val open: Boolean,+) {+    /** True when every seat is taken. An unknown capacity (0) is never "full". */+    val isFull: Boolean get() = capacity > 0 && playerCount >= capacity++    /** True when tapping this beacon should connect straight into the lobby. */+    val joinable: Boolean get() = open && !isFull++    /**+     * The TXT attributes for this beacon. The endpoint is absent on purpose:+     * NSD carries host and port in the service record itself, and an IP in+     * TXT would go stale the moment the host's address changed.+     */+    fun toTxtAttributes(): Map<String, String> =+        mapOf(+            TXT_FRIENDLY_NAME to hostName,+            TXT_PROTOCOL_VERSION to ControllerContract.CONTROLLER_PROTOCOL_VERSION.toString(),+            TXT_ID to hostId,+            TXT_GAME_ID to gameId,+            TXT_PLAYERS to playerCount.toString(),+            TXT_CAPACITY to capacity.toString(),+            TXT_TRACK to track,+            TXT_OPEN to if (open) "1" else "0",+        )++    companion object {+        const val TXT_FRIENDLY_NAME = "fn"+        const val TXT_PROTOCOL_VERSION = "pv"+        const val TXT_ID = "id"+        const val TXT_GAME_ID = "gameId"+        const val TXT_PLAYERS = "players"+        const val TXT_CAPACITY = "capacity"+        const val TXT_TRACK = "track"+        const val TXT_OPEN = "open"++        /**+         * Decode a beacon from TXT [attributes] plus the NSD-resolved+         * endpoint. Returns null when the endpoint is unusable — there is+         * no sensible default port for an ephemeral session socket.+         *+         * Missing or garbage TXT degrades to closed-with-unknown-counts,+         * never to open: a host opts into unilateral joins explicitly, so+         * older coded hosts (which publish none of the new keys) can never+         * be mistaken for open ones.+         */+        fun fromTxtAttributes(+            attributes: Map<String, String?>,+            hostAddress: String,+            port: Int,+            instanceName: String,+        ): LanGameBeacon? {+            if (hostAddress.isBlank() || port <= 0) return null++            fun text(key: String): String? = attributes[key]?.takeIf { it.isNotBlank() }++            fun count(key: String): Int = text(key)?.toIntOrNull()?.coerceAtLeast(0) ?: 0+            return LanGameBeacon(+                hostId = text(TXT_ID) ?: instanceName,+                hostName = text(TXT_FRIENDLY_NAME) ?: instanceName,+                gameId = text(TXT_GAME_ID).orEmpty(),+                hostAddress = hostAddress,+                port = port,+                playerCount = count(TXT_PLAYERS),+                capacity = count(TXT_CAPACITY),+                track = text(TXT_TRACK).orEmpty(),+                open = text(TXT_OPEN) == "1",+            )+        }+    }+}++/**+ * The live list of open LAN games: beacons as they arrive, pruned when they+ * stop.+ *+ * NSD reports a service lost when its registration goes away cleanly, but a+ * host that walks out of Wi-Fi range or dies mid-lobby never unregisters —+ * its last beacon would otherwise sit in the list forever. Every game here+ * therefore carries the time it was last seen, and [live] only returns+ * games seen within [ttlMs]. The host re-announces through NSD for the+ * whole time its lobby is open, so a healthy game never ages out.+ *+ * Pure and clock-injected, so expiry is a plain JVM test. Thread-safe: NSD+ * resolve callbacks and the UI's prune tick do not share a thread.+ */+class LanBeaconTracker(+    private val ttlMs: Long = DEFAULT_TTL_MS,+) {+    private data class Seen(+        val beacon: LanGameBeacon,+        val lastSeenMs: Long,+    )++    private val seen = mutableMapOf<String, Seen>()++    /** Record one beacon sighting. A repeat sighting replaces and refreshes. */+    @Synchronized+    fun observe(beacon: LanGameBeacon, nowMs: Long) {+        seen[beacon.hostId] = Seen(beacon, nowMs)+    }++    /** Games seen within the TTL, freshest last-seen order stable by host name. */+    @Synchronized+    fun live(nowMs: Long): List<LanGameBeacon> {+        val iterator = seen.entries.iterator()+        while (iterator.hasNext()) {+            if (nowMs - iterator.next().value.lastSeenMs > ttlMs) iterator.remove()+        }+        return seen.values.map { it.beacon }.sortedBy { it.hostName }+    }++    /** Drop one host now (its service-lost callback arrived). */+    @Synchronized+    fun forget(hostId: String) {+        seen.remove(hostId)+    }++    @Synchronized+    fun clear() {+        seen.clear()+    }++    companion object {+        /**+         * How long a game stays listed after its last beacon. NSD+         * re-announces a live registration continuously, so fifteen seconds+         * of silence means the host left, not that it is quiet.+         */+        const val DEFAULT_TTL_MS = 15_000L+    }+}
sdk/controller/src/test/java/com/vayunmathur/sdk/controller/ControllerOpenJoinTest.kt
diff --git a/sdk/controller/src/test/java/com/vayunmathur/sdk/controller/ControllerOpenJoinTest.kt b/sdk/controller/src/test/java/com/vayunmathur/sdk/controller/ControllerOpenJoinTest.ktnew file mode 100644index 0000000000..dd25e87fec--- /dev/null+++ b/sdk/controller/src/test/java/com/vayunmathur/sdk/controller/ControllerOpenJoinTest.kt@@ -0,0 +1,138 @@+package com.vayunmathur.sdk.controller++import androidx.test.ext.junit.runners.AndroidJUnit4+import java.net.InetAddress+import java.net.ServerSocket+import kotlin.test.Test+import kotlin.test.assertNull+import kotlin.test.assertTrue+import org.junit.runner.RunWith++/**+ * The open LAN flow: a host that broadcasts itself as open takes a seat for+ * any phone that connects — no pairing code, no host approval — while a host+ * that did not opt in still runs the code flow.+ */+@RunWith(AndroidJUnit4::class)+class ControllerOpenJoinTest {++    private fun await(desc: String, timeoutMs: Long = 15_000, condition: () -> Boolean) {+        val deadline = System.currentTimeMillis() + timeoutMs+        while (System.currentTimeMillis() < deadline) {+            if (condition()) return+            Thread.sleep(10)+        }+        throw AssertionError("timed out waiting for: $desc")+    }++    private class Harness(openJoin: Boolean) {+        val host = ControllerHost(+            gameId = "kart",+            hostId = "tv-open",+            hostName = "Open TV",+            providePublicBundle = { byteArrayOf(9, 8, 7) },+            unsealSecret = { sealed -> sealed },+            loadDeviceKey = { null },+            saveDeviceKey = { _, _ -> },+            openJoin = openJoin,+        )+        private val server = ServerSocket(0, 8, InetAddress.getByName("127.0.0.1"))+        val port: Int = server.localPort+        @Volatile var running = true+        private val thread = Thread {+            while (running) {+                try {+                    val accepted = server.accept()+                    val socket = ControllerSocket()+                    socket.attach(accepted)+                    host.accept(socket)+                } catch (_: Exception) {+                    if (running) throw AssertionError("accept failed")+                }+            }+        }.apply { isDaemon = true; start() }++        fun hostInfo(openJoin: Boolean): ControllerHostInfo = ControllerHostInfo(+            id = "tv-open", instanceName = "Open TV (Game Host)", friendlyName = "Open TV",+            host = "127.0.0.1", port = port,+            protocolVersion = ControllerContract.CONTROLLER_PROTOCOL_VERSION, gameId = "kart",+            openJoin = openJoin,+        )++        fun close() {+            running = false+            runCatching { server.close() }+            host.close()+        }+    }++    private fun newClient(id: String): ControllerClient = ControllerClient(+        senderId = id,+        senderName = "Phone $id",+        sealToBundle = { _, secret -> secret },+        loadDeviceKey = { null },+        saveDeviceKey = { _, _ -> },+    )++    @Test+    fun openHostJoinsWithoutAnyCode() {+        val harness = Harness(openJoin = true)+        val client = newClient("phone-open")+        try {+            client.connect(harness.hostInfo(openJoin = true))+            // Straight to PAIRED: no AWAITING_CODE stop, nothing on the host screen.+            await("paired without code") { client.state.value == ClientState.PAIRED }+            assertNull(harness.host.pairingCode)++            client.join("Racer")+            await("joined") { client.state.value == ClientState.JOINED }+            await("host seated phone") {+                harness.host.lobby.value.slots.any { it.playerId == "phone-open" }+            }+            client.sendInput(buttons = ControllerButton.A.bit)+            await("host input") { harness.host.inputs.value.containsKey("phone-open") }++            client.leave()+            await("idle after leave") { client.state.value == ClientState.IDLE }+            await("host freed seat") {+                harness.host.lobby.value.slots.none { it.playerId == "phone-open" }+            }+        } finally {+            client.close()+            harness.close()+        }+    }++    @Test+    fun openHostStillRefusesJoinsWhileRacing() {+        val harness = Harness(openJoin = true)+        val client = newClient("phone-late")+        try {+            harness.host.startRace()+            client.connect(harness.hostInfo(openJoin = true))+            await("paired without code") { client.state.value == ClientState.PAIRED }+            client.join("Late")+            await("join refused") { client.state.value == ClientState.IDLE }+            assertTrue(harness.host.lobby.value.slots.none { it.playerId == "phone-late" })+        } finally {+            client.close()+            harness.close()+        }+    }++    @Test+    fun codedHostStillStopsAtTheCodeForAnOpenSeekingClient() {+        // The generic pad flow is untouched: a host that never opted into open+        // play still puts a code on screen and waits for it.+        val harness = Harness(openJoin = false)+        val client = newClient("phone-coded")+        try {+            client.connect(harness.hostInfo(openJoin = false))+            await("awaiting code") { client.state.value == ClientState.AWAITING_CODE }+            assertTrue(ControllerPairCode.isWellFormed(harness.host.pairingCode ?: ""))+        } finally {+            client.close()+            harness.close()+        }+    }+}
sdk/controller/src/test/java/com/vayunmathur/sdk/controller/LanBeaconTest.kt
diff --git a/sdk/controller/src/test/java/com/vayunmathur/sdk/controller/LanBeaconTest.kt b/sdk/controller/src/test/java/com/vayunmathur/sdk/controller/LanBeaconTest.ktnew file mode 100644index 0000000000..ed8170ef4e--- /dev/null+++ b/sdk/controller/src/test/java/com/vayunmathur/sdk/controller/LanBeaconTest.kt@@ -0,0 +1,128 @@+package com.vayunmathur.sdk.controller++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue++class LanBeaconTest {++    private fun beacon(+        playerCount: Int = 2,+        capacity: Int = 8,+        open: Boolean = true,+    ) = LanGameBeacon(+        hostId = "host-1",+        hostName = "Pixel 9",+        gameId = "kart",+        hostAddress = "192.168.1.20",+        port = 4321,+        playerCount = playerCount,+        capacity = capacity,+        track = "Sunset Oval",+        open = open,+    )++    @Test+    fun txtRoundTripCarriesEverythingNeededToJoin() {+        val original = beacon()+        val decoded = LanGameBeacon.fromTxtAttributes(+            attributes = original.toTxtAttributes(),+            hostAddress = "192.168.1.20",+            port = 4321,+            instanceName = "Pixel 9 (Game Host)",+        )+        assertEquals(original, decoded)+    }++    @Test+    fun decodeFallsBackToInstanceNameAndClosedWhenTxtMissing() {+        val decoded = LanGameBeacon.fromTxtAttributes(+            attributes = emptyMap(),+            hostAddress = "192.168.1.21",+            port = 5000,+            instanceName = "Bare (Game Host)",+        )+        val beacon = assertNotNull(decoded)+        assertEquals("Bare (Game Host)", beacon.hostId)+        assertEquals("Bare (Game Host)", beacon.hostName)+        assertEquals("", beacon.gameId)+        assertEquals(0, beacon.playerCount)+        assertEquals(0, beacon.capacity)+        assertEquals("", beacon.track)+        // A record that does not say it is open is not joinable: open is opt-in+        // on the wire so older coded hosts never look tappable by accident.+        assertFalse(beacon.open)+        assertFalse(beacon.joinable)+    }++    @Test+    fun decodeRejectsRecordsWithoutUsableEndpoint() {+        val attrs = beacon().toTxtAttributes()+        assertNull(+            LanGameBeacon.fromTxtAttributes(attrs, hostAddress = "", port = 4321, instanceName = "X"),+        )+        assertNull(+            LanGameBeacon.fromTxtAttributes(attrs, hostAddress = "192.168.1.20", port = 0, instanceName = "X"),+        )+    }++    @Test+    fun decodeToleratesGarbageNumbers() {+        val attrs = beacon().toTxtAttributes() + mapOf(+            LanGameBeacon.TXT_PLAYERS to "banana",+            LanGameBeacon.TXT_CAPACITY to "-3",+        )+        val decoded = assertNotNull(+            LanGameBeacon.fromTxtAttributes(attrs, "192.168.1.20", 4321, "Pixel 9 (Game Host)"),+        )+        assertEquals(0, decoded.playerCount)+        assertEquals(0, decoded.capacity)+    }++    @Test+    fun fullAndClosedGamesAreNotJoinable() {+        assertTrue(beacon(playerCount = 2).joinable)+        assertFalse(beacon(playerCount = 8, capacity = 8).joinable)+        assertTrue(beacon(playerCount = 8, capacity = 8).isFull)+        assertFalse(beacon(open = false).joinable)+        assertFalse(beacon(open = false).isFull)+    }++    // ---- Discovery expiry ----++    @Test+    fun trackerExpiresGamesWhoseBeaconsStop() {+        val tracker = LanBeaconTracker(ttlMs = 15_000L)+        tracker.observe(beacon(), nowMs = 1_000L)+        assertEquals(1, tracker.live(nowMs = 1_000L).size)+        assertEquals(1, tracker.live(nowMs = 15_999L).size)+        // Silent past the TTL: the game is gone from the list, not greyed out.+        assertTrue(tracker.live(nowMs = 16_001L).isEmpty())+    }++    @Test+    fun trackerReobservationRefreshesAndReplaces() {+        val tracker = LanBeaconTracker(ttlMs = 15_000L)+        tracker.observe(beacon(playerCount = 1), nowMs = 0L)+        tracker.observe(beacon(playerCount = 5), nowMs = 10_000L)+        val live = tracker.live(nowMs = 24_999L)+        assertEquals(1, live.size)+        assertEquals(5, live.single().playerCount)+        assertTrue(tracker.live(nowMs = 25_001L).isEmpty())+    }++    @Test+    fun trackerKeepsHostsSeparateAndForgetRemovesOne() {+        val tracker = LanBeaconTracker(ttlMs = 15_000L)+        tracker.observe(beacon(), nowMs = 0L)+        tracker.observe(beacon().copy(hostId = "host-2", hostName = "Pixel 8"), nowMs = 0L)+        assertEquals(listOf("host-1", "host-2"), tracker.live(nowMs = 0L).map { it.hostId }.sorted())+        tracker.forget("host-1")+        assertEquals(listOf("host-2"), tracker.live(nowMs = 0L).map { it.hostId })+        tracker.clear()+        assertTrue(tracker.live(nowMs = 0L).isEmpty())+    }+}