Modern Apps git

← Modern-Apps.git

auto: add tests for channels, display, services and UI

Commit
3f2c10a1efce49c046976c5ab5da1563c6c2a0dd
Author
Vayun Mathur <[email protected]>
When
2026-11-07 03:17 UTC (29 days ago)
Parents
ebbebb3
Covers the GAL channel owners (audio/video/input/sensor/guidance/mic), CarDisplay/CarPresentation rendering under Robolectric, HostSession/HostManager hosting, messaging/telephony/small services, connectors, monitors, capture/TTS, and the phone-side Compose screens (AutoScreen, LauncherRoot, Pairing, pinned apps) plus their view models.

Coverage (merged, instructions): 42.6% -> 60.9% (14591/34267 -> 20874/34267) at session start; the module began this branch with 3 test files. Full suite passes (259 tests) via gslot ./gradlew :auto:createMergedCoverageReport.

Bugs fixed: none. Untestable remainder: ProjectionService session loop and HostSession binder round-trips (need a live head unit / bound car app), WifiDirect/USB accessory hardware paths, VideoSinkChannel streaming start (shadow MediaCodec vends no input surface), and privileged car services; their surrounding logic is covered. Note: PinnedAppsPrefs synchronous mirror can lag DataStore edits under load, which made its existing tests flaky in full-suite runs until the new view-model tests were made to land edits with runBlocking.

(cherry picked from commit e45aaaff9625c7f89d02d69ca70cbb1bc1f005fe)

Diff

auto/src/test/java/com/vayunmathur/auto/NavigationAndTelephonyTest.kt
diff --git a/auto/src/test/java/com/vayunmathur/auto/NavigationAndTelephonyTest.kt b/auto/src/test/java/com/vayunmathur/auto/NavigationAndTelephonyTest.ktnew file mode 100644index 0000000000..f0d33302a9--- /dev/null+++ b/auto/src/test/java/com/vayunmathur/auto/NavigationAndTelephonyTest.kt@@ -0,0 +1,47 @@+package com.vayunmathur.auto++import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onNodeWithText+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.auto.platform.AutoSessionState+import com.vayunmathur.auto.platform.AutoViewModel+import com.vayunmathur.auto.platform.PairingViewModel+import com.vayunmathur.auto.telephony.CarProjectionInCallService+import com.vayunmathur.auto.R as AutoR+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNull++@RunWith(RobolectricTestRunner::class)+class NavigationAndTelephonyTest {+    @get:Rule val rule = createComposeRule()+    private val ctx get() = ApplicationProvider.getApplicationContext<android.content.Context>()++    @BeforeTest fun reset() { AutoSessionState.onDisconnected() }++    @Test fun `navigation home renders the auto screen`() {+        rule.setContent { Navigation(AutoViewModel(), PairingViewModel()) }+        rule.onNodeWithText(ctx.getString(AutoR.string.state_disconnected)).assertExists()+        rule.onNodeWithText(ctx.getString(AutoR.string.connect_hint)).assertExists()+    }++    @Test fun `route objects are distinct nav keys`() {+        assertEquals(Route.Home, Route.Home)+        assertEquals(true, Route.Pairing != Route.Home)+        assertEquals(true, Route.PinnedApps != Route.Pairing)+    }++    @Test fun `in-call companion actions with nothing bound are no-ops`() {+        assertNull(CarProjectionInCallService.current)+        CarProjectionInCallService.answerCall()+        CarProjectionInCallService.endCall()+        CarProjectionInCallService.toggleHold()+        CarProjectionInCallService.toggleMute()+        assertNull(CarProjectionInCallService.current)+        assertNull(AutoSessionState.activeCall.value)+    }+}
auto/src/test/java/com/vayunmathur/auto/data/PinnedAppsPrefsTest.kt
diff --git a/auto/src/test/java/com/vayunmathur/auto/data/PinnedAppsPrefsTest.kt b/auto/src/test/java/com/vayunmathur/auto/data/PinnedAppsPrefsTest.ktnew file mode 100644index 0000000000..13449fab69--- /dev/null+++ b/auto/src/test/java/com/vayunmathur/auto/data/PinnedAppsPrefsTest.kt@@ -0,0 +1,77 @@+package com.vayunmathur.auto.data++import androidx.test.core.app.ApplicationProvider+import kotlinx.coroutines.flow.first+import kotlinx.coroutines.test.runTest+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue++/**+ * Auto module: [PinnedAppsPrefs] — the car dock's pinned order. Empty until+ * the user pins; writes truncate to [PinnedAppsPrefs.MAX_PINNED]; stale ids+ * never appear by construction (the UI intersects on load).+ */+@RunWith(RobolectricTestRunner::class)+class PinnedAppsPrefsTest {++    private val context: android.content.Context+        get() = ApplicationProvider.getApplicationContext()++    @Test+    fun `empty until the user pins something`() = runTest {+        PinnedAppsPrefs.setPinned(context, emptyList())+        assertEquals(emptyList(), PinnedAppsPrefs.pinnedNow(context))+        assertEquals(emptyList(), PinnedAppsPrefs.pinnedFlow(context).first())+    }++    @Test+    fun `pin order round-trips through the flow`() = runTest {+        val ids = listOf("com.a/.Car", "com.b/.Car")+        PinnedAppsPrefs.setPinned(context, ids)+        assertEquals(ids, PinnedAppsPrefs.pinnedNow(context))+        assertEquals(ids, PinnedAppsPrefs.pinnedFlow(context).first())+        PinnedAppsPrefs.setPinned(context, emptyList())+    }++    @Test+    fun `writes truncate to the max dock size`() = runTest {+        val ids = (1..8).map { "com.app$it/.Car" }+        PinnedAppsPrefs.setPinned(context, ids)+        assertEquals(ids.take(PinnedAppsPrefs.MAX_PINNED), PinnedAppsPrefs.pinnedNow(context))+        PinnedAppsPrefs.setPinned(context, emptyList())+    }++    @Test+    fun `pin appends and rejects when full`() = runTest {+        PinnedAppsPrefs.setPinned(context, emptyList())+        assertTrue(PinnedAppsPrefs.pin(context, "com.a/.Car"))+        // Re-pinning is a no-op success.+        assertTrue(PinnedAppsPrefs.pin(context, "com.a/.Car"))+        assertEquals(listOf("com.a/.Car"), PinnedAppsPrefs.pinnedNow(context))+        PinnedAppsPrefs.setPinned(context, (1..PinnedAppsPrefs.MAX_PINNED).map { "com.app$it/.Car" })+        assertFalse(PinnedAppsPrefs.pin(context, "com.full/.Car"))+        assertEquals(PinnedAppsPrefs.MAX_PINNED, PinnedAppsPrefs.pinnedNow(context).size)+        PinnedAppsPrefs.setPinned(context, emptyList())+    }++    @Test+    fun `unpin and move reorder the dock`() = runTest {+        PinnedAppsPrefs.setPinned(context, listOf("a", "b", "c"))+        PinnedAppsPrefs.unpin(context, "b")+        assertEquals(listOf("a", "c"), PinnedAppsPrefs.pinnedNow(context))+        // Unpinning an absent id is a no-op.+        PinnedAppsPrefs.unpin(context, "zzz")+        assertEquals(listOf("a", "c"), PinnedAppsPrefs.pinnedNow(context))+        PinnedAppsPrefs.move(context, "c", 0)+        assertEquals(listOf("c", "a"), PinnedAppsPrefs.pinnedNow(context))+        // Moving an absent id is a no-op; out-of-range indices clamp.+        PinnedAppsPrefs.move(context, "zzz", 0)+        PinnedAppsPrefs.move(context, "a", 99)+        assertEquals(listOf("c", "a"), PinnedAppsPrefs.pinnedNow(context))+        PinnedAppsPrefs.setPinned(context, emptyList())+    }+}
auto/src/test/java/com/vayunmathur/auto/domain/PinnedAppsViewModelTest.kt
diff --git a/auto/src/test/java/com/vayunmathur/auto/domain/PinnedAppsViewModelTest.kt b/auto/src/test/java/com/vayunmathur/auto/domain/PinnedAppsViewModelTest.ktnew file mode 100644index 0000000000..a734285e17--- /dev/null+++ b/auto/src/test/java/com/vayunmathur/auto/domain/PinnedAppsViewModelTest.kt@@ -0,0 +1,82 @@+package com.vayunmathur.auto.domain++import android.app.Application+import androidx.lifecycle.ViewModelProvider+import androidx.lifecycle.ViewModelStore+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.auto.data.PinnedAppsPrefs+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.ExperimentalCoroutinesApi+import kotlinx.coroutines.flow.collect+import kotlinx.coroutines.launch+import kotlinx.coroutines.runBlocking+import kotlinx.coroutines.test.resetMain+import kotlinx.coroutines.test.setMain+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import kotlin.test.AfterTest+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNull+import kotlin.test.assertTrue++@OptIn(ExperimentalCoroutinesApi::class)+@RunWith(RobolectricTestRunner::class)+class PinnedAppsViewModelTest {+    private val app get() = ApplicationProvider.getApplicationContext<Application>()+    private val ctx get() = ApplicationProvider.getApplicationContext<android.content.Context>()+    private var store = ViewModelStore()++    @BeforeTest fun setUp() { Dispatchers.setMain(Dispatchers.Unconfined) }++    // runBlocking (not runTest) so DataStore edits on IO actually land before+    // the next test class in this JVM reads the synchronous mirror.+    @AfterTest fun tearDown() = runBlocking {+        store.clear()+        PinnedAppsPrefs.setPinned(ctx, emptyList())+        Dispatchers.resetMain()+    }++    private fun vm(): PinnedAppsViewModel {+        store = ViewModelStore()+        return ViewModelProvider(store, object : ViewModelProvider.Factory {+            @Suppress("UNCHECKED_CAST")+            override fun <T : androidx.lifecycle.ViewModel> create(modelClass: Class<T>): T =+                PinnedAppsViewModel(app) as T+        })[PinnedAppsViewModel::class.java]+    }++    @Test fun `defaults are empty with no discovered apps`() = runBlocking {+        PinnedAppsPrefs.setPinned(ctx, emptyList())+        val vm = vm()+        assertEquals(emptyList(), vm.allApps.value)+        assertNull(vm.rejected.value)+    }++    @Test fun `pinned ids flow through while subscribed and rejection clears`() = runBlocking {+        PinnedAppsPrefs.setPinned(ctx, listOf("com.a/.Car"))+        val vm = vm()+        val job = CoroutineScope(Dispatchers.Unconfined).launch { vm.pinnedIds.collect() }+        try {+            assertEquals(listOf("com.a/.Car"), vm.pinnedIds.value)+        } finally { job.cancel() }+        vm.consumeRejected()+        assertNull(vm.rejected.value)+        assertTrue(vm.rows.value.isEmpty())+    }++    @Test fun `move on absent or first ids writes nothing`() = runBlocking {+        PinnedAppsPrefs.setPinned(ctx, listOf("a", "b"))+        val vm = vm()+        vm.moveUp("zzz"); vm.moveDown("zzz"); vm.moveUp("a")+        assertEquals(listOf("a", "b"), PinnedAppsPrefs.pinnedNow(ctx))+    }++    @Test fun `refresh keeps empty discovery on this device`() = runBlocking {+        val vm = vm()+        vm.refresh()+        assertEquals(emptyList(), vm.allApps.value)+    }+}
auto/src/test/java/com/vayunmathur/auto/network/ConnectorsTest.kt
diff --git a/auto/src/test/java/com/vayunmathur/auto/network/ConnectorsTest.kt b/auto/src/test/java/com/vayunmathur/auto/network/ConnectorsTest.ktnew file mode 100644index 0000000000..bb55b1e7de--- /dev/null+++ b/auto/src/test/java/com/vayunmathur/auto/network/ConnectorsTest.kt@@ -0,0 +1,54 @@+package com.vayunmathur.auto.network++import android.content.Context+import android.content.Intent+import android.hardware.usb.UsbManager+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.auto.platform.TransportState+import com.vayunmathur.auto.protocol.UsbSessionState+import com.vayunmathur.auto.protocol.WirelessSessionState+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue++@RunWith(RobolectricTestRunner::class)+class ConnectorsTest {+    private val ctx get() = ApplicationProvider.getApplicationContext<Context>()++    @Test fun `usb unrelated and missing-accessory intents are not consumed`() {+        assertFalse(UsbConnector.onAccessoryIntent(ctx, Intent("com.example.OTHER")))+        assertFalse(UsbConnector.onAccessoryIntent(ctx, Intent(UsbManager.ACTION_USB_ACCESSORY_ATTACHED)))+    }++    @Test fun `usb detach is consumed and publishes detached`() {+        assertTrue(UsbConnector.onAccessoryIntent(ctx, Intent(UsbManager.ACTION_USB_ACCESSORY_DETACHED)))+        assertEquals(UsbSessionState.DETACHED, TransportState.usbState.value)+    }++    @Test fun `usb force start with no accessory and permission edge cases`() {+        UsbConnector.forceStart(ctx) // no accessory seen: ignored, no crash+        assertFalse(UsbConnector.onPermissionResult(ctx, Intent("com.example.OTHER")))+        assertTrue(UsbConnector.onPermissionResult(ctx, Intent(UsbConnector.ACTION_USB_PERMISSION)))+        // denied / no accessory publishes denied-or-detached state without opening+        assertTrue(TransportState.usbState.value == UsbSessionState.DETACHED || TransportState.usbState.value == UsbSessionState.PERMISSION_DENIED)+        UsbConnector.retryPermission(ctx) // no accessory: no-op+    }++    @Test fun `wifi cancel when idle resets wireless state`() {+        WifiDirectConnector.cancel()+        assertEquals(WirelessSessionState.IDLE, TransportState.wirelessState.value)+        // connection-changed with no network info is ignored+        WifiDirectConnector.onConnectionChanged(Intent("x"))+        assertEquals(WirelessSessionState.IDLE, TransportState.wirelessState.value)+    }++    @Test fun `wifi request hidden network without start is safe`() {+        WifiDirectConnector.requestHiddenNetwork("CarSSID", "secret-pass")+        // appContext is set only via start(); without it this is a no-op, with it a framework request+        WifiDirectConnector.cancel()+        assertEquals(WirelessSessionState.IDLE, TransportState.wirelessState.value)+    }+}
auto/src/test/java/com/vayunmathur/auto/network/HeadUnitServerTest.kt
diff --git a/auto/src/test/java/com/vayunmathur/auto/network/HeadUnitServerTest.kt b/auto/src/test/java/com/vayunmathur/auto/network/HeadUnitServerTest.ktnew file mode 100644index 0000000000..81e670d0d5--- /dev/null+++ b/auto/src/test/java/com/vayunmathur/auto/network/HeadUnitServerTest.kt@@ -0,0 +1,57 @@+package com.vayunmathur.auto.network++import java.net.ServerSocket+import java.net.Socket+import java.util.concurrent.Executors+import java.util.concurrent.TimeUnit+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++/**+ * Auto module: [HeadUnitServer] — the DHU loopback listener. A real+ * client/server socket pair over loopback proves the accept path hands the+ * connection over with Nagle disabled; closing an unbound server is a+ * silent no-op.+ *+ * Robolectric (not plain JVM): the server logs through `android.util.Log`.+ */+@RunWith(RobolectricTestRunner::class)+class HeadUnitServerTest {++    private fun freePort(): Int = ServerSocket(0).use { it.localPort }++    @Test+    fun `dhu loopback port matches the head-unit default`() {+        assertEquals(5277, HeadUnitServer.DHU_PORT)+    }++    @Test+    fun `an accepted socket has nagle disabled`() {+        val port = freePort()+        val server = HeadUnitServer(port)+        val pool = Executors.newSingleThreadExecutor()+        try {+            val accepted = pool.submit<Socket> { server.accept() }+            // The backlog holds the client until accept() runs: no sleep needed.+            Socket("127.0.0.1", port).use {+                val socket = accepted.get(10, TimeUnit.SECONDS)+                try {+                    assertTrue(socket.tcpNoDelay)+                } finally {+                    socket.close()+                }+            }+        } finally {+            server.close()+            pool.shutdownNow()+        }+    }++    @Test+    fun `closing an unbound server is a silent no-op`() {+        HeadUnitServer(freePort()).close()+    }+}
auto/src/test/java/com/vayunmathur/auto/notifications/MessageMirrorBusTest.kt
diff --git a/auto/src/test/java/com/vayunmathur/auto/notifications/MessageMirrorBusTest.kt b/auto/src/test/java/com/vayunmathur/auto/notifications/MessageMirrorBusTest.ktnew file mode 100644index 0000000000..ae5f2a4f1c--- /dev/null+++ b/auto/src/test/java/com/vayunmathur/auto/notifications/MessageMirrorBusTest.kt@@ -0,0 +1,98 @@+package com.vayunmathur.auto.notifications++import com.vayunmathur.auto.protocol.gal.MessagingMessage+import com.vayunmathur.auto.protocol.gal.MessagingThread+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNull++/**+ * Auto module: [MessageMirrorBus] — the process-wide bus between the+ * notification listener and the projection session. Posts fan out to every+ * registered listener; closing the registration stops delivery.+ */+class MessageMirrorBusTest {++    private fun thread(id: String) = MessagingThread.newBuilder()+        .setThreadId(id)+        .setTitle("Title $id")+        .build()++    private fun message(threadId: String) = MessagingMessage.newBuilder()+        .setThreadId(threadId)+        .setMessageId("m-$threadId")+        .setBody("hello $threadId")+        .build()++    @Test+    fun `a post with no listeners is a silent no-op`() {+        MessageMirrorBus.post(thread("t0"), message("t0"), null)+    }++    @Test+    fun `a registered listener receives the thread message and route`() {+        var seenThread: MessagingThread? = null+        var seenMessage: MessagingMessage? = null+        var seenRoute: MessageReplyRoute? = null+        var calls = 0+        val route = MessageReplyRoute("t1", null, null, null)+        val registration = MessageMirrorBus.register { t, m, r ->+            seenThread = t+            seenMessage = m+            seenRoute = r+            calls+++        }+        try {+            MessageMirrorBus.post(thread("t1"), message("t1"), route)+            assertEquals(1, calls)+            assertEquals("t1", seenThread?.threadId)+            assertEquals("m-t1", seenMessage?.messageId)+            assertEquals(route, seenRoute)+        } finally {+            registration.close()+        }+    }++    @Test+    fun `closing the registration stops delivery`() {+        var calls = 0+        val registration = MessageMirrorBus.register { _, _, _ -> calls++ }+        registration.close()+        MessageMirrorBus.post(thread("t2"), message("t2"), null)+        assertEquals(0, calls)+    }++    @Test+    fun `multiple listeners each receive every post`() {+        val first = mutableListOf<String>()+        val second = mutableListOf<String>()+        val r1 = MessageMirrorBus.register { t, _, _ -> first += t.threadId }+        val r2 = MessageMirrorBus.register { t, _, _ -> second += t.threadId }+        try {+            MessageMirrorBus.post(thread("a"), message("a"), null)+            MessageMirrorBus.post(thread("b"), message("b"), null)+            assertEquals(listOf("a", "b"), first)+            assertEquals(listOf("a", "b"), second)+        } finally {+            r1.close()+            r2.close()+        }+    }++    @Test+    fun `a null route arrives as null at the listener`() {+        var routeSeen: MessageReplyRoute? = MessageReplyRoute("x", null, null, null)+        var calls = 0+        val registration = MessageMirrorBus.register { _, _, r ->+            routeSeen = r+            calls+++        }+        try {+            MessageMirrorBus.post(thread("t3"), message("t3"), null)+            assertEquals(1, calls)+            assertNull(routeSeen)+        } finally {+            registration.close()+        }+    }+}
auto/src/test/java/com/vayunmathur/auto/notifications/MessageMirrorServiceTest.kt
diff --git a/auto/src/test/java/com/vayunmathur/auto/notifications/MessageMirrorServiceTest.kt b/auto/src/test/java/com/vayunmathur/auto/notifications/MessageMirrorServiceTest.ktnew file mode 100644index 0000000000..4a9a41c63a--- /dev/null+++ b/auto/src/test/java/com/vayunmathur/auto/notifications/MessageMirrorServiceTest.kt@@ -0,0 +1,164 @@+package com.vayunmathur.auto.notifications++import android.app.Notification+import android.app.NotificationChannel+import android.app.NotificationManager+import android.content.Context+import android.service.notification.StatusBarNotification+import androidx.core.app.NotificationCompat+import androidx.core.app.Person+import androidx.test.core.app.ApplicationProvider+import org.junit.runner.RunWith+import org.robolectric.Robolectric+import org.robolectric.RobolectricTestRunner+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue++/**+ * Auto module: [MessageMirrorService] extraction. Only `MessagingStyle`+ * notifications with non-blank text extract to a ch14 snapshot; the+ * conversation key prefers the shortcut id and falls back to package+tag+id;+ * the active-message counter floors at zero.+ *+ * StatusBarNotifications come from posting through NotificationManager, the+ * same path the system listener would deliver them on.+ */+@RunWith(RobolectricTestRunner::class)+class MessageMirrorServiceTest {++    private val context: Context+        get() = ApplicationProvider.getApplicationContext()++    private val manager: NotificationManager+        get() = context.getSystemService(NotificationManager::class.java)++    private fun service(): MessageMirrorService =+        Robolectric.buildService(MessageMirrorService::class.java).get()++    private fun messageBuilder(+        text: CharSequence?,+        conversationTitle: CharSequence? = null,+        shortcutId: String? = null,+    ): NotificationCompat.Builder {+        val sender = Person.Builder().setName("Ada").build()+        val style = NotificationCompat.MessagingStyle(sender)+        if (conversationTitle != null) style.conversationTitle = conversationTitle+        if (text != null) style.addMessage(text, 1_700_000_000_000L, sender)+        return NotificationCompat.Builder(context, "messages")+            .setSmallIcon(android.R.drawable.sym_def_app_icon)+            .setStyle(style)+            .setCategory(Notification.CATEGORY_MESSAGE)+            .apply { if (shortcutId != null) setShortcutId(shortcutId) }+    }++    private fun posted(tag: String, id: Int, notification: Notification): StatusBarNotification {+        manager.createNotificationChannel(+            NotificationChannel("messages", "messages", NotificationManager.IMPORTANCE_LOW),+        )+        manager.notify(tag, id, notification)+        return manager.activeNotifications.first { it.tag == tag && it.id == id }+    }++    private fun postedMessage(+        text: CharSequence?,+        conversationTitle: CharSequence? = null,+        shortcutId: String? = null,+        tag: String = "tag1",+        id: Int = 7,+    ): StatusBarNotification =+        posted(tag, id, messageBuilder(text, conversationTitle, shortcutId).build())++    @Test+    fun `a messaging notification extracts its thread and message`() {+        val (thread, message) = assertNotNull(+            service().extract(postedMessage("On my way", "Ada")),+        )+        assertEquals("${context.packageName}:tag1:7", thread.threadId)+        assertEquals("Ada", thread.title)+        assertEquals("Ada", thread.sender)+        assertEquals("${context.packageName}:tag1:7", message.threadId)+        assertEquals("7:1700000000000", message.messageId)+        assertEquals("On my way", message.body)+        assertEquals(1_700_000_000_000L, message.timestampMs)+    }++    @Test+    fun `a notification without messages extracts to null`() {+        val sender = Person.Builder().setName("Ada").build()+        val notification = NotificationCompat.Builder(context, "messages")+            .setSmallIcon(android.R.drawable.sym_def_app_icon)+            .setStyle(NotificationCompat.MessagingStyle(sender))+            .setCategory(Notification.CATEGORY_MESSAGE)+            .build()+        assertNull(service().extract(posted("tag2", 8, notification)))+    }++    @Test+    fun `blank-only messages extract to null`() {+        assertNull(service().extract(postedMessage("   ", tag = "tag3", id = 9)))+    }++    @Test+    fun `the latest non-blank message wins`() {+        val sender = Person.Builder().setName("Ada").build()+        val style = NotificationCompat.MessagingStyle(sender)+        style.addMessage("first", 1_000L, sender)+        style.addMessage("second", 2_000L, sender)+        val notification = NotificationCompat.Builder(context, "messages")+            .setSmallIcon(android.R.drawable.sym_def_app_icon)+            .setStyle(style)+            .setCategory(Notification.CATEGORY_MESSAGE)+            .build()+        val (_, message) = assertNotNull(service().extract(posted("tag4", 10, notification)))+        assertEquals("second", message.body)+        assertEquals("10:2000", message.messageId)+    }++    @Test+    fun `a conversation title beats the sender name`() {+        val (thread, _) = assertNotNull(+            service().extract(postedMessage("hi", "Family group", tag = "tag5", id = 11)),+        )+        assertEquals("Family group", thread.title)+    }++    @Test+    fun `a shortcut id keys the conversation`() {+        val svc = service()+        val key = svc.conversationKey(postedMessage("hi", shortcutId = "conv42", tag = "tag6", id = 12))+        assertEquals("${context.packageName}:conv42", key)+    }++    @Test+    fun `package tag and id key the conversation without a shortcut`() {+        val svc = service()+        assertEquals(+            "${context.packageName}:tag1:7",+            svc.conversationKey(postedMessage("hi")),+        )+    }++    @Test+    fun `the active counter starts at zero and floors there`() {+        val base = MessageMirrorService.activeMessageCount()+        assertTrue(base >= 0)+        service().onNotificationRemoved(postedMessage("hi", tag = "tag7", id = 13))+        assertEquals(0, MessageMirrorService.activeMessageCount())+    }++    @Test+    fun `a non-message category never posts to the bus`() {+        val posted = mutableListOf<String>()+        val registration = MessageMirrorBus.register { thread, _, _ -> posted += thread.threadId }+        try {+            val notification = messageBuilder("hi").build().apply { category = "email" }+            service().onNotificationPosted(posted("tag8", 14, notification))+            assertEquals(emptyList(), posted)+        } finally {+            registration.close()+        }+    }+}
auto/src/test/java/com/vayunmathur/auto/platform/AudioSinkChannelTest.kt
diff --git a/auto/src/test/java/com/vayunmathur/auto/platform/AudioSinkChannelTest.kt b/auto/src/test/java/com/vayunmathur/auto/platform/AudioSinkChannelTest.ktnew file mode 100644index 0000000000..4dadc3f9ba--- /dev/null+++ b/auto/src/test/java/com/vayunmathur/auto/platform/AudioSinkChannelTest.kt@@ -0,0 +1,211 @@+package com.vayunmathur.auto.platform++import com.vayunmathur.auto.protocol.AudioSinkRole+import com.vayunmathur.auto.protocol.FocusArbitration+import com.vayunmathur.auto.protocol.GalConnection+import com.vayunmathur.auto.protocol.GalMessage+import com.vayunmathur.auto.protocol.GalService+import com.vayunmathur.auto.protocol.GalTransport+import com.vayunmathur.auto.protocol.gal.AudioConfiguration+import com.vayunmathur.auto.protocol.gal.MediaAck+import com.vayunmathur.auto.protocol.gal.MediaCodecType+import com.vayunmathur.auto.protocol.gal.MediaSetupResponse+import com.vayunmathur.auto.protocol.gal.MediaSinkService+import com.vayunmathur.auto.protocol.gal.Service+import com.vayunmathur.auto.protocol.gal.VideoFocusMode+import com.vayunmathur.auto.protocol.gal.AudioFocusState+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.Shadows+import java.io.ByteArrayOutputStream+import javax.net.ssl.SSLContext+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++/**+ * Auto module: [AudioSinkChannel] — one PCM sink (SYSTEM ch4 or MEDIA ch5).+ * An AAC-only discovery parks UNSUPPORTED; PCM negotiates setup → CONFIG →+ * START; acks/syncs count; malformed TTS wavs drop with a count; release+ * stops. Sends ride a closed real connection — see [InputChannelTest] for+ * the seam; the audio thread drains via idled loopers like+ * [MicSourceChannelTest].+ */+@RunWith(RobolectricTestRunner::class)+class AudioSinkChannelTest {++    private class FakeTransport : GalTransport {+        val written = ByteArrayOutputStream()+        override fun read(buffer: ByteArray, offset: Int, length: Int): Int = -1+        override fun write(bytes: ByteArray, offset: Int, length: Int) {+            written.write(bytes, offset, length)+        }+        override fun flush() = Unit+        override fun close() = Unit+    }++    private fun connection(): GalConnection {+        val context = SSLContext.getInstance("TLS").apply { init(null, null, null) }+        return GalConnection(FakeTransport(), context, deviceModel = "Test").also { it.close() }+    }++    private fun config(rate: Int = 44_100, bits: Int = 16, channels: Int = 1): AudioConfiguration =+        AudioConfiguration.newBuilder()+            .setSamplingRate(rate)+            .setNumberOfBits(bits)+            .setNumberOfChannels(channels)+            .build()++    private fun service(vararg configs: AudioConfiguration): Service =+        Service.newBuilder()+            .setId(GalService.AUDIO_SINK_SYSTEM.id)+            .setMediaSink(+                MediaSinkService.newBuilder()+                    .setAvailableType(MediaCodecType.MEDIA_CODEC_AUDIO_PCM)+                    .addAllAudioConfigs(configs.asList())+                    .build(),+            )+            .build()++    private fun projectingFocus(): FocusArbitration =+        FocusArbitration().also {+            it.onVideoFocus(VideoFocusMode.VIDEO_FOCUS_PROJECTED)+            it.onAudioFocus(AudioFocusState.AUDIO_FOCUS_STATE_GAIN)+        }++    private fun channel(+        service: Service = service(config()),+        events: MutableList<AudioEvent> = mutableListOf(),+    ): AudioSinkChannel = AudioSinkChannel(+        AudioSinkRole.SYSTEM,+        service,+        connection(),+        focus = ::projectingFocus,+        onEvent = { events += it },+    )++    private fun configResponse(): ByteArray =+        MediaSetupResponse.newBuilder().setMediaStatus(0).build().toByteArray()++    private fun drainLoopers() {+        for (looper in org.robolectric.shadows.ShadowLooper.getAllLoopers()) {+            runCatching { Shadows.shadowOf(looper).idle() }+        }+    }++    @Test+    fun `channel id comes from discovery`() {+        assertEquals(GalService.AUDIO_SINK_SYSTEM.id, channel().channelId)+    }++    @Test+    fun `an aac-only service parks unsupported`() {+        val events = mutableListOf<AudioEvent>()+        val aac = Service.newBuilder()+            .setId(GalService.AUDIO_SINK_SYSTEM.id)+            .setMediaSink(+                MediaSinkService.newBuilder()+                    .setAvailableType(MediaCodecType.MEDIA_CODEC_AUDIO_AAC_LC)+                    .addAudioConfigs(config())+                    .build(),+            )+            .build()+        channel(aac, events).requestSetup()+        val setup = events.filterIsInstance<AudioEvent.SinkSetup>()+        assertEquals(1, setup.size)+        assertEquals("SYSTEM", setup.single().role)+        val status = events.filterIsInstance<AudioEvent.SinkStatus>().last()+        assertEquals(AudioSinkState.UNSUPPORTED, status.status.state)+    }++    @Test+    fun `pcm setup negotiates and config starts the stream`() {+        val events = mutableListOf<AudioEvent>()+        val channel = channel(events = events)+        channel.requestSetup()+        assertTrue(events.filterIsInstance<AudioEvent.SinkSetup>().isNotEmpty())+        channel.onMessage(+            GalService.AUDIO_SINK_SYSTEM.id,+            GalMessage.Media.CONFIG,+            configResponse(),+        )+        val started = events.filterIsInstance<AudioEvent.SinkStarted>()+        assertEquals(1, started.size)+        assertEquals("SYSTEM", started.single().role)+        val status = events.filterIsInstance<AudioEvent.SinkStatus>().last()+        assertEquals(AudioSinkState.STARTED, status.status.state)+        channel.release()+        assertTrue(events.filterIsInstance<AudioEvent.SinkStopped>().isNotEmpty())+    }++    @Test+    fun `wrong-channel traffic is ignored`() {+        val events = mutableListOf<AudioEvent>()+        val channel = channel(events = events)+        channel.requestSetup()+        val before = events.size+        channel.onMessage(7, GalMessage.Media.CONFIG, configResponse())+        assertEquals(before, events.size)+        channel.release()+    }++    @Test+    fun `acks and syncs count`() {+        val events = mutableListOf<AudioEvent>()+        val channel = channel(events = events)+        channel.onMessage(+            GalService.AUDIO_SINK_SYSTEM.id,+            GalMessage.Media.ACK,+            MediaAck.newBuilder().setSessionId(0).build().toByteArray(),+        )+        channel.onMessage(GalService.AUDIO_SINK_SYSTEM.id, GalMessage.Audio.SYNC, byteArrayOf())+        assertEquals(1, events.filterIsInstance<AudioEvent.AckReceived>().size)+        assertEquals(1, events.filterIsInstance<AudioEvent.SyncReceived>().size)+        channel.release()+    }++    @Test+    fun `malformed tts wav drops with a count`() {+        val events = mutableListOf<AudioEvent>()+        val channel = channel(events = events)+        channel.requestSetup()+        channel.feedWav(byteArrayOf(1, 2, 3, 4))+        drainLoopers()+        assertTrue(events.filterIsInstance<AudioEvent.TtsDropped>().isNotEmpty())+        channel.release()+    }++    @Test+    fun `pcm before start drops without frames`() {+        val events = mutableListOf<AudioEvent>()+        val channel = channel(events = events)+        channel.requestSetup()+        // SETUP but no CONFIG: the stream never started, so feeds drop.+        channel.feedPcm(ByteArray(64), 44_100)+        drainLoopers()+        assertTrue(events.filterIsInstance<AudioEvent.FramesSent>().isEmpty())+        channel.release()+    }++    @Test+    fun `focus change republishes the sink status`() {+        val events = mutableListOf<AudioEvent>()+        val channel = channel(events = events)+        channel.requestSetup()+        val before = events.filterIsInstance<AudioEvent.SinkStatus>().size+        channel.onFocusChanged()+        assertEquals(before + 1, events.filterIsInstance<AudioEvent.SinkStatus>().size)+        channel.release()+    }++    @Test+    fun `unhandled types are observed and ignored`() {+        val events = mutableListOf<AudioEvent>()+        val channel = channel(events = events)+        channel.requestSetup()+        val before = events.size+        channel.onMessage(GalService.AUDIO_SINK_SYSTEM.id, 0x1234, byteArrayOf(1))+        assertEquals(before, events.size)+        channel.release()+    }+}
auto/src/test/java/com/vayunmathur/auto/platform/AutoSessionStateTest.kt
diff --git a/auto/src/test/java/com/vayunmathur/auto/platform/AutoSessionStateTest.kt b/auto/src/test/java/com/vayunmathur/auto/platform/AutoSessionStateTest.ktnew file mode 100644index 0000000000..9d78115331--- /dev/null+++ b/auto/src/test/java/com/vayunmathur/auto/platform/AutoSessionStateTest.kt@@ -0,0 +1,249 @@+package com.vayunmathur.auto.platform++import com.vayunmathur.auto.protocol.AudioGain+import com.vayunmathur.auto.protocol.AudioSinkRole+import com.vayunmathur.auto.protocol.FocusArbitration+import com.vayunmathur.auto.protocol.VideoFocus+import com.vayunmathur.auto.protocol.gal.AudioFocusState+import com.vayunmathur.auto.protocol.gal.VideoFocusMode+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNull+import kotlin.test.assertTrue++/**+ * Auto module: [AutoSessionState] — the session-to-UI bridge. Every event+ * family lands on its flows; socket accept/disconnect resets them.+ */+@RunWith(RobolectricTestRunner::class)+class AutoSessionStateTest {++    @BeforeTest+    fun reset() {+        AutoSessionState.onDisconnected()+        AutoSessionState.onSocketAccepted()+    }++    private fun projectingArbitration(): FocusArbitration =+        FocusArbitration().also {+            it.onVideoFocus(VideoFocusMode.VIDEO_FOCUS_PROJECTED)+            it.onAudioFocus(AudioFocusState.AUDIO_FOCUS_STATE_GAIN)+        }++    // --- Lifecycle ------------------------------------------------------------++    @Test+    fun `socket accept resets to connecting with cleared counters`() {+        AutoSessionState.onVideoEvent(VideoEvent.FrameSent(1L, 10L))+        AutoSessionState.onCallAdded(ActiveCallInfo(1, "555", 0L))+        AutoSessionState.onSocketAccepted()+        assertEquals(AutoConnectionState.Connecting, AutoSessionState.connection.value)+        assertEquals(0L, AutoSessionState.framesSent.value)+        assertNull(AutoSessionState.activeCall.value)+        assertNull(AutoSessionState.video.value)+    }++    @Test+    fun `active names the car and disconnect returns to idle`() {+        AutoSessionState.onActive("Test Car")+        assertEquals(+            AutoConnectionState.Projecting("Test Car"),+            AutoSessionState.connection.value,+        )+        AutoSessionState.onDisconnected()+        assertEquals(AutoConnectionState.Disconnected, AutoSessionState.connection.value)+    }++    @Test+    fun `rejected marks refusal and session end routes on its failure`() {+        AutoSessionState.onRejected()+        assertEquals(AutoConnectionState.Rejected, AutoSessionState.connection.value)+        AutoSessionState.onSessionEnd("cert")+        assertEquals(AutoConnectionState.Rejected, AutoSessionState.connection.value)+        AutoSessionState.onSessionEnd(null)+        assertEquals(AutoConnectionState.Disconnected, AutoSessionState.connection.value)+    }++    @Test+    fun `credential expiry lands on its flow`() {+        AutoSessionState.onCredentialExpiry(42L)+        assertEquals(42L, AutoSessionState.credentialDaysLeft.value)+    }++    // --- Focus ------------------------------------------------------------------++    @Test+    fun `focus arbitration mirrors into the phone-visible flows`() {+        AutoSessionState.onActive("Car")+        AutoSessionState.onFocusChanged(projectingArbitration())+        assertEquals(VideoFocus.PROJECTED, AutoSessionState.videoFocus.value)+        assertEquals(AudioFocusState.AUDIO_FOCUS_STATE_GAIN, AutoSessionState.audioFocus.value)+        assertTrue(AutoSessionState.inputAllowed.value)+        val projecting = AutoSessionState.connection.value as AutoConnectionState.Projecting+        assertEquals(VideoFocus.PROJECTED, projecting.videoFocus)+        assertEquals("Car", projecting.carName)+    }++    @Test+    fun `focus without a projection does not rewrite the connection`() {+        AutoSessionState.onFocusChanged(projectingArbitration())+        assertEquals(AutoConnectionState.Connecting, AutoSessionState.connection.value)+        assertTrue(AutoSessionState.inputAllowed.value)+    }++    // --- Video --------------------------------------------------------------------++    @Test+    fun `video setup focus frames and surface land`() {+        val info = VideoInfo(720, 480, 30, 1)+        AutoSessionState.onVideoEvent(VideoEvent.Setup(info))+        assertEquals(info, AutoSessionState.video.value)+        AutoSessionState.onVideoEvent(VideoEvent.FocusChanged("VIDEO_FOCUS_NATIVE"))+        assertEquals("VIDEO_FOCUS_NATIVE", AutoSessionState.focusMode.value)+        AutoSessionState.onVideoEvent(VideoEvent.FirstFrame)+        AutoSessionState.onVideoEvent(VideoEvent.FrameSent(100L, 50L))+        AutoSessionState.onVideoEvent(VideoEvent.FrameSent(200L, 70L))+        assertEquals(2L, AutoSessionState.framesSent.value)+        assertEquals(60L, AutoSessionState.avgEncodeLatencyUs.value)+        AutoSessionState.onVideoEvent(VideoEvent.SurfaceChanged(true))+        assertTrue(AutoSessionState.surfaceValid.value)+        AutoSessionState.onVideoEvent(VideoEvent.EncoderDrained(3))+        assertEquals(1L, AutoSessionState.encoderDrains.value)+    }++    @Test+    fun `acks advance the counters and the unwrapped sequence`() {+        AutoSessionState.onVideoEvent(VideoEvent.AckReceived(10L, 0))+        AutoSessionState.onVideoEvent(VideoEvent.AckReceived(11L, 1))+        assertEquals(2L, AutoSessionState.acksSeen.value)+        assertEquals(11L, AutoSessionState.lastAckSeq.value)+        assertTrue((AutoSessionState.lastAckAt.value ?: 0L) > 0L)+        assertEquals(0L, AutoSessionState.lastAckAgeMs.value)+    }++    @Test+    fun `an ack without a sequence still proves liveness`() {+        AutoSessionState.onVideoEvent(VideoEvent.AckReceived(null, 0))+        assertEquals(1L, AutoSessionState.acksSeen.value)+        assertNull(AutoSessionState.lastAckSeq.value)+        assertTrue((AutoSessionState.lastAckAt.value ?: 0L) > 0L)+    }++    @Test+    fun `mismatched acks count separately and still prove liveness`() {+        AutoSessionState.onVideoEvent(VideoEvent.AckMismatch(expected = 1, actual = 2))+        assertEquals(1L, AutoSessionState.acksSeen.value)+        assertEquals(1L, AutoSessionState.ackMismatches.value)+        assertTrue((AutoSessionState.lastAckAt.value ?: 0L) > 0L)+    }++    // --- Calls ----------------------------------------------------------------------++    @Test+    fun `call add change and remove drive the card snapshot`() {+        val ringing = ActiveCallInfo(telecomState = 1, number = "555", acceptedMs = 0L)+        assertTrue(ringing.isIncoming)+        AutoSessionState.onCallAdded(ringing)+        assertEquals(ringing, AutoSessionState.activeCall.value)+        val active = ringing.copy(acceptedMs = 1000L, held = true, muted = true)+        assertFalse(active.isIncoming)+        AutoSessionState.onCallChanged(active)+        assertEquals(active, AutoSessionState.activeCall.value)+        AutoSessionState.onCallRemoved()+        assertNull(AutoSessionState.activeCall.value)+        // Floors at zero, never negative.+        AutoSessionState.onCallRemoved()+        AutoSessionState.onCallAvailability(true)+        assertEquals(true, AutoSessionState.callAvailable.value)+    }++    // --- Media / messaging / input / audio / sensors --------------------------------------++    @Test+    fun `media now-playing lands`() {+        val info = NowPlayingInfo(title = "Song", artist = "Band", playing = true, positionMs = 0L, durationMs = null)+        AutoSessionState.onMediaEvent(MediaEvent.NowPlayingChanged(info))+        assertEquals(info, AutoSessionState.nowPlaying.value)+    }++    @Test+    fun `messaging counts threads messages and replies`() {+        AutoSessionState.onMessagingEvent(MessagingEvent.ThreadsPosted(3))+        AutoSessionState.onMessagingEvent(MessagingEvent.MessagePosted("t1"))+        AutoSessionState.onMessagingEvent(MessagingEvent.ReplyReceived("t1"))+        AutoSessionState.onMessagingEvent(MessagingEvent.ReplySent("t1"))+        AutoSessionState.onMessagingEvent(MessagingEvent.ReplyFailed("t1", "nope"))+        AutoSessionState.onMessagingEvent(MessagingEvent.MarkedRead("t1"))+        assertEquals(3L, AutoSessionState.threadsPosted.value)+        assertEquals(1L, AutoSessionState.messagesPosted.value)+        assertEquals(2L, AutoSessionState.repliesReceived.value)+    }++    @Test+    fun `input touches keys scrolls and drops count`() {+        AutoSessionState.onInputEvent(InputEvent.BindingRequested(2))+        AutoSessionState.onInputEvent(InputEvent.BindingAnswered(0))+        AutoSessionState.onInputEvent(InputEvent.Touch(action = 0, pointerCount = 1))+        AutoSessionState.onInputEvent(InputEvent.Key(keycode = 4, down = true))+        AutoSessionState.onInputEvent(InputEvent.Scroll(delta = 3))+        AutoSessionState.onInputEvent(InputEvent.VolumeKey(keycode = 24, down = true))+        AutoSessionState.onInputEvent(InputEvent.FeedbackSent(1))+        AutoSessionState.onInputEvent(InputEvent.DroppedNoFocus)+        assertEquals(1L, AutoSessionState.touchesInjected.value)+        assertEquals(2L, AutoSessionState.keysInjected.value)+        assertEquals(1L, AutoSessionState.scrollsInjected.value)+        assertEquals(1L, AutoSessionState.inputDropped.value)+    }++    @Test+    fun `audio sinks bytes syncs and music count`() {+        val status = AudioSinkStatus(role = AudioSinkRole.MEDIA, state = AudioSinkState.STARTED, gain = AudioGain.FULL)+        AutoSessionState.onAudioEvent(AudioEvent.SinkSetup("MEDIA", "d"))+        AutoSessionState.onAudioEvent(AudioEvent.SinkStatus(status))+        AutoSessionState.onAudioEvent(AudioEvent.SinkStarted("MEDIA", 0))+        AutoSessionState.onAudioEvent(AudioEvent.SinkStopped("MEDIA"))+        assertEquals(status, AutoSessionState.sinkStatus.value[AudioSinkRole.MEDIA])+        AutoSessionState.onAudioEvent(AudioEvent.FramesSent("MEDIA", 100L))+        AutoSessionState.onAudioEvent(AudioEvent.SyncReceived("MEDIA"))+        AutoSessionState.onAudioEvent(AudioEvent.AckReceived("MEDIA", 1L))+        AutoSessionState.onAudioEvent(AudioEvent.MusicCaptured(50L))+        AutoSessionState.onAudioEvent(AudioEvent.MusicDropped("busy"))+        assertEquals(100L, AutoSessionState.audioBytesSent.value)+        assertEquals(50L, AutoSessionState.musicBytesCaptured.value)+        assertEquals(1L, AutoSessionState.audioSyncs.value)+        assertEquals(1L, AutoSessionState.audioAcks.value)+    }++    @Test+    fun `audio tts and mic turns count`() {+        AutoSessionState.onAudioEvent(AudioEvent.TtsSpoken(10))+        AutoSessionState.onAudioEvent(AudioEvent.TtsDropped("late"))+        AutoSessionState.onAudioEvent(AudioEvent.MicTurn(200L))+        AutoSessionState.onAudioEvent(AudioEvent.MicAcked)+        AutoSessionState.onAudioEvent(AudioEvent.MicIdle)+        assertEquals(1L, AutoSessionState.ttsSpoken.value)+        assertEquals(1L, AutoSessionState.ttsDropped.value)+        assertEquals(1L, AutoSessionState.micTurns.value)+        assertEquals(1L, AutoSessionState.micAcks.value)+    }++    @Test+    fun `sensor guidance and nav posts count`() {+        AutoSessionState.onSensorEvent(SensorEvent.Subscribed("gyro"))+        AutoSessionState.onSensorEvent(SensorEvent.SubscriptionAnswered("gyro", 0))+        AutoSessionState.onSensorEvent(SensorEvent.BatchReceived(5))+        AutoSessionState.onSensorEvent(SensorEvent.SensorError("gyro", 1))+        AutoSessionState.onSensorEvent(SensorEvent.GuidanceSetup)+        AutoSessionState.onSensorEvent(SensorEvent.GuidanceConfigured(true))+        AutoSessionState.onSensorEvent(SensorEvent.NavStatusPosted)+        assertEquals(1L, AutoSessionState.sensorsSubscribed.value)+        assertEquals(1L, AutoSessionState.sensorBatches.value)+        assertEquals(1L, AutoSessionState.sensorErrors.value)+        assertEquals(2L, AutoSessionState.guidanceEvents.value)+        assertEquals(1L, AutoSessionState.navStatusPosts.value)+    }+}
auto/src/test/java/com/vayunmathur/auto/platform/AutoViewModelTest.kt
diff --git a/auto/src/test/java/com/vayunmathur/auto/platform/AutoViewModelTest.kt b/auto/src/test/java/com/vayunmathur/auto/platform/AutoViewModelTest.ktnew file mode 100644index 0000000000..614b83a8a9--- /dev/null+++ b/auto/src/test/java/com/vayunmathur/auto/platform/AutoViewModelTest.kt@@ -0,0 +1,111 @@+package com.vayunmathur.auto.platform++import androidx.lifecycle.ViewModelProvider+import androidx.lifecycle.ViewModelStore+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.auto.protocol.VideoFocus+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.ExperimentalCoroutinesApi+import kotlinx.coroutines.flow.collect+import kotlinx.coroutines.launch+import kotlinx.coroutines.test.resetMain+import kotlinx.coroutines.test.setMain+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import kotlin.test.AfterTest+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNull++/**+ * Auto module: [AutoViewModel] — the phone status screen's flow mirror. It+ * never writes: every exposed flow re-emits [AutoSessionState], starting+ * from the documented defaults until a collector subscribes.+ */+@OptIn(ExperimentalCoroutinesApi::class)+@RunWith(RobolectricTestRunner::class)+class AutoViewModelTest {++    private val context: android.content.Context+        get() = ApplicationProvider.getApplicationContext()++    @BeforeTest+    fun setUp() {+        Dispatchers.setMain(Dispatchers.Unconfined)+        AutoSessionState.onDisconnected()+    }++    @AfterTest+    fun tearDown() {+        Dispatchers.resetMain()+        AutoSessionState.onDisconnected()+    }++    private var store = ViewModelStore()++    private fun viewModel(): AutoViewModel {+        store.clear()+        store = ViewModelStore()+        return ViewModelProvider(store, object : ViewModelProvider.Factory {+            @Suppress("UNCHECKED_CAST")+            override fun <T : androidx.lifecycle.ViewModel> create(modelClass: Class<T>): T =+                AutoViewModel() as T+        })[AutoViewModel::class.java]+    }++    @Test+    fun `defaults mirror the disconnected session`() {+        val vm = viewModel()+        assertEquals(AutoConnectionState.Disconnected, vm.connection.value)+        assertNull(vm.video.value)+        assertNull(vm.focusMode.value)+        assertEquals(VideoFocus.NONE, vm.videoFocus.value)+        assertEquals(false, vm.inputAllowed.value)+        assertEquals(0L, vm.framesSent.value)+        assertEquals(0L, vm.acksSeen.value)+        assertEquals(0L, vm.ackMismatches.value)+        assertEquals(0.0, vm.encodedFps.value)+        assertEquals(0.0, vm.ackFps.value)+        assertNull(vm.lastAckAgeMs.value)+        assertNull(vm.lastAckAt.value)+        assertNull(vm.lastAckSeq.value)+        assertNull(vm.avgEncodeLatencyUs.value)+        assertEquals(0L, vm.encoderDrains.value)+        assertEquals(false, vm.surfaceValid.value)+        assertNull(vm.nowPlaying.value)+        assertEquals(0L, vm.threadsPosted.value)+        assertEquals(0L, vm.messagesPosted.value)+        assertEquals(0L, vm.repliesReceived.value)+        assertEquals(0L, vm.touchesInjected.value)+        assertEquals(0L, vm.keysInjected.value)+        assertEquals(0L, vm.scrollsInjected.value)+        assertEquals(0L, vm.inputDropped.value)+        assertEquals(emptyMap(), vm.sinkStatus.value)+        assertEquals(0L, vm.audioBytesSent.value)+        assertEquals(0L, vm.musicBytesCaptured.value)+        assertEquals(0L, vm.micTurns.value)+        assertEquals(0L, vm.micAcks.value)+        assertEquals(0L, vm.ttsSpoken.value)+        assertNull(vm.credentialDaysLeft.value)+        assertNull(vm.sessionStartedAt.value)+        store.clear()+    }++    @Test+    fun `an active session flows through to the viewmodel`() {+        AutoSessionState.onSocketAccepted()+        AutoSessionState.onActive("Test Car")+        val vm = viewModel()+        // stateIn(WhileSubscribed) only subscribes upstream while collected:+        // a collector must be active before .value reflects the session.+        val job = CoroutineScope(Dispatchers.Unconfined).launch { vm.connection.collect() }+        try {+            assertEquals(AutoConnectionState.Projecting("Test Car"), vm.connection.value)+        } finally {+            job.cancel()+            store.clear()+        }+    }+}
auto/src/test/java/com/vayunmathur/auto/platform/BringupReceiversTest.kt
diff --git a/auto/src/test/java/com/vayunmathur/auto/platform/BringupReceiversTest.kt b/auto/src/test/java/com/vayunmathur/auto/platform/BringupReceiversTest.ktnew file mode 100644index 0000000000..df8cca6a7e--- /dev/null+++ b/auto/src/test/java/com/vayunmathur/auto/platform/BringupReceiversTest.kt@@ -0,0 +1,173 @@+package com.vayunmathur.auto.platform++import android.bluetooth.BluetoothAdapter+import android.content.Context+import android.content.Intent+import android.hardware.usb.UsbManager+import android.net.ConnectivityManager+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.auto.network.UsbConnector+import com.vayunmathur.auto.network.WifiDirectConnector+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.Shadows+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue++/**+ * Auto module: the bring-up receivers — [UsbReceiver], [UsbTPlusReceiver],+ * [WifiBluetoothReceiver], [ConnectivityEventReceiver], [BootReceiver] and+ * [ConnectionResetReceiver]. Unknown actions are ignored; the USB denial and+ * TPlus paths funnel into [UsbConnector]; BT-off/ACL-disconnect cancel an+ * in-flight wireless bring-up; boot and USB-reset restart the listener.+ */+@RunWith(RobolectricTestRunner::class)+class BringupReceiversTest {++    private val context: Context+        get() = ApplicationProvider.getApplicationContext()++    private fun intent(action: String): Intent = Intent(action)++    // --- UsbReceiver ------------------------------------------------------------++    @Test+    fun `usb receiver ignores unknown actions`() {+        UsbReceiver().onReceive(context, intent("com.example.NOPE"))+        // No accessory seen: nothing latched.+        assertFalse(UsbConnector.onAccessoryIntent(context, intent("com.example.NOPE")))+    }++    @Test+    fun `usb detach clears the attach state`() {+        assertTrue(+            UsbConnector.onAccessoryIntent(context, intent(UsbManager.ACTION_USB_ACCESSORY_DETACHED)),+        )+    }++    @Test+    fun `usb permission denial is consumed`() {+        val denial = Intent(UsbConnector.ACTION_USB_PERMISSION).apply {+            putExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)+        }+        assertTrue(UsbConnector.onPermissionResult(context, denial))+        UsbReceiver().onReceive(context, denial)+    }++    @Test+    fun `usb force-start with no accessory is a logged no-op`() {+        UsbConnector.forceStart(context)+        UsbReceiver().onReceive(context, intent(UsbConnector.ACTION_USB_ACCESSORY_FORCE_START))+        // Retry without an accessory is a no-op too.+        UsbConnector.retryPermission(context)+    }++    // --- UsbTPlusReceiver ----------------------------------------------------------++    @Test+    fun `tplus receiver ignores unknown actions`() {+        UsbTPlusReceiver().onReceive(context, intent("com.example.NOPE"))+    }++    @Test+    fun `tplus detach re-drives without an accessory`() {+        // No stock extra and no accessory seen: falls back to force-start,+        // which is a no-op with nothing latched.+        UsbTPlusReceiver().onReceive(context, intent(UsbTPlusReceiver.ACTION_USB_TPLUS_DETACHED))+    }++    // --- WifiBluetoothReceiver -------------------------------------------------------++    @Test+    fun `bt receiver ignores unknown actions`() {+        WifiBluetoothReceiver().onReceive(context, intent("com.example.NOPE"))+    }++    @Test+    fun `acl disconnect cancels an idle bring-up safely`() {+        WifiDirectConnector.cancel()+        WifiBluetoothReceiver().onReceive(+            context,+            intent(android.bluetooth.BluetoothDevice.ACTION_ACL_DISCONNECTED),+        )+    }++    @Test+    fun `bluetooth off cancels an idle bring-up safely`() {+        WifiDirectConnector.cancel()+        WifiBluetoothReceiver().onReceive(+            context,+            Intent(BluetoothAdapter.ACTION_STATE_CHANGED).apply {+                putExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.STATE_OFF)+            },+        )+        // A non-off state change is ignored.+        WifiBluetoothReceiver().onReceive(+            context,+            Intent(BluetoothAdapter.ACTION_STATE_CHANGED).apply {+                putExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.STATE_ON)+            },+        )+    }++    @Test+    fun `acl connect without a device returns early`() {+        WifiBluetoothReceiver().onReceive(+            context,+            intent("android.bluetooth.device.action.ACL_CONNECTED"),+        )+    }++    // --- ConnectivityEventReceiver ----------------------------------------------------++    @Test+    fun `connectivity receiver ignores unknown actions`() {+        ConnectivityEventReceiver().onReceive(context, intent("com.example.NOPE"))+    }++    @Test+    fun `connectivity loss with no network is a no-op`() {+        // Robolectric starts with no active network: the receiver logs and returns.+        ConnectivityEventReceiver().onReceive(+            context,+            intent(ConnectivityManager.CONNECTIVITY_ACTION),+        )+    }++    // --- BootReceiver + ConnectionResetReceiver ------------------------------------------++    @Test+    fun `boot receiver ignores unknown actions`() {+        BootReceiver().onReceive(context, intent("com.example.NOPE"))+    }++    @Test+    fun `boot completed restarts the projection listener`() {+        BootReceiver().onReceive(context, intent(Intent.ACTION_BOOT_COMPLETED))+        val next = Shadows.shadowOf(context as android.app.Application)+            .nextStartedService+        assertTrue(next?.component?.className?.endsWith("ProjectionService") == true)+    }++    @Test+    fun `usb reset re-arms the projection listener`() {+        ConnectionResetReceiver().onReceive(+            context,+            intent(ConnectionResetReceiver.ACTION_RESET_USB_PORT),+        )+        val next = Shadows.shadowOf(context as android.app.Application)+            .nextStartedService+        assertTrue(next?.component?.className?.endsWith("ProjectionService") == true)+        // Unknown actions are ignored.+        ConnectionResetReceiver().onReceive(context, intent("com.example.NOPE"))+    }++    // --- Role + transport selection ------------------------------------------------------++    @Test+    fun `role reads fail closed with no role service`() {+        assertFalse(MaosRoleStatus.isProjectionRoleHeld(context))+    }+}
auto/src/test/java/com/vayunmathur/auto/platform/CaptureAndTtsTest.kt
diff --git a/auto/src/test/java/com/vayunmathur/auto/platform/CaptureAndTtsTest.kt b/auto/src/test/java/com/vayunmathur/auto/platform/CaptureAndTtsTest.ktnew file mode 100644index 0000000000..254ed90925--- /dev/null+++ b/auto/src/test/java/com/vayunmathur/auto/platform/CaptureAndTtsTest.kt@@ -0,0 +1,45 @@+package com.vayunmathur.auto.platform++import android.content.Context+import androidx.test.core.app.ApplicationProvider+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import java.util.concurrent.CountDownLatch+import java.util.concurrent.TimeUnit+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++@RunWith(RobolectricTestRunner::class)+class CaptureAndTtsTest {+    private val ctx get() = ApplicationProvider.getApplicationContext<Context>()++    @Test fun `music capture without thread or grant emits nothing`() {+        val events = mutableListOf<AudioEvent>()+        val capture = MusicCapture(ctx, mediaSink = { null }, isPlayingNow = { true }, onEvent = { events += it })+        capture.start(null) // no thread: dropped+        capture.stop()+        capture.startThread()+        capture.startThread() // idempotent+        capture.start(null) // no grant / not consented: stays silent (async on capture thread)+        capture.stop()+        capture.releaseThread()+        capture.start(null) // after release: dropped+        assertTrue(events.none { it is AudioEvent.MusicCaptured })+    }++    @Test fun `tts speak before start is dropped and after start reports unready engine`() {+        val events = mutableListOf<AudioEvent>()+        val latch = CountDownLatch(1)+        val tts = CarTts(ctx, systemSink = { null }, onEvent = { e -> events += e; if (e is AudioEvent.TtsDropped) latch.countDown() })+        tts.speak("hello") // no handler yet+        assertTrue(events.isEmpty())+        tts.start()+        tts.speak("hello car")+        // Engine never becomes ready under Robolectric, so synthesize drops with engine-unready+        assertTrue(latch.await(10, TimeUnit.SECONDS), "expected TtsDropped, got $events")+        assertEquals("engine-unready", events.filterIsInstance<AudioEvent.TtsDropped>().first().reason)+        tts.stop()+        tts.speak("after stop")+    }+}
auto/src/test/java/com/vayunmathur/auto/platform/CarDiscoveryTest.kt
diff --git a/auto/src/test/java/com/vayunmathur/auto/platform/CarDiscoveryTest.kt b/auto/src/test/java/com/vayunmathur/auto/platform/CarDiscoveryTest.ktnew file mode 100644index 0000000000..5f2b5190ae--- /dev/null+++ b/auto/src/test/java/com/vayunmathur/auto/platform/CarDiscoveryTest.kt@@ -0,0 +1,62 @@+package com.vayunmathur.auto.platform++import android.content.ComponentName+import androidx.test.core.app.ApplicationProvider+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue++/**+ * Auto module: [CarAppDiscovery], [CarApps] and [RefusedCarApps].+ *+ * Under Robolectric no car services are installed, so discovery resolves to+ * empty and queries degrade to the fail-closed empty grid — nothing dead is+ * ever shown. The refusal ledger round-trips per component.+ */+@RunWith(RobolectricTestRunner::class)+class CarDiscoveryTest {++    private val context: android.content.Context+        get() = ApplicationProvider.getApplicationContext()++    @Test+    fun `no installed car services means an empty grid`() {+        assertEquals(emptyList(), CarAppDiscovery.query(context))+        assertEquals(emptyList(), CarAppDiscovery.queryAll(context))+        assertEquals(emptyList(), CarAppDiscovery.firstParty(context))+        assertEquals(emptyList(), CarApps.query(context))+    }++    @Test+    fun `hosted categories cover the launcher tiles`() {+        val categories = CarAppDiscovery.HOSTED_CATEGORIES+        assertTrue(categories.isNotEmpty())+        assertEquals(categories.size, categories.toSet().size)+    }++    @Test+    fun `assistant resolves to null with no assistant installed`() {+        // Robolectric has no ASSIST/VOICE_COMMAND handler: skip-if-missing.+        assertEquals(null, CarApps.assistant(context))+    }++    @Test+    fun `refusal ledger starts clean per component`() {+        val component = ComponentName("com.example", "com.example.CarService")+        assertFalse(RefusedCarApps.isRefused(context, component))+    }++    @Test+    fun `pin id is the flattened component string`() {+        val app = DiscoveredApp(+            component = ComponentName("com.example", "com.example.CarService"),+            label = "Example",+            icon = null,+            categories = emptySet(),+        )+        assertEquals("com.example/com.example.CarService", app.id)+    }+}
auto/src/test/java/com/vayunmathur/auto/platform/CarDisplayTest.kt
diff --git a/auto/src/test/java/com/vayunmathur/auto/platform/CarDisplayTest.kt b/auto/src/test/java/com/vayunmathur/auto/platform/CarDisplayTest.ktnew file mode 100644index 0000000000..8b1972a37c--- /dev/null+++ b/auto/src/test/java/com/vayunmathur/auto/platform/CarDisplayTest.kt@@ -0,0 +1,82 @@+package com.vayunmathur.auto.platform++import android.content.res.Configuration+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.library.carhost.HostNavState+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.Shadows+import android.os.Looper+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNull+import kotlin.test.assertTrue++@RunWith(RobolectricTestRunner::class)+class CarDisplayTest {+    private val ctx get() = ApplicationProvider.getApplicationContext<android.content.Context>()+    @BeforeTest fun reset() {+        CarLauncherState.setDrivingRestricted(false); CarLauncherState.setNight(false)+        CarLauncherState.setActiveCall(null); CarLauncherState.selectApp(null)+    }+    private fun idleMain() = Shadows.shadowOf(Looper.getMainLooper()).idle()+    private fun display() = CarDisplay(ctx, 800, 480, 160)++    @Test fun `setters publish to launcher state without a presentation`() {+        val d = display()+        val info = NowPlayingInfo(title = "Song", artist = "Band", playing = true, positionMs = 0, durationMs = null)+        d.setNowPlaying(info)+        assertEquals(info, CarLauncherState.nowPlaying.value)+        d.setDrivingRestricted(true); assertTrue(CarLauncherState.drivingRestricted.value)+        d.setParkedBrowsingGate(true); assertFalse(CarLauncherState.drivingRestricted.value)+        d.setParkedBrowsingGate(false); assertTrue(CarLauncherState.drivingRestricted.value)+        d.setNight(true); assertTrue(CarLauncherState.nightDark.value)+        val call = ActiveCallInfo(telecomState = 1, number = "555", acceptedMs = 0)+        d.setActiveCall(call); assertEquals(call, CarLauncherState.activeCall.value)+        d.setActiveCall(null); assertNull(CarLauncherState.activeCall.value)+        idleMain()+    }++    @Test fun `night forwards to map applier and host nav publishes`() {+        val d = display()+        var dark: Boolean? = null+        d.mapDarkApplier = { dark = it }+        d.setNight(true)+        assertEquals(true, dark)+        val nav = HostNavState(navigating = true, cue = "Turn")+        d.setHostNavState(nav)+        assertEquals(nav, CarLauncherState.hostNav.value)+        idleMain()+    }++    @Test fun `tap bounds contain edges inclusively`() {+        val b = CarDisplay.TapBounds(10, 20, 110, 120)+        assertTrue(b.contains(10f, 20f)); assertTrue(b.contains(110f, 120f))+        assertFalse(b.contains(9f, 50f)); assertFalse(b.contains(50f, 121f))+    }++    @Test fun `lifecycle without show is safe`() {+        val d = display()+        d.setParked(true); d.setParked(false)+        d.onNightConfigChanged(Configuration())+        d.startFrameInvalidation(30); d.stopFrameInvalidation()+        d.updateConfig(800, 480, 160) // same size: no-op even without surface+        d.release(); idleMain()+        // input with no decor view drops+        assertFalse(d.input.injectTouch(0, listOf(Triple(1f, 2f, 0)), 0))+        assertFalse(d.input.injectKey(4, true))+        assertFalse(d.input.injectScroll(1))+    }++    @Test fun `late wired callbacks are stored`() {+        val d = display()+        var media = 0+        d.onMediaTap = { media++ }+        d.onMediaTap?.invoke(); assertEquals(1, media)+        d.phoneStatusSource = { PhoneStatus(signalBars = 2, batteryPercent = 50, batteryCharging = false) }+        assertEquals(50, d.phoneStatusSource?.invoke()?.batteryPercent)+        idleMain()+    }+}
auto/src/test/java/com/vayunmathur/auto/platform/CarLauncherStateTest.kt
diff --git a/auto/src/test/java/com/vayunmathur/auto/platform/CarLauncherStateTest.kt b/auto/src/test/java/com/vayunmathur/auto/platform/CarLauncherStateTest.ktnew file mode 100644index 0000000000..e45a32285d--- /dev/null+++ b/auto/src/test/java/com/vayunmathur/auto/platform/CarLauncherStateTest.kt@@ -0,0 +1,99 @@+package com.vayunmathur.auto.platform++import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNull+import kotlin.test.assertTrue++/**+ * Auto module: [CarLauncherState] — the car display's shared UI state.+ * Setters publish to their flows; hideApp drops one app; hideNowPlaying+ * only clears an idle snapshot so a stale "Playing" still clears on pause.+ */+@RunWith(RobolectricTestRunner::class)+class CarLauncherStateTest {++    @BeforeTest+    fun reset() {+        CarLauncherState.setNowPlaying(+            NowPlayingInfo(title = null, artist = null, playing = false, positionMs = 0L, durationMs = null),+        )+        CarLauncherState.hideNowPlaying()+        CarLauncherState.setDrivingRestricted(false)+        CarLauncherState.setNight(false)+        CarLauncherState.setActiveCall(null)+        CarLauncherState.selectApp(null)+        CarLauncherState.setDiscovered(emptyList())+        CarLauncherState.setPinnedOrder(emptyList())+    }++    @Test+    fun `now playing publishes and hide clears a showable snapshot`() {+        val live = NowPlayingInfo(title = "Song", artist = "Band", playing = true, positionMs = 0L, durationMs = null)+        CarLauncherState.setNowPlaying(live)+        assertEquals(live, CarLauncherState.nowPlaying.value)+        // Hide clears the card including a stale resume snapshot; the+        // launcher re-shows on the next visible snapshot. An already-idle+        // snapshot is retained (the card itself gates on shouldShowCard).+        CarLauncherState.hideNowPlaying()+        assertNull(CarLauncherState.nowPlaying.value)+        val idle = live.copy(playing = false, title = null)+        CarLauncherState.setNowPlaying(idle)+        CarLauncherState.hideNowPlaying()+        assertEquals(idle, CarLauncherState.nowPlaying.value)+    }++    @Test+    fun `flags and selection publish`() {+        CarLauncherState.setDrivingRestricted(true)+        assertTrue(CarLauncherState.drivingRestricted.value)+        CarLauncherState.setNight(true)+        assertTrue(CarLauncherState.nightDark.value)+        CarLauncherState.selectApp("maps")+        assertEquals("maps", CarLauncherState.selectedApp.value)+        CarLauncherState.selectApp(null)+        assertNull(CarLauncherState.selectedApp.value)+    }++    @Test+    fun `active call publishes and clears`() {+        val call = ActiveCallInfo(telecomState = 1, number = "555", acceptedMs = 0L)+        CarLauncherState.setActiveCall(call)+        assertEquals(call, CarLauncherState.activeCall.value)+        CarLauncherState.setActiveCall(null)+        assertNull(CarLauncherState.activeCall.value)+    }++    @Test+    fun `phone status and pinned order publish`() {+        val status = PhoneStatus(signalBars = 3, batteryPercent = 80, batteryCharging = false)+        CarLauncherState.setPhoneStatus(status)+        assertEquals(status, CarLauncherState.phoneStatus.value)+        CarLauncherState.setPinnedOrder(listOf("a", "b"))+        assertEquals(listOf("a", "b"), CarLauncherState.pinnedOrder.value)+    }++    @Test+    fun `actions update transforms the stored actions`() {+        var taps = 0+        CarLauncherState.updateActions { it.copy(onMediaTap = { taps++ }) }+        CarLauncherState.actions.value.onMediaTap()+        assertEquals(1, taps)+        // Restore the no-op default so later suites see a clean slate.+        CarLauncherState.updateActions { CarLauncherActions() }+        CarLauncherState.actions.value.onMediaTap()+        assertEquals(1, taps)+    }++    @Test+    fun `defaults are empty and unrestricted`() {+        assertFalse(CarLauncherState.drivingRestricted.value)+        assertFalse(CarLauncherState.nightDark.value)+        assertNull(CarLauncherState.selectedApp.value)+        assertEquals(emptyList(), CarLauncherState.discovered.value)+    }+}
auto/src/test/java/com/vayunmathur/auto/platform/ConsentPrefsTest.kt
diff --git a/auto/src/test/java/com/vayunmathur/auto/platform/ConsentPrefsTest.kt b/auto/src/test/java/com/vayunmathur/auto/platform/ConsentPrefsTest.ktnew file mode 100644index 0000000000..fcdd445344--- /dev/null+++ b/auto/src/test/java/com/vayunmathur/auto/platform/ConsentPrefsTest.kt@@ -0,0 +1,47 @@+package com.vayunmathur.auto.platform++import androidx.test.core.app.ApplicationProvider+import kotlinx.coroutines.test.runTest+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import kotlin.test.Test+import kotlin.test.assertFalse+import kotlin.test.assertTrue++/**+ * Auto module: [MessagingPrefs] and [MusicCapturePrefs] — device-level+ * consent switches. Both fail closed (false until the user opts in) and+ * round-trip through SharedPreferences.+ */+@RunWith(RobolectricTestRunner::class)+class ConsentPrefsTest {++    private val context: android.content.Context+        get() = ApplicationProvider.getApplicationContext()++    @Test+    fun `messaging consent defaults to false and round-trips`() = runTest {+        MessagingPrefs.setMirroringConsented(context, false)+        assertFalse(MessagingPrefs.isMirroringConsented(context))+        MessagingPrefs.setMirroringConsented(context, true)+        assertTrue(MessagingPrefs.isMirroringConsented(context))+        MessagingPrefs.setMirroringConsented(context, false)+        assertFalse(MessagingPrefs.isMirroringConsented(context))+    }++    @Test+    fun `music capture consent defaults to false and round-trips`() = runTest {+        MusicCapturePrefs.setMusicCaptureConsented(context, false)+        assertFalse(MusicCapturePrefs.isMusicCaptureConsented(context))+        MusicCapturePrefs.setMusicCaptureConsented(context, true)+        assertTrue(MusicCapturePrefs.isMusicCaptureConsented(context))+        MusicCapturePrefs.setMusicCaptureConsented(context, false)+        assertFalse(MusicCapturePrefs.isMusicCaptureConsented(context))+    }++    @Test+    fun `mic permission reads the platform grant state`() {+        // Robolectric grants nothing by default: fail-closed like production.+        assertFalse(MicPermission.isGranted(context))+    }+}
auto/src/test/java/com/vayunmathur/auto/platform/DisplayAndEncoderTest.kt
diff --git a/auto/src/test/java/com/vayunmathur/auto/platform/DisplayAndEncoderTest.kt b/auto/src/test/java/com/vayunmathur/auto/platform/DisplayAndEncoderTest.ktnew file mode 100644index 0000000000..ee80d41563--- /dev/null+++ b/auto/src/test/java/com/vayunmathur/auto/platform/DisplayAndEncoderTest.kt@@ -0,0 +1,60 @@+package com.vayunmathur.auto.platform++import android.graphics.SurfaceTexture+import android.view.Surface+import androidx.test.core.app.ApplicationProvider+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.Shadows+import android.os.Looper+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++@RunWith(RobolectricTestRunner::class)+class DisplayAndEncoderTest {+    private val ctx get() = ApplicationProvider.getApplicationContext<android.content.Context>()+    private fun idleMain() = Shadows.shadowOf(Looper.getMainLooper()).idle()++    @Test fun `encoder lifecycle without frames`() {+        var frames = 0+        val encoder = VideoEncoder(320, 240, 30, onFrame = { _, _ -> frames++ })+        encoder.requestKeyFrame() // no codec yet: no-op+        assertEquals(false, encoder.drain())+        encoder.start()+        // Robolectric's shadow codec may not vend an input surface; the lifecycle is the contract here+        encoder.requestKeyFrame()+        encoder.drain()+        encoder.stop()+        encoder.stop() // idempotent+        assertEquals(0, frames)+    }++    @Test fun `car display show and release renders the launcher`() {+        CarLauncherState.selectApp(null)+        CarLauncherState.setDiscovered(emptyList())+        val texture = SurfaceTexture(1)+        val surface = Surface(texture)+        val display = CarDisplay(ctx, 800, 480, 160)+        display.show(surface)+        idleMain()+        // The presentation is up: night/now-playing pushes reach shared state+        display.setNight(true)+        assertTrue(CarLauncherState.nightDark.value)+        display.startFrameInvalidation(30)+        idleMain()+        display.stopFrameInvalidation()+        // Input injection with a live decor view dispatches (returns true)+        assertTrue(display.input.injectTouch(0, listOf(Triple(10f, 10f, 0)), 0))+        assertTrue(display.input.injectKey(4, true))+        assertTrue(display.input.injectScroll(1))+        idleMain()+        display.updateConfig(1024, 600, 160)+        idleMain()+        display.release()+        idleMain()+        surface.release()+        texture.release()+        CarLauncherState.setNight(false)+    }+}
auto/src/test/java/com/vayunmathur/auto/platform/GuidanceChannelTest.kt
diff --git a/auto/src/test/java/com/vayunmathur/auto/platform/GuidanceChannelTest.kt b/auto/src/test/java/com/vayunmathur/auto/platform/GuidanceChannelTest.ktnew file mode 100644index 0000000000..7bd2ce2c41--- /dev/null+++ b/auto/src/test/java/com/vayunmathur/auto/platform/GuidanceChannelTest.kt@@ -0,0 +1,183 @@+package com.vayunmathur.auto.platform++import com.vayunmathur.auto.protocol.GalConnection+import com.vayunmathur.auto.protocol.GalService+import com.vayunmathur.auto.protocol.GalTransport+import com.vayunmathur.auto.protocol.gal.AudioConfiguration+import com.vayunmathur.auto.protocol.gal.MediaCodecType+import com.vayunmathur.auto.protocol.gal.MediaSetupResponse+import com.vayunmathur.auto.protocol.gal.MediaSinkService+import com.vayunmathur.auto.protocol.gal.Service+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import java.io.ByteArrayOutputStream+import javax.net.ssl.SSLContext+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++/**+ * Auto module: [GuidanceChannel] — the ch3 guidance sink. The grant claims+ * the channel; a TTS session that predates the grant arms the stream; CONFIG+ * confirms against discovery; stop parks without restarting. Sends ride a+ * closed real connection — see [InputChannelTest] for the seam.+ */+@RunWith(RobolectricTestRunner::class)+class GuidanceChannelTest {++    private class FakeTransport : GalTransport {+        val written = ByteArrayOutputStream()+        override fun read(buffer: ByteArray, offset: Int, length: Int): Int = -1+        override fun write(bytes: ByteArray, offset: Int, length: Int) {+            written.write(bytes, offset, length)+        }+        override fun flush() = Unit+        override fun close() = Unit+    }++    private fun connection(): GalConnection {+        val context = SSLContext.getInstance("TLS").apply { init(null, null, null) }+        return GalConnection(FakeTransport(), context, deviceModel = "Test").also { it.close() }+    }++    private fun config(rate: Int = 44_100, bits: Int = 16, channels: Int = 1): AudioConfiguration =+        AudioConfiguration.newBuilder()+            .setSamplingRate(rate)+            .setNumberOfBits(bits)+            .setNumberOfChannels(channels)+            .build()++    private fun guidanceService(vararg configs: AudioConfiguration): Service =+        Service.newBuilder()+            .setId(GalService.AUDIO_SINK_GUIDANCE.id)+            .setMediaSink(+                MediaSinkService.newBuilder()+                    .setAvailableType(MediaCodecType.MEDIA_CODEC_AUDIO_PCM)+                    .addAllAudioConfigs(configs.asList())+                    .build(),+            )+            .build()++    private fun configResponse(vararg indices: Int): ByteArray =+        MediaSetupResponse.newBuilder().setMediaStatus(0)+            .addAllConfigurationIndices(indices.asList()).build()+            .toByteArray()++    @Test+    fun `channel id comes from discovery`() {+        assertEquals(+            GalService.AUDIO_SINK_GUIDANCE.id,+            GuidanceChannel(guidanceService(config()), connection()).channelId,+        )+    }++    @Test+    fun `the grant claims the channel with a setup`() {+        val events = mutableListOf<SensorEvent>()+        GuidanceChannel(guidanceService(config()), connection(), onEvent = { events += it })+            .onChannelOpen()+        assertEquals(listOf<SensorEvent>(SensorEvent.GuidanceSetup), events)+    }++    @Test+    fun `an active tts session arms the stream on the grant`() {+        val events = mutableListOf<SensorEvent>()+        val channel = GuidanceChannel(+            guidanceService(config()), connection(),+            ttsActive = { true },+            onEvent = { events += it },+        )+        channel.onChannelOpen()+        assertEquals(listOf<SensorEvent>(SensorEvent.GuidanceSetup), events)+        // CONFIG confirms: the armed stream starts instead of parking idle.+        channel.onMessage(+            GalService.AUDIO_SINK_GUIDANCE.id,+            com.vayunmathur.auto.protocol.GalMessage.Media.CONFIG,+            configResponse(),+        )+        assertEquals(+            listOf(SensorEvent.GuidanceSetup, SensorEvent.GuidanceConfigured(true)),+            events,+        )+    }++    @Test+    fun `config without tts stays idle until start`() {+        val events = mutableListOf<SensorEvent>()+        val channel = GuidanceChannel(+            guidanceService(config()), connection(),+            ttsActive = { false },+            onEvent = { events += it },+        )+        channel.onChannelOpen()+        channel.onMessage(+            GalService.AUDIO_SINK_GUIDANCE.id,+            com.vayunmathur.auto.protocol.GalMessage.Media.CONFIG,+            configResponse(),+        )+        assertEquals(+            listOf(SensorEvent.GuidanceSetup, SensorEvent.GuidanceConfigured(true)),+            events,+        )+        // Start then stop: the stream parks, and a later CONFIG cannot restart it.+        channel.startStream()+        channel.stopStream()+        channel.onMessage(+            GalService.AUDIO_SINK_GUIDANCE.id,+            com.vayunmathur.auto.protocol.GalMessage.Media.CONFIG,+            configResponse(),+        )+        assertEquals(2, events.count { it is SensorEvent.GuidanceConfigured })+    }++    @Test+    fun `start before config arms and the confirm starts it`() {+        val events = mutableListOf<SensorEvent>()+        val channel = GuidanceChannel(guidanceService(config()), connection(), onEvent = { events += it })+        channel.onChannelOpen()+        channel.startStream()+        channel.onMessage(+            GalService.AUDIO_SINK_GUIDANCE.id,+            com.vayunmathur.auto.protocol.GalMessage.Media.CONFIG,+            configResponse(),+        )+        assertTrue(events.filterIsInstance<SensorEvent.GuidanceConfigured>().isNotEmpty())+    }++    @Test+    fun `wrong-channel traffic is ignored`() {+        val events = mutableListOf<SensorEvent>()+        val channel = GuidanceChannel(guidanceService(config()), connection(), onEvent = { events += it })+        channel.onChannelOpen()+        channel.onMessage(7, com.vayunmathur.auto.protocol.GalMessage.Media.CONFIG, configResponse())+        assertEquals(listOf<SensorEvent>(SensorEvent.GuidanceSetup), events)+    }++    @Test+    fun `acks and syncs are observed without events`() {+        val events = mutableListOf<SensorEvent>()+        val channel = GuidanceChannel(guidanceService(config()), connection(), onEvent = { events += it })+        channel.onChannelOpen()+        channel.onMessage(+            GalService.AUDIO_SINK_GUIDANCE.id,+            com.vayunmathur.auto.protocol.GalMessage.Media.ACK,+            com.vayunmathur.auto.protocol.gal.MediaAck.newBuilder().setSessionId(0).build().toByteArray(),+        )+        channel.onMessage(+            GalService.AUDIO_SINK_GUIDANCE.id,+            com.vayunmathur.auto.protocol.GalMessage.Audio.SYNC,+            byteArrayOf(),+        )+        assertEquals(listOf<SensorEvent>(SensorEvent.GuidanceSetup), events)+    }++    @Test+    fun `release parks the stream`() {+        val channel = GuidanceChannel(guidanceService(config()), connection())+        channel.onChannelOpen()+        channel.startStream()+        channel.release()+        // Post-release stop is safe (session id reset).+        channel.stopStream()+    }+}
auto/src/test/java/com/vayunmathur/auto/platform/HostManagerTest.kt
diff --git a/auto/src/test/java/com/vayunmathur/auto/platform/HostManagerTest.kt b/auto/src/test/java/com/vayunmathur/auto/platform/HostManagerTest.ktnew file mode 100644index 0000000000..46bbba0b03--- /dev/null+++ b/auto/src/test/java/com/vayunmathur/auto/platform/HostManagerTest.kt@@ -0,0 +1,92 @@+package com.vayunmathur.auto.platform++import android.content.ComponentName+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.library.carhost.HostTemplate+import com.vayunmathur.library.carhost.HostUiAction+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.Shadows+import android.os.Looper+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNull+import kotlin.test.assertTrue++@RunWith(RobolectricTestRunner::class)+class HostManagerTest {+    private val ctx get() = ApplicationProvider.getApplicationContext<android.content.Context>()+    private fun app(pkg: String, cats: Set<String>) = DiscoveredApp(ComponentName(pkg, "$pkg.Svc"), pkg, null, cats)+    private val maps = app("com.example.maps", setOf("nav"))+    private val noCat = app("com.example.nocat", emptySet())++    @BeforeTest fun reset() {+        CarLauncherState.setDiscovered(emptyList()); CarLauncherState.selectApp(null)+        CarLauncherState.updateActions { CarLauncherActions() }+    }+    private fun idleMain() = Shadows.shadowOf(Looper.getMainLooper()).idle()++    @Test fun `bindAll with no category binds nothing`() {+        val mgr = HostManager(ctx)+        mgr.bindAll(listOf(noCat))+        assertNull(mgr.templateFor(noCat.component))+        assertNull(mgr.focused.value)+        mgr.unbindAll()+    }++    @Test fun `bindAll with missing service posts error template`() {+        val mgr = HostManager(ctx)+        mgr.bindAll(listOf(maps))+        idleMain()+        val template = mgr.templateFor(maps.component)+        assertTrue(template is HostTemplate.Message, "expected Message, got $template")+        mgr.unbindAll()+        assertNull(mgr.templateFor(maps.component))+    }++    @Test fun `focus and surface forwarding with no session are safe`() {+        val mgr = HostManager(ctx)+        mgr.bindAll(listOf(maps)); idleMain()+        mgr.setFocused(maps.component)+        assertEquals(maps.component, mgr.focused.value)+        mgr.setFocused(maps.component) // same: no-op+        mgr.forwardSurface(null, 0, 0)+        assertFalse(mgr.injectMapTouch(0, 1f, 2f))+        mgr.setNight(true)+        mgr.resetApp(ComponentName("com.absent", "com.absent.Svc")) // absent: no-op+        mgr.setFocused(null)+        assertNull(mgr.focused.value)+        mgr.unbindAll()+        assertNull(mgr.focused.value)+    }++    @Test fun `dropGone removes templates for disappeared apps`() {+        val mgr = HostManager(ctx)+        mgr.bindAll(listOf(maps)); idleMain()+        assertTrue(mgr.templateFor(maps.component) is HostTemplate.Message)+        mgr.bindAll(emptyList()); idleMain()+        assertNull(mgr.templateFor(maps.component))+        mgr.unbindAll()+    }++    @Test fun `template bus maps navigation to legacy and ignores others`() {+        val nav = HostTemplate.Navigation(+            navigating = true, loading = false, cue = "Turn left", road = "Main St",+            distanceText = "200 m", etaText = "5 min", lanesText = "2",+            actions = listOf(HostUiAction("Dismiss") {}),+        )+        val legacy = HostTemplateBus.toLegacy(nav)+        assertEquals(true, legacy?.mapsPresent)+        assertEquals(true, legacy?.navigating)+        assertEquals("Turn left", legacy?.cue)+        assertEquals("Main St", legacy?.road)+        assertEquals(1, legacy?.actions?.size)+        assertNull(HostTemplateBus.toLegacy(HostTemplate.Pane(title = "x")))+        HostTemplateBus.publish(nav)+        assertEquals("Turn left", HostTemplateBus.legacyNav.value?.cue)+        HostTemplateBus.publish(HostTemplate.Pane(title = "y"))+        assertEquals("Turn left", HostTemplateBus.legacyNav.value?.cue)+    }+}
auto/src/test/java/com/vayunmathur/auto/platform/HostSessionTest.kt
diff --git a/auto/src/test/java/com/vayunmathur/auto/platform/HostSessionTest.kt b/auto/src/test/java/com/vayunmathur/auto/platform/HostSessionTest.ktnew file mode 100644index 0000000000..6c8607dd29--- /dev/null+++ b/auto/src/test/java/com/vayunmathur/auto/platform/HostSessionTest.kt@@ -0,0 +1,77 @@+package com.vayunmathur.auto.platform++import android.content.ComponentName+import android.graphics.SurfaceTexture+import android.view.Surface+import androidx.lifecycle.Lifecycle+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.library.carhost.HostTemplate+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.Shadows+import android.os.Looper+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue++@RunWith(RobolectricTestRunner::class)+class HostSessionTest {+    private val ctx get() = ApplicationProvider.getApplicationContext<android.content.Context>()+    private val component = ComponentName("com.example.maps", "com.example.maps.Svc")+    private fun idleMain() = Shadows.shadowOf(Looper.getMainLooper()).idle()++    @Test fun `missing service bind posts can't-open message`() {+        val templates = mutableListOf<HostTemplate>()+        val session = HostSession(ctx, component, "nav", "Maps", onTemplate = { templates += it })+        assertEquals(component, session.componentName())+        assertFalse(session.hasService())+        session.bind(); idleMain()+        val msg = templates.filterIsInstance<HostTemplate.Message>().single()+        assertEquals("Can't open Maps", msg.title)+        session.bind() // missing again: another message, still no crash+        idleMain()+        assertEquals(2, templates.filterIsInstance<HostTemplate.Message>().size)+    }++    @Test fun `no-app operations are safe no-ops`() {+        val session = HostSession(ctx, component, "nav", "Maps")+        assertFalse(session.injectMapTouch(0, 1f, 2f))+        session.setNight(true)+        session.clearSurface()+        session.fetchTemplate()+        val surface = Surface(SurfaceTexture(1))+        session.setSurface(surface, 800, 480)+        session.clearSurface()+        session.unbind()+        surface.release()+    }++    @Test fun `task stack counts pushes, refreshes and navigation resets`() {+        val stack = HostTaskStack()+        stack.record(HostTemplate.Pane(title = "a"))+        assertTrue(stack.isAllowed(HostTemplate.Pane(title = "b")))+        stack.record(HostTemplate.Pane(title = "b")) // same kind: refresh, no push+        stack.record(HostTemplate.Grid())+        stack.record(HostTemplate.PlaceList())+        stack.record(HostTemplate.Search())+        stack.record(HostTemplate.Tabs())+        stack.record(HostTemplate.SignIn())+        // depth now exceeds 5 for non-terminal kinds+        assertFalse(stack.isAllowed(HostTemplate.Grid()))+        assertTrue(stack.isAllowed(HostTemplate.Navigation()))+        assertTrue(stack.isAllowed(HostTemplate.Message(title = "x")))+        stack.record(HostTemplate.Navigation())+        assertTrue(stack.isAllowed(HostTemplate.Grid()))+        stack.reset()+        assertTrue(stack.isAllowed(HostTemplate.Grid()))+    }++    @Test fun `display lifecycle steps to resumed then destroyed`() {+        val lifecycle = CarDisplayLifecycle()+        lifecycle.moveToResumed()+        assertEquals(Lifecycle.State.RESUMED, lifecycle.lifecycle.currentState)+        lifecycle.moveToDestroyed()+        assertEquals(Lifecycle.State.DESTROYED, lifecycle.lifecycle.currentState)+    }+}
auto/src/test/java/com/vayunmathur/auto/platform/InputChannelTest.kt
diff --git a/auto/src/test/java/com/vayunmathur/auto/platform/InputChannelTest.kt b/auto/src/test/java/com/vayunmathur/auto/platform/InputChannelTest.ktnew file mode 100644index 0000000000..d4cd175a23--- /dev/null+++ b/auto/src/test/java/com/vayunmathur/auto/platform/InputChannelTest.kt@@ -0,0 +1,250 @@+package com.vayunmathur.auto.platform++import com.vayunmathur.auto.protocol.GalConnection+import com.vayunmathur.auto.protocol.GalMessage+import com.vayunmathur.auto.protocol.GalTransport+import com.vayunmathur.auto.protocol.InputCodec+import com.vayunmathur.auto.protocol.InputKey+import com.vayunmathur.auto.protocol.gal.InputSourceService+import com.vayunmathur.auto.protocol.gal.Service+import com.vayunmathur.auto.protocol.gal.TouchConfig+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import java.io.ByteArrayOutputStream+import javax.net.ssl.SSLContext+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++/**+ * Auto module: [InputChannel] — the head-unit input source. Binding echoes+ * the discovery keycodes; reports inject only with input focus and a car+ * display; volume keys are consumed, never injected; traffic before binding+ * or for another channel is dropped, never misparsed.+ *+ * The channel only needs `GalConnection.send(channelId, type, payload)`; a+ * real connection closed before use drops sends silently (see+ * `GalConnection.close`), so these tests drive the event/sink paths without+ * a TLS handshake or a socket.+ */+@RunWith(RobolectricTestRunner::class)+class InputChannelTest {++    private class FakeTransport : GalTransport {+        val written = ByteArrayOutputStream()+        override fun read(buffer: ByteArray, offset: Int, length: Int): Int = -1+        override fun write(bytes: ByteArray, offset: Int, length: Int) {+            written.write(bytes, offset, length)+        }+        override fun flush() = Unit+        override fun close() = Unit+    }++    /** A real connection, closed: sends drop silently, events still fire. */+    private fun connection(): GalConnection {+        val context = SSLContext.getInstance("TLS").apply { init(null, null, null) }+        return GalConnection(FakeTransport(), context, deviceModel = "Test").also { it.close() }+    }++    private fun service(+        keycodes: List<Int> = listOf(19, 20),+        feedback: List<Int> = emptyList(),+    ): Service = Service.newBuilder()+        .setId(8)+        .setInputSource(+            InputSourceService.newBuilder()+                .addAllKeycodesSupported(keycodes)+                .addAllFeedbackEventsSupported(feedback)+                .addTouchscreen(+                    TouchConfig.newBuilder().setWidth(800).setHeight(480).build(),+                ),+        )+        .build()++    @Test+    fun `channel id comes from discovery`() {+        val channel = InputChannel(service(), connection())+        assertEquals(8, channel.channelId)+    }++    @Test+    fun `traffic for another channel is ignored`() {+        val events = mutableListOf<InputEvent>()+        val channel = InputChannel(service(), connection(), onEvent = { events += it })+        channel.onMessage(99, GalMessage.Input.REPORT, InputCodec.buildReport())+        assertTrue(events.isEmpty())+    }++    @Test+    fun `traffic before binding drops without focus`() {+        val events = mutableListOf<InputEvent>()+        val channel = InputChannel(service(), connection(), onEvent = { events += it })+        channel.onMessage(8, GalMessage.Input.REPORT, InputCodec.buildReport())+        assertEquals(listOf<InputEvent>(InputEvent.DroppedNoFocus), events)+    }++    @Test+    fun `binding response before binding drops without focus`() {+        val events = mutableListOf<InputEvent>()+        val channel = InputChannel(service(), connection(), onEvent = { events += it })+        channel.onMessage(8, GalMessage.Input.KEY_BINDING_RESPONSE, byteArrayOf(0x08, 0x00))+        assertEquals(listOf<InputEvent>(InputEvent.DroppedNoFocus), events)+    }++    @Test+    fun `key report without input focus drops`() {+        val events = mutableListOf<InputEvent>()+        val channel = InputChannel(+            service(), connection(),+            isInputAllowed = { false },+            displaySize = { 800 to 480 },+            onEvent = { events += it },+            keySink = { error("must not inject without focus") },+        )+        channel.requestBinding()+        assertEquals(+            listOf(InputEvent.BindingRequested(2)),+            events.filterIsInstance<InputEvent.BindingRequested>(),+        )+        channel.onMessage(8, GalMessage.Input.REPORT, InputCodec.buildKeyReport(0, 19 to true))+        assertTrue(events.contains(InputEvent.DroppedNoFocus))+    }++    @Test+    fun `key report without a display drops`() {+        val events = mutableListOf<InputEvent>()+        val channel = InputChannel(+            service(), connection(),+            isInputAllowed = { true },+            displaySize = { null },+            onEvent = { events += it },+            keySink = { error("must not inject without a display") },+        )+        channel.requestBinding()+        channel.onMessage(8, GalMessage.Input.REPORT, InputCodec.buildKeyReport(0, 19 to true))+        assertTrue(events.contains(InputEvent.DroppedNoFocus))+    }++    @Test+    fun `key press injects and volume keys are consumed`() {+        val events = mutableListOf<InputEvent>()+        val injected = mutableListOf<InputKey>()+        val channel = InputChannel(+            service(), connection(),+            isInputAllowed = { true },+            displaySize = { 800 to 480 },+            onEvent = { events += it },+            keySink = { injected += it; true },+        )+        channel.requestBinding()+        channel.onMessage(8, GalMessage.Input.REPORT, InputCodec.buildKeyReport(0, 19 to true))+        assertEquals(listOf(InputKey(19, true)), injected)+        assertTrue(events.filterIsInstance<InputEvent.Key>().isNotEmpty())+        // Volume up is consumed (observed), never forwarded to the sink.+        channel.onMessage(8, GalMessage.Input.REPORT, InputCodec.buildKeyReport(0, 24 to true))+        assertEquals(listOf(InputKey(19, true)), injected)+        assertTrue(events.filterIsInstance<InputEvent.VolumeKey>().isNotEmpty())+    }++    @Test+    fun `touch report scales to the car display and injects`() {+        val injected = mutableListOf<ScaledTouch>()+        val channel = InputChannel(+            service(), connection(),+            isInputAllowed = { true },+            displaySize = { 800 to 480 },+            touchSink = { injected += it; true },+        )+        channel.requestBinding()+        channel.onMessage(8, GalMessage.Input.REPORT, InputCodec.buildReport())+        assertEquals(1, injected.size)+        assertEquals(1, injected.single().pointers.size)+    }++    @Test+    fun `unknown message types are observed and ignored`() {+        val events = mutableListOf<InputEvent>()+        val channel = InputChannel(+            service(), connection(),+            isInputAllowed = { true },+            displaySize = { 800 to 480 },+            onEvent = { events += it },+        )+        channel.requestBinding()+        val before = events.size+        channel.onMessage(8, 0x1234, byteArrayOf(1, 2, 3))+        assertEquals(before, events.size)+    }++    @Test+    fun `scroll report injects its delta`() {+        val events = mutableListOf<InputEvent>()+        val deltas = mutableListOf<Int>()+        val channel = InputChannel(+            service(), connection(),+            isInputAllowed = { true },+            displaySize = { 800 to 480 },+            onEvent = { events += it },+            scrollSink = { deltas += it; true },+        )+        channel.requestBinding()+        channel.onMessage(8, GalMessage.Input.REPORT, InputCodec.buildScrollReport(delta = 3))+        assertEquals(listOf(3), deltas)+        assertEquals(listOf<InputEvent>(InputEvent.Scroll(3)), events.filterIsInstance<InputEvent.Scroll>())+    }++    @Test+    fun `tap-as-select presses dpad center`() {+        val injected = mutableListOf<InputKey>()+        val channel = InputChannel(+            service(), connection(),+            isInputAllowed = { true },+            displaySize = { 800 to 480 },+            keySink = { injected += it; true },+        )+        channel.requestBinding()+        channel.onMessage(+            8, GalMessage.Input.REPORT,+            InputCodec.buildAbsoluteReport(keycode = InputCodec.TAP_SELECT_KEYCODE, value = 1),+        )+        assertEquals(listOf(InputKey(InputCodec.KEYCODE_DPAD_CENTER, true)), injected)+    }++    @Test+    fun `key binding answer is observed with its status`() {+        val events = mutableListOf<InputEvent>()+        val channel = InputChannel(service(), connection(), onEvent = { events += it })+        channel.requestBinding()+        channel.onMessage(8, GalMessage.Input.KEY_BINDING_RESPONSE, byteArrayOf(0x08, 0x00))+        assertEquals(+            listOf(InputEvent.BindingAnswered(0)),+            events.filterIsInstance<InputEvent.BindingAnswered>(),+        )+    }++    @Test+    fun `focus flap parks and re-binds`() {+        val events = mutableListOf<InputEvent>()+        val channel = InputChannel(service(), connection(), onEvent = { events += it })+        // No binding yet: focus changes are no-ops, never sends.+        channel.onInputFocusChanged(false)+        channel.onInputFocusChanged(true)+        assertTrue(events.isEmpty())+        channel.requestBinding()+        val binds = events.filterIsInstance<InputEvent.BindingRequested>().size+        channel.onInputFocusChanged(false)+        channel.onInputFocusChanged(true)+        assertEquals(+            binds + 1,+            events.filterIsInstance<InputEvent.BindingRequested>().size,+        )+    }++    @Test+    fun `feedback before binding is a silent no-op`() {+        val events = mutableListOf<InputEvent>()+        val channel = InputChannel(service(), connection(), onEvent = { events += it })+        channel.sendFeedback(5)+        assertTrue(events.isEmpty())+    }+}
auto/src/test/java/com/vayunmathur/auto/platform/MicSourceChannelTest.kt
diff --git a/auto/src/test/java/com/vayunmathur/auto/platform/MicSourceChannelTest.kt b/auto/src/test/java/com/vayunmathur/auto/platform/MicSourceChannelTest.ktnew file mode 100644index 0000000000..4deba90436--- /dev/null+++ b/auto/src/test/java/com/vayunmathur/auto/platform/MicSourceChannelTest.kt@@ -0,0 +1,187 @@+package com.vayunmathur.auto.platform++import com.vayunmathur.auto.protocol.GalConnection+import com.vayunmathur.auto.protocol.GalMessage+import com.vayunmathur.auto.protocol.GalService+import com.vayunmathur.auto.protocol.GalTransport+import org.junit.runner.RunWith+import org.junit.Rule+import org.junit.rules.Timeout+import org.robolectric.RobolectricTestRunner+import org.robolectric.Shadows+import org.robolectric.annotation.LooperMode+import java.io.ByteArrayOutputStream+import java.nio.ByteBuffer+import java.nio.ByteOrder+import javax.net.ssl.SSLContext+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++/**+ * Auto module: [MicSourceChannel] — the car microphone. Requests ack+ * opaquely; bulk chunks ack without retention until a permission-gated turn+ * buffers them; wrong-channel traffic is ignored. The mic thread is real+ * (HandlerThread), so turn tests drain it with a blocking round-trip.+ * Sends ride a closed real connection — see [InputChannelTest] for the seam.+ */+@RunWith(RobolectricTestRunner::class)+@LooperMode(LooperMode.Mode.LEGACY)+class MicSourceChannelTest {++    @get:Rule+    val timeout: Timeout = Timeout.seconds(30)++    /** Tripped by the next observed event; set by [drain] as a thread barrier. */+    @Volatile+    private var barrier: java.util.concurrent.CountDownLatch? = null++    private fun observe(events: MutableList<AudioEvent>): (AudioEvent) -> Unit = { event ->+        events += event+        barrier?.countDown()+    }++    private class FakeTransport : GalTransport {+        val written = ByteArrayOutputStream()+        override fun read(buffer: ByteArray, offset: Int, length: Int): Int = -1+        override fun write(bytes: ByteArray, offset: Int, length: Int) {+            written.write(bytes, offset, length)+        }+        override fun flush() = Unit+        override fun close() = Unit+    }++    private fun connection(): GalConnection {+        val context = SSLContext.getInstance("TLS").apply { init(null, null, null) }+        return GalConnection(FakeTransport(), context, deviceModel = "Test").also { it.close() }+    }++    private fun chunk(pcm: ByteArray): ByteArray {+        val header = ByteBuffer.allocate(8).order(ByteOrder.BIG_ENDIAN).putLong(123L).array()+        return header + pcm+    }++    @Test+    fun `channel id is the audio source`() {+        assertEquals(GalService.AUDIO_SOURCE.id, MicSourceChannel(connection()).channelId)+    }++    @Test+    fun `wrong-channel traffic is ignored`() {+        val events = mutableListOf<AudioEvent>()+        val channel = MicSourceChannel(connection(), onEvent = observe(events))+        channel.onChannelOpen()+        channel.onMessage(8, GalMessage.Microphone.REQUEST, byteArrayOf())+        channel.release()+        assertTrue(events.isEmpty())+    }++    @Test+    fun `mic requests ack without events`() {+        val events = mutableListOf<AudioEvent>()+        val channel = MicSourceChannel(connection(), onEvent = observe(events))+        channel.onChannelOpen()+        channel.onMessage(channel.channelId, GalMessage.Microphone.REQUEST, byteArrayOf(1, 2))+        // The ack rides the closed connection (dropped); the request itself+        // is acked opaquely and counted, never parsed.+        channel.release()+        assertEquals(listOf<AudioEvent>(AudioEvent.MicAcked), events)+    }++    @Test+    fun `chunks without a turn ack and count idle`() {+        val events = mutableListOf<AudioEvent>()+        val channel = MicSourceChannel(connection(), onEvent = observe(events))+        channel.onChannelOpen()+        channel.onMessage(channel.channelId, GalMessage.Media.DATA_WITH_TIMESTAMP, chunk(byteArrayOf(1, 2, 3)))+        drain(channel)+        channel.release()+        // The chunk and the barrier chunk each observe idle plus their ack.+        assertEquals(4, events.size)+        assertEquals(+            listOf(AudioEvent.MicIdle, AudioEvent.MicAcked, AudioEvent.MicIdle, AudioEvent.MicAcked),+            events,+        )+    }++    @Test+    fun `unparseable traffic is observed and ignored`() {+        val events = mutableListOf<AudioEvent>()+        val channel = MicSourceChannel(connection(), onEvent = observe(events))+        channel.onChannelOpen()+        channel.onMessage(channel.channelId, 0x1234, byteArrayOf(1))+        channel.onMessage(channel.channelId, GalMessage.Media.DATA, byteArrayOf())+        channel.release()+        assertTrue(events.isEmpty())+    }++    @Test+    fun `a turn without retention yields nothing`() {+        val events = mutableListOf<AudioEvent>()+        var callbackFired = false+        val channel = MicSourceChannel(+            connection(),+            retentionAllowed = { false },+            onEvent = observe(events),+        )+        channel.onChannelOpen()+        channel.beginTurn { callbackFired = true }+        channel.onMessage(channel.channelId, GalMessage.Media.DATA_WITH_TIMESTAMP, chunk(byteArrayOf(9)))+        channel.endTurn()+        drain(channel)+        channel.release()+        assertEquals(false, callbackFired)+    }++    @Test+    fun `a retained turn hands the buffered pcm to its callback`() {+        val events = mutableListOf<AudioEvent>()+        var result: ByteArray? = null+        val channel = MicSourceChannel(+            connection(),+            retentionAllowed = { true },+            onEvent = observe(events),+        )+        channel.onChannelOpen()+        channel.beginTurn { result = it }+        channel.onMessage(channel.channelId, GalMessage.Media.DATA_WITH_TIMESTAMP, chunk(byteArrayOf(1, 2)))+        channel.onMessage(channel.channelId, GalMessage.Media.DATA_WITH_TIMESTAMP, chunk(byteArrayOf(3, 4, 5)))+        channel.endTurn()+        drain(channel)+        channel.release()+        val pcm = result ?: error("expected retained pcm")+        assertEquals(listOf<Byte>(1, 2, 3, 4, 5), pcm.toList())+        assertEquals(1, events.count { it is AudioEvent.MicTurn })+        assertEquals(5L, (events.single { it is AudioEvent.MicTurn } as AudioEvent.MicTurn).bytes)+    }++    /**+     * Barrier on the mic thread: posts one chunk after every earlier post+     * (same FIFO handler). With no turn open the chunk observes MicIdle plus+     * its ack, which trips the latch — so await returns only after all+     * earlier posts ran. The barrier's own events stay in [events]; tests+     * that assert exact contents account for them.+     */+    private fun drain(channel: MicSourceChannel) {+        val latch = java.util.concurrent.CountDownLatch(1)+        barrier = latch+        try {+            channel.onMessage(+                channel.channelId,+                GalMessage.Media.DATA_WITH_TIMESTAMP,+                chunk(byteArrayOf(0)),+            )+            // The mic looper is paused under Robolectric: idle every known+            // looper (a no-op for idle ones) so the barrier chunk runs.+            for (looper in org.robolectric.shadows.ShadowLooper.getAllLoopers()) {+                runCatching { Shadows.shadowOf(looper).idle() }+            }+            assertTrue(+                latch.await(5, java.util.concurrent.TimeUnit.SECONDS),+                "mic thread did not drain",+            )+        } finally {+            barrier = null+        }+    }+}
auto/src/test/java/com/vayunmathur/auto/platform/MonitorsTest.kt
diff --git a/auto/src/test/java/com/vayunmathur/auto/platform/MonitorsTest.kt b/auto/src/test/java/com/vayunmathur/auto/platform/MonitorsTest.ktnew file mode 100644index 0000000000..797c2bd08b--- /dev/null+++ b/auto/src/test/java/com/vayunmathur/auto/platform/MonitorsTest.kt@@ -0,0 +1,74 @@+package com.vayunmathur.auto.platform++import android.content.Context+import android.location.Location+import android.location.LocationManager+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.auto.protocol.MapRoutePoint+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.Shadows+import android.os.Looper+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertTrue++@RunWith(RobolectricTestRunner::class)+class MonitorsTest {+    private val ctx get() = ApplicationProvider.getApplicationContext<Context>()+    private fun idleMain() = Shadows.shadowOf(Looper.getMainLooper()).idle()++    @Test fun `media monitor with no browser service leaves updates empty`() {+        val updates = mutableListOf<NowPlayingInfo>()+        val monitor = MediaPlaybackMonitor(ctx) { updates += it }+        monitor.start(); idleMain()+        assertTrue(updates.isEmpty())+        monitor.toggle(); monitor.seekToPrevious(); monitor.seekToNext(); idleMain()+        assertTrue(updates.isEmpty())+        monitor.stop(); idleMain()+    }++    @Test fun `nav monitor seeds from last known fix`() {+        val lm = ctx.getSystemService(LocationManager::class.java)+        val shadow = Shadows.shadowOf(lm)+        val loc = Location(LocationManager.GPS_PROVIDER).apply {+            latitude = 37.4; longitude = -122.1; time = 1234L+        }+        runCatching { shadow.setProviderEnabled(LocationManager.GPS_PROVIDER, true) }+        runCatching { shadow.setLastKnownLocation(LocationManager.GPS_PROVIDER, loc) }+        val updates = mutableListOf<com.vayunmathur.auto.protocol.NavSnapshot>()+        val monitor = NavGuidanceMonitor(ctx) { updates += it }+        monitor.start(); idleMain()+        // Seeding depends on Robolectric shadow behaviour; at minimum start/stop must not crash and state is consistent+        if (updates.isNotEmpty()) {+            assertEquals(374000000L, updates.last().latitudeE7)+        }+        monitor.stop(); idleMain()+    }++    @Test fun `nav monitor with route provider overlays guidance on simulated fix`() {+        val lm = ctx.getSystemService(LocationManager::class.java)+        val shadow = Shadows.shadowOf(lm)+        runCatching { shadow.setProviderEnabled(LocationManager.GPS_PROVIDER, true) }+        runCatching { shadow.setProviderEnabled(LocationManager.NETWORK_PROVIDER, true) }+        val updates = mutableListOf<com.vayunmathur.auto.protocol.NavSnapshot>()+        val monitor = NavGuidanceMonitor(ctx) { updates += it }+        monitor.routeProvider = RouteProvider {+            ActiveRoute(points = listOf(MapRoutePoint(37.4, -122.1)), nextRoad = "Main St", nextTurnDistanceM = 200, maneuver = "left")+        }+        monitor.start(); idleMain()+        val loc = Location(LocationManager.GPS_PROVIDER).apply {+            latitude = 37.5; longitude = -122.2; time = 99L; speed = 0f+        }+        runCatching { shadow.simulateLocation(loc) }+        idleMain()+        if (updates.isNotEmpty()) {+            val snap = updates.last()+            assertNotNull(snap)+            // parked heuristic: zero speed+            assertTrue(snap.parked)+        }+        monitor.stop(); idleMain()+    }+}
auto/src/test/java/com/vayunmathur/auto/platform/NavStatusChannelTest.kt
diff --git a/auto/src/test/java/com/vayunmathur/auto/platform/NavStatusChannelTest.kt b/auto/src/test/java/com/vayunmathur/auto/platform/NavStatusChannelTest.ktnew file mode 100644index 0000000000..fb688185ce--- /dev/null+++ b/auto/src/test/java/com/vayunmathur/auto/platform/NavStatusChannelTest.kt@@ -0,0 +1,100 @@+package com.vayunmathur.auto.platform++import com.vayunmathur.auto.protocol.GalConnection+import com.vayunmathur.auto.protocol.GalTransport+import com.vayunmathur.auto.protocol.NavStatusUpdate+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import java.io.ByteArrayOutputStream+import javax.net.ssl.SSLContext+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++/**+ * Auto module: [NavStatusChannel] — the phone-to-head-unit turn guidance+ * post on ch10. The grant posts the inactive stub; live updates dedupe+ * identical reposts; pre-grant posts drop; inbound traffic is observed and+ * ignored. Sends ride a closed real connection (dropped silently, events+ * still fire) — see [InputChannelTest] for the seam.+ */+@RunWith(RobolectricTestRunner::class)+class NavStatusChannelTest {++    private class FakeTransport : GalTransport {+        val written = ByteArrayOutputStream()+        override fun read(buffer: ByteArray, offset: Int, length: Int): Int = -1+        override fun write(bytes: ByteArray, offset: Int, length: Int) {+            written.write(bytes, offset, length)+        }+        override fun flush() = Unit+        override fun close() = Unit+    }++    private fun connection(): GalConnection {+        val context = SSLContext.getInstance("TLS").apply { init(null, null, null) }+        return GalConnection(FakeTransport(), context, deviceModel = "Test").also { it.close() }+    }++    @Test+    fun `channel id is the navigation-status service`() {+        assertEquals(10, NavStatusChannel(connection()).channelId)+    }++    @Test+    fun `the grant posts the inactive stub`() {+        val events = mutableListOf<SensorEvent>()+        NavStatusChannel(connection(), onEvent = { events += it }).onChannelOpen()+        assertEquals(listOf<SensorEvent>(SensorEvent.NavStatusPosted), events)+    }++    @Test+    fun `pre-grant posts drop without an event`() {+        val events = mutableListOf<SensorEvent>()+        val channel = NavStatusChannel(connection(), onEvent = { events += it })+        channel.postStatus(guidanceActive = true, nextRoad = "El Camino")+        channel.postUpdate(NavStatusUpdate(guidanceActive = true))+        assertTrue(events.isEmpty())+    }++    @Test+    fun `live posts go out and identical updates dedupe`() {+        val events = mutableListOf<SensorEvent>()+        val channel = NavStatusChannel(connection(), onEvent = { events += it })+        channel.onChannelOpen()+        // postStatus is a direct send: every call posts.+        channel.postStatus(guidanceActive = true, nextRoad = "El Camino")+        assertEquals(2, events.count { it is SensorEvent.NavStatusPosted })+        // postUpdate dedupes against the last update: the grant-time inactive+        // stub is the baseline, so the first live update posts once and the+        // identical repost is skipped.+        channel.postUpdate(NavStatusUpdate(guidanceActive = true, nextRoad = "El Camino"))+        channel.postUpdate(NavStatusUpdate(guidanceActive = true, nextRoad = "El Camino"))+        assertEquals(3, events.count { it is SensorEvent.NavStatusPosted })+        channel.postUpdate(NavStatusUpdate(guidanceActive = false))+        assertEquals(4, events.count { it is SensorEvent.NavStatusPosted })+    }++    @Test+    fun `inbound traffic is observed and ignored`() {+        val events = mutableListOf<SensorEvent>()+        val channel = NavStatusChannel(connection(), onEvent = { events += it })+        channel.onChannelOpen()+        val before = events.size+        channel.onMessage(10, 0x8001)+        assertEquals(before, events.size)+        // Another channel's traffic is ignored too.+        channel.onMessage(7, 0x8001)+        assertEquals(before, events.size)+    }++    @Test+    fun `release parks the channel`() {+        val events = mutableListOf<SensorEvent>()+        val channel = NavStatusChannel(connection(), onEvent = { events += it })+        channel.onChannelOpen()+        channel.release()+        channel.postStatus(guidanceActive = true)+        assertEquals(1, events.count { it is SensorEvent.NavStatusPosted })+    }+}
auto/src/test/java/com/vayunmathur/auto/platform/NowPlayingInfoTest.kt
diff --git a/auto/src/test/java/com/vayunmathur/auto/platform/NowPlayingInfoTest.kt b/auto/src/test/java/com/vayunmathur/auto/platform/NowPlayingInfoTest.ktnew file mode 100644index 0000000000..a5468c6103--- /dev/null+++ b/auto/src/test/java/com/vayunmathur/auto/platform/NowPlayingInfoTest.kt@@ -0,0 +1,65 @@+package com.vayunmathur.auto.platform++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNotEquals+import kotlin.test.assertTrue++/**+ * Auto module: [NowPlayingInfo] — the media snapshot. [shouldShowCard] gates+ * the car card (playing always shows, paused-with-a-title stays for instant+ * resume, idle hides), and equality compares artwork by content with the icon+ * by identity.+ */+class NowPlayingInfoTest {++    private fun info(+        title: String? = "Song",+        artist: String? = "Band",+        playing: Boolean = true,+    ) = NowPlayingInfo(+        title = title,+        artist = artist,+        playing = playing,+        positionMs = 0L,+        durationMs = null,+    )++    @Test+    fun `playing always shows the card`() {+        assertTrue(info(playing = true).shouldShowCard())+        assertTrue(info(title = null, playing = true).shouldShowCard())+    }++    @Test+    fun `paused with a title stays for instant resume`() {+        assertTrue(info(title = "Song", playing = false).shouldShowCard())+        assertTrue(info(title = "  ", playing = false).shouldShowCard().not())+    }++    @Test+    fun `idle with no title hides the card`() {+        assertFalse(info(title = null, playing = false).shouldShowCard())+        assertFalse(info(title = "", playing = false).shouldShowCard())+    }++    @Test+    fun `equal snapshots match and differ on scalar changes`() {+        assertEquals(info(), info())+        assertNotEquals(info(), info(title = "Other"))+        assertNotEquals(info(), info(artist = "Other"))+        assertNotEquals(info(), info(playing = false))+        assertNotEquals(info().copy(positionMs = 1L), info().copy(positionMs = 2L))+        assertNotEquals(info().copy(hasNext = true), info())+    }++    @Test+    fun `artwork compares by content while the icon compares by identity`() {+        val a = info().copy(artworkData = byteArrayOf(1, 2, 3))+        assertEquals(a, info().copy(artworkData = byteArrayOf(1, 2, 3)))+        assertNotEquals(a, info().copy(artworkData = byteArrayOf(1, 2, 4)))+        assertNotEquals(a, info())+        assertEquals(a.hashCode(), info().copy(artworkData = byteArrayOf(1, 2, 3)).hashCode())+    }+}
auto/src/test/java/com/vayunmathur/auto/platform/PairingViewModelTest.kt
diff --git a/auto/src/test/java/com/vayunmathur/auto/platform/PairingViewModelTest.kt b/auto/src/test/java/com/vayunmathur/auto/platform/PairingViewModelTest.ktnew file mode 100644index 0000000000..c91bdf0350--- /dev/null+++ b/auto/src/test/java/com/vayunmathur/auto/platform/PairingViewModelTest.kt@@ -0,0 +1,57 @@+package com.vayunmathur.auto.platform++import androidx.lifecycle.ViewModelProvider+import androidx.lifecycle.ViewModelStore+import com.vayunmathur.auto.protocol.UsbSessionState+import com.vayunmathur.auto.protocol.WirelessSessionState+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.ExperimentalCoroutinesApi+import kotlinx.coroutines.flow.collect+import kotlinx.coroutines.launch+import kotlinx.coroutines.test.resetMain+import kotlinx.coroutines.test.setMain+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import kotlin.test.AfterTest+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNull++@OptIn(ExperimentalCoroutinesApi::class)+@RunWith(RobolectricTestRunner::class)+class PairingViewModelTest {+    @BeforeTest fun setUp() {+        Dispatchers.setMain(Dispatchers.Unconfined)+        TransportState.publishRole(false)+    }+    @AfterTest fun tearDown() { Dispatchers.resetMain(); TransportState.publishRole(false) }++    private var store = ViewModelStore()+    private fun vm(): PairingViewModel {+        store.clear(); store = ViewModelStore()+        return ViewModelProvider(store, object : ViewModelProvider.Factory {+            @Suppress("UNCHECKED_CAST")+            override fun <T : androidx.lifecycle.ViewModel> create(c: Class<T>): T = PairingViewModel() as T+        })[PairingViewModel::class.java]+    }++    @Test fun `defaults mirror transport state`() {+        val vm = vm()+        assertEquals(UsbSessionState.DETACHED, vm.usbState.value)+        assertNull(vm.usbLabel.value)+        assertEquals(WirelessSessionState.IDLE, vm.wirelessState.value)+        assertFalse(vm.roleHeld.value)+        assertNull(vm.selected.value)+        store.clear()+    }++    @Test fun `role held flows through while subscribed`() {+        TransportState.publishRole(true)+        val vm = vm()+        val job = CoroutineScope(Dispatchers.Unconfined).launch { vm.roleHeld.collect() }+        try { assertEquals(true, vm.roleHeld.value) } finally { job.cancel(); store.clear() }+    }+}
auto/src/test/java/com/vayunmathur/auto/platform/PhoneStatusMonitorTest.kt
diff --git a/auto/src/test/java/com/vayunmathur/auto/platform/PhoneStatusMonitorTest.kt b/auto/src/test/java/com/vayunmathur/auto/platform/PhoneStatusMonitorTest.ktnew file mode 100644index 0000000000..db5ea142af--- /dev/null+++ b/auto/src/test/java/com/vayunmathur/auto/platform/PhoneStatusMonitorTest.kt@@ -0,0 +1,140 @@+package com.vayunmathur.auto.platform++import android.app.NotificationManager+import android.content.Context+import android.content.Intent+import android.os.BatteryManager+import androidx.test.core.app.ApplicationProvider+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNull+import kotlin.test.assertTrue++/**+ * Auto module: [PhoneStatusMonitor] — the rail cluster's phone snapshot.+ * Fail-closed throughout: no signal source means a gone icon, no battery+ * broadcast means unknown level, DND reads the interruption filter, and the+ * badge counts the listener's active message notifications. Start is+ * idempotent; stop unregisters everything.+ */+@RunWith(RobolectricTestRunner::class)+class PhoneStatusMonitorTest {++    private val context: Context+        get() = ApplicationProvider.getApplicationContext()++    @Test+    fun `fresh snapshot hides every icon`() {+        val monitor = PhoneStatusMonitor(context)+        assertNull(monitor.snapshot.signalBars)+        assertNull(monitor.snapshot.batteryPercent)+        assertFalse(monitor.snapshot.batteryCharging)+        assertFalse(monitor.snapshot.doNotDisturb)+        assertEquals(0, monitor.snapshot.notificationCount)+    }++    @Test+    fun `start is idempotent and stop unregisters`() {+        val monitor = PhoneStatusMonitor(context)+        monitor.start()+        monitor.start()+        monitor.stop()+        monitor.stop()+        // Restart works after a stop.+        monitor.start()+        monitor.stop()+    }++    @Test+    fun `dnd follows the interruption filter`() {+        val monitor = PhoneStatusMonitor(context)+        // The public setter routes into the shadow, which keeps the filter+        // as a plain field (no policy grant needed under Robolectric).+        val manager = context.getSystemService(NotificationManager::class.java)+        manager.setInterruptionFilter(NotificationManager.INTERRUPTION_FILTER_ALL)+        monitor.refreshDndAndBadge()+        assertFalse(monitor.snapshot.doNotDisturb)+        manager.setInterruptionFilter(NotificationManager.INTERRUPTION_FILTER_PRIORITY)+        monitor.refreshDndAndBadge()+        assertTrue(monitor.snapshot.doNotDisturb)+        manager.setInterruptionFilter(NotificationManager.INTERRUPTION_FILTER_ALL)+        monitor.refreshDndAndBadge()+        assertFalse(monitor.snapshot.doNotDisturb)+    }++    @Test+    fun `badge counts the active message notifications`() {+        val monitor = PhoneStatusMonitor(context)+        monitor.refreshDndAndBadge()+        assertTrue(monitor.snapshot.notificationCount >= 0)+    }++    @Test+    fun `battery broadcast updates the level and charging`() {+        val monitor = PhoneStatusMonitor(context)+        monitor.start()+        fun broadcast(intent: Intent) {+            context.sendBroadcast(intent)+            // Delivery to the registered receiver hops the paused main looper.+            org.robolectric.shadows.ShadowLooper.idleMainLooper()+        }+        try {+            broadcast(+                Intent(Intent.ACTION_BATTERY_CHANGED).apply {+                    putExtra(BatteryManager.EXTRA_LEVEL, 50)+                    putExtra(BatteryManager.EXTRA_SCALE, 100)+                    putExtra(BatteryManager.EXTRA_STATUS, BatteryManager.BATTERY_STATUS_CHARGING)+                },+            )+            assertEquals(50, monitor.snapshot.batteryPercent)+            assertTrue(monitor.snapshot.batteryCharging)+            // A full charge counts as charging; a discharge does not.+            broadcast(+                Intent(Intent.ACTION_BATTERY_CHANGED).apply {+                    putExtra(BatteryManager.EXTRA_LEVEL, 100)+                    putExtra(BatteryManager.EXTRA_SCALE, 100)+                    putExtra(BatteryManager.EXTRA_STATUS, BatteryManager.BATTERY_STATUS_FULL)+                },+            )+            assertTrue(monitor.snapshot.batteryCharging)+            broadcast(+                Intent(Intent.ACTION_BATTERY_CHANGED).apply {+                    putExtra(BatteryManager.EXTRA_LEVEL, 80)+                    putExtra(BatteryManager.EXTRA_SCALE, 100)+                    putExtra(BatteryManager.EXTRA_STATUS, BatteryManager.BATTERY_STATUS_DISCHARGING)+                },+            )+            assertEquals(80, monitor.snapshot.batteryPercent)+            assertFalse(monitor.snapshot.batteryCharging)+            // Garbage levels leave the last good snapshot alone.+            broadcast(+                Intent(Intent.ACTION_BATTERY_CHANGED).apply {+                    putExtra(BatteryManager.EXTRA_LEVEL, -1)+                    putExtra(BatteryManager.EXTRA_SCALE, -1)+                },+            )+            assertEquals(80, monitor.snapshot.batteryPercent)+            // Wrong actions are ignored.+            context.sendBroadcast(Intent(Intent.ACTION_POWER_CONNECTED))+            assertEquals(80, monitor.snapshot.batteryPercent)+        } finally {+            monitor.stop()+        }+    }++    @Test+    fun `signal listener is registered on start`() {+        val monitor = PhoneStatusMonitor(context)+        monitor.start()+        try {+            // Robolectric grants no telephony signal: the icon stays gone+            // (fail-closed), but the listener path ran without crashing.+            assertNull(monitor.snapshot.signalBars)+        } finally {+            monitor.stop()+        }+    }+}
auto/src/test/java/com/vayunmathur/auto/platform/SensorChannelTest.kt
diff --git a/auto/src/test/java/com/vayunmathur/auto/platform/SensorChannelTest.kt b/auto/src/test/java/com/vayunmathur/auto/platform/SensorChannelTest.ktnew file mode 100644index 0000000000..1374c79fe3--- /dev/null+++ b/auto/src/test/java/com/vayunmathur/auto/platform/SensorChannelTest.kt@@ -0,0 +1,162 @@+package com.vayunmathur.auto.platform++import com.vayunmathur.auto.protocol.GalConnection+import com.vayunmathur.auto.protocol.GalMessage+import com.vayunmathur.auto.protocol.GalService+import com.vayunmathur.auto.protocol.GalTransport+import com.vayunmathur.auto.protocol.SensorCodec+import com.vayunmathur.auto.protocol.gal.SensorResponse+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import java.io.ByteArrayOutputStream+import javax.net.ssl.SSLContext+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue++/**+ * Auto module: [SensorChannel] — the ch7 sensor source. The grant subscribes+ * to the advertised set and seeds night from the phone; answers attribute+ * FIFO; batches fold into the snapshot; wrong-channel traffic is ignored;+ * release unsubscribes. Sends ride a closed real connection — see+ * [InputChannelTest] for the seam.+ */+@RunWith(RobolectricTestRunner::class)+class SensorChannelTest {++    private class FakeTransport : GalTransport {+        val written = ByteArrayOutputStream()+        override fun read(buffer: ByteArray, offset: Int, length: Int): Int = -1+        override fun write(bytes: ByteArray, offset: Int, length: Int) {+            written.write(bytes, offset, length)+        }+        override fun flush() = Unit+        override fun close() = Unit+    }++    private fun connection(): GalConnection {+        val context = SSLContext.getInstance("TLS").apply { init(null, null, null) }+        return GalConnection(FakeTransport(), context, deviceModel = "Test").also { it.close() }+    }++    private fun channel(+        events: MutableList<SensorEvent> = mutableListOf(),+        night: Boolean = false

Diff truncated.