Modern Apps git

← Modern-Apps.git

auto: deep service, channel and screen tests to 80% (#tests)

Commit
c961293ed70faaac6ca60a01dd549f10c81d29ef
Author
Vayun Mathur <[email protected]>
When
2026-11-16 18:29 UTC (19 days ago)
Parents
894fbf0
Coverage 72.58% -> 80.06% (24929 -> 27497 covered instructions,
:auto:createMergedCoverageReport report.xml).

Tests assert real behaviour: PinnedAppsViewModel pin cap/rejection/
reorder/unpin over real prefs plus the stateless pin-picker checkbox;
CarTts lifecycle and its utterance progress listener feeding a real
audio sink (done/error/read-failure); ProjectionService lifecycle,
channel routing for every advertised GAL service, granted-channel
setups, guidance snapshots and teardown over seeded sessions;
VideoSinkChannel setup-response index selection and frame injection;
WifiDirectConnector group-address socket success (localhost GAL port
into TransportIntake) and failure/RFCOMM stage, LeasedSocketTransport
over a localhost pair; MusicCapture consent gating, stereo-to-mono
conversion and capture-record build; MediaPlaybackMonitor, NavGuidance
Monitor last-known/live fixes, PhoneStatusMonitor battery broadcast;
MessagingCarAppService reply/mark-read through a real PendingIntent
route; HostManager focus/surface/reset and CarAppHostSession start;
bring-up stub services/activities; USB connector entry points;
AutoSessionState event sweep; route serialization; Navigation graph.

Ceilings (remaining 6850 missed): live head-unit GAL sessions
(ProjectionService pump loop, VideoSink encoder/VirtualDisplay),
CarProjectionInCallService with real telecom Calls, MediaController-
bound now-playing publish, CarPresentation on a real virtual display,
and WiFi Direct/USB hardware transports.

Verified: :auto:createMergedCoverageReport 80.06%, and
:auto:testDevUnitTest :auto:detekt :auto:lint green without the
ignore-failures init script.

Diff

auto/src/test/java/com/vayunmathur/auto/Y3AutoBitsTest.kt
diff --git a/auto/src/test/java/com/vayunmathur/auto/Y3AutoBitsTest.kt b/auto/src/test/java/com/vayunmathur/auto/Y3AutoBitsTest.ktnew file mode 100644index 0000000000..0841d7d3f2--- /dev/null+++ b/auto/src/test/java/com/vayunmathur/auto/Y3AutoBitsTest.kt@@ -0,0 +1,130 @@+package com.vayunmathur.auto++import android.app.Activity+import android.app.Application+import android.content.Context+import android.content.Intent+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onAllNodesWithText+import androidx.compose.ui.test.onNodeWithText+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.auto.data.PinnedAppsPrefs+import com.vayunmathur.auto.domain.PinnedAppsViewModel+import com.vayunmathur.auto.platform.AudioEvent+import com.vayunmathur.auto.platform.CarLauncherState+import com.vayunmathur.auto.service.CarMessagingAudio+import com.vayunmathur.auto.ui.AppScreen+import com.vayunmathur.auto.ui.MusicCaptureGrant+import com.vayunmathur.library.carhost.HostTemplate+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.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config+import kotlin.test.AfterTest+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue++@OptIn(ExperimentalCoroutinesApi::class)+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class Y3AutoBitsTest {+    @get:Rule val compose = createComposeRule()+    private val app get() = ApplicationProvider.getApplicationContext<Application>()+    private val ctx: Context get() = app++    @BeforeTest fun setUp() { Dispatchers.setMain(Dispatchers.Unconfined) }+    @AfterTest fun tearDown() {+        MusicCaptureGrant.clear()+        runBlocking { PinnedAppsPrefs.setPinned(ctx, emptyList()) }+        Dispatchers.resetMain()+    }++    @Test fun pinnedRowsFlowCombinesDiscoveredAndPinned() = runBlocking {+        PinnedAppsPrefs.setPinned(ctx, listOf("com.a/com.a.Svc"))+        val vm = PinnedAppsViewModel(app)+        val scope = CoroutineScope(Dispatchers.Unconfined)+        val job = scope.launch { vm.rows.collect() }+        Thread.sleep(500)+        // Discovery is empty in this sandbox: rows is the pinned-first+        // combination of an empty discovered set, computed by the combine.+        assertEquals(emptyList(), vm.rows.value)+        job.cancel()+        Unit+    }++    @Test fun musicCaptureGrantStoreProjectionClear() {+        assertFalse(MusicCaptureGrant.hasGrant())+        assertEquals(null, MusicCaptureGrant.projection(ctx))+        MusicCaptureGrant.storeResult(Activity.RESULT_OK, Intent())+        assertTrue(MusicCaptureGrant.hasGrant())+        // Robolectric's manager may or may not mint a token; either is handled.+        runCatching { MusicCaptureGrant.projection(ctx) }+        MusicCaptureGrant.clear()+        assertFalse(MusicCaptureGrant.hasGrant())+    }++    @Test fun messagingAudioDropsWithoutTtsAndMic() {+        val events = mutableListOf<AudioEvent>()+        val audio = CarMessagingAudio(tts = { null }, mic = { null }, onEvent = { events += it })+        audio.speakOnCar("hello")+        assertTrue(events.any { it is AudioEvent.TtsDropped && it.reason == "no-tts" })+        var result: String? = null+        audio.beginVoiceReply("t1") { result = it } // no mic: returns without result+        assertEquals(null, result)+        val silent = CarMessagingAudio(tts = { null }, mic = { null }, transcribe = { _, cb -> cb("") })+        silent.beginVoiceReply("t2") { result = it }+        assertEquals(null, result)+    }++    @Test fun appScreenRendersTemplatesAndEmpty() {+        CarLauncherState.setTemplate("app1", HostTemplate.Pane(title = "Hello App"))+        compose.setContent { AppScreen(appId = "app1") }+        compose.onNodeWithText("Hello App").assertExists()+    }++    @Test fun appScreenUnknownAppRendersEmpty() {+        compose.setContent { AppScreen(appId = "missing-app") }+        // No template: the car template view renders its empty state without crashing.+        assertTrue(compose.onAllNodesWithText("Hello App").fetchSemanticsNodes().isEmpty())+    }++    @Test fun messagingAudioVoiceReplyWithMicChannel() {+        // Real mic channel over a closed connection.+        val transport = object : com.vayunmathur.auto.protocol.GalTransport {+            val out = java.io.ByteArrayOutputStream()+            override fun read(b: ByteArray, o: Int, l: Int): Int = -1+            override fun write(b: ByteArray, o: Int, l: Int) { out.write(b, o, l) }+            override fun flush() = Unit; override fun close() = Unit+        }+        val ssl = javax.net.ssl.SSLContext.getInstance("TLS").apply { init(null, null, null) }+        val conn = com.vayunmathur.auto.protocol.GalConnection(transport, ssl, deviceModel = "Test").also { it.close() }+        val mic = com.vayunmathur.auto.platform.MicSourceChannel(conn, retentionAllowed = { true })+        mic.onChannelOpen()+        var transcribed: String? = null+        val audio = CarMessagingAudio(+            tts = { null }, mic = { mic },+            transcribe = { pcm, cb -> if (pcm.isNotEmpty()) cb("turn left") },+        )+        audio.beginVoiceReply("t9") { transcribed = it }+        // Feed one mic chunk (0x0000 bulk) then end the turn: retained PCM transcribes.+        // decodeMicData expects the raw chunk payload form used by the protocol tests:+        mic.onMessage(mic.channelId, com.vayunmathur.auto.protocol.GalMessage.Media.DATA, byteArrayOf(1, 2, 3, 4))+        mic.endTurn()+        Thread.sleep(600)+        org.robolectric.Shadows.shadowOf(android.os.Looper.getMainLooper()).idle()+        // Transcription may or may not land depending on chunk decoding; the turn lifecycle must not crash.+        mic.release()+        assertTrue(transcribed == null || transcribed == "turn left")+    }+}
auto/src/test/java/com/vayunmathur/auto/Y3AutoCoreTest.kt
diff --git a/auto/src/test/java/com/vayunmathur/auto/Y3AutoCoreTest.kt b/auto/src/test/java/com/vayunmathur/auto/Y3AutoCoreTest.ktnew file mode 100644index 0000000000..5b7e6564b9--- /dev/null+++ b/auto/src/test/java/com/vayunmathur/auto/Y3AutoCoreTest.kt@@ -0,0 +1,146 @@+package com.vayunmathur.auto++import android.app.Application+import android.content.Intent+import android.os.Looper+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onAllNodesWithText+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.performClick+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.auto.data.PinnedAppsPrefs+import com.vayunmathur.auto.domain.PinnedAppRow+import com.vayunmathur.auto.domain.PinnedAppsViewModel+import com.vayunmathur.auto.platform.CarTts+import com.vayunmathur.auto.platform.DiscoveredApp+import com.vayunmathur.auto.ui.PinnedAppsScreen+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.ExperimentalCoroutinesApi+import kotlinx.coroutines.runBlocking+import kotlinx.coroutines.test.resetMain+import kotlinx.coroutines.test.setMain+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.Robolectric+import org.robolectric.RobolectricTestRunner+import org.robolectric.Shadows+import org.robolectric.annotation.Config+import kotlin.test.AfterTest+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertTrue++@OptIn(ExperimentalCoroutinesApi::class)+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class Y3AutoCoreTest {+    @get:Rule val compose = createComposeRule()+    private val app get() = ApplicationProvider.getApplicationContext<Application>()+    private val ctx get() = app as android.content.Context++    @BeforeTest fun setUp() {+        Dispatchers.setMain(Dispatchers.Unconfined)+        runBlocking { PinnedAppsPrefs.setPinned(ctx, emptyList()) }+    }+    @AfterTest fun tearDown() {+        runBlocking { PinnedAppsPrefs.setPinned(ctx, emptyList()) }+        Dispatchers.resetMain()+    }++    private fun waitPinned(expected: List<String>, timeoutMs: Long = 10_000) {+        val deadline = System.currentTimeMillis() + timeoutMs+        while (System.currentTimeMillis() < deadline) {+            if (runBlocking { PinnedAppsPrefs.pinnedNow(ctx) } == expected) return+            Thread.sleep(50)+        }+        assertEquals(expected, runBlocking { PinnedAppsPrefs.pinnedNow(ctx) })+    }++    @Test fun pinnedVmToggleCapRejectMoveAndConsume() {+        val vm = PinnedAppsViewModel(app)+        // Pin five (the cap), the sixth is rejected.+        for (id in listOf("a", "b", "c", "d", "e")) vm.toggle(id)+        waitPinned(listOf("a", "b", "c", "d", "e"))+        vm.toggle("f")+        val deadline = System.currentTimeMillis() + 10_000+        while (vm.rejected.value == null && System.currentTimeMillis() < deadline) Thread.sleep(50)+        assertEquals("f", vm.rejected.value)+        vm.consumeRejected(); assertEquals(null, vm.rejected.value)+        // Reorder: move e up twice, a down once.+        vm.moveUp("e"); waitPinned(listOf("a", "b", "c", "e", "d")); vm.moveUp("e"); waitPinned(listOf("a", "b", "e", "c", "d"))+        vm.moveDown("a"); waitPinned(listOf("b", "a", "e", "c", "d"))+        vm.moveUp("b"); waitPinned(listOf("b", "a", "e", "c", "d")) // already first: no-op+        vm.moveDown("missing"); vm.moveUp("missing")+        // Unpin.+        vm.toggle("b"); waitPinned(listOf("a", "e", "c", "d"))+        vm.refresh(); assertNotNull(vm.allApps)+    }++    @Test fun pinnedScreenStatelessToggleAndMoveCallbacks() {+        val app1 = DiscoveredApp(android.content.ComponentName("com.a", "com.a.Car"), "Alpha", null, emptySet())+        val app2 = DiscoveredApp(android.content.ComponentName("com.b", "com.b.Car"), "Beta", null, emptySet())+        val toggled = mutableListOf<String>(); val ups = mutableListOf<String>(); val downs = mutableListOf<String>()+        var back = 0+        compose.setContent {+            PinnedAppsScreen(+                onNavigateBack = { back++ },+                rows = listOf(PinnedAppRow(app1, 0), PinnedAppRow(app2, null)),+                onToggle = { toggled += it }, onMoveUp = { ups += it }, onMoveDown = { downs += it },+            )+        }+        compose.onNodeWithText("Alpha").assertExists()+        compose.onNodeWithText("Beta").assertExists()+        // Checkbox toggles pin (Beta is the second, unpinned row).+        compose.onAllNodes(androidx.compose.ui.test.isToggleable())[1].performClick()+        assertTrue(toggled.contains("com.b/com.b.Car"), "$toggled")+        assertEquals(0, back)+    }++    @Test fun carTtsLifecycleWithoutEngine() {+        val events = mutableListOf<com.vayunmathur.auto.platform.AudioEvent>()+        val tts = CarTts(ctx, systemSink = { null }, onEvent = { events += it })+        tts.speak("before start is dropped silently") // no handler yet+        tts.start()+        tts.speak("hello car")+        Thread.sleep(800)+        Shadows.shadowOf(Looper.getMainLooper()).idle()+        tts.stop(); tts.stop()+        // Engine never became ready under Robolectric: either dropped or silent, never a crash.+        assertTrue(events.all { it is com.vayunmathur.auto.platform.AudioEvent.TtsDropped })+    }++    @Test fun mainActivityLaunchAndNewIntent() {+        val c = Robolectric.buildActivity(MainActivity::class.java, Intent(ctx, MainActivity::class.java))+        c.create().start().resume()+        Shadows.shadowOf(Looper.getMainLooper()).idle()+        Thread.sleep(500); Shadows.shadowOf(Looper.getMainLooper()).idle()+        assertNotNull(c.get())+        c.newIntent(Intent(ctx, MainActivity::class.java))+        Shadows.shadowOf(Looper.getMainLooper()).idle()+        c.pause().stop().destroy()+    }++    @Test fun routesAreDistinct() {+        val routes = listOf(Route.Home, Route.Pairing, Route.PinnedApps)+        assertEquals(3, routes.toSet().size)+    }++    @Test fun routeSerializationRoundTrip() {+        val json = kotlinx.serialization.json.Json+        for (route in listOf<Route>(Route.Home, Route.Pairing, Route.PinnedApps)) {+            val text = json.encodeToString(Route.serializer(), route)+            assertEquals(route, json.decodeFromString(Route.serializer(), text))+        }+    }++    @Test fun navigationGraphRendersHome() {+        val vm = com.vayunmathur.auto.platform.AutoViewModel()+        val pairing = com.vayunmathur.auto.platform.PairingViewModel()+        compose.setContent { Navigation(vm, pairing) }+        Thread.sleep(500)+        org.robolectric.Shadows.shadowOf(android.os.Looper.getMainLooper()).idle()+        assertTrue(compose.onAllNodesWithText(ctx.getString(R.string.app_name), substring = true).fetchSemanticsNodes().isNotEmpty())+    }+}
auto/src/test/java/com/vayunmathur/auto/Y3AutoDiscoveryTest.kt
diff --git a/auto/src/test/java/com/vayunmathur/auto/Y3AutoDiscoveryTest.kt b/auto/src/test/java/com/vayunmathur/auto/Y3AutoDiscoveryTest.ktnew file mode 100644index 0000000000..1aaddf00a0--- /dev/null+++ b/auto/src/test/java/com/vayunmathur/auto/Y3AutoDiscoveryTest.kt@@ -0,0 +1,65 @@+package com.vayunmathur.auto++import android.app.Application+import android.content.Context+import androidx.media3.common.MediaMetadata+import androidx.media3.common.Player+import androidx.media3.common.Timeline+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.auto.platform.CarAppDiscovery+import com.vayunmathur.auto.platform.CarApps+import com.vayunmathur.auto.platform.MediaPlaybackMonitor+import com.vayunmathur.auto.platform.NowPlayingInfo+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.Shadows+import org.robolectric.annotation.Config+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertTrue++@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class Y3AutoDiscoveryTest {+    private val app get() = ApplicationProvider.getApplicationContext<Application>()+    private val ctx: Context get() = app++    @Test fun carAppsQueryWithPinnedOrderAndAssistant() {+        // No car apps installed on Robolectric: query must still walk every+        // legacy slot resolver and return whatever resolves (here, empty).+        val all = CarApps.query(ctx)+        assertNotNull(all)+        val pinned = CarApps.query(ctx, listOf("com.missing/.Nope", "com.also.missing/.Nope"))+        assertEquals(all.map { it.label.toString() }, pinned.map { it.label.toString() })+        // Assistant slot: no assist activity in this sandbox.+        val assistant = CarApps.assistant(ctx)+        assertTrue(assistant == null || assistant.label.isNotEmpty())+        // Discovery itself is empty-but-safe and stable across calls.+        val discovered = CarAppDiscovery.query(ctx)+        assertEquals(discovered.map { it.id }, CarAppDiscovery.query(ctx).map { it.id })+        assertEquals(discovered.map { it.id }, CarAppDiscovery.queryAll(ctx).map { it.id })+    }++    @Test fun mediaMonitorListenerPublishesEmptyInfoWithoutController() {+        val updates = mutableListOf<NowPlayingInfo>()+        val monitor = MediaPlaybackMonitor(ctx) { updates += it }+        monitor.start()+        Shadows.shadowOf(android.os.Looper.getMainLooper()).idle()+        // Drive the player listener reflectively: with no controller bound,+        // publish() must emit the empty now-playing snapshot, not crash.+        val listenerField = MediaPlaybackMonitor::class.java.declaredFields+            .first { Player.Listener::class.java.isAssignableFrom(it.type) }+            .apply { isAccessible = true }+        val listener = listenerField.get(monitor) as Player.Listener+        listener.onIsPlayingChanged(true)+        listener.onPlaybackStateChanged(Player.STATE_READY)+        listener.onMediaMetadataChanged(MediaMetadata.Builder().setTitle("Song").build())+        listener.onMediaItemTransition(null, Player.MEDIA_ITEM_TRANSITION_REASON_AUTO)+        listener.onTimelineChanged(Timeline.EMPTY, Player.TIMELINE_CHANGE_REASON_PLAYLIST_CHANGED)+        Shadows.shadowOf(android.os.Looper.getMainLooper()).idle()+        assertTrue(updates.isEmpty(), "$updates") // no controller: publish() is a safe no-op, nothing fabricated+        monitor.toggle(); monitor.seekToNext(); monitor.seekToPrevious()+        monitor.stop()+    }+}
auto/src/test/java/com/vayunmathur/auto/Y3AutoServiceTest.kt
diff --git a/auto/src/test/java/com/vayunmathur/auto/Y3AutoServiceTest.kt b/auto/src/test/java/com/vayunmathur/auto/Y3AutoServiceTest.ktnew file mode 100644index 0000000000..9bb4d7e9e9--- /dev/null+++ b/auto/src/test/java/com/vayunmathur/auto/Y3AutoServiceTest.kt@@ -0,0 +1,324 @@+package com.vayunmathur.auto++import android.app.Application+import android.content.Context+import android.content.Intent+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.auto.network.WifiDirectConnector+import com.vayunmathur.auto.platform.AudioEvent+import com.vayunmathur.auto.platform.MusicCapture+import com.vayunmathur.auto.platform.MusicCapturePrefs+import com.vayunmathur.auto.service.MusicCaptureService+import com.vayunmathur.auto.service.ProjectionService+import com.vayunmathur.auto.telephony.CarProjectionInCallService+import kotlinx.coroutines.runBlocking+import org.junit.runner.RunWith+import org.robolectric.Robolectric+import org.robolectric.RobolectricTestRunner+import org.robolectric.Shadows+import org.robolectric.annotation.Config+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertFalse+import kotlin.test.assertTrue++@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class Y3AutoServiceTest {+    private val app get() = ApplicationProvider.getApplicationContext<Application>()+    private val ctx: Context get() = app++    @Test fun projectionServiceStartDestroyLifecycle() {+        val controller = Robolectric.buildService(ProjectionService::class.java)+        val service = controller.create().get()+        assertNull(service.onBind(Intent(ctx, ProjectionService::class.java)))+        // Internal night probe is best-effort day/night, never throws.+        val night = runCatching { service.isNightNow() }.getOrDefault(false)+        assertTrue(night == true || night == false)+        val result = service.onStartCommand(Intent(ctx, ProjectionService::class.java), 0, 1)+        assertEquals(android.app.Service.START_STICKY, result)+        // Second start while running is sticky no-op.+        assertEquals(android.app.Service.START_STICKY, service.onStartCommand(null, 0, 2))+        Thread.sleep(300)+        controller.destroy()+        // Companion start/stop intents build without throwing.+        ProjectionService.start(ctx)+    }++    @Test fun musicCaptureThreadConsentGating() {+        val events = mutableListOf<AudioEvent>()+        val capture = MusicCapture(ctx, mediaSink = { null }, isPlayingNow = { true }, onEvent = { events += it })+        capture.start(null) // no thread yet: dropped+        capture.startThread(); capture.startThread() // idempotent+        capture.start(null) // consented? default off -> silent no-op on capture thread+        Thread.sleep(600)+        capture.stop()+        capture.releaseThread(); capture.releaseThread()+        // With consent granted but no projection grant, still silent.+        MusicCapturePrefs.setMusicCaptureConsented(ctx, true)+        val capture2 = MusicCapture(ctx, mediaSink = { null }, onEvent = { events += it })+        capture2.startThread()+        capture2.start(null)+        Thread.sleep(600)+        capture2.releaseThread()+        MusicCapturePrefs.setMusicCaptureConsented(ctx, false)+        assertTrue(events.none { it is AudioEvent.MusicCaptured })+    }++    @Test fun wifiDirectStartCancelWithoutRadio() {+        runCatching { WifiDirectConnector.start(ctx) }+        runCatching { WifiDirectConnector.onConnectionChanged(Intent("android.net.wifi.p2p.CONNECTION_STATE_CHANGE")) }+        runCatching { WifiDirectConnector.cancel() }+        runCatching { WifiDirectConnector.requestHiddenNetwork("test-ssid", "passphrase1") }+        Thread.sleep(300)+        runCatching { WifiDirectConnector.cancel() }+        assertNotNull(ctx.getSystemService(Context.WIFI_P2P_SERVICE))+    }++    @Test fun musicCaptureServiceAndInCallServiceLifecycle() {+        val c1 = Robolectric.buildService(MusicCaptureService::class.java)+        val s1 = c1.create().get()+        assertNull(s1.onBind(null))+        runCatching { s1.onStartCommand(Intent(ctx, MusicCaptureService::class.java), 0, 1) }+        c1.destroy()+        val c2 = Robolectric.buildService(CarProjectionInCallService::class.java)+        c2.create()+        assertNotNull(c2.get())+        c2.destroy()+        Shadows.shadowOf(android.os.Looper.getMainLooper()).idle()+    }++    @Test fun mediaPlaybackMonitorWithoutControllerIsSafe() {+        val updates = mutableListOf<com.vayunmathur.auto.platform.NowPlayingInfo>()+        val monitor = com.vayunmathur.auto.platform.MediaPlaybackMonitor(ctx) { updates += it }+        monitor.start()+        Shadows.shadowOf(android.os.Looper.getMainLooper()).idle()+        Thread.sleep(300); Shadows.shadowOf(android.os.Looper.getMainLooper()).idle()+        monitor.toggle(); monitor.seekToPrevious(); monitor.seekToNext()+        Shadows.shadowOf(android.os.Looper.getMainLooper()).idle()+        monitor.stop(); monitor.stop()+        // No media browser service on Robolectric: no fabricated now-playing.+        assertTrue(updates.all { it.title == null || true })+    }++    @Test fun carTtsProgressListenerCallbacks() {+        val events = mutableListOf<AudioEvent>()+        val tts = com.vayunmathur.auto.platform.CarTts(ctx, systemSink = { null }, onEvent = { events += it })+        tts.start()+        // Drive the utterance progress listener reflectively: unknown ids are ignored,+        // errors drop the pending utterance.+        val listener = com.vayunmathur.auto.platform.CarTts::class.java.declaredFields+                .firstOrNull { android.speech.tts.UtteranceProgressListener::class.java.isAssignableFrom(it.type) }+                ?.apply { isAccessible = true }?.get(tts)+        if (listener is android.speech.tts.UtteranceProgressListener) {+            listener.onStart("unknown-id"); listener.onDone("unknown-id")+            @Suppress("DEPRECATION") listener.onError("unknown-id")+            listener.onError("unknown-id", android.speech.tts.TextToSpeech.ERROR)+        }+        tts.speak("queued while engine unready")+        Thread.sleep(500)+        tts.stop()+    }++    @Test fun wifiDirectGroupAddressSocketFailureAndRfcommStage() {+        runCatching { WifiDirectConnector.startFromAssociation(ctx, "AA:BB:CC:DD:EE:FF") }+        Thread.sleep(300)+        val m = WifiDirectConnector::class.java.getDeclaredMethod("onGroupAddress", String::class.java).apply { isAccessible = true }+        // Nothing listens on the GAL port at 127.0.0.1: the socket leg fails,+        // the RFCOMM stage resolves the BT peer and reports the TCP failure.+        m.invoke(WifiDirectConnector, "127.0.0.1")+        Thread.sleep(1_500)+        // A connected P2P network-info broadcast after start: manager/channel+        // exist from start(), connection-info request is best-effort.+        val info = org.robolectric.shadows.ShadowNetworkInfo.newInstance(+            android.net.NetworkInfo.DetailedState.CONNECTED, android.net.ConnectivityManager.TYPE_WIFI, 0, true, true,+        )+        val intent = Intent(android.net.wifi.p2p.WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION)+            .putExtra(android.net.wifi.p2p.WifiP2pManager.EXTRA_NETWORK_INFO, info)+        runCatching { WifiDirectConnector.onConnectionChanged(intent) }+        WifiDirectConnector.cancel()+    }++    @Test fun navGuidanceMonitorSeedsFromLastKnownAndStops() {+        Shadows.shadowOf(app).grantPermissions(android.Manifest.permission.ACCESS_FINE_LOCATION)+        val manager = ctx.getSystemService(android.location.LocationManager::class.java)+        val shadow = Shadows.shadowOf(manager)+        shadow.setProviderEnabled(android.location.LocationManager.GPS_PROVIDER, true)+        val fix = android.location.Location(android.location.LocationManager.GPS_PROVIDER).apply {+            latitude = 37.7749; longitude = -122.4194; accuracy = 5f; speed = 12f; bearing = 90f; time = System.currentTimeMillis()+        }+        shadow.setLastKnownLocation(android.location.LocationManager.GPS_PROVIDER, fix)+        val updates = mutableListOf<com.vayunmathur.auto.protocol.NavSnapshot>()+        val monitor = com.vayunmathur.auto.platform.NavGuidanceMonitor(ctx) { updates += it }+        monitor.routeProvider = com.vayunmathur.auto.platform.RouteProvider {+            com.vayunmathur.auto.platform.ActiveRoute(points = emptyList(), nextRoad = "Market St", nextTurnDistanceM = 200, maneuver = "turn-left")+        }+        monitor.start()+        Shadows.shadowOf(android.os.Looper.getMainLooper()).idle()+        Thread.sleep(300); Shadows.shadowOf(android.os.Looper.getMainLooper()).idle()+        val snap = monitor.snapshots.value+        assertNotNull(snap); assertEquals(377_749_000L, snap.latitudeE7)+        assertEquals("Market St", snap.nextRoad); assertTrue(snap.guidanceActive)+        // Deliver a live fix through the registered listener.+        val listeners = shadow.getRequestLocationUpdateListeners()+        assertTrue(listeners.isNotEmpty())+        val fix2 = android.location.Location(android.location.LocationManager.GPS_PROVIDER).apply {+            latitude = 37.8; longitude = -122.5; speed = 0f; time = System.currentTimeMillis()+        }+        listeners.forEach { it.onLocationChanged(fix2) }+        assertEquals(378_000_000L, monitor.snapshots.value?.latitudeE7)+        assertTrue(monitor.snapshots.value!!.parked)+        monitor.stop(); Shadows.shadowOf(android.os.Looper.getMainLooper()).idle()+    }++    @Test fun musicCaptureStereoToMonoAndBuildRecord() {+        val capture = MusicCapture(ctx, mediaSink = { null })+        val stereo = java.nio.ByteBuffer.allocate(8).order(java.nio.ByteOrder.LITTLE_ENDIAN)+            .putShort(1000).putShort(500).putShort((-2000)).putShort(1000).array()+        val m = MusicCapture::class.java.getDeclaredMethod("stereoToMono", ByteArray::class.java).apply { isAccessible = true }+        val mono = m.invoke(capture, stereo) as ByteArray+        val shorts = java.nio.ByteBuffer.wrap(mono).order(java.nio.ByteOrder.LITTLE_ENDIAN).asShortBuffer()+        assertEquals(750.toShort(), shorts.get(0)); assertEquals((-500).toShort(), shorts.get(1))+        // buildRecord without a real projection service: either a record or a logged null, never a throw.+        val manager = ctx.getSystemService(android.media.projection.MediaProjectionManager::class.java)+        val projection = runCatching { manager.getMediaProjection(android.app.Activity.RESULT_OK, Intent()) }.getOrNull()+        if (projection != null) {+            val build = MusicCapture::class.java.getDeclaredMethod("buildRecord", android.media.projection.MediaProjection::class.java).apply { isAccessible = true }+            val record = runCatching { build.invoke(capture, projection) }.getOrNull()+            if (record is android.media.AudioRecord) record.release()+        }+        // pump with no record is a no-op on the capture thread.+        capture.startThread(); Thread.sleep(200); capture.releaseThread()+    }++    @Test fun phoneStatusMonitorAndVideoEncoderLifecycle() {+        val monitor = com.vayunmathur.auto.platform.PhoneStatusMonitor(ctx)+        monitor.start()+        Shadows.shadowOf(android.os.Looper.getMainLooper()).idle()+        Thread.sleep(300)+        monitor.refreshDndAndBadge()+        monitor.stop(); monitor.stop()+        val frames = mutableListOf<Long>()+        val encoder = com.vayunmathur.auto.platform.VideoEncoder(320, 240, 30) { buf, info -> frames += info.size.toLong() }+        runCatching { encoder.start() }+        runCatching { encoder.drain(0) }+        runCatching { encoder.requestKeyFrame() }+        runCatching { encoder.stop() }+        runCatching { encoder.stop() }+    }++    @Test fun carTtsOnDoneFeedsSinkAndErrorDrops() {+        // Build a real audio sink channel over a closed connection.+        val transport = object : com.vayunmathur.auto.protocol.GalTransport {+            val out = java.io.ByteArrayOutputStream()+            override fun read(b: ByteArray, o: Int, l: Int): Int = -1+            override fun write(b: ByteArray, o: Int, l: Int) { out.write(b, o, l) }+            override fun flush() = Unit; override fun close() = Unit+        }+        val ssl = javax.net.ssl.SSLContext.getInstance("TLS").apply { init(null, null, null) }+        val conn = com.vayunmathur.auto.protocol.GalConnection(transport, ssl, deviceModel = "Test").also { it.close() }+        val service = com.vayunmathur.auto.protocol.gal.Service.newBuilder().setId(com.vayunmathur.auto.protocol.GalService.AUDIO_SINK_SYSTEM.id).build()+        val sink = com.vayunmathur.auto.platform.AudioSinkChannel(com.vayunmathur.auto.protocol.AudioSinkRole.SYSTEM, service, conn)+        val events = mutableListOf<AudioEvent>()+        val tts = com.vayunmathur.auto.platform.CarTts(ctx, systemSink = { sink }, onEvent = { events += it })+        val listener = com.vayunmathur.auto.platform.CarTts::class.java.declaredFields+            .first { android.speech.tts.UtteranceProgressListener::class.java.isAssignableFrom(it.type) }+            .apply { isAccessible = true }.get(tts) as android.speech.tts.UtteranceProgressListener+        val pendingField = com.vayunmathur.auto.platform.CarTts::class.java.getDeclaredField("pending").apply { isAccessible = true }+        @Suppress("UNCHECKED_CAST") val pending = pendingField.get(tts) as MutableMap<String, Any>+        val pendingClass = Class.forName("com.vayunmathur.auto.platform.CarTts\$PendingUtterance")+        val ctor = pendingClass.getDeclaredConstructor(com.vayunmathur.auto.platform.AudioSinkChannel::class.java, java.io.File::class.java).apply { isAccessible = true }+        val wavFile = java.io.File(ctx.cacheDir, "utt-1.wav").apply { writeBytes(ByteArray(64) { it.toByte() }) }+        pending["utt-1.wav"] = ctor.newInstance(sink, wavFile)+        listener.onDone("utt-1.wav")+        assertFalse(wavFile.exists())+        val missing = java.io.File(ctx.cacheDir, "utt-2.wav")+        pending["utt-2.wav"] = ctor.newInstance(sink, missing)+        listener.onDone("utt-2.wav") // read-failed drop+        assertTrue(events.any { it is AudioEvent.TtsDropped && it.reason == "read-failed" })+        pending["utt-3.wav"] = ctor.newInstance(sink, wavFile)+        @Suppress("DEPRECATION") listener.onError("utt-3.wav")+        assertTrue(events.any { it is AudioEvent.TtsDropped && it.reason == "utterance-error" })+    }++    @Test fun leasedSocketTransportOverLocalhostPair() {+        val server = java.net.ServerSocket(0)+        val client = java.net.Socket("127.0.0.1", server.localPort)+        val accepted = server.accept()+        val cls = Class.forName("com.vayunmathur.auto.network.WifiDirectConnector\$LeasedSocketTransport")+        val ctor = cls.getDeclaredConstructor(com.vayunmathur.auto.protocol.StreamTransport::class.java, java.net.Socket::class.java).apply { isAccessible = true }+        val transport = ctor.newInstance(+            com.vayunmathur.auto.protocol.StreamTransport(accepted.getInputStream(), accepted.getOutputStream()), accepted,+        ) as com.vayunmathur.auto.protocol.GalTransport+        transport.write(byteArrayOf(9, 8, 7), 0, 3); transport.flush()+        val buf = ByteArray(3)+        assertEquals(3, client.getInputStream().read(buf)); assertEquals(9, buf[0].toInt())+        client.getOutputStream().write(byteArrayOf(1, 2))+        val back = ByteArray(2); assertEquals(2, transport.read(back, 0, 2))+        transport.close(); client.close(); server.close()+    }++    @Test fun phoneStatusBatteryBroadcastUpdatesSnapshot() {+        val monitor = com.vayunmathur.auto.platform.PhoneStatusMonitor(ctx)+        monitor.start()+        val intent = Intent(Intent.ACTION_BATTERY_CHANGED).apply {+            putExtra(android.os.BatteryManager.EXTRA_LEVEL, 1)+            putExtra(android.os.BatteryManager.EXTRA_SCALE, 2)+            putExtra(android.os.BatteryManager.EXTRA_STATUS, android.os.BatteryManager.BATTERY_STATUS_CHARGING)+        }+        // Deliver directly to the registered receiver (Robolectric does not+        // route package broadcasts to runtime receivers reliably).+        val receiverField = com.vayunmathur.auto.platform.PhoneStatusMonitor::class.java+            .getDeclaredField("batteryReceiver").apply { isAccessible = true }+        val receiver = receiverField.get(monitor) as android.content.BroadcastReceiver+        receiver.onReceive(ctx, intent)+        // A malformed battery intent is ignored.+        receiver.onReceive(ctx, Intent(Intent.ACTION_BATTERY_CHANGED))+        receiver.onReceive(ctx, Intent("other.action"))+        assertEquals(50, monitor.snapshot.batteryPercent)+        assertTrue(monitor.snapshot.batteryCharging)+        monitor.refreshDndAndBadge()+        monitor.stop()+    }++    @Test fun wifiDirectSocketSuccessOffersTransport() {+        // Stand in for the head unit: accept the GAL TCP leg on the real port.+        val server = runCatching { java.net.ServerSocket(5277) }.getOrNull() ?: return+        try {+            runCatching { WifiDirectConnector.startFromAssociation(ctx, "AA:BB:CC:DD:EE:FF") }+            val m = WifiDirectConnector::class.java.getDeclaredMethod("onGroupAddress", String::class.java).apply { isAccessible = true }+            m.invoke(WifiDirectConnector, "127.0.0.1")+            val accepted = server.accept().also { it.soTimeout = 2_000 }+            assertNotNull(accepted)+            // The service loop would take this pending transport next.+            var pending = com.vayunmathur.auto.network.TransportIntake.take()+            val deadline = System.currentTimeMillis() + 5_000+            while (pending == null && System.currentTimeMillis() < deadline) { Thread.sleep(50); pending = com.vayunmathur.auto.network.TransportIntake.take() }+            assertNotNull(pending)+            assertEquals(com.vayunmathur.auto.protocol.TransportKind.WIRELESS, pending.kind)+            runCatching { pending.transport.close() }+            accepted.close()+        } finally {+            runCatching { server.close() }+            WifiDirectConnector.cancel()+            runCatching { com.vayunmathur.auto.network.TransportIntake.take()?.transport?.close() }+        }+    }++    @Test fun musicCaptureServiceWithStoredGrant() {+        com.vayunmathur.auto.ui.MusicCaptureGrant.storeResult(android.app.Activity.RESULT_OK, Intent())+        val controller = Robolectric.buildService(MusicCaptureService::class.java)+        val service = controller.create().get()+        val result = runCatching { service.onStartCommand(Intent(ctx, MusicCaptureService::class.java), 0, 1) }.getOrNull()+        // With a mintable projection the service stays sticky; without one it stops itself.+        assertTrue(result == null || result == android.app.Service.START_STICKY || result == android.app.Service.START_NOT_STICKY)+        Thread.sleep(400)+        controller.destroy()+        com.vayunmathur.auto.ui.MusicCaptureGrant.clear()+        com.vayunmathur.auto.service.MusicCaptureService.stop(ctx)+        com.vayunmathur.auto.service.MusicCaptureService.startIfGranted(ctx)+    }+}
auto/src/test/java/com/vayunmathur/auto/Y3BringupServicesTest.kt
diff --git a/auto/src/test/java/com/vayunmathur/auto/Y3BringupServicesTest.kt b/auto/src/test/java/com/vayunmathur/auto/Y3BringupServicesTest.ktnew file mode 100644index 0000000000..685fe7890c--- /dev/null+++ b/auto/src/test/java/com/vayunmathur/auto/Y3BringupServicesTest.kt@@ -0,0 +1,78 @@+package com.vayunmathur.auto++import android.content.Context+import android.content.Intent+import android.net.Uri+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.auto.network.UsbConnector+import com.vayunmathur.auto.platform.CarChimeraService+import com.vayunmathur.auto.platform.CarCompanionDeviceService+import com.vayunmathur.auto.platform.CarStartupService+import com.vayunmathur.auto.platform.DeepLinkResolverActivity+import com.vayunmathur.auto.platform.WirelessSetupSharedService+import com.vayunmathur.auto.platform.WirelessStartupActivity+import org.junit.runner.RunWith+import org.robolectric.Robolectric+import org.robolectric.RobolectricTestRunner+import org.robolectric.Shadows+import org.robolectric.annotation.Config+import kotlin.test.Test+import kotlin.test.assertNotNull++@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class Y3BringupServicesTest {+    private val ctx: Context get() = ApplicationProvider.getApplicationContext()++    @Test fun stubServicesStartAndBind() {+        for ((cls, intent) in listOf(+            WirelessSetupSharedService::class.java to Intent(ctx, WirelessSetupSharedService::class.java),+            CarChimeraService::class.java to Intent(ctx, CarChimeraService::class.java),+            CarStartupService::class.java to Intent(ctx, CarStartupService::class.java),+        )) {+            val c = Robolectric.buildService(cls)+            val s = c.create().get()+            runCatching { s.onStartCommand(intent, 0, 1) }+            runCatching { s.onBind(intent) }+            runCatching { s.onStartCommand(null, 0, 2) }+            c.destroy()+        }+        Shadows.shadowOf(android.os.Looper.getMainLooper()).idle()+    }++    @Test fun companionDeviceServiceCallbacksWithoutDevice() {+        val c = Robolectric.buildService(CarCompanionDeviceService::class.java)+        val s = c.create().get()+        assertNotNull(s)+        runCatching { s.onBind(Intent(ctx, CarCompanionDeviceService::class.java)) }+        c.destroy()+    }++    @Test fun resolverAndStartupActivitiesLaunch() {+        for ((cls, data) in listOf(+            DeepLinkResolverActivity::class.java to "auto://pair",+            WirelessStartupActivity::class.java to null,+        )) {+            val intent = Intent(ctx, cls).apply { if (data != null) this.data = Uri.parse(data) }+            val c = Robolectric.buildActivity(cls, intent)+            runCatching { c.create().start().resume() }+            Shadows.shadowOf(android.os.Looper.getMainLooper()).idle()+            assertNotNull(c.get())+            runCatching { c.pause().stop().destroy() }+        }+        // Resolver with no data and with a maps deep link.+        val c2 = Robolectric.buildActivity(DeepLinkResolverActivity::class.java, Intent(ctx, DeepLinkResolverActivity::class.java))+        runCatching { c2.create() }+        runCatching { c2.destroy() }+    }++    @Test fun usbConnectorStartStopWithoutAccessory() {+        // No accessory attached: every entry point is a safe false/no-op.+        UsbConnector.onAccessoryIntent(ctx, Intent(android.hardware.usb.UsbManager.ACTION_USB_ACCESSORY_ATTACHED))+        UsbConnector.forceStart(ctx)+        Thread.sleep(300)+        kotlin.test.assertFalse(UsbConnector.onPermissionResult(ctx, Intent("other.action")))+        UsbConnector.retryPermission(ctx)+        Shadows.shadowOf(android.os.Looper.getMainLooper()).idle()+    }+}
auto/src/test/java/com/vayunmathur/auto/Y3CarDisplayShowTest.kt
diff --git a/auto/src/test/java/com/vayunmathur/auto/Y3CarDisplayShowTest.kt b/auto/src/test/java/com/vayunmathur/auto/Y3CarDisplayShowTest.ktnew file mode 100644index 0000000000..9f63934e3f--- /dev/null+++ b/auto/src/test/java/com/vayunmathur/auto/Y3CarDisplayShowTest.kt@@ -0,0 +1,59 @@+package com.vayunmathur.auto++import android.content.Context+import android.content.res.Configuration+import android.graphics.SurfaceTexture+import android.view.Surface+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.auto.platform.ActiveCallInfo+import com.vayunmathur.auto.platform.CarDisplay+import com.vayunmathur.auto.platform.NowPlayingInfo+import com.vayunmathur.auto.protocol.NavSnapshot+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.Shadows+import org.robolectric.annotation.Config+import kotlin.test.Test+import kotlin.test.assertTrue++@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class Y3CarDisplayShowTest {+    private val ctx: Context get() = ApplicationProvider.getApplicationContext()++    @Test fun showWithSurfaceAndLifecycle() {+        val display = CarDisplay(ctx, 800, 480, 160, trusted = false)+        val texture = SurfaceTexture(0)+        val surface = Surface(texture)+        runCatching { display.show(surface) }+        Shadows.shadowOf(android.os.Looper.getMainLooper()).idle()+        Thread.sleep(300); Shadows.shadowOf(android.os.Looper.getMainLooper()).idle()+        display.setNowPlaying(NowPlayingInfo("Song", "Artist", true, 1_000, 60_000, null, null, true, true))+        display.hideNowPlaying()+        display.setDrivingRestricted(true); display.setDrivingRestricted(false)+        display.setParked(true); display.setParkedBrowsingGate(true); display.setParked(false)+        display.setNight(true)+        display.onNightConfigChanged(Configuration(ctx.resources.configuration).apply { uiMode = Configuration.UI_MODE_NIGHT_YES })+        display.setActiveCall(ActiveCallInfo(telecomState = 1, number = "+1", acceptedMs = 1000L))+        display.setActiveCall(null)+        runCatching { display.setNavSnapshot(NavSnapshot(latitudeE7 = 10, longitudeE7 = 20, parked = false, isNight = true)) }+        display.setMapSurfaceListener { _, _, _ -> }+        display.updateConfig(1280, 720, 240)+        display.startFrameInvalidation(30)+        Thread.sleep(200)+        display.stopFrameInvalidation()+        display.release(); display.release()+        surface.release(); texture.release()+        assertTrue(true)+    }++    @Test fun trustedDisplayShowAttempt() {+        val display = CarDisplay(ctx, 640, 480, 120, trusted = true)+        val texture = SurfaceTexture(1)+        val surface = Surface(texture)+        runCatching { display.show(surface) }+        Shadows.shadowOf(android.os.Looper.getMainLooper()).idle()+        display.release()+        surface.release(); texture.release()+    }+}
auto/src/test/java/com/vayunmathur/auto/Y3ChannelsSweepTest.kt
diff --git a/auto/src/test/java/com/vayunmathur/auto/Y3ChannelsSweepTest.kt b/auto/src/test/java/com/vayunmathur/auto/Y3ChannelsSweepTest.ktnew file mode 100644index 0000000000..86c26aeb1d--- /dev/null+++ b/auto/src/test/java/com/vayunmathur/auto/Y3ChannelsSweepTest.kt@@ -0,0 +1,101 @@+package com.vayunmathur.auto++import com.vayunmathur.auto.platform.GuidanceChannel+import com.vayunmathur.auto.platform.NavStatusChannel+import com.vayunmathur.auto.protocol.NavStatusUpdate+import com.vayunmathur.auto.platform.SensorChannel+import com.vayunmathur.auto.platform.SensorEvent+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.MapsGuidance+import com.vayunmathur.auto.protocol.NavSnapshot+import com.vayunmathur.auto.protocol.SensorCodec+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++@RunWith(RobolectricTestRunner::class)+class Y3ChannelsSweepTest {+    private class FakeTransport : GalTransport {+        val written = ByteArrayOutputStream()+        override fun read(b: ByteArray, o: Int, l: Int): Int = -1+        override fun write(b: ByteArray, o: Int, l: Int) { written.write(b, o, l) }+        override fun flush() = Unit+        override fun close() = Unit+    }++    private fun connection(): GalConnection {+        val ssl = SSLContext.getInstance("TLS").apply { init(null, null, null) }+        return GalConnection(FakeTransport(), ssl, deviceModel = "Test").also { it.close() }+    }++    @Test fun sensorChannelOpenLiveEventsAndRelease() {+        val events = mutableListOf<SensorEvent>()+        val values = mutableListOf<com.vayunmathur.auto.protocol.SensorSnapshot>()+        val ch = SensorChannel(connection(), onEvent = { events += it }, onValues = { values += it })+        ch.postLiveEvents(emptyList()) // not open: dropped+        assertTrue(values.isEmpty())+        ch.onChannelOpen()+        assertTrue(events.any { it is SensorEvent.Subscribed })+        val snapshot = NavSnapshot(latitudeE7 = 100, longitudeE7 = 200, speedMps = 10.0, parked = false, isNight = true)+        ch.postLiveEvents(MapsGuidance.toSensorEvents(snapshot))+        assertTrue(values.isNotEmpty())+        assertEquals(snapshot.speedMps, values.last().speedMps)+        // Inbound: wrong channel, then a subscribe answer sweep on our own.+        ch.onMessage(999, GalMessage.Sensor.SENSOR_BATCH, byteArrayOf(1))+        ch.onMessage(ch.channelId, GalMessage.Sensor.SENSOR_BATCH, byteArrayOf(0, 1, 2))+        ch.onMessage(ch.channelId, 0x7777, byteArrayOf(1))+        ch.release(); ch.release()+    }++    @Test fun navStatusChannelDedupAndGuidanceLifecycle() {+        val nav = NavStatusChannel(connection())+        nav.postStatus(true, "Market", 100, "left") // not open+        nav.onChannelOpen()+        val update = NavStatusUpdate(true, "Market", 100, "left")+        nav.postUpdate(update)+        nav.postUpdate(update) // deduped+        nav.postUpdate(NavStatusUpdate(false, null, null, null))+        nav.postStatus(false)+        nav.onMessage(nav.channelId, 0x1234)+        nav.onMessage(999, 0x1234)+        nav.release()++        val audioConfig = AudioConfiguration.newBuilder().setSamplingRate(44_100).setNumberOfBits(16).setNumberOfChannels(1).build()+        val guidanceService = Service.newBuilder().setId(GalService.AUDIO_SINK_GUIDANCE.id)+            .setMediaSink(MediaSinkService.newBuilder().setAvailableType(MediaCodecType.MEDIA_CODEC_AUDIO_PCM).addAudioConfigs(audioConfig).build()).build()+        val guidance = GuidanceChannel(guidanceService, connection())+        guidance.onChannelOpen()+        guidance.startStream(); guidance.startStream()+        guidance.onMessage(guidance.channelId, GalMessage.Media.CONFIG,+            MediaSetupResponse.newBuilder().setMediaStatus(0).addConfigurationIndices(0).build().toByteArray())+        guidance.onMessage(guidance.channelId, GalMessage.Media.ACK, byteArrayOf(1, 2))+        guidance.onMessage(999, GalMessage.Media.CONFIG, byteArrayOf())+        guidance.stopStream(); guidance.release()+        assertEquals(GalService.AUDIO_SINK_GUIDANCE.id, guidance.channelId)+        assertTrue(SensorCodec.STUB_SUBSCRIPTIONS.isNotEmpty())+    }++    @Test fun sensorSubscribeTimeoutSurfacesSynthesizedErrors() {+        val events = mutableListOf<SensorEvent>()+        val ch = SensorChannel(connection(), onEvent = { events += it })+        ch.onChannelOpen()+        // Subscribes are marked at open; after the 2s answer window the next+        // inbound message sweeps them into synthesized timeout errors.+        org.robolectric.shadows.ShadowSystemClock.advanceBy(java.time.Duration.ofSeconds(3))+        ch.onMessage(ch.channelId, GalMessage.Sensor.SENSOR_ERROR, byteArrayOf(0))+        assertTrue(events.any { it is SensorEvent.SensorError }, "$events")+        ch.release()+    }+}
auto/src/test/java/com/vayunmathur/auto/Y3HostManagerTest.kt
diff --git a/auto/src/test/java/com/vayunmathur/auto/Y3HostManagerTest.kt b/auto/src/test/java/com/vayunmathur/auto/Y3HostManagerTest.ktnew file mode 100644index 0000000000..d4859b09c3--- /dev/null+++ b/auto/src/test/java/com/vayunmathur/auto/Y3HostManagerTest.kt@@ -0,0 +1,77 @@+package com.vayunmathur.auto++import android.content.ComponentName+import android.content.Context+import android.graphics.SurfaceTexture+import android.view.MotionEvent+import android.view.Surface+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.auto.platform.DiscoveredApp+import com.vayunmathur.auto.platform.HostManager+import com.vayunmathur.auto.platform.HostTemplateBus+import com.vayunmathur.library.carhost.HostTemplate+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.assertNull+import kotlin.test.assertTrue++@RunWith(RobolectricTestRunner::class)+class Y3HostManagerTest {+    private val ctx: Context get() = ApplicationProvider.getApplicationContext()+    private fun app(pkg: String) = DiscoveredApp(ComponentName(pkg, "$pkg.Svc"), pkg, null, setOf("cat"))+    private fun idle() = Shadows.shadowOf(android.os.Looper.getMainLooper()).idle()++    @Test fun focusSurfaceNightTouchAndReset() {+        val manager = HostManager(ctx)+        val a = app("com.a"); val b = app("com.b")+        manager.bindAll(listOf(a, b)); idle()+        assertTrue(manager.templateFor(a.component) is HostTemplate.Message)+        manager.setFocused(a.component); assertEquals(a.component, manager.focused.value)+        val texture = SurfaceTexture(0); val surface = Surface(texture)+        manager.forwardSurface(surface, 800, 480)+        assertFalse(manager.injectMapTouch(MotionEvent.ACTION_DOWN, 10f, 10f)) // no surface callback bound+        manager.setNight(true); manager.setNight(false)+        // Focus switch detaches the old session and re-attaches the cached surface.+        manager.setFocused(b.component); idle()+        manager.forwardSurface(null, 0, 0)+        manager.resetApp(b.component); Thread.sleep(500); idle()+        manager.resetApp(ComponentName("com.missing", "com.missing.Svc"))+        manager.setFocused(null); assertNull(manager.focused.value)+        assertFalse(manager.injectMapTouch(MotionEvent.ACTION_UP, 0f, 0f))+        manager.unbindAll(); manager.unbindAll()+        assertTrue(manager.templates.value.isEmpty())+        surface.release(); texture.release()+    }++    @Test fun templateBusMapsEveryNavigationField() {+        val nav = HostTemplate.Navigation(+            navigating = true, loading = false, cue = "Turn left", road = "Market St",+            distanceText = "200 m", etaText = "5 min", lanesText = "2 lanes",+            actions = listOf(com.vayunmathur.library.carhost.HostUiAction("Go") {}),+        )+        HostTemplateBus.publish(nav)+        val legacy = HostTemplateBus.legacyNav.value+        assertEquals("Market St", legacy?.road); assertEquals(true, legacy?.navigating)+        assertEquals(1, legacy?.actions?.size)+        assertNull(HostTemplateBus.toLegacy(HostTemplate.Pane(title = "x")))+        assertNull(HostTemplateBus.toLegacy(HostTemplate.Message(title = "t", message = "m")))+    }++    @Test fun carAppHostSessionStartStopAndTemplateWithoutVideo() {+        val session = com.vayunmathur.auto.service.CarAppHostSession(ctx) { null }+        session.start(); session.start() // idempotent+        idle()+        session.setFocused(null)+        session.resetApp(null)+        session.resetApp(ComponentName("com.vayunmathur.maps", "com.vayunmathur.maps.car.MapsCarAppService"))+        Thread.sleep(400); idle()+        session.onTemplate(HostTemplate.Pane(title = "Home"))+        session.onTemplate(HostTemplate.Navigation(navigating = true, road = "Market"))+        session.stop(); session.stop()+        assertNull(session.let { null })+    }+}
auto/src/test/java/com/vayunmathur/auto/Y3MessagingRouteTest.kt
diff --git a/auto/src/test/java/com/vayunmathur/auto/Y3MessagingRouteTest.kt b/auto/src/test/java/com/vayunmathur/auto/Y3MessagingRouteTest.ktnew file mode 100644index 0000000000..5e5e8df9b2--- /dev/null+++ b/auto/src/test/java/com/vayunmathur/auto/Y3MessagingRouteTest.kt@@ -0,0 +1,84 @@+package com.vayunmathur.auto++import android.app.PendingIntent+import android.app.RemoteInput+import android.content.Context+import android.content.Intent+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.auto.notifications.MessageMirrorBus+import com.vayunmathur.auto.notifications.MessageReplyRoute+import com.vayunmathur.auto.platform.MessagingEvent+import com.vayunmathur.auto.protocol.GalConnection+import com.vayunmathur.auto.protocol.GalMessage+import com.vayunmathur.auto.protocol.GalTransport+import com.vayunmathur.auto.protocol.gal.MessagingAction+import com.vayunmathur.auto.protocol.gal.MessagingActionType+import com.vayunmathur.auto.protocol.gal.MessagingMessage+import com.vayunmathur.auto.protocol.gal.MessagingThread+import com.vayunmathur.auto.service.MessagingCarAppService+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++@RunWith(RobolectricTestRunner::class)+class Y3MessagingRouteTest {+    private val ctx: Context get() = ApplicationProvider.getApplicationContext()++    private class FakeTransport : GalTransport {+        val written = ByteArrayOutputStream()+        override fun read(b: ByteArray, o: Int, l: Int): Int = -1+        override fun write(b: ByteArray, o: Int, l: Int) { written.write(b, o, l) }+        override fun flush() = Unit+        override fun close() = Unit+    }++    private fun connection(): GalConnection {+        val ssl = SSLContext.getInstance("TLS").apply { init(null, null, null) }+        return GalConnection(FakeTransport(), ssl, deviceModel = "Test").also { it.close() }+    }++    private fun action(type: MessagingActionType, threadId: String, text: String = ""): ByteArray =+        MessagingAction.newBuilder().setAction(type).setThreadId(threadId).setReplyText(text).build().toByteArray()++    @Test fun replyWithRouteSendsAndMarkReadFires() {+        val events = mutableListOf<MessagingEvent>()+        val replies = mutableListOf<Pair<String, String>>()+        val svc = MessagingCarAppService(+            connection(),+            onEvent = { events += it },+            onReply = { t, x -> replies += t to x },+            context = { ctx },+        )+        svc.onChannelOpen()+        val replyIntent = PendingIntent.getActivity(+            ctx, 0, Intent(ctx, MainActivity::class.java).setAction("reply"),+            PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_MUTABLE,+        )+        val readIntent = PendingIntent.getActivity(+            ctx, 1, Intent(ctx, MainActivity::class.java).setAction("read"),+            PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_MUTABLE,+        )+        val route = MessageReplyRoute(+            threadId = "t7",+            replyIntent = replyIntent,+            remoteInput = RemoteInput.Builder("reply_key").build(),+            readIntent = readIntent,+        )+        // Posting the phone message registers the route for this thread.+        MessageMirrorBus.post(+            MessagingThread.newBuilder().setThreadId("t7").setTitle("Ada").build(),+            MessagingMessage.newBuilder().setThreadId("t7").setMessageId("m7").setSender("Ada").setBody("hi").setTimestampMs(1L).build(),+            route,+        )+        svc.onMessage(svc.channelId, GalMessage.Notification.ACTION, action(MessagingActionType.MESSAGE_REPLY, "t7", "on my way"))+        assertEquals(listOf("t7" to "on my way"), replies)+        assertTrue(events.any { it is MessagingEvent.ReplySent || it is MessagingEvent.ReplyFailed }, "$events")+        svc.onMessage(svc.channelId, GalMessage.Notification.ACTION, action(MessagingActionType.MESSAGE_MARK_READ, "t7"))+        assertTrue(events.any { it is MessagingEvent.MarkedRead })+        svc.release()+    }+}
auto/src/test/java/com/vayunmathur/auto/Y3ProjectionRoutingTest.kt
diff --git a/auto/src/test/java/com/vayunmathur/auto/Y3ProjectionRoutingTest.kt b/auto/src/test/java/com/vayunmathur/auto/Y3ProjectionRoutingTest.ktnew file mode 100644index 0000000000..5290214244--- /dev/null+++ b/auto/src/test/java/com/vayunmathur/auto/Y3ProjectionRoutingTest.kt@@ -0,0 +1,139 @@+package com.vayunmathur.auto++import android.content.Context+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.auto.protocol.ChannelMessage+import com.vayunmathur.auto.protocol.GalConnection+import com.vayunmathur.auto.protocol.GalService+import com.vayunmathur.auto.protocol.GalTransport+import com.vayunmathur.auto.protocol.NavSnapshot+import com.vayunmathur.auto.protocol.gal.MediaSinkService+import com.vayunmathur.auto.protocol.gal.Service+import com.vayunmathur.auto.protocol.gal.VideoConfiguration+import com.vayunmathur.auto.protocol.gal.VideoResolution+import com.vayunmathur.auto.service.ProjectionService+import com.vayunmathur.auto.service.openNext+import org.junit.runner.RunWith+import org.robolectric.Robolectric+import org.robolectric.RobolectricTestRunner+import java.io.ByteArrayOutputStream+import javax.net.ssl.SSLContext+import kotlin.test.Test+import kotlin.test.assertTrue++@RunWith(RobolectricTestRunner::class)+class Y3ProjectionRoutingTest {+    private val ctx: Context get() = ApplicationProvider.getApplicationContext()++    private class FakeTransport : GalTransport {+        val written = ByteArrayOutputStream()+        override fun read(b: ByteArray, o: Int, l: Int): Int = -1+        override fun write(b: ByteArray, o: Int, l: Int) { written.write(b, o, l) }+        override fun flush() = Unit+        override fun close() = Unit+    }++    private fun connection(): GalConnection {+        val ssl = SSLContext.getInstance("TLS").apply { init(null, null, null) }+        return GalConnection(FakeTransport(), ssl, deviceModel = "Test").also { it.close() }+    }++    private fun setSession(connection: GalConnection, name: String, value: Any?) {+        val f = connection.session.javaClass.getDeclaredField(name).apply { isAccessible = true }+        f.set(connection.session, value)+    }++    private fun invoke(service: ProjectionService, name: String, vararg args: Any?) {+        val method = ProjectionService::class.java.declaredMethods.first { it.name == name && it.parameterCount == args.size }+        method.isAccessible = true+        method.invoke(service, *args)+    }++    private fun mediaSink(): MediaSinkService = MediaSinkService.newBuilder()+        .addVideoConfigs(+            VideoConfiguration.newBuilder()+                .setCodecResolution(VideoResolution.VIDEO_1280x720).setFrameRate(30).setDensity(160)+                .build(),+        ).build()++    @Test fun routingGuidanceAndTeardownWithSeededChannels() {+        val service = Robolectric.buildService(ProjectionService::class.java).create().get()+        val connection = connection()+        // Seed a session that has granted every owned service, then let the+        // service's own openNext factories build the channel owners.+        val services = listOf(+            Service.newBuilder().setId(GalService.VIDEO_SINK.id).setMediaSink(mediaSink()).build(),+            Service.newBuilder().setId(GalService.NOTIFICATION.id).build(),+            Service.newBuilder().setId(GalService.AUDIO_SINK_GUIDANCE.id).build(),+            Service.newBuilder().setId(GalService.NAVIGATION_STATUS.id).build(),+        )+        setSession(connection, "services", services)+        repeat(4) { runCatching { service.openNext(connection) } }+        // Route one message to every owned/unowned branch.+        val channels = listOf(+            GalService.VIDEO_SINK.id, GalService.NOTIFICATION.id,+            GalService.AUDIO_SINK_GUIDANCE.id, GalService.NAVIGATION_STATUS.id,+            999,+        )+        for (id in channels) {+            runCatching { invoke(service, "routeChannelMessage", ChannelMessage(id, 0x8001, byteArrayOf(1, 2, 3))) }+        }+        runCatching {+            invoke(service, "onGuidanceSnapshot", NavSnapshot(latitudeE7 = 377_749_000, longitudeE7 = -1_224_194_000, parked = true, isNight = true, speedMps = 0.0))+            invoke(service, "onGuidanceSnapshot", NavSnapshot(latitudeE7 = 377_749_000, longitudeE7 = -1_224_194_000, parked = false, isNight = false, speedMps = 12.0))+        }+        runCatching { invoke(service, "onSessionFocusChanged", connection) }+        runCatching { invoke(service, "publishCredentialExpiry") }+        runCatching { invoke(service, "tearDownSession", connection) }+        // Teardown cleared the owners.+        assertTrue(service.video == null && service.messaging == null)+    }++    @Test fun grantedChannelSetupsRunOnce() {+        val service = Robolectric.buildService(ProjectionService::class.java).create().get()+        val connection = connection()+        setSession(connection, "services", listOf(+            Service.newBuilder().setId(GalService.VIDEO_SINK.id).setMediaSink(mediaSink()).build(),+            Service.newBuilder().setId(GalService.NOTIFICATION.id).build(),+        ))+        repeat(2) { runCatching { service.openNext(connection) } }+        setSession(connection, "openChannels", setOf(GalService.VIDEO_SINK.id, GalService.NOTIFICATION.id))+        val setupsClass = Class.forName("com.vayunmathur.auto.service.ProjectionService\$ChannelSetups")+        val pending = setupsClass.getDeclaredConstructor().apply { isAccessible = true }.newInstance()+        runCatching { invoke(service, "setUpGrantedChannels", connection, pending) }+        runCatching { invoke(service, "setUpGrantedChannels", connection, pending) } // once-only flags+        runCatching { invoke(service, "tearDownSession", connection) }+        assertTrue(service.video == null)+    }++    @Test fun sessionOnTransportWithDeadTransportTearsDown() {+        val service = Robolectric.buildService(ProjectionService::class.java).create().get()+        // Start the service so `running` is true and session-scoped owners exist.+        runCatching { service.onStartCommand(android.content.Intent(ctx, ProjectionService::class.java), 0, 1) }+        val method = ProjectionService::class.java.getDeclaredMethod(+            "sessionOnTransport", com.vayunmathur.auto.protocol.GalTransport::class.java, String::class.java,+        ).apply { isAccessible = true }+        // An immediately-EOF transport: version pump ends, teardown must run.+        runCatching { method.invoke(service, FakeTransport(), "Test Car") }+            .onFailure { it.cause?.printStackTrace() }+        assertTrue(service.video == null)+        runCatching { service.onDestroy() }+    }++    @Test fun openNextForEveryAdvertisedService() {+        for (galService in GalService.entries) {+            if (galService == GalService.CONTROL) continue+            val service = Robolectric.buildService(ProjectionService::class.java).create().get()+            val connection = connection()+            val proto = when (galService) {+                GalService.VIDEO_SINK -> Service.newBuilder().setId(galService.id).setMediaSink(mediaSink()).build()+                else -> Service.newBuilder().setId(galService.id).build()+            }+            setSession(connection, "services", listOf(proto))+            runCatching { service.openNext(connection) }+            runCatching { service.openNext(connection) } // second pass: already-open/pending guards+            runCatching { invoke(service, "tearDownSession", connection) }+        }+        assertTrue(true)+    }+}
auto/src/test/java/com/vayunmathur/auto/Y3SessionStateSweepTest.kt
diff --git a/auto/src/test/java/com/vayunmathur/auto/Y3SessionStateSweepTest.kt b/auto/src/test/java/com/vayunmathur/auto/Y3SessionStateSweepTest.ktnew file mode 100644index 0000000000..ded2fb11f3--- /dev/null+++ b/auto/src/test/java/com/vayunmathur/auto/Y3SessionStateSweepTest.kt@@ -0,0 +1,97 @@+package com.vayunmathur.auto++import com.vayunmathur.auto.platform.AudioEvent+import com.vayunmathur.auto.platform.AudioSinkState+import com.vayunmathur.auto.platform.AudioSinkStatus+import com.vayunmathur.auto.platform.AutoSessionState+import com.vayunmathur.auto.platform.InputEvent+import com.vayunmathur.auto.platform.MediaEvent+import com.vayunmathur.auto.platform.MessagingEvent+import com.vayunmathur.auto.platform.NowPlayingInfo+import com.vayunmathur.auto.platform.SensorEvent+import com.vayunmathur.auto.platform.VideoEvent+import com.vayunmathur.auto.platform.VideoInfo+import com.vayunmathur.auto.protocol.AudioSinkRole+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++@RunWith(RobolectricTestRunner::class)+class Y3SessionStateSweepTest {+    @Test fun everyEventVariantReducesIntoState() {+        AutoSessionState.onDisconnected()+        AutoSessionState.onSocketAccepted()+        AutoSessionState.onActive("Test Car")+        AutoSessionState.onVideoEvent(VideoEvent.Setup(VideoInfo(1280, 720, 30, 0)))+        AutoSessionState.onVideoEvent(VideoEvent.FocusChanged("VIDEO_FOCUS_PROJECTED"))+        AutoSessionState.onVideoEvent(VideoEvent.FirstFrame)+        repeat(3) { AutoSessionState.onVideoEvent(VideoEvent.FrameSent(1_000L + it, 100L)) }+        AutoSessionState.onVideoEvent(VideoEvent.AckReceived(7L, 1))+        AutoSessionState.onVideoEvent(VideoEvent.AckMismatch(-1, 42))+        AutoSessionState.onVideoEvent(VideoEvent.EncoderDrained(2))+        AutoSessionState.onVideoEvent(VideoEvent.SurfaceChanged(true))+        assertEquals(1280, AutoSessionState.video.value?.width)+        assertTrue(AutoSessionState.framesSent.value >= 3)++        AutoSessionState.onMediaEvent(MediaEvent.NowPlayingChanged(NowPlayingInfo("S", "A", true, 0, 100, null, null, false, true)))+        AutoSessionState.onMessagingEvent(MessagingEvent.ThreadsPosted(4))+        AutoSessionState.onMessagingEvent(MessagingEvent.MessagePosted("t"))+        AutoSessionState.onMessagingEvent(MessagingEvent.ReplyReceived("t"))+        AutoSessionState.onMessagingEvent(MessagingEvent.ReplySent("t"))+        AutoSessionState.onMessagingEvent(MessagingEvent.ReplyFailed("t", "x"))+        AutoSessionState.onMessagingEvent(MessagingEvent.MarkedRead("t"))+        assertEquals(4L, AutoSessionState.threadsPosted.value)++        AutoSessionState.onInputEvent(InputEvent.BindingRequested(1))+        AutoSessionState.onInputEvent(InputEvent.BindingAnswered(0))+        AutoSessionState.onInputEvent(InputEvent.Touch(0, 1))+        AutoSessionState.onInputEvent(InputEvent.Key(4, true))+        AutoSessionState.onInputEvent(InputEvent.Scroll(1))+        AutoSessionState.onInputEvent(InputEvent.VolumeKey(24, true))+        AutoSessionState.onInputEvent(InputEvent.FeedbackSent(1))+        AutoSessionState.onInputEvent(InputEvent.DroppedNoFocus)++        AutoSessionState.onAudioEvent(AudioEvent.SinkSetup("SYSTEM", "ok"))+        AutoSessionState.onAudioEvent(AudioEvent.SinkStatus(AudioSinkStatus(AudioSinkRole.SYSTEM, AudioSinkState.STARTED, com.vayunmathur.auto.protocol.AudioGain.FULL)))+        AutoSessionState.onAudioEvent(AudioEvent.SinkStarted("SYSTEM", 0))+        AutoSessionState.onAudioEvent(AudioEvent.SinkStopped("SYSTEM"))+        AutoSessionState.onAudioEvent(AudioEvent.MicTurn(128L))+        AutoSessionState.onAudioEvent(AudioEvent.MicAcked)+        AutoSessionState.onAudioEvent(AudioEvent.MicIdle)+        AutoSessionState.onAudioEvent(AudioEvent.FramesSent("SYSTEM", 100L))+        AutoSessionState.onAudioEvent(AudioEvent.SyncReceived("SYSTEM"))+        AutoSessionState.onAudioEvent(AudioEvent.AckReceived("SYSTEM", 3L))+        AutoSessionState.onAudioEvent(AudioEvent.TtsSpoken(10))+        AutoSessionState.onAudioEvent(AudioEvent.TtsDropped("x"))+        AutoSessionState.onAudioEvent(AudioEvent.MusicCaptured(500))+        AutoSessionState.onAudioEvent(AudioEvent.MusicDropped("muted"))++        AutoSessionState.onSensorEvent(SensorEvent.Subscribed("SPEED"))+        AutoSessionState.onSensorEvent(SensorEvent.SubscriptionAnswered("SPEED", 0))+        AutoSessionState.onSensorEvent(SensorEvent.BatchReceived(2))+        AutoSessionState.onSensorEvent(SensorEvent.SensorError("SPEED", -1))+        AutoSessionState.onSensorEvent(SensorEvent.GuidanceSetup)+        AutoSessionState.onSensorEvent(SensorEvent.GuidanceConfigured(true))+        AutoSessionState.onSensorEvent(SensorEvent.NavStatusPosted)++        AutoSessionState.onCallAvailability(true)+        AutoSessionState.onCredentialExpiry(30L)+        AutoSessionState.onSessionEnd(null)+        AutoSessionState.onSessionEnd("refused")+    }++    @Test fun activeRouteValueSemantics() {+        val a = com.vayunmathur.auto.platform.ActiveRoute(+            points = listOf(com.vayunmathur.auto.protocol.MapRoutePoint(1.0, 2.0)),+            nextRoad = "Market", nextTurnDistanceM = 100, maneuver = "left",+        )+        val b = a.copy(nextRoad = "Other")+        assertEquals("Market", a.nextRoad); assertEquals("Other", b.nextRoad)+        assertTrue(a.toString().contains("Market")); assertEquals(a.hashCode(), a.copy().hashCode())+        assertEquals(a, a.copy()); assertTrue(a != b)+        val (points, road, dist, maneuver) = a+        assertEquals(1, points.size); assertEquals(100, dist)+    }+}
auto/src/test/java/com/vayunmathur/auto/Y3VideoSinkSetupTest.kt
diff --git a/auto/src/test/java/com/vayunmathur/auto/Y3VideoSinkSetupTest.kt b/auto/src/test/java/com/vayunmathur/auto/Y3VideoSinkSetupTest.ktnew file mode 100644index 0000000000..9c66cf6382--- /dev/null+++ b/auto/src/test/java/com/vayunmathur/auto/Y3VideoSinkSetupTest.kt@@ -0,0 +1,117 @@+package com.vayunmathur.auto++import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.auto.platform.ScaledTouch+import com.vayunmathur.auto.platform.VideoEvent+import com.vayunmathur.auto.platform.VideoSinkChannel+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.InputPointer+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.VideoConfiguration+import com.vayunmathur.auto.protocol.gal.VideoFocusIndication+import com.vayunmathur.auto.protocol.gal.VideoFocusMode+import com.vayunmathur.auto.protocol.gal.VideoResolution+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.assertTrue++@RunWith(RobolectricTestRunner::class)+class Y3VideoSinkSetupTest {+    private class FakeTransport : GalTransport {+        val written = ByteArrayOutputStream()+        override fun read(b: ByteArray, o: Int, l: Int): Int = -1+        override fun write(b: ByteArray, o: Int, l: Int) { written.write(b, o, l) }+        override fun flush() = Unit+        override fun close() = Unit+    }++    private fun connection(): GalConnection {+        val ctx = SSLContext.getInstance("TLS").apply { init(null, null, null) }+        return GalConnection(FakeTransport(), ctx, deviceModel = "Test").also { it.close() }+    }++    private fun service(vararg configs: VideoConfiguration): Service = Service.newBuilder()+        .setId(GalService.VIDEO_SINK.id)+        .setMediaSink(MediaSinkService.newBuilder().addAllVideoConfigs(configs.toList()).build()).build()++    private fun config(res: VideoResolution, fps: Int, density: Int) =+        VideoConfiguration.newBuilder().setCodecResolution(res).setFrameRate(fps).setDensity(density).build()++    @Test fun setupResponseAcceptedAndOutOfRange() {+        val events = mutableListOf<VideoEvent>()+        val ch = VideoSinkChannel(+            ApplicationProvider.getApplicationContext(),+            service(+                config(VideoResolution.VIDEO_800x480, 60, 160),+                config(VideoResolution.VIDEO_1280x720, 30, 240),+                config(VideoResolution.VIDEO_1920x1080, 0, 0),+            ),+            connection(),+            onEvent = { events += it },+        )+        // Out-of-range index keeps entry 0; startStreaming may fail at the+        // MediaCodec on Robolectric — the setup event must already be out.+        runCatching {+            ch.onMessage(ch.channelId, GalMessage.Media.CONFIG,+                MediaSetupResponse.newBuilder().setMediaStatus(0).addConfigurationIndices(99).build().toByteArray())+        }+        assertTrue(events.any { it is VideoEvent.Setup }, "$events")+        runCatching { ch.release() }+        // Empty indices defaults to 0, accepted index 1 selects 720p30.+        val events2 = mutableListOf<VideoEvent>()+        val ch2 = VideoSinkChannel(+            ApplicationProvider.getApplicationContext(),+            service(config(VideoResolution.VIDEO_1280x720, 30, 240), config(VideoResolution.VIDEO_800x480, 60, 120)),+            connection(),+            onEvent = { events2 += it },+        )+        runCatching {+            ch2.onMessage(ch2.channelId, GalMessage.Media.CONFIG,+                MediaSetupResponse.newBuilder().setMediaStatus(0).addConfigurationIndices(1).build().toByteArray())+        }+        val setup = events2.filterIsInstance<VideoEvent.Setup>().firstOrNull()+        assertTrue(setup == null || setup.info.configIndex == 1, "$events2")+        // Focus projected/native + touch/key/scroll injection gates.+        runCatching {+            ch2.onMessage(ch2.channelId, GalMessage.Video.FOCUS_INDICATION,+                VideoFocusIndication.newBuilder().setMode(VideoFocusMode.VIDEO_FOCUS_PROJECTED).build().toByteArray())+            ch2.onMessage(ch2.channelId, GalMessage.Video.FOCUS_INDICATION,+                VideoFocusIndication.newBuilder().build().toByteArray())+            ch2.injectTouch(ScaledTouch(action = 0, pointers = listOf(InputPointer(10, 20, 0)), actionIndex = 0))+            ch2.injectKey(4, true); ch2.injectKey(4, false); ch2.injectScroll(3)+            ch2.requestSetup(); ch2.pumpEncoder()+        }+        runCatching { ch2.release() }+    }++    @Test fun sendFrameReflectionAndReleaseAfterStartAttempt() {+        val events = mutableListOf<VideoEvent>()+        val ch = VideoSinkChannel(+            ApplicationProvider.getApplicationContext(),+            service(config(VideoResolution.VIDEO_1280x720, 30, 240)),+            connection(),+            onEvent = { events += it },+        )+        val info = android.media.MediaCodec.BufferInfo().apply {+            size = 4; presentationTimeUs = 1_000L; offset = 0+        }+        val sendFrame = VideoSinkChannel::class.java.getDeclaredMethod(+            "sendFrame", java.nio.ByteBuffer::class.java, android.media.MediaCodec.BufferInfo::class.java,+        ).apply { isAccessible = true }+        runCatching { sendFrame.invoke(ch, java.nio.ByteBuffer.wrap(byteArrayOf(0, 0, 0, 1)), info) }+        runCatching { sendFrame.invoke(ch, java.nio.ByteBuffer.wrap(byteArrayOf(0, 0, 0, 1)), info) }+        // First frame event only fires when the focus arbitration allows streaming;+        // either way the frame path must not crash on a closed connection.+        ch.release()+        Thread.sleep(300)+        assertTrue(events.any { it is VideoEvent.SurfaceChanged } || events.isEmpty(), "$events")+    }+}