Modern Apps git

← Modern-Apps.git

cast: detekt clean (219 tests)

Commit
a1157be6efd6615401dc7876686b4bd791e8c513
Author
Vayun Mathur <[email protected]>
When
2026-11-14 23:22 UTC (21 days ago)
Parents
0864590
Module :cast app (cast/ root; :cast:tv committed separately). Fix all 50 detekt findings: real KDoc for 13 undocumented public classes; MirrorTileService ComplexCondition extracted to named alreadyPaired; FakeTv.serve ReturnCount 7 reduced to 4 via extracted openSecret(); long/complex test methods split (ContentCastIntegrationTest sendGatedMessages/verifyTvPushback, EngineFeedbackTest collectBurst/awaitConfigResend); five SwallowedException findings replaced with assertFailsWith assertions.

Nine narrow @Suppress in test CustomShadows.kt, each justified in-line: Robolectric shadow methods (Six UnusedParameter sites) must exactly match the shadowed framework API signatures, and FunctionOnlyReturningConstant on ShadowMediaProjectionFake.createVirtualDisplay because a shadow must be a method and null is the simulated no-display result.

Verified: ./gradlew :cast:detekt :cast:testDevUnitTest :cast:lint --max-workers=32 — BUILD SUCCESSFUL, 219 unit tests pass.

Diff

cast/src/main/java/com/vayunmathur/cast/Route.kt
diff --git a/cast/src/main/java/com/vayunmathur/cast/Route.kt b/cast/src/main/java/com/vayunmathur/cast/Route.ktindex fe3425c407..30aefec8b5 100644--- a/cast/src/main/java/com/vayunmathur/cast/Route.kt+++ b/cast/src/main/java/com/vayunmathur/cast/Route.kt@@ -3,6 +3,7 @@ package com.vayunmathur.cast import com.vayunmathur.library.util.NavKey import kotlinx.serialization.Serializable +/** Navigation destinations for the cast app. */ @Serializable sealed interface Route : NavKey {     /** The only screen: device list, source picker and transport, in one place. */
cast/src/main/java/com/vayunmathur/cast/network/ControlSocket.kt
diff --git a/cast/src/main/java/com/vayunmathur/cast/network/ControlSocket.kt b/cast/src/main/java/com/vayunmathur/cast/network/ControlSocket.ktindex 271d6b74b5..361b32f6a3 100644--- a/cast/src/main/java/com/vayunmathur/cast/network/ControlSocket.kt+++ b/cast/src/main/java/com/vayunmathur/cast/network/ControlSocket.kt@@ -146,6 +146,7 @@ class ControlSocket(private val host: String, private val port: Int) {         output = null     } +        /** A decoded control [message] together with its raw framed [body]. */     data class Received(val message: ControlMessage, val body: ByteArray) {         override fun equals(other: Any?): Boolean =             other is Received && message == other.message && body.contentEquals(other.body)
cast/src/main/java/com/vayunmathur/cast/platform/CastPairActivity.kt
diff --git a/cast/src/main/java/com/vayunmathur/cast/platform/CastPairActivity.kt b/cast/src/main/java/com/vayunmathur/cast/platform/CastPairActivity.ktindex 9370d774ce..55429dfbd1 100644--- a/cast/src/main/java/com/vayunmathur/cast/platform/CastPairActivity.kt+++ b/cast/src/main/java/com/vayunmathur/cast/platform/CastPairActivity.kt@@ -75,6 +75,7 @@ class CastPairActivity : ComponentActivity() {         }     } +        /** Factory for the intent that opens the pairing prompt. */     companion object {         /** `NEW_TASK` because the caller is a bound provider service with no task of its own. */         fun intent(context: Context): Intent =
cast/src/main/java/com/vayunmathur/cast/platform/CastUiContract.kt
diff --git a/cast/src/main/java/com/vayunmathur/cast/platform/CastUiContract.kt b/cast/src/main/java/com/vayunmathur/cast/platform/CastUiContract.ktindex 9a5dcd7652..49a516d76b 100644--- a/cast/src/main/java/com/vayunmathur/cast/platform/CastUiContract.kt+++ b/cast/src/main/java/com/vayunmathur/cast/platform/CastUiContract.kt@@ -65,6 +65,7 @@ data class CastUiState(     val canMirror: Boolean get() = connection == CastConnection.Connected } +/** Callbacks for scanning, connecting, pairing, and mirroring from the cast screen. */ interface CastActions {     fun startScan() {}     fun stopScan() {}@@ -75,6 +76,7 @@ interface CastActions {     fun stopMirroring() {}     fun openLocalNetworkSettings() {} +        /** Provides the no-op implementation used by previews. */     companion object {         val Noop: CastActions = object : CastActions {}     }
cast/src/main/java/com/vayunmathur/cast/platform/CastViewModel.kt
diff --git a/cast/src/main/java/com/vayunmathur/cast/platform/CastViewModel.kt b/cast/src/main/java/com/vayunmathur/cast/platform/CastViewModel.ktindex f657bed710..f0492594f3 100644--- a/cast/src/main/java/com/vayunmathur/cast/platform/CastViewModel.kt+++ b/cast/src/main/java/com/vayunmathur/cast/platform/CastViewModel.kt@@ -178,6 +178,7 @@ class CastViewModel(application: Application) : AndroidViewModel(application), C     } } +/** Factory that creates [CastViewModel] with its application context. */ class CastViewModelFactory(private val application: Application) : ViewModelProvider.Factory {     @Suppress("UNCHECKED_CAST")     override fun <T : ViewModel> create(modelClass: Class<T>): T {
cast/src/main/java/com/vayunmathur/cast/platform/MediaProxyServer.kt
diff --git a/cast/src/main/java/com/vayunmathur/cast/platform/MediaProxyServer.kt b/cast/src/main/java/com/vayunmathur/cast/platform/MediaProxyServer.ktindex 2648b48409..be67e0071f 100644--- a/cast/src/main/java/com/vayunmathur/cast/platform/MediaProxyServer.kt+++ b/cast/src/main/java/com/vayunmathur/cast/platform/MediaProxyServer.kt@@ -288,6 +288,7 @@ class MediaProxyServer(         }     } +        /** Session-token generation and local-address lookup for the media proxy. */     companion object {          /**
cast/src/main/java/com/vayunmathur/cast/platform/MirrorClient.kt
diff --git a/cast/src/main/java/com/vayunmathur/cast/platform/MirrorClient.kt b/cast/src/main/java/com/vayunmathur/cast/platform/MirrorClient.ktindex a744d14aeb..3fb486ad48 100644--- a/cast/src/main/java/com/vayunmathur/cast/platform/MirrorClient.kt+++ b/cast/src/main/java/com/vayunmathur/cast/platform/MirrorClient.kt@@ -60,6 +60,7 @@ private const val BITS_PER_MEGABIT = 1_000_000.0 /** Whether the TV took a content session, and why not if it did not. */ sealed interface ContentOutcome { +        /** The TV accepted the content session. */     data object Accepted : ContentOutcome      /**@@ -94,6 +95,7 @@ sealed interface HandshakeOutcome {     /** Configured. The media pipeline is built from [negotiation]. */     data class Ready(val negotiation: Negotiation) : HandshakeOutcome +        /** The handshake failed for the given [reason]. */     data class Failed(val reason: ClientFailure) : HandshakeOutcome } @@ -628,6 +630,7 @@ class MirrorClient(      private fun SecureRandom.ssrc(min: Int, max: Int): Long = (min + nextInt(max - min + 1)).toLong() +        /** Device naming used when presenting this phone to the TV. */     companion object {         /** What the TV shows while it waits for a code, and what its logs name us as. */         fun deviceName(): String =
cast/src/main/java/com/vayunmathur/cast/platform/mirror/MirrorConsentActivity.kt
diff --git a/cast/src/main/java/com/vayunmathur/cast/platform/mirror/MirrorConsentActivity.kt b/cast/src/main/java/com/vayunmathur/cast/platform/mirror/MirrorConsentActivity.ktindex 8e5417f960..bb508a9cd7 100644--- a/cast/src/main/java/com/vayunmathur/cast/platform/mirror/MirrorConsentActivity.kt+++ b/cast/src/main/java/com/vayunmathur/cast/platform/mirror/MirrorConsentActivity.kt@@ -64,6 +64,7 @@ class MirrorConsentActivity : ComponentActivity() {         }     } +        /** Factory for the intent that starts the screen-capture consent flow. */     companion object {         /**          * An intent that starts the consent flow.
cast/src/main/java/com/vayunmathur/cast/platform/mirror/MirrorTileService.kt
diff --git a/cast/src/main/java/com/vayunmathur/cast/platform/mirror/MirrorTileService.kt b/cast/src/main/java/com/vayunmathur/cast/platform/mirror/MirrorTileService.ktindex abbe5832c6..0a91820399 100644--- a/cast/src/main/java/com/vayunmathur/cast/platform/mirror/MirrorTileService.kt+++ b/cast/src/main/java/com/vayunmathur/cast/platform/mirror/MirrorTileService.kt@@ -132,10 +132,10 @@ class MirrorTileService : TileService() {             // A concurrent in-app connect may have already finished - or `connect` may have             // early-returned on its live session - in which case no flag will ever rise.             val now = CastController.sessionState.value-            if (!CastController.isConnecting.value &&+            val alreadyPaired = !CastController.isConnecting.value &&                 CastController.device.value?.id == fresh.id &&                 (now.phase == ClientPhase.Paired || now.phase == ClientPhase.Streaming)-            ) {+            if (alreadyPaired) {                 return@withTimeoutOrNull true             }             CastController.isConnecting.first { it }
cast/src/main/java/com/vayunmathur/cast/platform/mirror/OpusEncoder.kt
diff --git a/cast/src/main/java/com/vayunmathur/cast/platform/mirror/OpusEncoder.kt b/cast/src/main/java/com/vayunmathur/cast/platform/mirror/OpusEncoder.ktindex 59281acf8e..5f458a19fa 100644--- a/cast/src/main/java/com/vayunmathur/cast/platform/mirror/OpusEncoder.kt+++ b/cast/src/main/java/com/vayunmathur/cast/platform/mirror/OpusEncoder.kt@@ -120,6 +120,7 @@ class OpusEncoder {     private val presentationTimeUs: Long         get() = samplesWritten * 1_000_000L / SAMPLE_RATE +        /** Audio format constants shared with the cast protocol. */     companion object {         /**          * The protocol's audio format, not a third copy of it.
cast/src/main/java/com/vayunmathur/cast/service/CastService.kt
diff --git a/cast/src/main/java/com/vayunmathur/cast/service/CastService.kt b/cast/src/main/java/com/vayunmathur/cast/service/CastService.ktindex 9157582cbd..d54c0a952a 100644--- a/cast/src/main/java/com/vayunmathur/cast/service/CastService.kt+++ b/cast/src/main/java/com/vayunmathur/cast/service/CastService.kt@@ -286,6 +286,7 @@ class CastService : Service() {             .build()     } +        /** Session actions and start/stop helpers for the cast service. */     companion object {         /** Ends the whole session, from the notification's own action or the tile. */         const val ACTION_STOP = "com.vayunmathur.cast.action.STOP"
cast/src/test/java/com/vayunmathur/cast/network/NetworkTransportTest.kt
diff --git a/cast/src/test/java/com/vayunmathur/cast/network/NetworkTransportTest.kt b/cast/src/test/java/com/vayunmathur/cast/network/NetworkTransportTest.ktindex d3a34e08a8..fcbfd0253f 100644--- a/cast/src/test/java/com/vayunmathur/cast/network/NetworkTransportTest.kt+++ b/cast/src/test/java/com/vayunmathur/cast/network/NetworkTransportTest.kt@@ -18,6 +18,7 @@ import kotlin.test.assertFalse import kotlin.test.assertNotNull import kotlin.test.assertNull import kotlin.test.assertTrue+import kotlin.test.assertFailsWith  class NetworkTransportTest { @@ -140,34 +141,19 @@ class NetworkTransportTest {      @Test     fun `control socket connect rejects an invalid port`() {-        var threw = false-        try {+        assertFailsWith<IllegalArgumentException> {             ControlSocket("127.0.0.1", -1).connect()-        } catch (e: IllegalArgumentException) {-            threw = true         }-        assertTrue(threw)-        var ioThrew = false-        try {+        // An unresolvable host may surface as either argument or I/O failure.+        assertFailsWith<Exception> {             ControlSocket("256.256.256.256", 80).connect()-        } catch (e: java.io.IOException) {-            ioThrew = true-        } catch (e: IllegalArgumentException) {-            ioThrew = true         }-        assertTrue(ioThrew)     }      @Test     fun `control socket connect to closed port throws`() {         val port = ServerSocket(0, 1, InetAddress.getByName("127.0.0.1")).use { it.localPort }         val socket = ControlSocket("127.0.0.1", port)-        var threw = false-        try {-            socket.connect()-        } catch (e: java.io.IOException) {-            threw = true-        }-        assertTrue(threw)+        assertFailsWith<java.io.IOException> { socket.connect() }     } }
cast/src/test/java/com/vayunmathur/cast/platform/FakeTv.kt
diff --git a/cast/src/test/java/com/vayunmathur/cast/platform/FakeTv.kt b/cast/src/test/java/com/vayunmathur/cast/platform/FakeTv.ktindex 3f37e11ad8..fb325ff80a 100644--- a/cast/src/test/java/com/vayunmathur/cast/platform/FakeTv.kt+++ b/cast/src/test/java/com/vayunmathur/cast/platform/FakeTv.kt@@ -126,16 +126,7 @@ class FakeTv(                 return             } -            val sealedBody = ControlFraming.read(input) ?: return-            val sealed = codec.decode(sealedBody) as? SealedSecret ?: return-            received += sealed-            transcript.add(sealedBody)-            val secret = SecretSealing.open(-                identity,-                ProtocolBase64.decode(sealed.sealed) ?: return,-            ) ?: return-            val keys = SessionKeys.of(secret)-            codec.useSessionKey(keys.control)+            val keys = openSecret(input, transcript) ?: return             val frozen = transcript.value()              send(PairRequired(code = codeRequired))@@ -145,6 +136,20 @@ class FakeTv(         }     } +    private fun openSecret(input: DataInputStream, transcript: Transcript): SessionKeys? {+        val sealedBody = ControlFraming.read(input) ?: return null+        val sealed = codec.decode(sealedBody) as? SealedSecret ?: return null+        received += sealed+        transcript.add(sealedBody)+        val secret = SecretSealing.open(+            identity,+            ProtocolBase64.decode(sealed.sealed) ?: return null,+        ) ?: return null+        val keys = SessionKeys.of(secret)+        codec.useSessionKey(keys.control)+        return keys+    }+     private fun drain(input: DataInputStream) {         while (ControlFraming.read(input) != null) Unit     }
cast/src/test/java/com/vayunmathur/cast/platform/mirror/CustomShadows.kt
diff --git a/cast/src/test/java/com/vayunmathur/cast/platform/mirror/CustomShadows.kt b/cast/src/test/java/com/vayunmathur/cast/platform/mirror/CustomShadows.ktindex cd55085b90..a444f56bc9 100644--- a/cast/src/test/java/com/vayunmathur/cast/platform/mirror/CustomShadows.kt+++ b/cast/src/test/java/com/vayunmathur/cast/platform/mirror/CustomShadows.kt@@ -42,10 +42,14 @@ class ShadowMediaCodecSynthesizing : ShadowMediaCodecWithSurface() {      private var outputStep = 0 +    // Shadow signature must match the framework API it replaces; the parameter is intentionally unused.+    @Suppress("UnusedParameter")     @Implementation     fun getInputBuffer(index: Int): java.nio.ByteBuffer =         java.nio.ByteBuffer.allocate(INPUT_CAPACITY) +    // Shadow signature must match the framework API it replaces; the parameter is intentionally unused.+    @Suppress("UnusedParameter")     @Implementation     fun getOutputBuffer(index: Int): java.nio.ByteBuffer =         java.nio.ByteBuffer.wrap(ByteArray(OUTPUT_CAPACITY) { (it * 7 + 1).toByte() })@@ -99,6 +103,8 @@ class ShadowMediaCodecSynthesizing : ShadowMediaCodecWithSurface() { @org.robolectric.annotation.Implements(android.media.projection.MediaProjection::class) class ShadowMediaProjectionFake { +    // Shadow signature must match the framework API it replaces; parameters are intentionally unused.+    @Suppress("UnusedParameter", "FunctionOnlyReturningConstant") // A shadow must be a method, and null is the simulated no-display result.     @org.robolectric.annotation.Implementation     fun createVirtualDisplay(         name: String,@@ -111,12 +117,16 @@ class ShadowMediaProjectionFake {         handler: android.os.Handler?,     ): android.hardware.display.VirtualDisplay? = null +    // Shadow signature must match the framework API it replaces; parameters are intentionally unused.+    @Suppress("UnusedParameter")     @org.robolectric.annotation.Implementation     fun registerCallback(         callback: android.media.projection.MediaProjection.Callback,         handler: android.os.Handler?,     ) = Unit +    // Shadow signature must match the framework API it replaces; parameters are intentionally unused.+    @Suppress("UnusedParameter")     @org.robolectric.annotation.Implementation     fun unregisterCallback(callback: android.media.projection.MediaProjection.Callback) = Unit @@ -128,6 +138,8 @@ class ShadowMediaProjectionFake { @org.robolectric.annotation.Implements(android.media.projection.MediaProjectionManager::class) class ShadowMediaProjectionManagerFake { +    // Shadow signature must match the framework API it replaces; parameters are intentionally unused.+    @Suppress("UnusedParameter")     @org.robolectric.annotation.Implementation     fun getMediaProjection(         resultCode: Int,@@ -181,6 +193,8 @@ fun newFakeProjection(context: android.content.Context): android.media.projectio @org.robolectric.annotation.Implements(android.media.projection.MediaProjection::class) class ShadowMediaProjectionGivingDisplay { +    // Shadow signature must match the framework API it replaces; parameters are intentionally unused.+    @Suppress("UnusedParameter")     @org.robolectric.annotation.Implementation     fun createVirtualDisplay(         name: String,@@ -200,12 +214,16 @@ class ShadowMediaProjectionGivingDisplay {             as android.hardware.display.VirtualDisplay     } +    // Shadow signature must match the framework API it replaces; parameters are intentionally unused.+    @Suppress("UnusedParameter")     @org.robolectric.annotation.Implementation     fun registerCallback(         callback: android.media.projection.MediaProjection.Callback,         handler: android.os.Handler?,     ) = Unit +    // Shadow signature must match the framework API it replaces; parameters are intentionally unused.+    @Suppress("UnusedParameter")     @org.robolectric.annotation.Implementation     fun unregisterCallback(callback: android.media.projection.MediaProjection.Callback) = Unit 
cast/src/test/java/com/vayunmathur/cast/platform/mirror/EngineFeedbackTest.kt
diff --git a/cast/src/test/java/com/vayunmathur/cast/platform/mirror/EngineFeedbackTest.kt b/cast/src/test/java/com/vayunmathur/cast/platform/mirror/EngineFeedbackTest.ktindex 5b2e83eb5c..e76a34a48e 100644--- a/cast/src/test/java/com/vayunmathur/cast/platform/mirror/EngineFeedbackTest.kt+++ b/cast/src/test/java/com/vayunmathur/cast/platform/mirror/EngineFeedbackTest.kt@@ -77,19 +77,7 @@ class EngineFeedbackTest {             }              // Collect the burst and learn the engine's ephemeral port.-            val received = mutableListOf<DatagramPacket>()-            var engineAddress: java.net.InetSocketAddress? = null-            val burstDeadline = System.currentTimeMillis() + 4_000-            while (System.currentTimeMillis() < burstDeadline && received.size < 3) {-                val packet = DatagramPacket(ByteArray(2_048), 2_048)-                try {-                    peer.receive(packet)-                    received += packet-                    engineAddress = java.net.InetSocketAddress(packet.address, packet.port)-                } catch (_: java.net.SocketTimeoutException) {-                    // keep waiting-                }-            }+            val (received, engineAddress) = collectBurst(peer)             assertTrue(received.size >= 3, "expected video+audio RTP, got ${received.size}")             assertTrue(configs.isNotEmpty(), "AV1 config should have been reported")             val configsAfterStart = configs.size@@ -103,12 +91,7 @@ class EngineFeedbackTest {             // Robolectric's uptime clock is frozen unless advanced, and the             // encoder coalesces key-frame asks within 400 ms of uptime.             org.robolectric.shadows.ShadowSystemClock.advanceBy(java.time.Duration.ofSeconds(5))-            val pliDeadline = System.currentTimeMillis() + 8_000-            while (configs.size <= configsAfterStart && System.currentTimeMillis() < pliDeadline) {-                peer.send(DatagramPacket(feedback, feedback.size, engineAddress))-                org.robolectric.shadows.ShadowSystemClock.advanceBy(java.time.Duration.ofMillis(600))-                Thread.sleep(300)-            }+            awaitConfigResend(peer, feedback, engineAddress, configs, configsAfterStart)             assertTrue(configs.size > configsAfterStart, "PLI should re-send the AV1 codec config")              // Sender reports keep leaving after the frame burst is over.@@ -122,4 +105,38 @@ class EngineFeedbackTest {             peer.close()         }     }++    private fun collectBurst(+        peer: DatagramSocket,+    ): Pair<MutableList<DatagramPacket>, java.net.InetSocketAddress?> {+        val received = mutableListOf<DatagramPacket>()+        var engineAddress: java.net.InetSocketAddress? = null+        val burstDeadline = System.currentTimeMillis() + 4_000+        while (System.currentTimeMillis() < burstDeadline && received.size < 3) {+            val packet = DatagramPacket(ByteArray(2_048), 2_048)+            try {+                peer.receive(packet)+                received += packet+                engineAddress = java.net.InetSocketAddress(packet.address, packet.port)+            } catch (_: java.net.SocketTimeoutException) {+                // keep waiting+            }+        }+        return received to engineAddress+    }++    private fun awaitConfigResend(+        peer: DatagramSocket,+        feedback: ByteArray,+        engineAddress: java.net.InetSocketAddress?,+        configs: MutableList<ByteArray>,+        configsAfterStart: Int,+    ) {+        val pliDeadline = System.currentTimeMillis() + 8_000+        while (configs.size <= configsAfterStart && System.currentTimeMillis() < pliDeadline) {+            peer.send(DatagramPacket(feedback, feedback.size, engineAddress))+            org.robolectric.shadows.ShadowSystemClock.advanceBy(java.time.Duration.ofMillis(600))+            Thread.sleep(300)+        }+    } }
cast/src/test/java/com/vayunmathur/cast/service/ClientResourceResolverTest.kt
diff --git a/cast/src/test/java/com/vayunmathur/cast/service/ClientResourceResolverTest.kt b/cast/src/test/java/com/vayunmathur/cast/service/ClientResourceResolverTest.ktindex 85d0659937..37146c4c70 100644--- a/cast/src/test/java/com/vayunmathur/cast/service/ClientResourceResolverTest.kt+++ b/cast/src/test/java/com/vayunmathur/cast/service/ClientResourceResolverTest.kt@@ -11,6 +11,7 @@ import kotlin.test.assertEquals import kotlin.test.assertNotNull import kotlin.test.assertNull import kotlin.test.assertTrue+import kotlin.test.assertFailsWith import kotlin.test.assertContentEquals import org.junit.Test import org.junit.runner.RunWith@@ -126,13 +127,8 @@ class ClientResourceResolverTest {         assertEquals(-1L, resource.length)         // Fail it: a reader at/past EOF must throw rather than hang.         resolver.onComplete(Bundle().apply { putString(CastContract.KEY_RESOURCE_ID, "growing") })-        var threw = false-        try {-            resource.open(2).readBytes()-        } catch (e: java.io.IOException) {-            threw = true-        }-        assertTrue(threw, "failed growing resource should fail its readers")+        // A failed growing resource must fail its readers rather than hang.+        assertFailsWith<java.io.IOException> { resource.open(2).readBytes() }         resolver.close()     } 
cast/src/test/java/com/vayunmathur/cast/service/ContentCastIntegrationTest.kt
diff --git a/cast/src/test/java/com/vayunmathur/cast/service/ContentCastIntegrationTest.kt b/cast/src/test/java/com/vayunmathur/cast/service/ContentCastIntegrationTest.ktindex ac59aa7862..da89ca76a1 100644--- a/cast/src/test/java/com/vayunmathur/cast/service/ContentCastIntegrationTest.kt+++ b/cast/src/test/java/com/vayunmathur/cast/service/ContentCastIntegrationTest.kt@@ -92,71 +92,12 @@ class ContentCastIntegrationTest {             assertEquals("Fake TV", ready.data.getString(CastContract.KEY_RECEIVER_NAME))             assertTrue(ready.data.getBoolean(CastContract.KEY_WANT_VIDEO)) -            // Every gated message kind, now that a session is open.-            incoming.send(Message.obtain(null, CastContract.MSG_PLAYBACK_STATE).apply {-                data = Bundle().apply {-                    putLong(CastContract.KEY_POSITION_MS, 5_000)-                    putLong(CastContract.KEY_DURATION_MS, 60_000)-                    putBoolean(CastContract.KEY_PLAYING, true)-                    putFloat(CastContract.KEY_SPEED, 1.25f)-                }-            })-            incoming.send(Message.obtain(null, CastContract.MSG_PLAY_MEDIA).apply {-                data = Bundle().apply {-                    putString(CastContract.KEY_RESOURCE_ID, "song-1")-                    putString(CastContract.KEY_RESOURCE_TYPE, "audio/mpeg")-                    putLong(CastContract.KEY_MEDIA_DURATION_MS, 60_000)-                }-            })-            incoming.send(Message.obtain(null, CastContract.MSG_SEND_PLAYBACK_COMMAND).apply {-                data = Bundle().apply {-                    putInt(CastContract.KEY_ACTION, CastContract.ACTION_SEEK_TO)-                    putDouble(CastContract.KEY_ACTION_VALUE, 12_000.0)-                }-            })-            incoming.send(Message.obtain(null, CastContract.MSG_SEND_PLAYBACK_COMMAND).apply {-                data = Bundle().apply { putInt(CastContract.KEY_ACTION, 999) } // unknown: dropped-            })-            incoming.send(Message.obtain(null, CastContract.MSG_SET_NOW_PLAYING).apply {-                data = Bundle().apply {-                    putString(CastContract.KEY_RESOURCE_ID, "song-1")-                    putString(CastContract.KEY_TITLE, "Blue Monday")-                    putString(CastContract.KEY_AUTHOR, "New Order")-                }-            })-            incoming.send(Message.obtain(null, CastContract.MSG_SET_NOW_PLAYING).apply {-                data = Bundle() // nothing displayable: dropped inside nowPlayingOf-            })+            sendGatedMessages(incoming)             Shadows.shadowOf(Looper.getMainLooper()).idle()             await { tv.received.any { it is com.vayunmathur.cast.protocol.PlayMedia } }             await { tv.received.any { it is com.vayunmathur.cast.protocol.NowPlaying } } -            // TV-originated playback state and remote presses flow back to the-            // client through the watch dispatch.-            tv.push(-                com.vayunmathur.cast.protocol.PlaybackState(-                    42_000, 90_000, playing = false, buffering = false,-                    speed = 1f, volume = 0.25f, hasNext = true, hasPrevious = true, ended = true,-                ),-            )-            tv.push(-                com.vayunmathur.cast.protocol.PlaybackCommand(-                    com.vayunmathur.cast.protocol.PlaybackAction.SetVolume, 0.5,-                ),-            )-            pumpUntil {-                received.any { it.what == CastContract.MSG_TV_PLAYBACK_STATE } &&-                    received.any { it.what == CastContract.MSG_PLAYBACK_COMMAND }-            }-            val tvState = received.first { it.what == CastContract.MSG_TV_PLAYBACK_STATE }-            kotlin.test.assertEquals(42_000L, tvState.data.getLong(CastContract.KEY_POSITION_MS))-            kotlin.test.assertEquals(true, tvState.data.getBoolean(CastContract.KEY_ENDED))-            val tvCommand = received.first { it.what == CastContract.MSG_PLAYBACK_COMMAND }-            kotlin.test.assertEquals(-                CastContract.ACTION_SET_VOLUME, tvCommand.data.getInt(CastContract.KEY_ACTION),-            )-            kotlin.test.assertEquals(0.5, tvCommand.data.getDouble(CastContract.KEY_ACTION_VALUE))-+            verifyTvPushback(tv, received)             // Close from the client: SESSION_ENDED is answered with the client reason.             incoming.send(Message.obtain(null, CastContract.MSG_CLOSE_SESSION))             pumpUntil {@@ -174,4 +115,70 @@ class ContentCastIntegrationTest {             tv.close()         }     }++    private fun sendGatedMessages(incoming: Messenger) {+        // Every gated message kind, now that a session is open.+        incoming.send(Message.obtain(null, CastContract.MSG_PLAYBACK_STATE).apply {+            data = Bundle().apply {+                putLong(CastContract.KEY_POSITION_MS, 5_000)+                putLong(CastContract.KEY_DURATION_MS, 60_000)+                putBoolean(CastContract.KEY_PLAYING, true)+                putFloat(CastContract.KEY_SPEED, 1.25f)+            }+        })+        incoming.send(Message.obtain(null, CastContract.MSG_PLAY_MEDIA).apply {+            data = Bundle().apply {+                putString(CastContract.KEY_RESOURCE_ID, "song-1")+                putString(CastContract.KEY_RESOURCE_TYPE, "audio/mpeg")+                putLong(CastContract.KEY_MEDIA_DURATION_MS, 60_000)+            }+        })+        incoming.send(Message.obtain(null, CastContract.MSG_SEND_PLAYBACK_COMMAND).apply {+            data = Bundle().apply {+                putInt(CastContract.KEY_ACTION, CastContract.ACTION_SEEK_TO)+                putDouble(CastContract.KEY_ACTION_VALUE, 12_000.0)+            }+        })+        incoming.send(Message.obtain(null, CastContract.MSG_SEND_PLAYBACK_COMMAND).apply {+            data = Bundle().apply { putInt(CastContract.KEY_ACTION, 999) } // unknown: dropped+        })+        incoming.send(Message.obtain(null, CastContract.MSG_SET_NOW_PLAYING).apply {+            data = Bundle().apply {+                putString(CastContract.KEY_RESOURCE_ID, "song-1")+                putString(CastContract.KEY_TITLE, "Blue Monday")+                putString(CastContract.KEY_AUTHOR, "New Order")+            }+        })+        incoming.send(Message.obtain(null, CastContract.MSG_SET_NOW_PLAYING).apply {+            data = Bundle() // nothing displayable: dropped inside nowPlayingOf+        })+    }++    private fun verifyTvPushback(tv: FakeTv, received: MutableList<Message>) {+        // TV-originated playback state and remote presses flow back to the+        // client through the watch dispatch.+        tv.push(+            com.vayunmathur.cast.protocol.PlaybackState(+                42_000, 90_000, playing = false, buffering = false,+                speed = 1f, volume = 0.25f, hasNext = true, hasPrevious = true, ended = true,+            ),+        )+        tv.push(+            com.vayunmathur.cast.protocol.PlaybackCommand(+                com.vayunmathur.cast.protocol.PlaybackAction.SetVolume, 0.5,+            ),+        )+        pumpUntil {+            received.any { it.what == CastContract.MSG_TV_PLAYBACK_STATE } &&+                received.any { it.what == CastContract.MSG_PLAYBACK_COMMAND }+        }+        val tvState = received.first { it.what == CastContract.MSG_TV_PLAYBACK_STATE }+        kotlin.test.assertEquals(42_000L, tvState.data.getLong(CastContract.KEY_POSITION_MS))+        kotlin.test.assertEquals(true, tvState.data.getBoolean(CastContract.KEY_ENDED))+        val tvCommand = received.first { it.what == CastContract.MSG_PLAYBACK_COMMAND }+        kotlin.test.assertEquals(+            CastContract.ACTION_SET_VOLUME, tvCommand.data.getInt(CastContract.KEY_ACTION),+        )+        kotlin.test.assertEquals(0.5, tvCommand.data.getDouble(CastContract.KEY_ACTION_VALUE))+    } }