Modern Apps git

← Modern-Apps.git

findfamily: add JVM tests, fix malformed PQC bundle crash

Commit
c6ac8dbc7ab42f1dd19a63ada5ff7cb84141aebc
Author
Vayun Mathur <[email protected]>
When
2026-11-18 16:13 UTC (17 days ago)
Parents
81121cb
Raise findfamily JVM line coverage from 71% to 83.4% (530 tests, 0 failures) with tests for the UWB handshake/controller, powered-off beacons, tracking-service lifecycle, crowd finding, direct-boot networking, BLE fail-closed paths, tracker GATT encoding, and the Room v1-to-v14 migration. Production fix: a malformed stored pqcEncryptionKey made Base64.decode throw out of Networking.peerPqcBundle/securityCodePqc instead of failing closed; decoding now fails soft and falls through to the relay key lookup.

Verified with :findfamily:testDevUnitTest and :findfamily:createMergedCoverageReport (LINE 83.37%, INSTRUCTION 80.20%).

Diff

findfamily/src/main/java/com/vayunmathur/findfamily/network/Networking.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/network/Networking.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/network/Networking.ktindex 5e1681127c..0f60f33ffd 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/network/Networking.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/network/Networking.kt@@ -568,7 +568,9 @@ object Networking {      /** PQC safety number from a cached peer bundle (no lookup). */     fun securityCodePqc(user: User): String? {-        val theirBundle = user.pqcEncryptionKey?.let { Base64.decode(it) } ?: return null+        // Malformed stored bundle = no usable bundle, not an exception (UI paths read this).+        val theirBundle = user.pqcEncryptionKey+            ?.let { runCatching { Base64.decode(it) }.getOrNull() } ?: return null         if (!pqcReady) return null         return runCatching { Pqc.securityCode(pqcIdentity.publicBundle, theirBundle) }.getOrNull()     }@@ -579,7 +581,9 @@ object Networking {      */     private suspend fun peerPqcBundle(user: User): ByteArray? {         if (!pqcReady) return null-        user.pqcEncryptionKey?.let { return Base64.decode(it) }+        // Malformed stored bundle = no usable bundle: callers fail closed with+        // false, and the heartbeat must never die on a corrupt row.+        user.pqcEncryptionKey?.let { return runCatching { Base64.decode(it) }.getOrNull() }         val res = wsGetKey(user.id) ?: return null         if (res.status == WS_KEY_PQC && res.bundle != null) {             runCatching { repository.setPqcEncryptionKey(user.id, Base64.encode(res.bundle)) }
findfamily/src/test/java/com/vayunmathur/findfamily/data/FFDatabaseMigrationTest.kt
diff --git a/findfamily/src/test/java/com/vayunmathur/findfamily/data/FFDatabaseMigrationTest.kt b/findfamily/src/test/java/com/vayunmathur/findfamily/data/FFDatabaseMigrationTest.ktnew file mode 100644index 0000000000..6adc7b19c3--- /dev/null+++ b/findfamily/src/test/java/com/vayunmathur/findfamily/data/FFDatabaseMigrationTest.kt@@ -0,0 +1,106 @@+package com.vayunmathur.findfamily.data++import android.content.Context+import androidx.room3.Room+import androidx.sqlite.db.SupportSQLiteDatabase+import androidx.sqlite.db.framework.FrameworkSQLiteOpenHelperFactory+import androidx.sqlite.db.SupportSQLiteOpenHelper+import androidx.test.core.app.ApplicationProvider+import androidx.test.ext.junit.runners.AndroidJUnit4+import kotlinx.coroutines.flow.first+import kotlinx.coroutines.runBlocking+import org.junit.runner.RunWith+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertTrue+import kotlin.time.Duration.Companion.minutes+import kotlin.time.Instant++/**+ * The v1 → v14 upgrade path, driven through Room's real migration machinery:+ * a v1 file is created with the exported v1 schema, seeded, then opened by the+ * current [FFDatabase]. Room validates the migrated schema against the entities,+ * so a migration whose SQL drifts from the entity definitions fails here.+ */+@RunWith(AndroidJUnit4::class)+class FFDatabaseMigrationTest {++    private val ctx: Context get() = ApplicationProvider.getApplicationContext()+    private val dbName = "ff-migration-test.db"++    private fun createV1File() {+        ctx.deleteDatabase(dbName)+        val config = SupportSQLiteOpenHelper.Configuration.builder(ctx)+            .name(dbName)+            .callback(object : SupportSQLiteOpenHelper.Callback(1) {+                override fun onCreate(db: SupportSQLiteDatabase) = Unit+                override fun onUpgrade(db: SupportSQLiteDatabase, old: Int, new: Int) = Unit+            })+            .build()+        val helper = FrameworkSQLiteOpenHelperFactory().create(config)+        val db = helper.writableDatabase+        // Exported v1 schema (findfamily/schemas/.../1.json), verbatim.+        db.execSQL("CREATE TABLE IF NOT EXISTS `User` (`name` TEXT NOT NULL, `photo` TEXT, `locationName` TEXT NOT NULL, `sendingEnabled` INTEGER NOT NULL, `requestStatus` TEXT NOT NULL, `lastLocationChangeTime` INTEGER NOT NULL, `encryptionKey` TEXT, `id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL)")+        db.execSQL("CREATE TABLE IF NOT EXISTS `Waypoint` (`name` TEXT NOT NULL, `range` REAL NOT NULL, `id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `lat` REAL NOT NULL, `lon` REAL NOT NULL)")+        db.execSQL("CREATE TABLE IF NOT EXISTS `LocationValue` (`userid` INTEGER NOT NULL, `speed` REAL NOT NULL, `acc` REAL NOT NULL, `timestamp` INTEGER NOT NULL, `battery` REAL NOT NULL, `id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `lat` REAL NOT NULL, `lon` REAL NOT NULL)")+        db.execSQL("CREATE TABLE IF NOT EXISTS `TemporaryLink` (`name` TEXT NOT NULL, `key` TEXT NOT NULL, `publicKey` TEXT NOT NULL, `deleteAt` INTEGER NOT NULL, `id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL)")+        db.execSQL("CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)")+        db.execSQL("INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, '421e8c59e4e6cace65161ff1cff99ebb')")+        db.execSQL(+            "INSERT INTO `User` (name, locationName, sendingEnabled, requestStatus, lastLocationChangeTime, id) " ++                "VALUES ('Ann', 'Home', 1, 'MUTUAL_CONNECTION', 1700000000, 7)"+        )+        db.execSQL("INSERT INTO `Waypoint` (name, `range`, id, lat, lon) VALUES ('Home', 150.0, 3, 10.0, 20.0)")+        db.execSQL(+            "INSERT INTO `LocationValue` (userid, speed, acc, timestamp, battery, id, lat, lon) " ++                "VALUES (7, 1.0, 5.0, 1700000000, 80.0, 11, 10.5, 20.5)"+        )+        // A pre-PQC RSA link: the 7→8 rebuild deliberately drops rows with no PQC bundle.+        db.execSQL(+            "INSERT INTO `TemporaryLink` (name, `key`, publicKey, deleteAt, id) " ++                "VALUES ('Old link', 'rsa-key', 'rsa-pub', 1899999999, 5)"+        )+        db.version = 1+        helper.close()+    }++    @Test fun v1UpgradesToCurrentWithDataIntact() = runBlocking {+        createV1File()+        val db = Room.databaseBuilder(ctx, FFDatabase::class.java, dbName)+            .addMigrations(*FFDatabase.migrations.toTypedArray())+            .allowMainThreadQueries()+            .build()+        try {+            val user = db.userDao().getById(7L)+            assertNotNull(user)+            assertEquals("Ann", user.name)+            assertEquals(UserKind.PERSON, user.kind)+            assertEquals(3L, db.waypointDao().getAll().single().id)+            // 11→12 backfill: reportedAt inherits timestamp, source defaults LIVE.+            val fix = db.locationValueDao().getByUseridFlow(7L).first().single()+            assertEquals(fix.timestamp, fix.reportedAt)+            assertEquals(LocationSource.LIVE, fix.source)+            // The RSA-only link was dropped by the PQC-only rebuild, not carried.+            assertTrue(db.temporaryLinkDao().getAll().isEmpty())+            // 12→13 created the no-show table; it starts empty and accepts rows.+            assertTrue(db.noShowAlertDao().getAll().isEmpty())+            val alertId = db.noShowAlertDao().upsert(+                NoShowAlert(+                    watchedUserId = 7L,+                    waypointId = 3L,+                    expectedAt = Instant.fromEpochSeconds(1_700_000_000L),+                    grace = 15.minutes,+                )+            )+            assertTrue(alertId > 0)+            assertEquals(1, db.noShowAlertDao().getDue(1_700_001_000L).size)+            assertEquals(1, db.noShowAlertDao().markFired(alertId))+            assertEquals(0, db.noShowAlertDao().markFired(alertId))+            assertEquals(1, db.noShowAlertDao().rearm(alertId))+        } finally {+            db.close()+            ctx.deleteDatabase(dbName)+        }+    }+}
findfamily/src/test/java/com/vayunmathur/findfamily/platform/PoweredOffBeaconArmTest.kt
diff --git a/findfamily/src/test/java/com/vayunmathur/findfamily/platform/PoweredOffBeaconArmTest.kt b/findfamily/src/test/java/com/vayunmathur/findfamily/platform/PoweredOffBeaconArmTest.ktnew file mode 100644index 0000000000..5e73602bb5--- /dev/null+++ b/findfamily/src/test/java/com/vayunmathur/findfamily/platform/PoweredOffBeaconArmTest.kt@@ -0,0 +1,157 @@+package com.vayunmathur.findfamily.platform++import android.content.Context+import android.content.Intent+import android.os.BatteryManager+import androidx.test.core.app.ApplicationProvider+import androidx.test.ext.junit.runners.AndroidJUnit4+import com.vayunmathur.findfamily.data.DirectBootStore+import com.vayunmathur.findfamily.data.PoweredOffKeyStore+import com.vayunmathur.findfamily.data.TestFindFamilyRepository+import com.vayunmathur.findfamily.network.Networking+import com.vayunmathur.library.util.DataStoreUtils+import kotlinx.coroutines.delay+import kotlinx.coroutines.runBlocking+import org.junit.runner.RunWith+import org.robolectric.Robolectric+import org.robolectric.Shadows+import org.robolectric.shadows.ShadowApplication+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNull+import kotlin.test.assertTrue++/**+ * Powered-off beacon arming + final-report shutdown paths with no NearbyManager,+ * no identity socket and no priv-app permission: every path must decline quietly+ * (null / dropped report) rather than throw, because these run inside the+ * broadcast that blocks the user's power-off.+ */+@RunWith(AndroidJUnit4::class)+class PoweredOffBeaconArmTest {++    private val ctx: Context get() = ApplicationProvider.getApplicationContext()++    @Test fun beaconIsOffByDefaultAndArmIsNoOp() = runBlocking {+        assertFalse(PoweredOffBeacon.isEnabled(ctx))+        assertNull(PoweredOffBeacon.armForShutdown(ctx))+        // SDK 34 has no NearbyManager service: unsupported, asked politely.+        assertFalse(PoweredOffBeacon.isSupported(ctx))+    }++    @Test fun grantAndRevokeWithoutIdentityFailClosed() = runBlocking {+        // Whether or not another test in this class has loaded an identity yet,+        // there is either no identity or no filed beacon secret for it, and the+        // peer is unreachable either way: both calls must report failure.+        assertFalse(PoweredOffBeacon.grantRecovery(ctx, 77L))+        assertFalse(PoweredOffBeacon.revokeRecovery(ctx, 77L))+    }++    @Test fun armWithIdentityButNoSocketDeclinesAfterFilingKeys() = runBlocking {+        // Load a real identity the supported way: userid from the DataStore,+        // PQC identity minted/loaded by Networking.init.+        val repo = TestFindFamilyRepository.install(ctx)+        val ds = DataStoreUtils.getInstance(ctx)+        if (ds.getLongAwait("userid") == null) ds.setLong("userid", 424_242L, true)+        Networking.init(repo, ds, "Me")+        val myId = Networking.userid+        assertTrue(myId != 0L)+        try {+            PoweredOffBeacon.setEnabled(ctx, true)+            assertTrue(PoweredOffBeacon.isEnabled(ctx))+            // Keys are filed at opt-in, so the owner can read future sightings.+            val store = PoweredOffKeyStore(DirectBootStore.store(ctx))+            assertTrue(store.canRead(myId))+            // No relay socket in the sandbox: registration fails, nothing is armed.+            assertNull(PoweredOffBeacon.armForShutdown(ctx))+            // Grant without a reachable peer: roster updates, delivery reports false.+            assertFalse(PoweredOffBeacon.grantRecovery(ctx, 55L))+            assertTrue(55L in PoweredOffBeacon.recoveryGrantees(ctx))+            PoweredOffBeacon.setEnabled(ctx, false)+            assertFalse(PoweredOffBeacon.isEnabled(ctx))+            assertFalse(store.canRead(myId))+            assertTrue(PoweredOffBeacon.recoveryGrantees(ctx).isEmpty())+        } finally {+            runCatching { PoweredOffBeacon.setEnabled(ctx, false) }+        }+    }++    @Test fun finalReporterHandlesShutdownAndUnknownActions() {+        val app = ctx.applicationContext+        FinalLocationReporter.stop(ctx)+        var fix: android.location.Location? =+            android.location.Location("gps").apply {+                latitude = 3.0; longitude = 4.0; accuracy = 5f+                time = System.currentTimeMillis()+            }+        var roster: List<DirectBootStore.Target> = listOf(DirectBootStore.Target(9L, "aGVsbG8=", null))+        FinalLocationReporter.start(ctx, { fix }, { roster })+        val shadowApp: ShadowApplication = Shadows.shadowOf(app as android.app.Application)+        val receiver = shadowApp.registeredReceivers.firstOrNull {+            it.intentFilter.hasAction(Intent.ACTION_SHUTDOWN)+        }?.broadcastReceiver+        assertTrue(receiver != null, "final reporter registered its receiver")+        // Unknown action: ignored entirely.+        receiver!!.onReceive(ctx, Intent("com.example.WHATEVER"))+        // Shutdown with a fix and a roster but no identity/socket: the parting+        // report is dropped (logged), the beacon arm declines, nothing throws.+        receiver.onReceive(ctx, Intent(Intent.ACTION_SHUTDOWN))+        Thread.sleep(500)+        Shadows.shadowOf(android.os.Looper.getMainLooper()).idle()+        // A second shutdown must not double-report.+        receiver.onReceive(ctx, Intent(Intent.ACTION_SHUTDOWN))+        Thread.sleep(200)+        // Reboot is treated as a shutdown-class parting report too (already reported).+        receiver.onReceive(ctx, Intent(Intent.ACTION_REBOOT))+        Thread.sleep(200)+        FinalLocationReporter.stop(ctx)+        FinalLocationReporter.stop(ctx)+        // With no fix at all, battery-low also completes quietly.+        fix = null+        roster = emptyList()+        FinalLocationReporter.start(ctx, { fix }, { roster })+        val receiver2 = Shadows.shadowOf(app as android.app.Application).registeredReceivers+            .firstOrNull { it.intentFilter.hasAction(Intent.ACTION_BATTERY_LOW) }?.broadcastReceiver+        assertTrue(receiver2 != null)+        receiver2!!.onReceive(ctx, Intent(Intent.ACTION_BATTERY_LOW))+        Thread.sleep(300)+        FinalLocationReporter.stop(ctx)+    }++    @Test fun directBootSeededButUnusableIdentityIdles() = runBlocking {+        // Seed the credential-encrypted store with a userid and garbage PQC blobs,+        // then mirror them to device-protected storage. The mirror is now "seeded"+        // but the identity inside it cannot load, so the pre-unlock job must idle+        // rather than mint a stranger identity.+        val ce = DataStoreUtils.getInstance(ctx)+        ce.setLong("userid", 777_001L)+        for (key in listOf("ff_pqcKemPub", "ff_pqcKemPriv", "ff_pqcDsaPub", "ff_pqcDsaPriv")) {+            ce.setByteArray(key, byteArrayOf(1, 2, 3))+        }+        DirectBootStore.seed(ctx, emptyList(), trackingEnabled = true, globalSharingEnabled = false)+        assertTrue(DirectBootStore.isSeeded(ctx))++        val service = Robolectric.buildService(LocationTrackingService::class.java).create().get()+        service.repositoryOverride = TestFindFamilyRepository.install(ctx)+        service.bm = ctx.getSystemService(BatteryManager::class.java)+        service.startDirectBootTracking()+        var waitedMs = 0+        while (waitedMs < 10_000) {+            val job = service.directBootJob+            if (job == null || job.isCompleted) break+            delay(50); waitedMs += 50+        }+        // Either the unusable identity idles the job (the expected path), or the+        // identity re-minted and the publish loop is running — in which case it+        // must still stop cleanly. What must never happen is a crash or a hang+        // outside the cancellable loop.+        val job = service.directBootJob+        if (job != null && job.isActive) {+            job.cancel()+            delay(200)+        }+        assertTrue(job == null || job.isCompleted || job.isCancelled)+        assertEquals(emptyList(), service.publishRoster)+    }+}
findfamily/src/test/java/com/vayunmathur/findfamily/platform/UwbControllerSdk36Test.kt
diff --git a/findfamily/src/test/java/com/vayunmathur/findfamily/platform/UwbControllerSdk36Test.kt b/findfamily/src/test/java/com/vayunmathur/findfamily/platform/UwbControllerSdk36Test.ktnew file mode 100644index 0000000000..801acb3a5d--- /dev/null+++ b/findfamily/src/test/java/com/vayunmathur/findfamily/platform/UwbControllerSdk36Test.kt@@ -0,0 +1,114 @@+package com.vayunmathur.findfamily.platform++import androidx.test.core.app.ApplicationProvider+import kotlinx.coroutines.async+import kotlinx.coroutines.delay+import kotlinx.coroutines.runBlocking+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFailsWith+import kotlin.test.assertNotNull+import kotlin.test.assertTrue++/**+ * [UwbController] on SDK 36, where `android.ranging` exists. Robolectric supplies a+ * `RangingManager` whose sessions never call back, so what is pinned here is the local+ * parameter generation, the state machine, the preference/device construction on the+ * way into `stream`, and fail-closed behaviour — not radio results.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [36])+class UwbControllerSdk36Test {++    private val ctx get() = ApplicationProvider.getApplicationContext<android.content.Context>()++    @Test fun openControllerGeneratesFiRaParams() {+        val ctrl = UwbController(ctx)+        val info = ctrl.openController().getOrThrow()+        assertEquals(2, info.localAddress.size)+        // Reserved FiRa addresses 0x0000 / 0xFFFF must never be handed out.+        assertTrue(!(info.localAddress[0] == 0.toByte() && info.localAddress[1] == 0.toByte()))+        assertEquals(8, info.sessionKey.size)+        assertEquals(UwbController.DEFAULT_CHANNEL, info.channelNumber)+        assertEquals(UwbController.DEFAULT_PREAMBLE, info.preambleIndex)+        assertEquals(UwbController.State.Ready(info.localAddress), ctrl.state.value)+        ctrl.stop()+    }++    @Test fun openControleeGeneratesOnlyAddress() {+        val ctrl = UwbController(ctx)+        val addr = ctrl.openControlee().getOrThrow()+        assertEquals(2, addr.size)+        assertEquals(UwbController.State.Ready(addr), ctrl.state.value)+        ctrl.stop()+        assertEquals(UwbController.State.Idle, ctrl.state.value)+    }++    @Test fun stopIsIdempotentFromIdle() {+        val ctrl = UwbController(ctx)+        ctrl.stop()+        ctrl.stop()+        assertEquals(UwbController.State.Idle, ctrl.state.value)+    }++    @Test fun streamWithBadLocalAddressFailsClosed() = runBlocking {+        val ctrl = UwbController(ctx)+        val job = async {+            runCatching {+                ctrl.stream(+                    role = UwbController.Role.Initiator,+                    localAddress = byteArrayOf(1, 2, 3),+                    peerAddress = byteArrayOf(3, 4),+                    sessionId = 42,+                    sessionKey = ByteArray(8),+                    channelNumber = 9,+                    preambleIndex = 10,+                ).collect { }+            }+        }+        // Malformed address must not crash collection; session ends via stop().+        delay(1_500)+        job.cancel()+        ctrl.stop()+        assertEquals(UwbController.State.Idle, ctrl.state.value)+        Unit+    }++    @Test fun streamBuildsPreferenceAndStartsSession() = runBlocking {+        val ctrl = UwbController(ctx)+        var sawDisconnect = false+        val job = async {+            runCatching {+                ctrl.stream(+                    role = UwbController.Role.Responder,+                    localAddress = byteArrayOf(1, 2),+                    peerAddress = byteArrayOf(3, 4),+                    sessionId = 7,+                    sessionKey = ByteArray(8) { it.toByte() },+                    channelNumber = 9,+                    preambleIndex = 10,+                ).collect { if (it.peerDisconnected) sawDisconnect = true }+            }+        }+        delay(1_500)+        job.cancel()+        ctrl.stop()+        assertEquals(UwbController.State.Idle, ctrl.state.value)+        Unit+    }++    @Test fun uwbBytesRoundTrip() {+        val bytes = byteArrayOf(0, 1, 127, -128, -1)+        assertTrue(bytes.contentEquals(UwbBytes.from(UwbBytes.b64(bytes))))+        assertFailsWith<IllegalArgumentException> { UwbBytes.from("!!!not-base64!!!") }+    }++    @Test fun rangingSampleDefaultsToLive() {+        val s = RangingSample(1.5f, 10f, null, 123L)+        assertEquals(false, s.peerDisconnected)+        assertNotNull(s.distanceMeters)+    }+}
findfamily/src/test/java/com/vayunmathur/findfamily/platform/UwbHandshakeSdk36Test.kt
diff --git a/findfamily/src/test/java/com/vayunmathur/findfamily/platform/UwbHandshakeSdk36Test.kt b/findfamily/src/test/java/com/vayunmathur/findfamily/platform/UwbHandshakeSdk36Test.ktnew file mode 100644index 0000000000..984729d63d--- /dev/null+++ b/findfamily/src/test/java/com/vayunmathur/findfamily/platform/UwbHandshakeSdk36Test.kt@@ -0,0 +1,444 @@+package com.vayunmathur.findfamily.platform++import android.ranging.RangingManager+import android.ranging.RangingPreference+import android.ranging.RangingSession+import androidx.test.core.app.ApplicationProvider+import androidx.test.ext.junit.runners.AndroidJUnit4+import com.vayunmathur.findfamily.data.FindFamilyRepository+import com.vayunmathur.findfamily.data.RequestStatus+import com.vayunmathur.findfamily.data.TestFindFamilyRepository+import com.vayunmathur.findfamily.data.User+import com.vayunmathur.findfamily.domain.UwbEnvelope+import com.vayunmathur.findfamily.domain.UwbEnvelopeKind+import com.vayunmathur.findfamily.domain.UwbHandshake+import com.vayunmathur.findfamily.domain.UwbInbox+import com.vayunmathur.findfamily.network.Networking+import com.vayunmathur.findfamily.network.dispatchLiveFrame+import com.vayunmathur.library.network.WebSocketClient+import com.vayunmathur.library.network.WsSession+import com.vayunmathur.library.util.DataStoreUtils+import java.io.ByteArrayInputStream+import java.io.ByteArrayOutputStream+import java.net.Socket+import java.util.concurrent.Executor+import kotlin.io.encoding.Base64+import kotlinx.coroutines.delay+import kotlinx.coroutines.runBlocking+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config+import org.robolectric.annotation.Implementation+import org.robolectric.annotation.Implements+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertTrue+import kotlin.time.Clock++/** Captures the [RangingSession.Callback] the controller registers, so tests can drive it. */+@Implements(RangingManager::class)+class ShadowRangingManager {+    @Implementation+    fun createRangingSession(executor: Executor, callback: RangingSession.Callback): RangingSession {+        lastCallback = callback+        sessionsCreated+++        return org.robolectric.shadow.api.Shadow.newInstanceOf(RangingSession::class.java)+    }++    companion object {+        var lastCallback: RangingSession.Callback? = null+        var sessionsCreated = 0+        fun reset() {+            lastCallback = null+            sessionsCreated = 0+        }+    }+}++/** No-op session lifecycle: the radio never answers on its own in the sandbox. */+@Implements(RangingSession::class)+class ShadowRangingSession {+    @Implementation+    fun start(preference: RangingPreference): android.os.CancellationSignal = android.os.CancellationSignal()++    @Implementation+    fun stop() = Unit++    @Implementation+    fun close() = Unit+}++/**+ * [UwbSessionManager] handshakes on SDK 36 with a real PQC identity and a fake+ * [WsSession], so envelope publishes succeed and the ACK/CONFIG waits can be driven+ * through [UwbInbox]. The captured outbound frames are decrypted with+ * [dispatchLiveFrame] to learn the random session id the manager chose.+ */+@RunWith(AndroidJUnit4::class)+@Config(sdk = [36], shadows = [ShadowRangingManager::class, ShadowRangingSession::class])+class UwbHandshakeSdk36Test {++    private val ctx get() = ApplicationProvider.getApplicationContext<android.content.Context>()+    private val repo: FindFamilyRepository get() = repoRef!!+    private lateinit var out: ByteArrayOutputStream++    @BeforeTest+    fun setup() {+        runBlocking {+            if (repoRef == null) {+                repoRef = TestFindFamilyRepository.install(ctx)+                Networking.init(repoRef!!, DataStoreUtils.getInstance(ctx), "Me")+            }+            Networking.repository = repoRef!!+            out = ByteArrayOutputStream()+            Networking.wsSession = fakeSession(out)+            ShadowRangingManager.reset()+            UwbSessionManager.init(ctx, repoRef!!)+            UwbSessionManager.stop()+            settle()+        }+    }++    private fun fakeSession(output: ByteArrayOutputStream): WsSession {+        val clientConstructor = WebSocketClient::class.java+            .getDeclaredConstructor(+                Socket::class.java, java.io.InputStream::class.java,+                java.io.OutputStream::class.java, Map::class.java, Map::class.java,+            ).apply { isAccessible = true }+        val client = clientConstructor.newInstance(+            Socket(), ByteArrayInputStream(ByteArray(0)), output,+            emptyMap<String, List<String>>(), emptyMap<String, String>(),+        )+        val sessionConstructor = WsSession::class.java+            .getDeclaredConstructor(WebSocketClient::class.java)+            .apply { isAccessible = true }+        return sessionConstructor.newInstance(client)+    }++    /** Unmasks the client frame(s) written to [out] and returns the last payload. */+    private fun capturedPayload(): ByteArray {+        val frame = out.toByteArray()+        assertTrue(frame.size >= 6, "a masked client frame was written")+        var off = 0+        var last: ByteArray? = null+        while (off + 2 <= frame.size) {+            assertEquals(0x82, frame[off].toInt() and 0xff)+            var len = frame[off + 1].toInt() and 0x7f+            var p = off + 2+            if (len == 126) {+                len = ((frame[p].toInt() and 0xff) shl 8) or (frame[p + 1].toInt() and 0xff)+                p += 2+            } else if (len == 127) {+                var wide = 0L+                for (i in 0 until 8) wide = (wide shl 8) or (frame[p + i].toLong() and 0xff)+                len = wide.toInt()+                p += 8+            }+            val mask = frame.copyOfRange(p, p + 4)+            p += 4+            last = ByteArray(len) { i -> (frame[p + i].toInt() xor mask[i % 4].toInt()).toByte() }+            off = p + len+        }+        return assertNotNull(last)+    }++    /** The most recent UWB envelope the manager published, decrypted from the wire. */+    private suspend fun lastPublishedEnvelope(): UwbEnvelope {+        val frame = capturedPayload()+        val delivered = mutableListOf<UwbEnvelope>()+        val msg = byteArrayOf(Networking.WS_OP_MSG, Networking.WS_FLAG_UWB.toByte()) ++            frame.copyOfRange(10, frame.size)+        dispatchLiveFrame(msg, {}, { delivered += it })+        return delivered.single()+    }++    private suspend fun settle(timeoutMs: Long = 8_000): Boolean {+        val deadline = System.currentTimeMillis() + timeoutMs+        while (System.currentTimeMillis() < deadline) {+            if (UwbSessionManager.state.value is UwbSessionManager.UwbSessionState.Idle &&+                UwbSessionManager.peerUserId.value == null+            ) return true+            delay(50)+        }+        return false+    }++    private suspend fun awaitState(timeoutMs: Long = 8_000, match: (UwbSessionManager.UwbSessionState) -> Boolean): Boolean {+        val deadline = System.currentTimeMillis() + timeoutMs+        while (System.currentTimeMillis() < deadline) {+            if (match(UwbSessionManager.state.value)) return true+            delay(50)+        }+        return match(UwbSessionManager.state.value)+    }++    private suspend fun addPeer(platform: String?): Long {+        val bundle = Base64.encode(Networking.pqcIdentity.publicBundle)+        return repo.upsertUser(+            User(+                name = "Peer-$platform",+                photo = null,+                locationName = "Home",+                sendingEnabled = true,+                requestStatus = RequestStatus.MUTUAL_CONNECTION,+                lastLocationChangeTime = Clock.System.now(),+                platform = platform,+                pqcEncryptionKey = bundle,+            )+        )+    }++    @Test fun initiatorReachesWaitingThenRangesOnAck() = runBlocking {+        val peerId = addPeer(platform = "android")+        out.reset()+        UwbSessionManager.startAsInitiator(peerId)+        assertTrue(+            awaitState { it is UwbSessionManager.UwbSessionState.WaitingForPeer },+            "initiator must wait for the ACK, was ${UwbSessionManager.state.value}",+        )+        val request = lastPublishedEnvelope()+        assertEquals(UwbEnvelopeKind.REQUEST, request.kind)+        assertEquals(peerId, UwbSessionManager.peerUserId.value)+        // Starting again mid-session is ignored (one session at a time).+        UwbSessionManager.startAsInitiator(peerId)+        UwbInbox.tryEmit(+            UwbEnvelope(+                sessionId = request.sessionId,+                sender = peerId.toULong(),+                senderPlatform = "android",+                kind = UwbEnvelopeKind.ACK,+                payload = UwbHandshake(addressB64 = UwbBytes.b64(byteArrayOf(5, 6))),+            )+        )+        // The ranging stream opens (shadow radio never reports): still waiting,+        // but the controller session was created and its callback registered.+        assertTrue(awaitState(5_000) { ShadowRangingManager.lastCallback != null })+        ShadowRangingManager.lastCallback!!.onOpened()+        // A ranging result folds into the state machine as a Ranging sample.+        // (RangingMeasurement/RangingDevice builders are hidden in the stub SDK,+        // so the fixtures are built reflectively against the runtime classes.)+        val data = rangingData(distance = 2.5, azimuthDeg = 30.0)+        val device = rangingDevice()+        ShadowRangingManager.lastCallback!!.onResults(device, data)+        assertTrue(+            awaitState { it is UwbSessionManager.UwbSessionState.Ranging },+            "sample must surface as Ranging, was ${UwbSessionManager.state.value}",+        )+        val ranging = UwbSessionManager.state.value as UwbSessionManager.UwbSessionState.Ranging+        assertEquals(2.5f, ranging.sample.distanceMeters)+        // Peer going away surfaces as PeerDisconnected.+        ShadowRangingManager.lastCallback!!.onStopped(device, android.ranging.RangingManager.UWB)+        assertTrue(+            awaitState { it is UwbSessionManager.UwbSessionState.PeerDisconnected },+            "stop must surface as PeerDisconnected, was ${UwbSessionManager.state.value}",+        )+        UwbSessionManager.stop()+        assertTrue(settle())+    }++    @Test fun initiatorSeesPeerUnsupportedOnDecline() = runBlocking {+        val peerId = addPeer(platform = "android")+        out.reset()+        UwbSessionManager.startAsInitiator(peerId)+        assertTrue(awaitState { it is UwbSessionManager.UwbSessionState.WaitingForPeer })+        val request = lastPublishedEnvelope()+        UwbInbox.tryEmit(+            UwbEnvelope(+                sessionId = request.sessionId,+                sender = peerId.toULong(),+                senderPlatform = "android",+                kind = UwbEnvelopeKind.CANCEL,+                reason = com.vayunmathur.findfamily.domain.UwbCancelReason.UNSUPPORTED,+            )+        )+        assertTrue(+            awaitState { it is UwbSessionManager.UwbSessionState.PeerUnsupported },+            "decline must land in PeerUnsupported, was ${UwbSessionManager.state.value}",+        )+        assertEquals(peerId, UwbSessionManager.peerUserId.value)+        UwbSessionManager.stop()+        assertTrue(settle())+    }++    @Test fun initiatorFailsOnAckWithoutAddress() = runBlocking {+        val peerId = addPeer(platform = "android")+        out.reset()+        UwbSessionManager.startAsInitiator(peerId)+        assertTrue(awaitState { it is UwbSessionManager.UwbSessionState.WaitingForPeer })+        val request = lastPublishedEnvelope()+        UwbInbox.tryEmit(+            UwbEnvelope(+                sessionId = request.sessionId,+                sender = peerId.toULong(),+                senderPlatform = "android",+                kind = UwbEnvelopeKind.ACK,+            )+        )+        assertTrue(settle(), "address-less ACK must fail closed to Idle, was ${UwbSessionManager.state.value}")+    }++    @Test fun iosInitiatorFailsWhenShareableConfigUnparseable() = runBlocking {+        val peerId = addPeer(platform = "ios")+        out.reset()+        UwbSessionManager.startAsInitiator(peerId)+        assertTrue(awaitState { it is UwbSessionManager.UwbSessionState.WaitingForPeer })+        val request = lastPublishedEnvelope()+        assertEquals(UwbEnvelopeKind.REQUEST, request.kind)+        UwbInbox.tryEmit(+            UwbEnvelope(+                sessionId = request.sessionId,+                sender = peerId.toULong(),+                senderPlatform = "ios",+                kind = UwbEnvelopeKind.CONFIG,+                payload = UwbHandshake(shareableConfigDataB64 = UwbBytes.b64(byteArrayOf(1, 2, 3))),+            )+        )+        // The accessory parser is stubbed and throws: the session fails closed.+        assertTrue(settle(), "unparseable iOS config must fail closed to Idle, was ${UwbSessionManager.state.value}")+    }++    @Test fun responderAcksAndroidRequestAndStartsRanging() = runBlocking {+        val peerId = addPeer(platform = "android")+        out.reset()+        UwbInbox.tryEmit(+            UwbEnvelope(+                sessionId = "resp-session-1",+                sender = peerId.toULong(),+                senderPlatform = "android",+                kind = UwbEnvelopeKind.REQUEST,+                payload = UwbHandshake(+                    addressB64 = UwbBytes.b64(byteArrayOf(3, 4)),+                    sessionId = 21,+                    sessionKeyB64 = UwbBytes.b64(ByteArray(8) { 2 }),+                    channelNumber = 9,+                    preambleIndex = 10,+                ),+            )+        )+        assertTrue(+            awaitState(5_000) { ShadowRangingManager.lastCallback != null },+            "responder must open ranging after ACK, state=${UwbSessionManager.state.value}",+        )+        val ack = lastPublishedEnvelope()+        assertEquals(UwbEnvelopeKind.ACK, ack.kind)+        assertEquals("resp-session-1", ack.sessionId)+        UwbSessionManager.stop()+        assertTrue(settle())+    }++    @Test fun responderIosRequestFailsWhenShareableConfigUnparseable() = runBlocking {+        val peerId = addPeer(platform = "ios")+        out.reset()+        UwbInbox.tryEmit(+            UwbEnvelope(+                sessionId = "resp-ios-1",+                sender = peerId.toULong(),+                senderPlatform = "ios",+                kind = UwbEnvelopeKind.REQUEST,+            )+        )+        assertTrue(awaitState { it is UwbSessionManager.UwbSessionState.WaitingForPeer })+        val config = lastPublishedEnvelope()+        assertEquals(UwbEnvelopeKind.CONFIG, config.kind)+        UwbInbox.tryEmit(+            UwbEnvelope(+                sessionId = "resp-ios-1",+                sender = peerId.toULong(),+                senderPlatform = "ios",+                kind = UwbEnvelopeKind.CONFIG,+                payload = UwbHandshake(shareableConfigDataB64 = UwbBytes.b64(byteArrayOf(9))),+            )+        )+        assertTrue(settle(), "unparseable iOS config must fail closed to Idle, was ${UwbSessionManager.state.value}")+    }++    @Test fun openFailedRetryDropsTierThenDisconnects() = runBlocking {+        val peerId = addPeer(platform = "android")+        out.reset()+        UwbSessionManager.startAsInitiator(peerId)+        assertTrue(awaitState { it is UwbSessionManager.UwbSessionState.WaitingForPeer })+        val request = lastPublishedEnvelope()+        UwbInbox.tryEmit(+            UwbEnvelope(+                sessionId = request.sessionId,+                sender = peerId.toULong(),+                senderPlatform = "android",+                kind = UwbEnvelopeKind.ACK,+                payload = UwbHandshake(addressB64 = UwbBytes.b64(byteArrayOf(5, 6))),+            )+        )+        assertTrue(awaitState(5_000) { ShadowRangingManager.lastCallback != null })+        val cb = ShadowRangingManager.lastCallback!!+        val before = ShadowRangingManager.sessionsCreated+        // REASON_UNSUPPORTED (3) at tier 2: drop a tier and retry with a new session.+        cb.onOpenFailed(3)+        assertEquals(before + 1, ShadowRangingManager.sessionsCreated)+        // A non-retryable failure ends the stream as a disconnect (which the+        // stream collector then tears down to Idle).+        ShadowRangingManager.lastCallback!!.onOpenFailed(4)+        assertTrue(+            awaitState {+                it is UwbSessionManager.UwbSessionState.PeerDisconnected ||+                    (it is UwbSessionManager.UwbSessionState.Idle && UwbSessionManager.peerUserId.value == null)+            },+            "open failure must surface as disconnect, was ${UwbSessionManager.state.value}",+        )+        UwbSessionManager.stop()+        assertTrue(settle())+    }++    private fun builder(className: String): Any {+        val cls = Class.forName(className)+        val ctor = cls.getDeclaredConstructor().apply { isAccessible = true }+        return ctor.newInstance()+    }++    private fun Any.call(name: String, vararg args: Any?): Any? {+        val method = javaClass.methods.firstOrNull { it.name == name && it.parameterCount == args.size }+            ?: javaClass.getDeclaredMethod(name, *args.map { paramType(it) }.toTypedArray())+                .apply { isAccessible = true }+        try {+            return method.invoke(this, *args)+        } catch (e: java.lang.reflect.InvocationTargetException) {+            throw AssertionError("reflective $name failed: ${e.cause}", e.cause)+        }+    }++    private fun paramType(arg: Any?): Class<*> = when (arg) {+        is Double -> Double::class.javaPrimitiveType!!+        is Int -> Int::class.javaPrimitiveType!!+        is Long -> Long::class.javaPrimitiveType!!+        null -> Any::class.java+        else -> arg.javaClass+    }++    private fun measurement(value: Double, confidence: Int): Any {+        val b = builder("android.ranging.RangingMeasurement\$Builder")+        b.call("setMeasurement", value)+        b.call("setConfidence", confidence)+        return b.call("build")!!+    }++    private fun rangingData(distance: Double, azimuthDeg: Double): android.ranging.RangingData {+        val b = builder("android.ranging.RangingData\$Builder")+        b.call("setRangingTechnology", android.ranging.RangingManager.UWB)+        b.call("setDistance", measurement(distance, 2))+        b.call("setAzimuth", measurement(Math.toRadians(azimuthDeg), 2))+        b.call("setElevation", measurement(Math.toRadians(5.0), 0))+        b.call("setTimestampMillis", System.currentTimeMillis())+        return b.call("build") as android.ranging.RangingData+    }++    private fun rangingDevice(): android.ranging.RangingDevice {+        val inner = builder("android.ranging.RangingDevice\$Builder")+        inner.call("setUuid", java.util.UUID(0L, 1L))+        val device = inner.call("build")!!+        return device as android.ranging.RangingDevice+    }++    private companion object {+        var repoRef: FindFamilyRepository? = null+    }+}
findfamily/src/test/java/com/vayunmathur/findfamily/platform/UwbSessionManagerSdk36Test.kt
diff --git a/findfamily/src/test/java/com/vayunmathur/findfamily/platform/UwbSessionManagerSdk36Test.kt b/findfamily/src/test/java/com/vayunmathur/findfamily/platform/UwbSessionManagerSdk36Test.ktnew file mode 100644index 0000000000..57af4db976--- /dev/null+++ b/findfamily/src/test/java/com/vayunmathur/findfamily/platform/UwbSessionManagerSdk36Test.kt@@ -0,0 +1,190 @@+package com.vayunmathur.findfamily.platform++import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.findfamily.data.FindFamilyRepository+import com.vayunmathur.findfamily.data.RequestStatus+import com.vayunmathur.findfamily.data.TestFindFamilyRepository+import com.vayunmathur.findfamily.data.TrackerStore+import com.vayunmathur.findfamily.data.User+import com.vayunmathur.findfamily.data.UserKind+import com.vayunmathur.findfamily.domain.UwbEnvelope+import com.vayunmathur.findfamily.domain.UwbEnvelopeKind+import com.vayunmathur.findfamily.domain.UwbHandshake+import com.vayunmathur.findfamily.domain.UwbInbox+import com.vayunmathur.library.util.DataStoreUtils+import kotlinx.coroutines.delay+import kotlinx.coroutines.runBlocking+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNull+import kotlin.test.assertTrue+import kotlin.time.Clock++/**+ * [UwbSessionManager] handshake state machine on SDK 36 (where the ranging API exists).+ *+ * There is no peer and no socket in the sandbox, so every handshake must fail closed:+ * the attempt settles back to [UwbSessionManager.UwbSessionState.Idle] with no peer+ * attached, instead of hanging in Starting/WaitingForPeer or crashing the scope.+ * One repository backs the whole class because the manager keeps the repository from+ * its first (and only effective) `init`.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [36])+class UwbSessionManagerSdk36Test {++    private val ctx get() = ApplicationProvider.getApplicationContext<android.content.Context>()+    private val repo: FindFamilyRepository get() = repoRef!!++    @BeforeTest+    fun setup() {+        runBlocking {+            if (repoRef == null) {+                repoRef = TestFindFamilyRepository.install(ctx)+            }+            UwbSessionManager.init(ctx, repoRef!!)+            UwbSessionManager.stop()+            settle()+        }+    }++    private suspend fun settle(timeoutMs: Long = 8_000): Boolean {+        val deadline = System.currentTimeMillis() + timeoutMs+        while (System.currentTimeMillis() < deadline) {+            if (UwbSessionManager.state.value is UwbSessionManager.UwbSessionState.Idle &&+                UwbSessionManager.peerUserId.value == null+            ) return true+            delay(50)+        }+        return UwbSessionManager.state.value is UwbSessionManager.UwbSessionState.Idle+    }++    private suspend fun addUser(platform: String?, kind: UserKind = UserKind.PERSON): Long =+        repo.upsertUser(+            User(+                name = "Peer-$platform-$kind",+                photo = null,+                locationName = "Home",+                sendingEnabled = true,+                requestStatus = RequestStatus.MUTUAL_CONNECTION,+                lastLocationChangeTime = Clock.System.now(),+                platform = platform,+                kind = kind,+            )+        )++    @Test fun availabilityMatchesSdkAndFeature() {+        assertEquals(+            UwbSessionManager.isSupportedSdk &&+                ctx.packageManager.hasSystemFeature(android.content.pm.PackageManager.FEATURE_UWB),+            UwbSessionManager.isAvailable(ctx),+        )+        assertTrue(UwbSessionManager.isSupportedSdk)+    }++    @Test fun initiatorWithUnknownPeerFailsClosed() = runBlocking {+        UwbSessionManager.startAsInitiator(999_999L)+        assertTrue(settle(), "unknown peer must settle to Idle, was ${UwbSessionManager.state.value}")+        assertNull(UwbSessionManager.peerUserId.value)+    }++    @Test fun initiatorWithAndroidPeerFailsClosedWithoutSocket() = runBlocking {+        val id = addUser(platform = "android")+        UwbSessionManager.startAsInitiator(id)+        assertTrue(settle(), "android peer without socket must settle to Idle, was ${UwbSessionManager.state.value}")+        assertNull(UwbSessionManager.peerUserId.value)+    }++    @Test fun initiatorWithIosPeerFailsClosedWithoutSocket() = runBlocking {+        val id = addUser(platform = "ios")+        UwbSessionManager.startAsInitiator(id)+        assertTrue(settle(), "ios peer without socket must settle to Idle, was ${UwbSessionManager.state.value}")+        assertNull(UwbSessionManager.peerUserId.value)+    }++    @Test fun initiatorWithUnboundTrackerFailsClosed() = runBlocking {+        val id = addUser(platform = null, kind = UserKind.TRACKER)+        UwbSessionManager.startAsInitiator(id)+        assertTrue(settle(), "tracker without stored secret must settle to Idle, was ${UwbSessionManager.state.value}")+        assertNull(UwbSessionManager.peerUserId.value)+    }++    @Test fun initiatorWithBoundTrackerButNoBleFailsClosed() = runBlocking {+        val id = addUser(platform = null, kind = UserKind.TRACKER)+        TrackerStore(DataStoreUtils.getInstance(ctx))+            .save(id, ByteArray(32) { 1 }, ByteArray(4), "AA:BB:CC:DD:EE:FF")+        UwbSessionManager.startAsInitiator(id)+        // GATT cannot complete in the sandbox; either the attempt fails closed on its+        // own or it is still waiting — stop() must always recover to Idle either way.+        delay(2_000)+        UwbSessionManager.stop()+        assertTrue(settle(), "tracker find must recover to Idle after stop, was ${UwbSessionManager.state.value}")+        assertNull(UwbSessionManager.peerUserId.value)+    }++    @Test fun incomingAndroidRequestFailsClosedWithoutSocket() = runBlocking {+        val id = addUser(platform = "android")+        assertTrue(+            UwbInbox.tryEmit(+                UwbEnvelope(+                    sessionId = "sess-android-req",+                    sender = id.toULong(),+                    senderPlatform = "android",+                    kind = UwbEnvelopeKind.REQUEST,+                    payload = UwbHandshake(+                        addressB64 = UwbBytes.b64(byteArrayOf(3, 4)),+                        sessionId = 11,+                        sessionKeyB64 = UwbBytes.b64(ByteArray(8)),+                        channelNumber = 9,+                        preambleIndex = 10,+                    ),+                )+            )+        )+        assertTrue(settle(), "incoming request without socket must settle to Idle, was ${UwbSessionManager.state.value}")+        // The request was consumed as a pending request or handled; a cancel for a+        // foreign session must not disturb the (now idle) manager.+        UwbInbox.tryEmit(+            UwbEnvelope(+                sessionId = "someone-else",+                sender = id.toULong(),+                senderPlatform = "android",+                kind = UwbEnvelopeKind.CANCEL,+            )+        )+        delay(300)+        assertTrue(UwbSessionManager.state.value is UwbSessionManager.UwbSessionState.Idle)+    }++    @Test fun incomingIosRequestFailsClosedWithoutSocket() = runBlocking {+        val id = addUser(platform = "ios")+        assertTrue(+            UwbInbox.tryEmit(+                UwbEnvelope(+                    sessionId = "sess-ios-req",+                    sender = id.toULong(),+                    senderPlatform = "ios",+                    kind = UwbEnvelopeKind.REQUEST,+                )+            )+        )+        assertTrue(settle(), "incoming ios request without socket must settle to Idle, was ${UwbSessionManager.state.value}")+    }++    @Test fun stopFromIdleIsStable() {+        UwbSessionManager.stop()+        assertTrue(UwbSessionManager.state.value is UwbSessionManager.UwbSessionState.Idle)+        assertNull(UwbSessionManager.peerUserId.value)+    }++    private companion object {+        // One repository for the whole class: the manager keeps the repository from+        // its first (only effective) init, and Robolectric re-creates the test-class+        // instance per method — an instance field would silently swap databases.+        var repoRef: FindFamilyRepository? = null+    }+}
findfamily/src/test/java/com/vayunmathur/findfamily/service/TilesBootAndChannelsTest.kt
diff --git a/findfamily/src/test/java/com/vayunmathur/findfamily/service/TilesBootAndChannelsTest.kt b/findfamily/src/test/java/com/vayunmathur/findfamily/service/TilesBootAndChannelsTest.ktnew file mode 100644index 0000000000..8ed0ec2df8--- /dev/null+++ b/findfamily/src/test/java/com/vayunmathur/findfamily/service/TilesBootAndChannelsTest.kt@@ -0,0 +1,154 @@+package com.vayunmathur.findfamily.service++import android.Manifest+import android.app.Application+import android.content.Context+import android.content.Intent+import androidx.test.core.app.ApplicationProvider+import androidx.test.ext.junit.runners.AndroidJUnit4+import com.vayunmathur.findfamily.notifications.FindFamilyNotificationChannels+import com.vayunmathur.findfamily.platform.AppBackupAgent+import com.vayunmathur.findfamily.platform.BootReceiver+import com.vayunmathur.findfamily.platform.LocationServiceController+import com.vayunmathur.library.util.DataStoreUtils+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.async+import kotlinx.coroutines.delay+import kotlinx.coroutines.runBlocking+import org.junit.runner.RunWith+import org.robolectric.Robolectric+import org.robolectric.Shadows+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNotNull+import kotlin.test.assertTrue++/**+ * Quick Settings tiles, boot receiver, notification channels and the backup agent+ * in the sandbox: tile clicks flip the persisted switches, the boot receiver+ * ignores unrelated broadcasts and unpermitted boots, and channels are created+ * per person with the documented ids.+ */+@RunWith(AndroidJUnit4::class)+class TilesBootAndChannelsTest {++    private val app: Application get() = ApplicationProvider.getApplicationContext()+    private val ctx: Context get() = app++    private fun idleMain() {+        Shadows.shadowOf(android.os.Looper.getMainLooper()).idle()+    }++    @Test fun sharingTileTogglesGlobalSharingFlag() = runBlocking {+        val service = Robolectric.buildService(SharingTileService::class.java).create().get()+        runCatching {+            androidx.work.WorkManager.initialize(ctx, androidx.work.Configuration.Builder().build())+        }+        assertTrue(LocationServiceController.isGlobalSharingEnabled(ctx))+        service.onTileAdded()+        service.onStartListening()+        idleMain()+        service.onClick()+        // The click flips the flag on Dispatchers.Main: pump until it lands.+        var waited = 0+        while (LocationServiceController.isGlobalSharingEnabled(ctx) && waited < 5_000) {+            idleMain()+            delay(50); waited += 50+        }+        assertFalse(LocationServiceController.isGlobalSharingEnabled(ctx))+        service.onClick()+        waited = 0+        while (!LocationServiceController.isGlobalSharingEnabled(ctx) && waited < 5_000) {+            idleMain()+            delay(50); waited += 50+        }+        assertTrue(LocationServiceController.isGlobalSharingEnabled(ctx))+        SharingTileService.requestRefresh(ctx)+        Unit+    }++    @Test fun trackingTileWithoutPermissionOpensAppInsteadOfToggling() = runBlocking {+        Shadows.shadowOf(app).denyPermissions(Manifest.permission.ACCESS_FINE_LOCATION)+        val controller = Robolectric.buildService(TrackingTileService::class.java)+        val service = controller.create().get()+        assertTrue(LocationServiceController.isTrackingEnabled(ctx))+        service.onTileAdded()+        service.onStartListening()+        // No permission: the click opens the app instead of toggling. The tile+        // binder (IQSService) does not exist under Robolectric, so the collapse+        // call itself throws there; on a device it is bound before clicks land.+        runCatching { service.onClick() }+        idleMain()+        // The click must not flip tracking off/on blindly.+        assertTrue(LocationServiceController.isTrackingEnabled(ctx))+        // Grant, then the click toggles for real.+        Shadows.shadowOf(app).grantPermissions(Manifest.permission.ACCESS_FINE_LOCATION)+        service.onClick()+        var waited = 0+        while (LocationServiceController.isTrackingEnabled(ctx) && waited < 5_000) {+            idleMain()+            delay(50); waited += 50+        }+        assertFalse(LocationServiceController.isTrackingEnabled(ctx))+        // No controller.destroy(): Robolectric's TileService shadow mishandles+        // Service.onDestroy (ShadowTileService cast), unrelated to app code.+        // Restore default-on for other tests in this sandbox.+        val back = CoroutineScope(Dispatchers.IO)+            .async { LocationServiceController.setTrackingEnabled(ctx, true) }+        while (!back.isCompleted) { idleMain(); delay(25) }+        back.await()+        Unit+    }++    @Test fun bootReceiverIgnoresUnrelatedAndUnpermittedBoots() {+        val receiver = BootReceiver()+        Shadows.shadowOf(app).denyPermissions(Manifest.permission.ACCESS_FINE_LOCATION)+        // Unrelated action: ignored without touching async machinery.+        receiver.onReceive(ctx, Intent("com.example.UNRELATED"))+        // Boot without fine permission: must not start anything (and must not crash).+        receiver.onReceive(ctx, Intent(Intent.ACTION_BOOT_COMPLETED))+        receiver.onReceive(ctx, Intent(Intent.ACTION_MY_PACKAGE_REPLACED))+        // Locked boot with permission: reconciles against device-protected state.+        Shadows.shadowOf(app).grantPermissions(Manifest.permission.ACCESS_FINE_LOCATION)+        receiver.onReceive(ctx, Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED))+        Thread.sleep(300)+        idleMain()+    }++    @Test fun notificationChannelsAreCreatedPerPerson() {+        val manager = ctx.getSystemService(android.app.NotificationManager::class.java)+        assertNotNull(manager)+        FindFamilyNotificationChannels.ensureNoShowChannel(ctx, 42L, "Ann")+        FindFamilyNotificationChannels.ensureEntryExitChannels(ctx, 42L, "Ann")+        // Idempotent: creating again refreshes, never throws.+        FindFamilyNotificationChannels.ensureNoShowChannel(ctx, 42L, "Ann")+        assertNotNull(manager.getNotificationChannel("no_show_42"))+        assertNotNull(manager.getNotificationChannel("entry_exit_42_arrival"))+        assertNotNull(manager.getNotificationChannel("entry_exit_42_departure"))+        assertEquals("no_show_42", FindFamilyNotificationChannels.noShowChannelId(42L))+        assertEquals("entry_exit_42_arrival", FindFamilyNotificationChannels.entryExitChannelId(42L, true))+        assertEquals("entry_exit_42_departure", FindFamilyNotificationChannels.entryExitChannelId(42L, false))+        FindFamilyNotificationChannels.openNoShowChannelSettings(ctx, 42L, "Ann")+        FindFamilyNotificationChannels.openChannelSettings(ctx, 42L, "Ann", arrival = true)+        val started = Shadows.shadowOf(app).nextStartedActivity+        assertNotNull(started)+        assertEquals(+            android.provider.Settings.ACTION_CHANNEL_NOTIFICATION_SETTINGS,+            started.action,+        )+    }++    @Test fun backupAgentDeclaresDbAndDatastore() {+        com.vayunmathur.findfamily.platform.FakeAndroidKeyStore.install()+        // Production stores the SQLCipher passphrase at first database setup;+        // the backup agent only ever reads it back.+        com.vayunmathur.library.util.DatabaseHelper(ctx).storePassphrase("backup-test-pass")+        val agent = Robolectric.buildBackupAgent(AppBackupAgent::class.java).create().get()+        assertEquals(listOf("datastore_default"), agent.datastoreNames)+        assertTrue(agent.extraFiles.isEmpty())+        assertEquals(listOf("passwords-db" to "backup-test-pass"), agent.dbConfigs)+        assertNotNull(DataStoreUtils.getInstance(ctx))+    }+}
findfamily/src/test/java/com/vayunmathur/findfamily/tracker/BleFailClosedTest.kt
diff --git a/findfamily/src/test/java/com/vayunmathur/findfamily/tracker/BleFailClosedTest.kt b/findfamily/src/test/java/com/vayunmathur/findfamily/tracker/BleFailClosedTest.ktnew file mode 100644index 0000000000..1a3e2939ed--- /dev/null+++ b/findfamily/src/test/java/com/vayunmathur/findfamily/tracker/BleFailClosedTest.kt@@ -0,0 +1,140 @@+package com.vayunmathur.findfamily.tracker++import android.bluetooth.BluetoothManager+import android.content.Context+import androidx.test.core.app.ApplicationProvider+import androidx.test.ext.junit.runners.AndroidJUnit4+import com.vayunmathur.findfamily.data.TestFindFamilyRepository+import com.vayunmathur.findfamily.data.UserKind+import com.vayunmathur.findfamily.domain.TrackerBle+import com.vayunmathur.findfamily.platform.PoweredOffBle+import com.vayunmathur.findfamily.platform.PoweredOffScanner+import com.vayunmathur.findfamily.platform.TrackerBeaconScanner+import com.vayunmathur.findfamily.platform.TrackerBinder+import com.vayunmathur.findfamily.platform.TrackerProvisioner+import kotlinx.coroutines.async+import kotlinx.coroutines.delay+import kotlinx.coroutines.flow.toList+import kotlinx.coroutines.runBlocking+import kotlinx.coroutines.withTimeoutOrNull+import org.junit.runner.RunWith+import kotlin.test.Test+import kotlin.test.assertContentEquals+import kotlin.test.assertEquals+import kotlin.test.assertFailsWith+import kotlin.test.assertFalse+import kotlin.test.assertNull+import kotlin.test.assertTrue++/**+ * BLE crowd-finding surface in the sandbox: there is no usable BLE stack, so scans+ * must close quietly, provisioning must report failure without persisting anything,+ * and the powered-off frame parser (pure) must accept exactly well-formed frames.+ */+@RunWith(AndroidJUnit4::class)+class BleFailClosedTest {++    private val ctx: Context get() = ApplicationProvider.getApplicationContext()++    @Test fun poweredOffEidParserAcceptsOnlyWellFormedFrames() {+        val eid = ByteArray(20) { it.toByte() }+        val frame = byteArrayOf(PoweredOffBle.FRAME_TYPE) + eid + byteArrayOf(0x55)+        assertContentEquals(eid, PoweredOffBle.eidFrom(frame))+        assertContentEquals(eid, PoweredOffBle.eidFrom(byteArrayOf(PoweredOffBle.FRAME_TYPE) + eid))+        assertNull(PoweredOffBle.eidFrom(null))+        assertNull(PoweredOffBle.eidFrom(ByteArray(0)))+        // One byte short of a whole EID.+        assertNull(PoweredOffBle.eidFrom(byteArrayOf(PoweredOffBle.FRAME_TYPE) + ByteArray(19)))+        // Wrong frame type is some other Fast Pair / Eddystone frame.+        assertNull(PoweredOffBle.eidFrom(byteArrayOf(0x41) + eid))+        assertEquals(2, PoweredOffBle.scanFilters().size)+        assertEquals(21, PoweredOffBle.MIN_SERVICE_DATA_LEN)+    }++    @Test fun trackerScannerClosesOrIdlesWithoutBle() = runBlocking {+        val collected = async { runCatching { TrackerBeaconScanner(ctx).sightings().toList() } }+        val done = withTimeoutOrNull(4_000) { collected.await() }+        if (done == null) {+            // A shadow scanner that accepts startScan simply never reports; the+            // flow staying open without emitting is the other correct outcome.+            collected.cancel()+        } else {+            assertTrue(done.isSuccess, "scan flow must close, not fail: $done")+            assertTrue(done.getOrThrow().isEmpty())+        }+        Unit+    }++    @Test fun poweredOffScannerClosesOrIdlesWithoutBle() = runBlocking {+        val collected = async { runCatching { PoweredOffScanner(ctx).sightings().toList() } }+        val done = withTimeoutOrNull(4_000) { collected.await() }+        if (done == null) {+            collected.cancel()+        } else {+            assertTrue(done.isSuccess, "scan flow must close, not fail: $done")+            assertTrue(done.getOrThrow().isEmpty())+        }+        Unit+    }++    @Test fun provisionerScanClosesOrIdlesWithoutBle() = runBlocking {+        val collected = async { runCatching { TrackerProvisioner(ctx).unprovisioned().toList() } }+        val done = withTimeoutOrNull(4_000) { collected.await() }+        if (done == null) {+            collected.cancel()+        } else {+            assertTrue(done.isSuccess, "scan flow must close, not fail: $done")+            assertTrue(done.getOrThrow().isEmpty())+        }+        Unit+    }++    @Test fun provisionRejectsWrongSecretSize() = runBlocking {+        val manager = ctx.getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager+        val device = manager.adapter.getRemoteDevice("AA:BB:CC:DD:EE:FF")+        assertFailsWith<IllegalArgumentException> {+            TrackerProvisioner(ctx).provision(device, 1L, ByteArray(16))+        }+        Unit+    }++    @Test fun provisionToUnreachableDeviceReturnsFalse() = runBlocking {+        val manager = ctx.getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager+        val device = manager.adapter.getRemoteDevice("AA:BB:CC:DD:EE:FF")+        // The shadow GATT accepts the connection attempt and never calls back, so+        // the write can never report success; cancelling the attempt must settle+        // it as a failure (the invokeOnCancellation finish path), not a throw.+        val attempt = async { TrackerProvisioner(ctx).provision(device, 1L, ByteArray(32) { 7 }) }+        delay(1_500)+        attempt.cancel()+        assertEquals(false, runCatching { attempt.await() }.getOrElse { false })+        Unit+    }++    @Test fun binderPersistsNothingWhenProvisioningFails() = runBlocking {+        val repo = TestFindFamilyRepository.install(ctx)+        val manager = ctx.getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager+        val device = manager.adapter.getRemoteDevice("AA:BB:CC:DD:EE:FF")+        val attempt = async { TrackerBinder.bind(ctx, "Keys", device) }+        // Provisioning never completes in the sandbox; bind must not persist the+        // tracker up front (that ordering is the point of TrackerBinder), so even+        // mid-attempt the family list stays empty.+        delay(2_500)+        assertTrue(repo.getAllUsers().none { it.kind == UserKind.TRACKER })+        attempt.cancel()+        runCatching { attempt.await() }+        assertTrue(repo.getAllUsers().none { it.kind == UserKind.TRACKER })+        Unit+    }++    @Test fun trackerUuidsAreDistinct() {+        val uuids = listOf(+            TrackerBle.SERVICE_UUID,+            TrackerBle.UNPROVISIONED_SERVICE_UUID,+            TrackerBle.PROVISION_CHARACTERISTIC_UUID,+            TrackerBle.UWB_SESSION_CHARACTERISTIC_UUID,+        )+        assertEquals(uuids.size, uuids.toSet().size)+        assertFalse(TrackerBle.SERVICE_UUID == TrackerBle.UNPROVISIONED_SERVICE_UUID)+    }+}
findfamily/src/test/java/com/vayunmathur/findfamily/tracker/TrackerUwbGattEncodeTest.kt
diff --git a/findfamily/src/test/java/com/vayunmathur/findfamily/tracker/TrackerUwbGattEncodeTest.kt b/findfamily/src/test/java/com/vayunmathur/findfamily/tracker/TrackerUwbGattEncodeTest.ktnew file mode 100644index 0000000000..dc8f3b4fd4--- /dev/null+++ b/findfamily/src/test/java/com/vayunmathur/findfamily/tracker/TrackerUwbGattEncodeTest.kt@@ -0,0 +1,73 @@+package com.vayunmathur.findfamily.tracker++import com.vayunmathur.findfamily.domain.TrackerBle+import com.vayunmathur.findfamily.domain.UwbAccessoryProtocol+import com.vayunmathur.findfamily.platform.TrackerUwbGatt+import kotlin.test.Test+import kotlin.test.assertContentEquals+import kotlin.test.assertEquals+import kotlin.test.assertFailsWith++/** Pure byte-layout tests for the tracker UWB session-params frame and accessory stub. */+class TrackerUwbGattEncodeTest {++    @Test fun sessionParamsLayoutIsBigEndian() {+        val frame = TrackerUwbGatt.encodeSessionParams(+            TrackerUwbGatt.SessionParams(+                localAddress = byteArrayOf(0xAB.toByte(), 0xCD.toByte()),+                sessionId = 0x01020304,+                channelNumber = 9,+                preambleIndex = 10,+            )+        )+        assertContentEquals(+            byteArrayOf(0xAB.toByte(), 0xCD.toByte(), 1, 2, 3, 4, 9, 10),+            frame,+        )+    }++    @Test fun sessionParamsHandlesNegativeSessionId() {+        val frame = TrackerUwbGatt.encodeSessionParams(+            TrackerUwbGatt.SessionParams(byteArrayOf(0, 1), -1, 5, 6)+        )+        assertContentEquals(byteArrayOf(0, 1, -1, -1, -1, -1, 5, 6), frame)+    }++    @Test fun sessionParamsRejectsWrongAddressSize() {+        assertFailsWith<IllegalArgumentException> {+            TrackerUwbGatt.encodeSessionParams(+                TrackerUwbGatt.SessionParams(byteArrayOf(1), 1, 9, 10)+            )+        }+        assertFailsWith<IllegalArgumentException> {+            TrackerUwbGatt.encodeSessionParams(+                TrackerUwbGatt.SessionParams(byteArrayOf(1, 2, 3), 1, 9, 10)+            )+        }+    }++    @Test fun trackerBleConstantsMatchFirmwareContract() {+        assertEquals(48, TrackerBle.PROVISION_BLOB_LEN)+        assertEquals(40, TrackerBle.PROVISION_BLOB_LEN_NO_TIME)+        assertEquals(+            TrackerBle.PROVISION_BLOB_LEN - 8,+            TrackerBle.PROVISION_BLOB_LEN_NO_TIME,+        )+    }++    @Test fun accessoryConfigIsVersionPrefixPlusAddress() {+        val addr = byteArrayOf(9, 8)+        assertContentEquals(+            byteArrayOf(0x01, 0x00, 9, 8),+            UwbAccessoryProtocol.encodeAccessoryConfigurationData(addr),+        )+    }++    @Test fun shareableConfigParseIsStillStubbed() {+        // The Apple accessory byte format is not implemented yet; callers rely on+        // this throwing so the session fails closed instead of ranging on garbage.+        assertFailsWith<NotImplementedError> {+            UwbAccessoryProtocol.parseShareableConfigurationData(byteArrayOf(1, 2, 3))+        }+    }+}
findfamily/src/test/java/com/vayunmathur/findfamily/util/CrowdFindingAndControllerTest.kt
diff --git a/findfamily/src/test/java/com/vayunmathur/findfamily/util/CrowdFindingAndControllerTest.kt b/findfamily/src/test/java/com/vayunmathur/findfamily/util/CrowdFindingAndControllerTest.ktnew file mode 100644index 0000000000..51b5761ed4--- /dev/null+++ b/findfamily/src/test/java/com/vayunmathur/findfamily/util/CrowdFindingAndControllerTest.kt@@ -0,0 +1,183 @@+package com.vayunmathur.findfamily.util++import android.Manifest+import android.app.Application+import android.content.Context+import android.content.pm.PackageManager+import android.os.BatteryManager+import androidx.test.core.app.ApplicationProvider+import androidx.test.ext.junit.runners.AndroidJUnit4+import com.vayunmathur.findfamily.data.DirectBootStore+import com.vayunmathur.findfamily.data.PoweredOffKeyStore+import com.vayunmathur.findfamily.data.RequestStatus+import com.vayunmathur.findfamily.data.TestFindFamilyRepository+import com.vayunmathur.findfamily.data.TrackerStore+import com.vayunmathur.findfamily.data.User+import com.vayunmathur.findfamily.data.UserKind+import com.vayunmathur.findfamily.data.awaitFamilyCondition+import com.vayunmathur.findfamily.platform.LocationServiceController+import com.vayunmathur.findfamily.platform.LocationTrackingService+import com.vayunmathur.findfamily.platform.pollPoweredOffSightings+import com.vayunmathur.findfamily.platform.pollTrackerReports+import com.vayunmathur.findfamily.platform.startPoweredOffScanner+import com.vayunmathur.findfamily.platform.startTrackerScanner+import com.vayunmathur.library.util.DataStoreUtils+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.async+import kotlinx.coroutines.flow.first+import kotlinx.coroutines.runBlocking+import org.junit.runner.RunWith+import org.robolectric.Robolectric+import org.robolectric.Shadows+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue+import kotlin.time.Clock++/**+ * Crowd-finding owner polls + [LocationServiceController] switches against the real+ * in-memory repository. With no relay socket every network call fails closed, so the+ * polls must complete with nothing stored and nothing thrown.+ */+@RunWith(AndroidJUnit4::class)+class CrowdFindingAndControllerTest {++    private val app: Application get() = ApplicationProvider.getApplicationContext()+    private val ctx: Context get() = app+    private lateinit var service: LocationTrackingService++    @BeforeTest+    fun setup() {+        runCatching {+            androidx.work.WorkManager.initialize(+                ctx, androidx.work.Configuration.Builder().build()+            )+        }+        service = Robolectric.buildService(LocationTrackingService::class.java).create().get()+        service.repositoryOverride = TestFindFamilyRepository.install(ctx)+        service.bm = ctx.getSystemService(BatteryManager::class.java)+    }++    private fun user(kind: UserKind): User = User(+        name = "U-$kind",+        photo = null,+        locationName = "Home",+        sendingEnabled = false,+        requestStatus = RequestStatus.MUTUAL_CONNECTION,+        lastLocationChangeTime = Clock.System.now(),+        kind = kind,+    )++    @Test fun trackerPollWithNoStoreAndNoTrackersIsNoOp() = runBlocking {+        service.trackerStore = null+        service.pollTrackerReports()+        service.trackerStore = TrackerStore(DataStoreUtils.getInstance(ctx))+        // Repository has no tracker rows yet.+        service.pollTrackerReports()+        val repo = service.repository+        val trackerId = repo.upsertUser(user(UserKind.TRACKER))+        // Tracker row exists but no secret/bundle on file: register + fetch both+        // fail closed and nothing reaches the location table.+        service.pollTrackerReports()+        assertTrue(repo.locationHistory(trackerId).first().isEmpty())+        // A person row is ignored by the tracker poll entirely.+        repo.upsertUser(user(UserKind.PERSON))+        service.pollTrackerReports()+        Unit+    }++    @Test fun poweredOffPollRespectsRateLimitAndMissingKeys() = runBlocking {+        service.poweredOffKeys = null+        service.pollPoweredOffSightings()+        val store = PoweredOffKeyStore(DirectBootStore.store(ctx))+        service.poweredOffKeys = store+        service.lastPoweredOffPollMs = 0L+        val repo = service.repository+        val peerId = repo.upsertUser(user(UserKind.PERSON))+        // No keys held for the peer: skipped.+        service.pollPoweredOffSightings()+        // Immediate second poll is rate-limited (5-minute interval).+        service.pollPoweredOffSightings()+        // Keys held but no socket: fetch comes back empty, nothing stored.+        store.save(peerId, ByteArray(32) { 3 }, ByteArray(8) { 4 }, epoch = 1L)+        service.lastPoweredOffPollMs = 0L+        service.pollPoweredOffSightings()+        assertTrue(repo.locationHistory(peerId).first().isEmpty())+    }++    @Test fun scannersStartAndStopWithoutBle() = runBlocking {+        service.startTrackerScanner()+        service.startPoweredOffScanner()+        // Starting twice is a no-op while the jobs are alive (or already done:+        // with no BLE scanner both flows close immediately, which is also fine).+        service.startTrackerScanner()+        service.startPoweredOffScanner()+        assertTrue(+            awaitFamilyCondition(5_000) {+                (service.trackerScanJob?.isCompleted ?: true) ||+                    (service.trackerScanJob?.isActive ?: false)+            }+        )+        service.trackerScanJob?.cancel()+        service.poweredOffScanJob?.cancel()+        Unit+    }++    @Test fun controllerSwitchesAndPermissionGate() = runBlocking {+        // No permission granted in the sandbox by default.+        Shadows.shadowOf(app).denyPermissions(Manifest.permission.ACCESS_FINE_LOCATION)+        assertFalse(LocationServiceController.hasFineLocationPermission(ctx))+        assertEquals(+            PackageManager.PERMISSION_DENIED,+            androidx.core.content.ContextCompat.checkSelfPermission(+                ctx, Manifest.permission.ACCESS_FINE_LOCATION+            ),+        )+        Shadows.shadowOf(app).grantPermissions(Manifest.permission.ACCESS_FINE_LOCATION)+        assertTrue(LocationServiceController.hasFineLocationPermission(ctx))++        // Tracking defaults on, persists, and drives syncServiceState off the+        // main thread (syncServiceState hops to Dispatchers.Main internally).+        assertTrue(LocationServiceController.isTrackingEnabled(ctx))+        val toggle = async(Dispatchers.IO) {+            LocationServiceController.setTrackingEnabled(ctx, false)+        }+        assertTrue(awaitFamilyCondition(5_000) { toggle.isCompleted })+        toggle.await()+        assertFalse(LocationServiceController.isTrackingEnabled(ctx))+        val toggleBack = async(Dispatchers.IO) {+            LocationServiceController.setTrackingEnabled(ctx, true)+        }+        assertTrue(awaitFamilyCondition(5_000) { toggleBack.isCompleted })+        toggleBack.await()+        assertTrue(LocationServiceController.isTrackingEnabled(ctx))++        // Sharing defaults on and persists independently of tracking.+        assertTrue(LocationServiceController.isGlobalSharingEnabled(ctx))+        LocationServiceController.setGlobalSharingEnabled(ctx, false)+        assertFalse(LocationServiceController.isGlobalSharingEnabled(ctx))+        assertFalse(LocationServiceController.globalSharingEnabledFlow(ctx).first())+        LocationServiceController.setGlobalSharingEnabled(ctx, true)+        assertTrue(LocationServiceController.globalSharingEnabledFlow(ctx).first())++        // Crowd finding is mandatory-true now.+        assertTrue(LocationServiceController.crowdFindingEnabledFlow(ctx).first())+        LocationServiceController.setCrowdFindingEnabled(ctx, false)+        assertTrue(LocationServiceController.crowdFindingEnabledFlow(ctx).first())++        // Nobody else is sharing yet (only rows in the DB count, self excluded).+        assertFalse(LocationServiceController.isSharingEnabled(ctx))+        LocationServiceController.stop(ctx)+        // Locked (pre-unlock) sync: unseeded mirror or missing permission -> no-op.+        val locked = async(Dispatchers.IO) { LocationServiceController.syncServiceStateLocked(ctx) }+        assertTrue(awaitFamilyCondition(5_000) { locked.isCompleted })+        locked.await()+        Shadows.shadowOf(app).denyPermissions(Manifest.permission.ACCESS_FINE_LOCATION)+        val locked2 = async(Dispatchers.IO) { LocationServiceController.syncServiceStateLocked(ctx) }+        assertTrue(awaitFamilyCondition(5_000) { locked2.isCompleted })+        locked2.await()+        Unit+    }+}
findfamily/src/test/java/com/vayunmathur/findfamily/util/NetworkingDirectBootBootstrapTest.kt
diff --git a/findfamily/src/test/java/com/vayunmathur/findfamily/util/NetworkingDirectBootBootstrapTest.kt b/findfamily/src/test/java/com/vayunmathur/findfamily/util/NetworkingDirectBootBootstrapTest.ktnew file mode 100644index 0000000000..e2333f6a75--- /dev/null+++ b/findfamily/src/test/java/com/vayunmathur/findfamily/util/NetworkingDirectBootBootstrapTest.kt@@ -0,0 +1,61 @@+package com.vayunmathur.findfamily.util++import androidx.test.core.app.ApplicationProvider+import androidx.test.ext.junit.runners.AndroidJUnit4+import com.vayunmathur.findfamily.data.DirectBootStore+import com.vayunmathur.findfamily.data.TestFindFamilyRepository+import com.vayunmathur.findfamily.network.Networking+import com.vayunmathur.library.util.DataStoreUtils+import kotlinx.coroutines.runBlocking+import org.junit.runner.RunWith+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNotNull+import kotlin.test.assertTrue++/**+ * Direct-boot identity bootstrap in a fresh sandbox (Networking's one-shot init+ * flags make this order-dependent with any other Networking test, so it lives+ * alone): [Networking.initDirectBoot] loads the identity from the+ * device-protected mirror without minting anything, and+ * [Networking.promoteToUnlocked] hands over to the credential-encrypted store.+ */+@RunWith(AndroidJUnit4::class)+class NetworkingDirectBootBootstrapTest {++    private val ctx get() = ApplicationProvider.getApplicationContext<android.content.Context>()++    @Test fun directBootBootstrapAndPromote() = runBlocking {+        val repo = TestFindFamilyRepository.install(ctx)+        // Unseeded mirror (fresh sandbox): initDirectBoot must refuse rather+        // than mint an identity. Seed the userid, then it must bootstrap.+        val mirror = DirectBootStore.store(ctx)+        mirror.setLong("userid", 313_131L, true)+        assertTrue(Networking.initDirectBoot(mirror), "seeded mirror must bootstrap")+        assertTrue(Networking.inDirectBootMode)+        assertEquals(313_131L, Networking.userid)+        // Second call is a no-op reporting the current mode.+        assertTrue(Networking.initDirectBoot(mirror))+        // Promote to the unlocked store: mode clears and the full init runs.+        val ce = DataStoreUtils.getInstance(ctx)+        if (ce.getLongAwait("userid") == null) ce.setLong("userid", 313_131L, true)+        Networking.promoteToUnlocked(repo, ce, "Me")+        assertFalse(Networking.inDirectBootMode)+        assertEquals(313_131L, Networking.userid)+        assertNotNull(repo.getUser(313_131L))+        Unit+    }++    @Test fun unseededMirrorRefusesToBootstrap() = runBlocking {+        // This sandbox may already have bootstrapped via the sibling test; the+        // refusal branch is only observable before any init. Guard accordingly:+        // with no userid in a *different*, empty store, initDirectBoot is either+        // refused (fresh) or reports the already-running mode (not a mint).+        val empty = DirectBootStore.store(ctx)+        if (!Networking.inDirectBootMode && Networking.userid == 0L) {+            assertFalse(Networking.initDirectBoot(empty))+        }+        Unit+    }+}
findfamily/src/test/java/com/vayunmathur/findfamily/util/NetworkingDirectBootTest.kt
diff --git a/findfamily/src/test/java/com/vayunmathur/findfamily/util/NetworkingDirectBootTest.kt b/findfamily/src/test/java/com/vayunmathur/findfamily/util/NetworkingDirectBootTest.ktnew file mode 100644index 0000000000..6d9c79bd8d--- /dev/null+++ b/findfamily/src/test/java/com/vayunmathur/findfamily/util/NetworkingDirectBootTest.kt@@ -0,0 +1,123 @@+package com.vayunmathur.findfamily.util++import androidx.test.core.app.ApplicationProvider+import androidx.test.ext.junit.runners.AndroidJUnit4+import com.vayunmathur.findfamily.data.Coord+import com.vayunmathur.findfamily.data.LocationValue+import com.vayunmathur.findfamily.data.RequestStatus+import com.vayunmathur.findfamily.data.TestFindFamilyRepository+import com.vayunmathur.findfamily.data.User+import com.vayunmathur.findfamily.network.Networking+import com.vayunmathur.library.network.WebSocketClient+import com.vayunmathur.library.network.WsSession+import com.vayunmathur.library.util.DataStoreUtils+import java.io.ByteArrayInputStream+import java.io.ByteArrayOutputStream+import java.net.Socket+import kotlin.io.encoding.Base64+import kotlinx.coroutines.runBlocking+import org.junit.runner.RunWith+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue+import kotlin.time.Clock++/**+ * Direct-boot identity bootstrap ([Networking.initDirectBoot] /+ * [Networking.promoteToUnlocked]) and the malformed-peer-bundle behaviour of the+ * publish path: a corrupt stored bundle must read as "no usable bundle"+ * (false/null), never as an exception escaping toward the heartbeat.+ */+@RunWith(AndroidJUnit4::class)+class NetworkingDirectBootTest {++    private val ctx get() = ApplicationProvider.getApplicationContext<android.content.Context>()++    @BeforeTest+    fun setup() = runBlocking {+        Networking.stopLive()+        val repo = TestFindFamilyRepository.install(ctx)+        Networking.repository = repo+        Unit+    }++    private fun fakeSession(output: ByteArrayOutputStream): WsSession {+        val clientConstructor = WebSocketClient::class.java+            .getDeclaredConstructor(+                Socket::class.java, java.io.InputStream::class.java,+                java.io.OutputStream::class.java, Map::class.java, Map::class.java,+            ).apply { isAccessible = true }+        val client = clientConstructor.newInstance(+            Socket(), ByteArrayInputStream(ByteArray(0)), output,+            emptyMap<String, List<String>>(), emptyMap<String, String>(),+        )+        val sessionConstructor = WsSession::class.java+            .getDeclaredConstructor(WebSocketClient::class.java)+            .apply { isAccessible = true }+        return sessionConstructor.newInstance(client)+    }++    private fun peer(id: Long, bundle: String?, outboundPairId: String? = "pair-x") = User(+        name = "Peer",+        photo = null,+        locationName = "Home",+        sendingEnabled = true,+        requestStatus = RequestStatus.MUTUAL_CONNECTION,+        lastLocationChangeTime = Clock.System.now(),+        id = id,+        pqcEncryptionKey = bundle,+        outboundPairId = outboundPairId,+    )++    private fun fix() = LocationValue(+        userid = Networking.userid,+        coord = Coord(1.0, 2.0),+        speed = 0f,+        acc = 5f,+        timestamp = Clock.System.now(),+        battery = 50f,+    )++    @Test fun malformedPeerBundleFailsClosed() = runBlocking {+        val repo = TestFindFamilyRepository.install(ctx)+        Networking.repository = repo+        Networking.init(repo, DataStoreUtils.getInstance(ctx), "Me")+        assertTrue(Networking.pqcReady)+        val bad = peer(901L, bundle = "!!!not-base64!!!")+        repo.upsertUser(bad)+        // Documented contract: publish returns false when the peer has no usable+        // bundle; a corrupt stored value is exactly that, not an exception.+        assertFalse(Networking.publishLocation(fix(), bad))+        assertNull(Networking.securityCode(bad))+        assertNull(Networking.securityCodePqc(bad))+        val envelope = com.vayunmathur.findfamily.domain.UwbEnvelope(+            sessionId = "s", sender = 1uL, senderPlatform = "android", kind = "request"+        )+        assertFalse(Networking.publishUwbMessage(envelope, 901L, bad))+        Unit+    }++    @Test fun outboundPairIdIsGeneratedOnceAndReused() = runBlocking {+        val repo = TestFindFamilyRepository.install(ctx)+        Networking.repository = repo+        Networking.init(repo, DataStoreUtils.getInstance(ctx), "Me")+        val out = ByteArrayOutputStream()+        Networking.wsSession = fakeSession(out)+        val bundle = Base64.encode(Networking.pqcIdentity.publicBundle)+        val id = repo.upsertUser(peer(0L, bundle = bundle, outboundPairId = null).copy(name = "Peer"))+        val stored = repo.getUser(id)!!+        assertNull(stored.outboundPairId)+        assertTrue(Networking.publishLocation(fix(), stored))+        val generated = repo.getUser(id)!!.outboundPairId+        assertNotNull(generated)+        // Second publish reuses the pinned value instead of rotating it.+        out.reset()+        assertTrue(Networking.publishLocation(fix(), repo.getUser(id)!!))+        assertEquals(generated, repo.getUser(id)!!.outboundPairId)+        Networking.wsSession = null+    }+}
findfamily/src/test/java/com/vayunmathur/findfamily/util/TrackingServiceLifecycleTest.kt
diff --git a/findfamily/src/test/java/com/vayunmathur/findfamily/util/TrackingServiceLifecycleTest.kt b/findfamily/src/test/java/com/vayunmathur/findfamily/util/TrackingServiceLifecycleTest.ktnew file mode 100644index 0000000000..736c977bdf--- /dev/null+++ b/findfamily/src/test/java/com/vayunmathur/findfamily/util/TrackingServiceLifecycleTest.kt@@ -0,0 +1,103 @@+package com.vayunmathur.findfamily.util++import android.Manifest+import android.app.Application+import android.content.Context+import android.location.Location+import android.location.LocationManager+import android.os.BatteryManager+import androidx.test.core.app.ApplicationProvider+import androidx.test.ext.junit.runners.AndroidJUnit4+import androidx.work.ListenableWorker+import androidx.work.testing.TestListenableWorkerBuilder+import com.vayunmathur.findfamily.data.TestFindFamilyRepository+import com.vayunmathur.findfamily.data.awaitFamilyCondition+import com.vayunmathur.findfamily.platform.LocationTrackingService+import com.vayunmathur.findfamily.platform.ServiceRestartWorker+import com.vayunmathur.findfamily.platform.ensureSync+import com.vayunmathur.findfamily.platform.fetchAddress+import com.vayunmathur.findfamily.platform.onLocationFix+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.async+import kotlinx.coroutines.runBlocking+import org.junit.runner.RunWith+import org.robolectric.Robolectric+import org.robolectric.Shadows+import org.robolectric.android.controller.ServiceController+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNull+import kotlin.test.assertTrue++/**+ * Full [LocationTrackingService] lifecycle in the sandbox: startTracking brings up+ * sensors/location requests, a fix flows through intake, and destroy tears down+ * without touching uninitialized lateinit state. No relay is reachable, so the+ * live loop simply retries in the background for the life of the test.+ */+@RunWith(AndroidJUnit4::class)+class TrackingServiceLifecycleTest {++    private val app: Application get() = ApplicationProvider.getApplicationContext()+    private val ctx: Context get() = app+    private lateinit var controller: ServiceController<LocationTrackingService>+    private lateinit var service: LocationTrackingService++    @BeforeTest+    fun setup() {+        runCatching {+            androidx.work.WorkManager.initialize(ctx, androidx.work.Configuration.Builder().build())+        }+        Shadows.shadowOf(app).grantPermissions(Manifest.permission.ACCESS_FINE_LOCATION)+        controller = Robolectric.buildService(LocationTrackingService::class.java)+        service = controller.create().get()+        service.repositoryOverride = TestFindFamilyRepository.install(ctx)+        service.bm = ctx.getSystemService(BatteryManager::class.java)+        service.locationManager = ctx.getSystemService(LocationManager::class.java)+        service.powerManager = ctx.getSystemService(android.os.PowerManager::class.java)+    }++    @Test fun startTrackingRegistersAndDestroysCleanly() = runBlocking {+        service.startTracking()+        assertTrue(+            awaitFamilyCondition(10_000) { service.trackingInitialized },+            "startTracking must finish initialization",+        )+        // Idempotent re-entry: a second start does not re-initialize.+        service.startTracking()+        service.registerSensors()+        service.setupLocationUpdates()+        val fix = Location(LocationManager.GPS_PROVIDER).apply {+            latitude = 37.0; longitude = -122.0; accuracy = 5f+            time = System.currentTimeMillis()+            elapsedRealtimeNanos = System.nanoTime()+        }+        service.onLocationFix(fix)+        assertEquals(37.0, service.lastKnownLocation?.latitude)+        controller.destroy()+        Unit+    }++    @Test fun destroyWithoutStartIsClean() {+        // Destroying a service that never started tracking must not throw on the+        // guarded lateinit sensor/location managers.+        controller.destroy()+    }++    @Test fun restartWorkerReconcilesAndEnsureSyncEnqueues() = runBlocking {+        val worker = TestListenableWorkerBuilder<ServiceRestartWorker>(ctx).build()+        val result = async(Dispatchers.IO) { worker.doWork() }+        assertTrue(awaitFamilyCondition(10_000) { result.isCompleted })+        assertEquals(ListenableWorker.Result.success(), result.await())+        // Enqueueing the periodic reconcile must not throw with WorkManager up.+        ensureSync(ctx)+        Unit+    }++    @Test fun fetchAddressWithoutGeocoderBackendIsNull() = runBlocking {+        // Robolectric has no geocode backend: a null result, never a hang or throw.+        assertNull(ctx.fetchAddress(37.0, -122.0))+        Unit+    }+}