findfamily: auto-decline Find Nearby on phones without UWB (#869)
- Commit
6aee53e6d9f67b18720e82ec2ac4ff323d334a50- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-12 17:34 UTC (23 days ago)
- Parents
09e28da
Request (GitHub #869): the Find Nearby (UWB) button is already hidden on
phones that can't range, but such a phone still receives other people's
requests. It posts the "Someone is finding you" notification and never
answers, so the requesting phone sits on "Waiting for the other device"
until its 60 s timeout. The requester should be told straight away.
Cause: the requester already handles a CANCEL reply to its REQUEST, but
the receiving side never sends one. handleUwbEnvelopes() forwarded
every REQUEST to UwbInbox and posted the notification whether or not
UwbSessionManager.isAvailable() (Android 16 ranging API + FEATURE_UWB)
was true. On older Android the session manager isn't even initialised,
so nothing ever replied; on an Android 16 phone without a radio the
auto-accept path tried to open the controlee, failed, and went back to
Idle without telling the peer.
Changes:
- UwbEnvelope gains an optional `reason` field, plus UwbCancelReason
with UNSUPPORTED = "unsupported". Backward compatible both ways:
null is a plain cancel, defaults aren't encoded so a plain cancel is
byte-identical to what older builds send, and older Android
(ignoreUnknownKeys) and iOS (JSONDecoder) peers ignore the key and
see the plain cancel they already handle.
- LocationTrackingInbound.handleUwbEnvelopes(): when this phone can't
do Find Nearby, a REQUEST is answered at once with CANCEL +
reason=unsupported and is neither forwarded to UwbInbox nor
notified. The reply is published on serviceScope, since this runs on
the live socket's reader coroutine. The availability check and the
sender are default parameters so tests can drive both branches.
- UwbSessionManager: new terminal state PeerUnsupported. Both CANCEL
handlers (the inbox collector and the initiator's ACK wait) now go
through one synchronized endOnPeerCancel(), keyed on the current
session id, because both see the same envelope and used to race.
stateAfterPeerCancel() maps reason=unsupported to PeerUnsupported;
no reason or an unknown one stays the old behaviour (back to Idle).
The terminal state keeps the peer id so closing the screen still
calls stop() and resets the manager for the next find or incoming
request.
- UwbRangingScreen renders PeerUnsupported with the new string
uwb_status_peer_unsupported, "Their phone doesn't support Find
Nearby." (English only; other locales fall back until Weblate).
User-visible effect: asking someone whose phone has no UWB (or runs
Android 15 or older) to Find Nearby now shows "Their phone doesn't
support Find Nearby." within a round trip instead of a 60 s wait, and
that person no longer gets a notification they can't act on. A plain
stop by the peer and a real timeout behave as before.
Verification: new and updated unit tests.
- LocationTrackingInboundTest: an unsupported receiver (default gate on
the SDK 34 Robolectric sandbox, even with FEATURE_UWB set) replies
CANCEL with reason=unsupported and the request's session id to the
sender, posts no notification and caches nothing in UwbInbox; a
supported receiver still notifies and sends nothing. The existing
REQUEST-notification test now passes uwbAvailable = true.
- UwbPeerDeclineTest: reason=unsupported maps to PeerUnsupported, no
reason or an unknown reason maps to Idle; PeerUnsupported renders the
new message and Failed("Peer did not respond") still renders the old
one.
- W5UwbEnvelopeTest: CANCEL round-trips with the reason; a plain
cancel omits the key on the wire; an old-format cancel decodes with
reason null; a pre-#869 envelope class decodes a cancel that carries
a reason.
- :findfamily compileDevKotlin, testDevUnitTest, lint and detekt in
the build container.Diff
findfamily/src/main/java/com/vayunmathur/findfamily/ui/UwbRangingScreen.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/ui/UwbRangingScreen.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/ui/UwbRangingScreen.ktindex 8a4effbb91..42065fa37b 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/ui/UwbRangingScreen.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/ui/UwbRangingScreen.kt@@ -160,6 +160,10 @@ fun UwbRangingContent( sub = s.reason, progress = false )+ UwbSessionManager.UwbSessionState.PeerUnsupported -> StatusBlock(+ main = stringResource(R.string.uwb_status_peer_unsupported),+ progress = false+ ) is UwbSessionManager.UwbSessionState.Failed -> StatusBlock( main = stringResource(R.string.uwb_status_failed), sub = s.reason,
findfamily/src/main/java/com/vayunmathur/findfamily/util/LocationTrackingInbound.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/util/LocationTrackingInbound.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/util/LocationTrackingInbound.ktindex fa5be86f2e..52b8002350 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/util/LocationTrackingInbound.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/util/LocationTrackingInbound.kt@@ -10,6 +10,7 @@ import com.vayunmathur.findfamily.data.havershine import com.vayunmathur.findfamily.data.RequestStatus import com.vayunmathur.findfamily.domain.NoShowPolicy import com.vayunmathur.findfamily.domain.PairAuth+import com.vayunmathur.findfamily.uwb.UwbCancelReason import com.vayunmathur.findfamily.uwb.UwbEnvelope import com.vayunmathur.findfamily.uwb.UwbEnvelopeKind import com.vayunmathur.findfamily.uwb.UwbInbox@@ -39,6 +40,12 @@ private const val LOW_BATTERY_THRESHOLD = 15f /** Assumed battery when no prior fix exists to compare against. */ private const val FULL_BATTERY = 100f +private const val TAG_UWB = "FF-Uwb"++/** Sends one UWB envelope to a peer; shaped like [Networking.publishUwbMessage] so tests can swap it. */+internal typealias UwbEnvelopeSender =+ suspend (envelope: UwbEnvelope, recipientUserId: Long, recipient: User?) -> Boolean+ /** * Authenticated entry point for every inbound fix carrying a claimed sender. *@@ -350,13 +357,23 @@ private fun LocationTrackingService.maybeNotifyEntryExit( * Powered-off recovery grants ride the same channel (see [UwbEnvelopeKind.POF_GRANT]) and are * handled here instead, deliberately without reaching [UwbInbox]: they are not ranging * traffic and have no business waking the Find Nearby screen.+ *+ * On a phone that can't do Find Nearby ([uwbAvailable] false: below Android 16 or no UWB+ * radio) a REQUEST is declined on the spot instead (#869): see [declineUnsupportedUwbRequest].+ * [sendUwb] is the reply path, swappable for tests. */-internal suspend fun LocationTrackingService.handleUwbEnvelopes(list: List<UwbEnvelope>) {+internal suspend fun LocationTrackingService.handleUwbEnvelopes(+ list: List<UwbEnvelope>,+ uwbAvailable: Boolean = UwbSessionManager.isAvailable(this),+ sendUwb: UwbEnvelopeSender = Networking::publishUwbMessage,+) { if (list.isEmpty()) return val users = repository.getAllUsers() for (envelope in list) {- when (envelope.kind) {- UwbEnvelopeKind.POF_GRANT -> acceptPoweredOffGrant(envelope)+ when {+ envelope.kind == UwbEnvelopeKind.POF_GRANT -> acceptPoweredOffGrant(envelope)+ envelope.kind == UwbEnvelopeKind.REQUEST && !uwbAvailable ->+ declineUnsupportedUwbRequest(envelope, users, sendUwb) else -> { UwbInbox.tryEmit(envelope) if (envelope.kind == UwbEnvelopeKind.REQUEST) {@@ -370,6 +387,47 @@ internal suspend fun LocationTrackingService.handleUwbEnvelopes(list: List<UwbEn } } +/**+ * Answer a Find Nearby REQUEST this phone can never serve with an immediate CANCEL carrying+ * [UwbCancelReason.UNSUPPORTED], so the requester shows "their phone doesn't support it"+ * instead of waiting out its 60 s timeout.+ *+ * The request is not forwarded to [UwbInbox] and posts no notification: tapping it could only+ * open a screen that fails, and on an Android 16 phone without a radio the inbox would also+ * start the auto-accept path in [UwbSessionManager], which fails silently. The reply goes out+ * on [LocationTrackingService.serviceScope] because publishing is a network round trip and+ * this runs on the live socket's reader coroutine.+ *+ * Broad catch is deliberate, same as `UwbSessionManager.publish`: the reply crosses Room and+ * the relay socket, and a failed courtesy reply must not take the scope down with it.+ */+@Suppress("TooGenericExceptionCaught")+private fun LocationTrackingService.declineUnsupportedUwbRequest(+ request: UwbEnvelope,+ users: List<User>,+ sendUwb: UwbEnvelopeSender,+) {+ val senderId = request.sender.toLong()+ if (senderId == Networking.userid) return+ val decline = UwbEnvelope(+ sessionId = request.sessionId,+ sender = Networking.userid.toULong(),+ senderPlatform = "android",+ kind = UwbEnvelopeKind.CANCEL,+ reason = UwbCancelReason.UNSUPPORTED,+ )+ val peer = users.firstOrNull { it.id == senderId }+ serviceScope.launch {+ val sent = try {+ sendUwb(decline, senderId, peer)+ } catch (e: Exception) {+ Log.status(TAG_UWB, "decline reply to ${senderId.toULong()} threw", e)+ false+ }+ Log.status(TAG_UWB, "declined Find Nearby request from ${senderId.toULong()} (no UWB here), sent=$sent")+ }+}+ /** * Store a family member's powered-off keys so this device can go and find their lost phone. *
findfamily/src/main/java/com/vayunmathur/findfamily/util/UwbSessionManager.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/util/UwbSessionManager.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/util/UwbSessionManager.ktindex de5b3badeb..76170043d5 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/util/UwbSessionManager.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/util/UwbSessionManager.kt@@ -19,6 +19,7 @@ import com.vayunmathur.findfamily.tracker.TrackerUwbGatt import com.vayunmathur.findfamily.uwb.RangingSample import com.vayunmathur.findfamily.uwb.UwbAccessoryProtocol import com.vayunmathur.findfamily.uwb.UwbBytes+import com.vayunmathur.findfamily.uwb.UwbCancelReason import com.vayunmathur.findfamily.uwb.UwbController import com.vayunmathur.findfamily.uwb.UwbEnvelope import com.vayunmathur.findfamily.uwb.UwbEnvelopeKind@@ -63,6 +64,11 @@ object UwbSessionManager { data class Ranging(val sample: RangingSample) : UwbSessionState data object PeerDisconnected : UwbSessionState data class Unsupported(val reason: String? = null) : UwbSessionState+ /**+ * The peer's phone declined the REQUEST because it can't do Find Nearby at all+ * (CANCEL with [UwbCancelReason.UNSUPPORTED], #869). Terminal until the screen closes.+ */+ data object PeerUnsupported : UwbSessionState data class Failed(val reason: String) : UwbSessionState } @@ -139,11 +145,7 @@ object UwbSessionManager { } // If already busy, drop — UWB is one-session-at-a-time. }- UwbEnvelopeKind.CANCEL -> {- if (env.sessionId == currentSessionId) {- stopLocal()- }- }+ UwbEnvelopeKind.CANCEL -> endOnPeerCancel(env) // ACK and CONFIG envelopes are consumed by the waiting // initiator/responder coroutines via UwbInbox.flow.first {...}. else -> {}@@ -264,8 +266,7 @@ object UwbSessionManager { return } if (ack.kind == UwbEnvelopeKind.CANCEL) {- _state.value = UwbSessionState.Idle- stopLocal()+ endOnPeerCancel(ack) return } val peerAddress = ack.payload?.addressB64?.let(UwbBytes::from)@@ -595,6 +596,40 @@ object UwbSessionManager { } } + /**+ * The state a requester lands in when the peer answers its REQUEST with [cancel].+ * Only [UwbCancelReason.UNSUPPORTED] gets its own state; a plain cancel, an unknown+ * reason from a newer peer, or no reason from an older one all mean "peer stopped".+ */+ internal fun stateAfterPeerCancel(cancel: UwbEnvelope): UwbSessionState =+ if (cancel.reason == UwbCancelReason.UNSUPPORTED) {+ UwbSessionState.PeerUnsupported+ } else {+ UwbSessionState.Idle+ }++ /**+ * Tear down the session [cancel] belongs to and publish [stateAfterPeerCancel].+ *+ * Both the inbox collector in [init] and the initiator's ACK wait see the same CANCEL+ * and race to handle it, so this is synchronized and keyed on [currentSessionId]: the+ * first caller wins, the second finds the session already gone. A terminal state keeps+ * the peer id so the screen's dispose still matches it and calls [stop], which resets+ * the manager to Idle for the next find or incoming request.+ */+ @Synchronized+ private fun endOnPeerCancel(cancel: UwbEnvelope) {+ if (cancel.sessionId != currentSessionId) return+ val peer = _peerUserId.value+ stopLocal()+ val next = stateAfterPeerCancel(cancel)+ if (next != UwbSessionState.Idle) {+ Log.status(TAG, "peer declined session ${cancel.sessionId}: reason=${cancel.reason}")+ _peerUserId.value = peer+ _state.value = next+ }+ }+ private fun stopLocal() { streamJob?.cancel(); streamJob = null waitJob?.cancel(); waitJob = null
findfamily/src/main/java/com/vayunmathur/findfamily/uwb/UwbEnvelope.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/uwb/UwbEnvelope.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/uwb/UwbEnvelope.ktindex 91e5c176e8..24c9606fae 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/uwb/UwbEnvelope.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/uwb/UwbEnvelope.kt@@ -38,8 +38,27 @@ data class UwbEnvelope( * iOS peer would drain it and fail to parse it as a location. */ val recovery: PoweredOffGrant? = null,+ /**+ * Why a [UwbEnvelopeKind.CANCEL] was sent, one of [UwbCancelReason]; null everywhere else.+ *+ * Optional and additive, the same way [recovery] is: null is a plain cancel (user stopped,+ * screen closed), which is all a peer that predates this field ever sends. Defaults are not+ * encoded, so a plain cancel is byte-identical on the wire to what older builds produce, and+ * an older peer that does get a reason drops the unknown key (`ignoreUnknownKeys` on+ * Android, `JSONDecoder` on iOS) and treats it as the plain cancel it already understands.+ */+ val reason: String? = null, ) +/** Values for [UwbEnvelope.reason]. Unknown values must be treated as a plain cancel. */+object UwbCancelReason {+ /**+ * The receiving phone can't do Find Nearby at all (below Android 16 or no UWB radio), so it+ * declined the REQUEST on arrival instead of letting the requester wait out its timeout.+ */+ const val UNSUPPORTED = "unsupported"+}+ /** * The keys a peer needs to find this device once it is switched off, sealed to that peer's own * public bundle before it ever reaches the relay.
findfamily/src/main/res/values/strings.xml
diff --git a/findfamily/src/main/res/values/strings.xml b/findfamily/src/main/res/values/strings.xmlindex 95ae37810c..4cb50fa3a5 100644--- a/findfamily/src/main/res/values/strings.xml+++ b/findfamily/src/main/res/values/strings.xml@@ -268,6 +268,8 @@ <string name="uwb_status_unsupported">Find Nearby (UWB) isn\'t supported on this device.</string> <!-- UwbRangingScreen: Generic failure status. Sentence --> <string name="uwb_status_failed">Find Nearby (UWB) failed.</string>+ <!-- UwbRangingScreen: Status when the other person's phone declined the request because it has no UWB / Find Nearby support. Sentence -->+ <string name="uwb_status_peer_unsupported">Their phone doesn\'t support Find Nearby.</string> <!-- SecurityCodeDialog: Title. Noun phrase --> <string name="security_code">Security code</string>
findfamily/src/test/java/com/vayunmathur/findfamily/util/LocationTrackingInboundTest.kt
diff --git a/findfamily/src/test/java/com/vayunmathur/findfamily/util/LocationTrackingInboundTest.kt b/findfamily/src/test/java/com/vayunmathur/findfamily/util/LocationTrackingInboundTest.ktindex 4d41bd4a87..b994cd1984 100644--- a/findfamily/src/test/java/com/vayunmathur/findfamily/util/LocationTrackingInboundTest.kt+++ b/findfamily/src/test/java/com/vayunmathur/findfamily/util/LocationTrackingInboundTest.kt@@ -3,6 +3,7 @@ package com.vayunmathur.findfamily.util import android.app.Application import android.app.NotificationManager import android.content.Context+import android.content.pm.PackageManager import androidx.room3.Room import androidx.test.core.app.ApplicationProvider import androidx.test.ext.junit.runners.AndroidJUnit4@@ -14,11 +15,15 @@ import com.vayunmathur.findfamily.data.LocationValue import com.vayunmathur.findfamily.data.RequestStatus import com.vayunmathur.findfamily.data.User import com.vayunmathur.findfamily.data.Waypoint+import com.vayunmathur.findfamily.uwb.UwbCancelReason import com.vayunmathur.findfamily.uwb.UwbEnvelope import com.vayunmathur.findfamily.uwb.UwbEnvelopeKind+import com.vayunmathur.findfamily.uwb.UwbInbox+import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.delay import kotlinx.coroutines.flow.first import kotlinx.coroutines.runBlocking+import kotlinx.coroutines.withTimeout import org.junit.runner.RunWith import org.robolectric.Robolectric import org.robolectric.Shadows@@ -27,6 +32,7 @@ import kotlin.test.BeforeTest import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertNotNull+import kotlin.test.assertNull import kotlin.test.assertTrue import kotlin.time.Clock import kotlin.time.Instant@@ -162,11 +168,15 @@ class LocationTrackingInboundTest { val before = Shadows.shadowOf(nm).allNotifications.size assertTrue(before >= 2) service.handleUwbEnvelopes(emptyList())- service.handleUwbEnvelopes(listOf(- // Different sender than the direct call above, whose notification it would replace.- UwbEnvelope(sessionId = "s1", sender = 77uL, senderPlatform = "android", kind = UwbEnvelopeKind.REQUEST),- UwbEnvelope(sessionId = "s2", sender = 56uL, senderPlatform = "android", kind = UwbEnvelopeKind.ACK),- ))+ service.handleUwbEnvelopes(+ listOf(+ // Different sender than the direct call above, whose notification it would replace.+ UwbEnvelope(sessionId = "s1", sender = 77uL, senderPlatform = "android", kind = UwbEnvelopeKind.REQUEST),+ UwbEnvelope(sessionId = "s2", sender = 56uL, senderPlatform = "android", kind = UwbEnvelopeKind.ACK),+ ),+ // The Robolectric sandbox (SDK 34) has no UWB; this path is about a phone that does.+ uwbAvailable = true,+ ) delay(300) assertTrue(Shadows.shadowOf(nm).allNotifications.size > before) // Powered-off grant from unknown/unconfigured path: silently ignored (no keys store).@@ -177,6 +187,52 @@ class LocationTrackingInboundTest { Unit } + @Test+ fun unsupportedPhoneDeclinesUwbRequestWithoutNotifying() = runBlocking {+ service.setupNotificationChannels()+ // Even with the radio feature present, the SDK 34 sandbox is below the Android 16+ // ranging API, so the default availability gate must say no (#869).+ Shadows.shadowOf(ctx.packageManager).setSystemFeature(PackageManager.FEATURE_UWB, true)+ val bob = repo.upsertUser(user("Bob"))+ val nm = ctx.getSystemService(NotificationManager::class.java)+ val before = Shadows.shadowOf(nm).allNotifications.size+ val reply = CompletableDeferred<Pair<UwbEnvelope, Long>>()+ service.handleUwbEnvelopes(+ listOf(UwbEnvelope(sessionId = "req-1", sender = bob.toULong(), senderPlatform = "android", kind = UwbEnvelopeKind.REQUEST)),+ sendUwb = { env, to, peer ->+ assertEquals("Bob", peer?.name)+ reply.complete(env to to)+ true+ },+ )+ val (env, to) = withTimeout(5_000) { reply.await() }+ assertEquals(bob, to)+ assertEquals(UwbEnvelopeKind.CANCEL, env.kind)+ assertEquals(UwbCancelReason.UNSUPPORTED, env.reason)+ assertEquals("req-1", env.sessionId)+ // No "someone is finding you" notification, and nothing handed to the ranging inbox.+ assertEquals(before, Shadows.shadowOf(nm).allNotifications.size)+ assertNull(UwbInbox.consumePendingRequest(bob))+ }++ @Test+ fun supportedPhoneStillNotifiesAndSendsNoDecline() = runBlocking {+ service.setupNotificationChannels()+ val nm = ctx.getSystemService(NotificationManager::class.java)+ val before = Shadows.shadowOf(nm).allNotifications.size+ var replies = 0+ service.handleUwbEnvelopes(+ listOf(UwbEnvelope(sessionId = "req-2", sender = 88uL, senderPlatform = "android", kind = UwbEnvelopeKind.REQUEST)),+ uwbAvailable = true,+ sendUwb = { _, _, _ -> replies++; true },+ )+ delay(300)+ assertEquals(0, replies)+ assertTrue(Shadows.shadowOf(nm).allNotifications.size > before)+ assertNotNull(UwbInbox.consumePendingRequest(88L))+ Unit+ }+ @Test fun serviceStartWithoutPermissionStops() { val controller = Robolectric.buildService(LocationTrackingService::class.java)
findfamily/src/test/java/com/vayunmathur/findfamily/util/UwbPeerDeclineTest.kt
diff --git a/findfamily/src/test/java/com/vayunmathur/findfamily/util/UwbPeerDeclineTest.kt b/findfamily/src/test/java/com/vayunmathur/findfamily/util/UwbPeerDeclineTest.ktnew file mode 100644index 0000000000..b704ec8cf7--- /dev/null+++ b/findfamily/src/test/java/com/vayunmathur/findfamily/util/UwbPeerDeclineTest.kt@@ -0,0 +1,74 @@+package com.vayunmathur.findfamily.util++import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onNodeWithText+import androidx.test.ext.junit.runners.AndroidJUnit4+import com.vayunmathur.findfamily.ui.UwbRangingContent+import com.vayunmathur.findfamily.uwb.UwbCancelReason+import com.vayunmathur.findfamily.uwb.UwbEnvelope+import com.vayunmathur.findfamily.uwb.UwbEnvelopeKind+import org.junit.Rule+import org.junit.runner.RunWith+import kotlin.test.Test+import kotlin.test.assertEquals++/**+ * Requester side of #869: a CANCEL whose reason says the peer's phone can't do Find Nearby+ * lands in [UwbSessionManager.UwbSessionState.PeerUnsupported] and renders its own message;+ * every other CANCEL keeps the old "peer stopped" behaviour.+ */+@RunWith(AndroidJUnit4::class)+class UwbPeerDeclineTest {++ @get:Rule val rule = createComposeRule()++ private fun cancel(reason: String?) = UwbEnvelope(+ sessionId = "s",+ sender = 7uL,+ senderPlatform = "android",+ kind = UwbEnvelopeKind.CANCEL,+ reason = reason,+ )++ @Test+ fun unsupportedReasonMapsToPeerUnsupported() {+ assertEquals(+ UwbSessionManager.UwbSessionState.PeerUnsupported,+ UwbSessionManager.stateAfterPeerCancel(cancel(UwbCancelReason.UNSUPPORTED)),+ )+ }++ @Test+ fun plainOrUnknownCancelStaysIdle() {+ // No reason: every older peer, and a user-initiated stop.+ assertEquals(UwbSessionManager.UwbSessionState.Idle, UwbSessionManager.stateAfterPeerCancel(cancel(null)))+ // A reason this build doesn't know yet (newer peer) is a plain cancel too.+ assertEquals(UwbSessionManager.UwbSessionState.Idle, UwbSessionManager.stateAfterPeerCancel(cancel("busy")))+ }++ @Test+ fun peerUnsupportedRendersItsOwnMessage() {+ rule.setContent {+ UwbRangingContent(+ peerName = "Alice",+ session = UwbSessionManager.UwbSessionState.PeerUnsupported,+ onBack = {},+ )+ }+ rule.onNodeWithText("Their phone doesn't support Find Nearby.").assertIsDisplayed()+ }++ @Test+ fun timeoutKeepsTheOldMessage() {+ rule.setContent {+ UwbRangingContent(+ peerName = "Alice",+ session = UwbSessionManager.UwbSessionState.Failed("Peer did not respond"),+ onBack = {},+ )+ }+ rule.onNodeWithText("Find Nearby (UWB) failed.").assertIsDisplayed()+ rule.onNodeWithText("Peer did not respond").assertIsDisplayed()+ }+}
findfamily/src/test/java/com/vayunmathur/findfamily/uwb/W5UwbEnvelopeTest.kt
diff --git a/findfamily/src/test/java/com/vayunmathur/findfamily/uwb/W5UwbEnvelopeTest.kt b/findfamily/src/test/java/com/vayunmathur/findfamily/uwb/W5UwbEnvelopeTest.ktindex 74b40aa73c..91f36f4c58 100644--- a/findfamily/src/test/java/com/vayunmathur/findfamily/uwb/W5UwbEnvelopeTest.kt+++ b/findfamily/src/test/java/com/vayunmathur/findfamily/uwb/W5UwbEnvelopeTest.kt@@ -1,9 +1,11 @@ package com.vayunmathur.findfamily.uwb import kotlinx.coroutines.test.runTest+import kotlinx.serialization.Serializable import kotlinx.serialization.json.Json import kotlin.test.Test import kotlin.test.assertEquals+import kotlin.test.assertFalse import kotlin.test.assertNull import kotlin.test.assertTrue @@ -75,6 +77,42 @@ class W5UwbEnvelopeTest { assertEquals("sig", decoded.recovery?.sigB64) } + @Test+ fun cancelReasonRoundTripsJson() {+ val e = envelope(UwbEnvelopeKind.CANCEL).copy(reason = UwbCancelReason.UNSUPPORTED)+ val wire = json.encodeToString(UwbEnvelope.serializer(), e)+ assertTrue(wire.contains("\"reason\":\"unsupported\""))+ assertEquals(e, json.decodeFromString(UwbEnvelope.serializer(), wire))+ }++ @Test+ fun plainCancelOmitsReasonOnTheWire() {+ // Defaults aren't encoded, so a plain cancel is exactly what pre-#869 builds send.+ val wire = json.encodeToString(UwbEnvelope.serializer(), envelope(UwbEnvelopeKind.CANCEL))+ assertFalse(wire.contains("reason"))+ assertNull(json.decodeFromString(UwbEnvelope.serializer(), wire).reason)+ }++ @Test+ fun cancelFromOlderPeerDecodesAsPlainCancel() {+ val raw = """{"sessionId":"s","sender":7,"senderPlatform":"android","kind":"cancel"}"""+ val decoded = json.decodeFromString(UwbEnvelope.serializer(), raw)+ assertEquals(UwbEnvelopeKind.CANCEL, decoded.kind)+ assertNull(decoded.reason)+ }++ @Test+ fun olderPeerParsesCancelWithReason() {+ // An older build's envelope class has no `reason`; it must still decode the new cancel.+ val wire = json.encodeToString(+ UwbEnvelope.serializer(),+ envelope(UwbEnvelopeKind.CANCEL).copy(reason = UwbCancelReason.UNSUPPORTED),+ )+ val legacy = json.decodeFromString(LegacyUwbEnvelope.serializer(), wire)+ assertEquals(UwbEnvelopeKind.CANCEL, legacy.kind)+ assertEquals("session-1", legacy.sessionId)+ }+ @Test fun inboxCachesRequestsUntilConsumed() = runTest { val req = envelope(UwbEnvelopeKind.REQUEST, sender = 11uL)@@ -107,3 +145,14 @@ class W5UwbEnvelopeTest { assertEquals("two", UwbInbox.consumePendingRequest(14L)?.sessionId) } }++/** [UwbEnvelope] as builds before #869 declared it: no `reason` field. */+@Serializable+private data class LegacyUwbEnvelope(+ val sessionId: String,+ val sender: ULong,+ val senderPlatform: String,+ val kind: String,+ val payload: UwbHandshake? = null,+ val recovery: PoweredOffGrant? = null,+)