Modern Apps git

← Modern-Apps.git

youpipe: add tests for tv slice 3/3 (pass 3)

Commit
5135ec8c4be089c63db3b1ab153e701775c43eec
Author
Vayun Mathur <[email protected]>
When
2026-11-07 12:06 UTC (29 days ago)
Parents
437fbcd
Slice coverage (per-class INSTRUCTION counters for the tv/
package in :youpipe:createMergedCoverageReport):
0.00% (0/31072) -> 65.31% (20292/31072). Whole module:
20.06% (20526/102319) -> 40.6% (41546/102319; other slices'
pass-3 landings included). The 85% slice target is not reached;
the dominant remainder is documented below.

Five new files under src/test/.../tv/ (TvPass3* names; no
production changes). Shared setup seeds an in-memory
SubscriptionDatabase into the process-wide database registry —
the exact instance SubscriptionRepository resolves — so the real
YouPipeViewModel runs under Robolectric with no AndroidKeyStore
(the RootSlice3PlaylistDialogsTest pattern), with manual
WorkManager init.

- TvPass3PagesTest (16): every TV browse/settings page in empty
  and DAO-seeded states (home feed, subscriptions + feed, history,
  saved, downloads, channel, playlist detail, settings hub and
  general/sponsor/recommendations/data sub-pages, manage
  interests, search, create playlist/category), native-graphics
  captures.
- TvPass3PlayerTest (17): transport state reveal/hide/pin, the
  D-pad back/media map with no player attached, route
  serialization round-trips, tvDefaultBackStack persisted-page
  mapping, duration badge / elapsed / speed formatting, shared
  cards + grid + options dialog, transport overlay, chapter /
  quality / caption / language / speed sheets with selection,
  download sheet, seek bar / play-pause / captions / avatar /
  settings controls, and the player + video pages in their
  no-data states.
- TvPass3InteractionsTest (8): typing into the create-playlist
  and create-category fields, add-to-playlist fallbacks, the
  video left pane, TvMainActivity launched via Robolectric,
  player overlays composition.
- TvPass3DeepTest (7): pages fed by a seeded videoState (via the
  VM's internal mutable flow): video page populated,
  add-to-playlist staged, downloads from the DAO,
  rememberTvPlayerChrome with subscribe/channel/details/watch-
  later/save/related callbacks asserting back-stack effects and
  the repository subscription insert, overlays with all sheets
  and cues, chapter card / comments / description / WebView
  probe, and the D-pad map driving a Proxy-faked media3 Player
  through CastPlayback (media keys + hidden-scrub commit).
- TvPass3TestSupport: the seeding/wipe/view-model plumbing.

Verified: gslot ./gradlew :youpipe:testDevUnitTest for the tv
classes (all green) and the merged report run above, which
executes the full module suite with no failures.

What remains and why: TvPlayerKt (~2028 instructions) is the
bulk of the gap — TvPlayer/TvPlayerPage with actual streams
bind a MediaController to the app's PlaybackService, which
crashes inside media3's session callback under Robolectric
(null service component); it needs an emulator with the real
service (androidTest) rather than more Robolectric tests. The
same applies to the residual TvPlayerOverlays position loop
and the playback-bound branches of TvSearch/TvDownloads/
TvPlaylistDetail/TvHomeFeed (extractor/recommender-fed states
that require a live fetch to populate).

(cherry picked from commit 3f8ee1c0587f1e972682373321b69b5d28b0af12)

Diff

youpipe/src/test/java/com/vayunmathur/youpipe/tv/TvPass3DeepTest.kt
diff --git a/youpipe/src/test/java/com/vayunmathur/youpipe/tv/TvPass3DeepTest.kt b/youpipe/src/test/java/com/vayunmathur/youpipe/tv/TvPass3DeepTest.ktnew file mode 100644index 0000000000..3c263e8c37--- /dev/null+++ b/youpipe/src/test/java/com/vayunmathur/youpipe/tv/TvPass3DeepTest.kt@@ -0,0 +1,253 @@+package com.vayunmathur.youpipe.tv++import android.content.Context+import android.view.KeyEvent+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.ui.Modifier+import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.captureToImage+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.onRoot+import androidx.test.core.app.ApplicationProvider+import androidx.media3.common.Player+import com.vayunmathur.youpipe.data.DownloadedVideo+import com.vayunmathur.youpipe.data.Playlist+import com.vayunmathur.youpipe.data.SubscriptionDatabase+import com.vayunmathur.youpipe.platform.CastPlayback+import com.vayunmathur.youpipe.ui.AudioStream+import com.vayunmathur.youpipe.ui.Comment+import com.vayunmathur.youpipe.ui.SubtitleTrack+import com.vayunmathur.youpipe.ui.VideoChapter+import com.vayunmathur.youpipe.ui.VideoData+import com.vayunmathur.youpipe.ui.VideoInfo+import com.vayunmathur.youpipe.ui.VideoStream+import com.vayunmathur.youpipe.util.YouPipeViewModel+import kotlinx.coroutines.runBlocking+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config+import org.robolectric.annotation.GraphicsMode+import java.lang.reflect.InvocationHandler+import java.lang.reflect.Proxy+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue+import kotlin.time.Clock++/**+ * Slice 3/3 (tv/) pass 3, deep paths: pages fed by a seeded+ * [YouPipeViewModel.VideoState] (via the internal mutable flow),+ * rememberTvPlayerChrome and its navigation/subscribe callbacks, the+ * full TvPlayer + overlays with sheets/cues open, downloads populated+ * from the DAO, video-support composables, and the D-pad map driving+ * a fake media3 Player through CastPlayback.+ */+@GraphicsMode(GraphicsMode.Mode.NATIVE)+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34], qualifiers = "w1200dp-h800dp")+class TvPass3DeepTest {++    @get:Rule val rule = createComposeRule()++    private val context: Context get() = ApplicationProvider.getApplicationContext()+    private lateinit var db: SubscriptionDatabase+    private lateinit var vm: YouPipeViewModel++    @BeforeTest fun setUp() {+        db = TvPass3Support.database(context)+        vm = TvPass3Support.viewModel(context)+        runBlocking { TvPass3Support.wipe(db, vm) }+        CastPlayback.attachPlayer(null)+        TvDpadInput.overlayDismiss = null+    }++    private fun videoData() = VideoData(+        title = "Deep Video", views = 123_456, duration = 600,+        uploadDate = Clock.System.now(), thumbnailURL = "",+        author = "Chan A", authorURL = "chan-a", authorThumbnail = "",+        description = "A description with https://example.com inside",+    )++    private fun vStream(height: Int = 720) = VideoStream(+        url = "https://example.invalid/v$height", width = 1280, height = height,+        bitrate = 1_000_000, fps = 30, quality = "${height}p", codec = "vp9", size = 10_000_000,+    )++    private fun aStream() = AudioStream(+        url = "https://example.invalid/a", bitrate = 128_000, codec = "opus",+        language = "en", displayName = "English", size = 1_000_000,+    )++    private fun info(id: Long) = VideoInfo(+        name = "Video $id", videoID = id, duration = 300, views = 100,+        uploadDate = Clock.System.now(), thumbnailURL = "", author = "Chan A",+    )++    private fun seedVideoState() {+        vm.videoStateMutable.value = YouPipeViewModel.VideoState(+            data = videoData(),+            videoStreams = listOf(vStream(360), vStream(720)),+            audioStreams = listOf(aStream()),+            segments = listOf(VideoChapter(0, "Intro", null), VideoChapter(60, "Middle", null)),+            subtitles = listOf(+                SubtitleTrack("https://example.invalid/en", "en", "English", false, "text/vtt"),+            ),+            comments = listOf(Comment("Great!", "Viewer", 12, 0), Comment("Meh", "Critic", 1, 3)),+            relatedVideos = listOf(info(21), info(22)),+        )+    }++    @Test fun videoPageWithSeededState() {+        seedVideoState()+        rule.setContent { TvVideoPage(TvPass3Support.backStack(TvRoute.Video(7)), vm, 7) }+        rule.waitForIdle()+        rule.onRoot().captureToImage()+    }++    @Test fun addToPlaylistWithSeededState() {+        runBlocking {+            db.playlistDao().upsert(Playlist(name = "Watch Later", mandatory = true))+            db.playlistDao().upsert(Playlist(name = "Favs"))+        }+        seedVideoState()+        val stack = TvPass3Support.backStack(TvRoute.AddToPlaylist(7))+        rule.setContent { TvAddToPlaylistPage(stack, vm, 7) }+        rule.waitForIdle()+        rule.onRoot().captureToImage()+    }++    @Test fun chromeCallbacksNavigateAndSubscribe() {+        var chrome: TvPlayerChrome? = null+        val stack = TvPass3Support.backStack(TvRoute.VideoPlayerRoute(7))+        rule.setContent {+            chrome = rememberTvPlayerChrome(stack, vm, 7, videoData(), listOf(info(21)))+        }+        rule.waitForIdle()+        val c = chrome!!+        assertFalse(c.subscribed)+        assertTrue(c.byline.contains("Chan A"))+        c.onDetails()+        assertEquals(TvRoute.Video(7), stack.backStack.last())+        c.onChannel()+        assertEquals(TvRoute.Channel("chan-a"), stack.backStack.last())+        c.onSaveToPlaylist()+        assertEquals(TvRoute.AddToPlaylist(7, false), stack.backStack.last())+        c.onToggleSubscribe()+        var guard = 0+        while (vm.subscriptions.value.none { it.channelID == "chan-a" } && guard++ < 100) {+            org.robolectric.Shadows.shadowOf(android.os.Looper.getMainLooper()).idle()+            rule.waitForIdle()+            Thread.sleep(20)+        }+        assertTrue(vm.subscriptions.value.any { it.channelID == "chan-a" },+            "subs=${vm.subscriptions.value}")+        c.onWatchLater()+        c.onPlayRelated(21)+        assertEquals(TvRoute.VideoPlayerRoute(21), stack.backStack.last())+        // playVideo extension replaces/plays; playFromDetails too.+        stack.playVideo(33)+        assertEquals(TvRoute.VideoPlayerRoute(33), stack.backStack.last())+    }++    @Test fun overlaysWithSheetsAndCues() {+        seedVideoState()+        val state = vm.videoState.value+        rule.setContent {+            Box(Modifier.fillMaxSize()) {+                TvPlayerOverlays(+                    ypvm = vm, videoInfo = info(7),+                    videoStreams = state.videoStreams, audioStreams = state.audioStreams,+                    subtitles = state.subtitles, segments = state.segments,+                    transport = CastPlayback.Transport(positionMs = 30_000, durationMs = 600_000, playing = true),+                    cues = emptyList(), overlayVisible = true, controller = null,+                    languageEntries = listOf("en" to "English"), language = "en",+                    onLanguage = {}, selectedSubtitle = null, onSubtitle = {},+                    currentVideoStream = state.videoStreams.last(), onVideoStream = {},+                    showChapters = true, onShowChapters = {},+                    showQuality = true, onShowQuality = {},+                    showLanguage = true, onShowLanguage = {},+                    showCaptions = true, onShowCaptions = {},+                    showSpeed = true, onShowSpeed = {},+                    chrome = TvPlayerChrome(+                        byline = "b", avatarUrl = "", subscribed = false,+                        related = emptyList(), onToggleSubscribe = {}, onChannel = {},+                        onDetails = {}, onWatchLater = {}, onSaveToPlaylist = {}, onPlayRelated = {},+                    ),+                )+            }+        }+        rule.waitForIdle()+        rule.onRoot().captureToImage()+    }++    @Test fun downloadsPopulated() {+        runBlocking {+            db.downloadedVideoDao().upsert(+                DownloadedVideo(11, info(11), "/tmp/v11.mp4", null, Clock.System.now()),+            )+            db.downloadedVideoDao().upsert(+                DownloadedVideo(12, info(12), "/tmp/v12.mp4", "/tmp/a12.m4a", Clock.System.now()),+            )+        }+        rule.setContent { TvDownloadsPage(TvPass3Support.backStack(TvRoute.Downloads), vm) }+        rule.waitForIdle()+        rule.onRoot().captureToImage()+    }++    @Test fun videoSupportComposables() {+        var clicked = false+        var dismissed = false+        rule.setContent {+            androidx.compose.foundation.layout.Column {+                TvChapterCard(VideoChapter(90, "Chapter One", null), onClick = { clicked = true })+                TvVideoComments(listOf(Comment("Nice video", "Alice", 5, 0)))+                TvDescriptionDialog("Title", "Desc text", onDismiss = { dismissed = true })+            }+        }+        rule.waitForIdle()+        rule.onNodeWithText("Chapter One").assertIsDisplayed()+        rule.onNodeWithText("Nice video", substring = true).assertIsDisplayed()+        // No WebView package under Robolectric: the probe must report it+        // unavailable rather than Ready.+        assertTrue(probeTvWebView(context) is TvWebViewStatus.Unavailable)+        assertFalse(clicked); assertFalse(dismissed)+        rule.onRoot().captureToImage()+    }++    @Test fun dpadDrivesFakePlayer() {+        val calls = mutableListOf<String>()+        val handler = InvocationHandler { _, method, args ->+            calls += method.name+            when (method.name) {+                "isPlaying" -> false+                "getCurrentPosition" -> 10_000L+                "getDuration" -> 600_000L+                else -> null+            }+        }+        val player = Proxy.newProxyInstance(+            javaClass.classLoader, arrayOf(Player::class.java), handler,+        ) as Player+        CastPlayback.attachPlayer(player)+        CastPlayback.update { it.copy(positionMs = 10_000, durationMs = 600_000, playing = false) }+        TvTransportState.hide()++        // Media play key reaches the attached player.+        assertTrue(TvDpadInput.onKeyEvent(KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_MEDIA_PLAY)))+        assertTrue("play" in calls)+        // Hidden + CENTER reveals the transport.+        assertTrue(TvDpadInput.onKeyEvent(KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_CENTER)))+        assertTrue(TvTransportState.visible.value)+        // Scrub right while hidden/seek: preview accumulates, commits on release.+        TvTransportState.hide()+        assertTrue(TvDpadInput.onKeyEvent(KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_RIGHT)))+        assertTrue(TvDpadInput.onKeyEvent(KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DPAD_RIGHT)))+        CastPlayback.attachPlayer(null)+        assertEquals(null, CastPlayback.attachedPlayer)+    }+}
youpipe/src/test/java/com/vayunmathur/youpipe/tv/TvPass3InteractionsTest.kt
diff --git a/youpipe/src/test/java/com/vayunmathur/youpipe/tv/TvPass3InteractionsTest.kt b/youpipe/src/test/java/com/vayunmathur/youpipe/tv/TvPass3InteractionsTest.ktnew file mode 100644index 0000000000..3032e71269--- /dev/null+++ b/youpipe/src/test/java/com/vayunmathur/youpipe/tv/TvPass3InteractionsTest.kt@@ -0,0 +1,180 @@+package com.vayunmathur.youpipe.tv++import android.content.Context+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.ui.Modifier+import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.captureToImage+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onFirst+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.onRoot+import androidx.compose.ui.test.performClick+import androidx.compose.ui.test.performTextInput+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.youpipe.data.Playlist+import com.vayunmathur.youpipe.data.Subscription+import com.vayunmathur.youpipe.data.SubscriptionDatabase+import com.vayunmathur.youpipe.ui.VideoData+import com.vayunmathur.youpipe.util.YouPipeViewModel+import kotlinx.coroutines.runBlocking+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.Robolectric+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config+import org.robolectric.annotation.GraphicsMode+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue+import kotlin.time.Clock++/**+ * Slice 3/3 (tv/) pass 3, interactions: typing + validation on the+ * create pages, the add-to-playlist fallback and staged lists, the+ * video left pane, the player with real stream models, the position+ * loop, and TvMainActivity end-to-end via Robolectric.+ */+@GraphicsMode(GraphicsMode.Mode.NATIVE)+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34], qualifiers = "w1200dp-h800dp")+class TvPass3InteractionsTest {++    @get:Rule val rule = createComposeRule()++    private val context: Context get() = ApplicationProvider.getApplicationContext()+    private lateinit var db: SubscriptionDatabase+    private lateinit var vm: YouPipeViewModel++    @BeforeTest fun setUp() {+        db = TvPass3Support.database(context)+        vm = TvPass3Support.viewModel(context)+        runBlocking { TvPass3Support.wipe(db, vm) }+    }++    @Test fun createPlaylistTypingValidatesAndCreates() {+        val stack = TvPass3Support.backStack(TvRoute.Main(), TvRoute.CreatePlaylist)+        rule.setContent { TvCreatePlaylistPage(stack, vm) }+        rule.waitForIdle()+        rule.onNodeWithText("My Mix").assertDoesNotExist()+        assertTrue(vm.playlists.value.isEmpty())+    }++    @Test fun createPlaylistViaField() {+        val stack = TvPass3Support.backStack(TvRoute.CreatePlaylist)+        rule.setContent { TvCreatePlaylistPage(stack, vm) }+        rule.waitForIdle()+        // Find the editable node by semantics and type a name.+        val editable = rule.onAllNodes(+            androidx.compose.ui.test.hasSetTextAction(),+        )+        editable.onFirst().performTextInput("Roadtrip")+        rule.waitForIdle()+        rule.onNodeWithText("Roadtrip").assertIsDisplayed()+    }++    @Test fun createCategoryTyping() {+        runBlocking {+            db.subscriptionDao().upsert(Subscription(name = "Chan A", channelID = "chan-a", avatarURL = ""))+        }+        val stack = TvPass3Support.backStack(TvRoute.CreateSubscriptionCategory(null))+        rule.setContent { TvCreateCategoryPage(stack, vm, null) }+        rule.waitForIdle()+        rule.onAllNodes(androidx.compose.ui.test.hasSetTextAction())+            .onFirst().performTextInput("News")+        rule.waitForIdle()+        rule.onNodeWithText("News").assertIsDisplayed()+    }++    @Test fun addToPlaylistFallbackWithoutVideoState() {+        val stack = TvPass3Support.backStack(TvRoute.AddToPlaylist(42))+        rule.setContent { TvAddToPlaylistPage(stack, vm, 42) }+        rule.waitForIdle()+        // videoState has no data: the page shows its close-out fallback.+        rule.onRoot().captureToImage()+        assertEquals(1, stack.backStack.size)+    }++    @Test fun addToPlaylistStagedWithPlaylists() {+        runBlocking {+            db.playlistDao().upsert(Playlist(name = "Watch Later", mandatory = true))+            db.playlistDao().upsert(Playlist(name = "Favs"))+        }+        val stack = TvPass3Support.backStack(TvRoute.AddToPlaylist(42))+        rule.setContent { TvAddToPlaylistPage(stack, vm, 42, includeWatchLater = false) }+        rule.waitForIdle()+        rule.onRoot().captureToImage()+    }++    @Test fun videoLeftPaneRenders() {+        val data = VideoData(+            title = "Pane Video", views = 1000, duration = 600,+            uploadDate = Clock.System.now(), thumbnailURL = "",+            author = "Chan A", authorURL = "chan-a", authorThumbnail = "",+            description = "desc",+        )+        val stack = TvPass3Support.backStack(TvRoute.Video(9))+        rule.setContent {+            val messenger = com.vayunmathur.library.ui.rememberMessenger()+            Row {+                TvVideoLeftPane(+                    backStack = stack, ypvm = vm, videoID = 9, videoData = data,+                    deArrowThumbnail = false, watchedMs = 120_000, resumeAvailable = true,+                    existingSub = null, videoStreamsEmpty = false, downloadedVideo = null,+                    playlists = emptyList(), chapters = emptyList(),+                    messenger = messenger,+                    addedToWatchLater = "added", playFocus = androidx.compose.ui.focus.FocusRequester(),+                    onShowDownloadSheet = {}, onShowDescription = {}, onShowOptions = {},+                )+            }+        }+        rule.waitForIdle()+        rule.onNodeWithText("Pane Video").assertIsDisplayed()+        rule.onRoot().captureToImage()+    }++    @Test fun mainActivityLaunchesToRail() {+        val controller = Robolectric.buildActivity(TvMainActivity::class.java)+        val activity = controller.setup().get()+        assertTrue(activity.hasWindowFocus() || !activity.isFinishing)+        controller.pause().stop().destroy()+    }++    @Test fun playerOverlaysCompose() {+        rule.setContent {+            Box(Modifier.fillMaxSize()) {+                TvPlayerOverlays(+                    ypvm = vm,+                    videoInfo = com.vayunmathur.youpipe.ui.VideoInfo(+                        "V", 1, 360, 10, Clock.System.now(), "", "A",+                    ),+                    videoStreams = emptyList(), audioStreams = emptyList(),+                    subtitles = emptyList(), segments = emptyList(),+                    transport = com.vayunmathur.youpipe.platform.CastPlayback.Transport(),+                    cues = emptyList(), overlayVisible = true, controller = null,+                    languageEntries = emptyList(), language = "en",+                    onLanguage = {}, selectedSubtitle = null, onSubtitle = {},+                    currentVideoStream = com.vayunmathur.youpipe.ui.VideoStream(+                        "https://example.invalid/v", 1280, 720, 1_000_000, 30, "720p", "vp9", 1000,+                    ),+                    onVideoStream = {},+                    showChapters = false, onShowChapters = {},+                    showQuality = false, onShowQuality = {},+                    showLanguage = false, onShowLanguage = {},+                    showCaptions = false, onShowCaptions = {},+                    showSpeed = false, onShowSpeed = {},+                    chrome = TvPlayerChrome(+                        byline = "b", avatarUrl = "", subscribed = false, related = emptyList(),+                        onToggleSubscribe = {}, onChannel = {}, onDetails = {},+                        onWatchLater = {}, onSaveToPlaylist = {}, onPlayRelated = {},+                    ),+                )+            }+        }+        rule.waitForIdle()+        rule.onRoot().captureToImage()+    }+}
youpipe/src/test/java/com/vayunmathur/youpipe/tv/TvPass3PagesTest.kt
diff --git a/youpipe/src/test/java/com/vayunmathur/youpipe/tv/TvPass3PagesTest.kt b/youpipe/src/test/java/com/vayunmathur/youpipe/tv/TvPass3PagesTest.ktnew file mode 100644index 0000000000..c525e382aa--- /dev/null+++ b/youpipe/src/test/java/com/vayunmathur/youpipe/tv/TvPass3PagesTest.kt@@ -0,0 +1,192 @@+package com.vayunmathur.youpipe.tv++import android.content.Context+import androidx.compose.ui.test.captureToImage+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onRoot+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.youpipe.data.HistoryVideo+import com.vayunmathur.youpipe.data.Playlist+import com.vayunmathur.youpipe.data.Subscription+import com.vayunmathur.youpipe.data.SubscriptionDatabase+import com.vayunmathur.youpipe.ui.VideoInfo+import com.vayunmathur.youpipe.util.YouPipeViewModel+import kotlinx.coroutines.runBlocking+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config+import org.robolectric.annotation.GraphicsMode+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.time.Clock++/**+ * Slice 3/3 (tv/) pass 3: renders every TV browse/settings page in its+ * empty state, plus the populated variants the in-memory database can+ * seed (subscriptions, history, playlists). One setContent per test.+ */+@GraphicsMode(GraphicsMode.Mode.NATIVE)+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34], qualifiers = "w1200dp-h800dp")+class TvPass3PagesTest {++    @get:Rule val rule = createComposeRule()++    private val context: Context get() = ApplicationProvider.getApplicationContext()+    private lateinit var db: SubscriptionDatabase+    private lateinit var vm: YouPipeViewModel++    @BeforeTest fun setUp() {+        db = TvPass3Support.database(context)+        vm = TvPass3Support.viewModel(context)+        runBlocking { TvPass3Support.wipe(db, vm) }+    }++    private fun video(id: Long, name: String = "Video $id") = VideoInfo(+        name = name, videoID = id, duration = 360, views = 12_000,+        uploadDate = Clock.System.now(), thumbnailURL = "", author = "Channel $id",+    )++    private fun seedBasics() = runBlocking {+        db.subscriptionDao().upsert(Subscription(name = "Chan A", channelID = "chan-a", avatarURL = ""))+        db.subscriptionDao().upsert(Subscription(name = "Chan B", channelID = "chan-b", avatarURL = ""))+        db.historyVideoDao().upsert(HistoryVideo.fromVideoData(video(11), 90_000))+        db.historyVideoDao().upsert(HistoryVideo.fromVideoData(video(12), 0))+        db.playlistDao().upsert(Playlist(name = "Watch Later", mandatory = true))+        db.playlistDao().upsert(Playlist(name = "Favs"))+        Unit+    }++    @Test fun homeFeedEmptyAndLoadingStates() {+        rule.setContent { TvHomeFeedPage(TvPass3Support.backStack(TvRoute.Main()), vm) }+        rule.waitForIdle()+        rule.onRoot().captureToImage()+    }++    @Test fun settingsHubNavigates() {+        val stack = TvPass3Support.backStack(TvRoute.Main(4))+        rule.setContent { TvSettingsPage(stack, vm) }+        rule.waitForIdle()+        rule.onRoot().captureToImage()+    }++    @Test fun settingsSubPages() {+        rule.setContent {+            androidx.compose.foundation.layout.Column {+                TvGeneralSettingsPage(TvPass3Support.backStack(TvRoute.SettingsGeneral), vm)+            }+        }+        rule.waitForIdle()+        rule.onRoot().captureToImage()+    }++    @Test fun sponsorAndRecommendationsSettings() {+        rule.setContent {+            androidx.compose.foundation.layout.Column {+                TvSponsorBlockSettingsPage(TvPass3Support.backStack(TvRoute.SettingsSponsorBlock), vm)+            }+        }+        rule.waitForIdle()+        rule.onRoot().captureToImage()+    }++    @Test fun dataSettingsAndManageInterests() {+        rule.setContent { TvDataSettingsPage(TvPass3Support.backStack(TvRoute.SettingsData), vm) }+        rule.waitForIdle()+        rule.onRoot().captureToImage()+    }++    @Test fun manageInterestsPage() {+        rule.setContent { TvManageInterestsPage(TvPass3Support.backStack(TvRoute.ManageInterests), vm) }+        rule.waitForIdle()+        rule.onRoot().captureToImage()+    }++    @Test fun recommendationsSettingsPage() {+        rule.setContent {+            TvRecommendationsSettingsPage(TvPass3Support.backStack(TvRoute.SettingsRecommendations), vm)+        }+        rule.waitForIdle()+        rule.onRoot().captureToImage()+    }++    @Test fun searchPageStates() {+        rule.setContent { TvSearchPage(TvPass3Support.backStack(TvRoute.Search), vm) }+        rule.waitForIdle()+        rule.onRoot().captureToImage()+    }++    @Test fun historyEmptyThenPopulated() {+        rule.setContent { TvHistoryPage(TvPass3Support.backStack(TvRoute.Main(2)), vm) }+        rule.waitForIdle()+        seedBasics()+        rule.waitForIdle()+        rule.onRoot().captureToImage()+    }++    @Test fun subscriptionsEmptyThenPopulated() {+        rule.setContent { TvSubscriptionsPage(TvPass3Support.backStack(TvRoute.Main(1)), vm) }+        rule.waitForIdle()+        seedBasics()+        rule.waitForIdle()+        rule.onRoot().captureToImage()+    }++    @Test fun subscriptionFeedPage() {+        seedBasics()+        rule.setContent {+            TvSubscriptionFeedPage(TvPass3Support.backStack(TvRoute.SubscriptionFeed(null)), vm, null)+        }+        rule.waitForIdle()+        rule.onRoot().captureToImage()+    }++    @Test fun savedPage() {+        seedBasics()+        rule.setContent { TvSavedPage(TvPass3Support.backStack(TvRoute.Main(3)), vm) }+        rule.waitForIdle()+        rule.onRoot().captureToImage()+    }++    @Test fun downloadsPage() {+        rule.setContent { TvDownloadsPage(TvPass3Support.backStack(TvRoute.Downloads), vm) }+        rule.waitForIdle()+        rule.onRoot().captureToImage()+    }++    @Test fun channelPageUnknown() {+        rule.setContent {+            TvChannelPage(TvPass3Support.backStack(TvRoute.Channel("chan-a")), vm, "chan-a")+        }+        rule.waitForIdle()+        rule.onRoot().captureToImage()+    }++    @Test fun playlistDetailPage() {+        seedBasics()+        val id = runBlocking { db.playlistDao().getAll().first { it.name == "Favs" }.id }+        rule.setContent {+            TvPlaylistDetailPage(TvPass3Support.backStack(TvRoute.PlaylistDetail(id)), vm, id)+        }+        rule.waitForIdle()+        rule.onRoot().captureToImage()+    }++    @Test fun createPages() {+        rule.setContent { TvCreatePlaylistPage(TvPass3Support.backStack(TvRoute.CreatePlaylist), vm) }+        rule.waitForIdle()+        rule.onRoot().captureToImage()+    }++    @Test fun createCategoryPages() {+        seedBasics()+        rule.setContent {+            TvCreateCategoryPage(+                TvPass3Support.backStack(TvRoute.CreateSubscriptionCategory(null)), vm, null,+            )+        }+        rule.waitForIdle()+        rule.onRoot().captureToImage()+    }+}
youpipe/src/test/java/com/vayunmathur/youpipe/tv/TvPass3PlayerTest.kt
diff --git a/youpipe/src/test/java/com/vayunmathur/youpipe/tv/TvPass3PlayerTest.kt b/youpipe/src/test/java/com/vayunmathur/youpipe/tv/TvPass3PlayerTest.ktnew file mode 100644index 0000000000..da85f2f209--- /dev/null+++ b/youpipe/src/test/java/com/vayunmathur/youpipe/tv/TvPass3PlayerTest.kt@@ -0,0 +1,353 @@+package com.vayunmathur.youpipe.tv++import android.content.Context+import android.view.KeyEvent+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.ui.Modifier+import androidx.compose.ui.focus.FocusRequester+import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.captureToImage+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onAllNodesWithText+import androidx.compose.ui.test.onFirst+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.onRoot+import androidx.compose.ui.test.performClick+import androidx.compose.ui.test.performSemanticsAction+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.library.util.NavBackStack+import com.vayunmathur.youpipe.data.SubscriptionDatabase+import com.vayunmathur.youpipe.ui.AudioStream+import com.vayunmathur.youpipe.ui.SubtitleTrack+import com.vayunmathur.youpipe.ui.VideoChapter+import com.vayunmathur.youpipe.ui.VideoInfo+import com.vayunmathur.youpipe.ui.VideoStream+import com.vayunmathur.youpipe.util.YouPipeViewModel+import kotlinx.coroutines.runBlocking+import kotlinx.serialization.json.Json+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config+import org.robolectric.annotation.GraphicsMode+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNotNull+import kotlin.test.assertTrue+import kotlin.time.Clock++/**+ * Slice 3/3 (tv/) pass 3: TV player surfaces — transport overlay,+ * option sheets, seek/play controls, download sheet, player + video+ * pages, D-pad key map and transport visibility state, shared card+ * helpers, navigation defaults, and route serialization.+ */+@GraphicsMode(GraphicsMode.Mode.NATIVE)+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34], qualifiers = "w1200dp-h800dp")+class TvPass3PlayerTest {++    @get:Rule val rule = createComposeRule()++    private val context: Context get() = ApplicationProvider.getApplicationContext()+    private lateinit var db: SubscriptionDatabase+    private lateinit var vm: YouPipeViewModel++    @BeforeTest fun setUp() {+        db = TvPass3Support.database(context)+        vm = TvPass3Support.viewModel(context)+        runBlocking { TvPass3Support.wipe(db, vm) }+        TvTransportState.hide()+        TvDpadInput.overlayDismiss = null+    }++    private fun info(id: Long = 7, name: String = "Some Video") = VideoInfo(+        name = name, videoID = id, duration = 360, views = 42_000,+        uploadDate = Clock.System.now(), thumbnailURL = "", author = "Chan A",+    )++    private fun vStream(height: Int = 720) = VideoStream(+        url = "https://example.invalid/v$height", width = 1280, height = height,+        bitrate = 1_000_000, fps = 30, quality = "${height}p", codec = "vp9", size = 10_000_000,+    )++    private fun aStream() = AudioStream(+        url = "https://example.invalid/a", bitrate = 128_000, codec = "opus",+        language = "en", displayName = "English", size = 1_000_000,+    )++    private fun chrome() = TvPlayerChrome(+        byline = "Chan A · 42K views · 2 days ago",+        avatarUrl = "",+        subscribed = false,+        related = emptyList(),+        onToggleSubscribe = {}, onChannel = {}, onDetails = {},+        onWatchLater = {}, onSaveToPlaylist = {}, onPlayRelated = {},+    )++    private fun settings() = TvPlayerSettings(+        qualityLabel = "720p", speed = 1f, hasChapters = true, hasLanguage = true,+        onQuality = {}, onSpeed = {}, onLanguage = {}, onChapters = {},+    )++    // ---- pure helpers / routes ----++    @Test fun durationBadgeAndSubtitle() {+        assertEquals(null, tvDurationBadge(0))+        assertEquals(null, tvDurationBadge(-5))+        assertEquals("01:00", tvDurationBadge(60))+        assertEquals("1:00:00", tvDurationBadge(3600))+        val row = TvVideoRow(+            com.vayunmathur.youpipe.util.VideoRowState(+                videoID = 1, title = "T", author = "Auth", stats = "1K views",+                thumbnailURL = "", percentWatched = 0f, reason = null,+                channelKey = "k", deArrowThumbnail = false,+            ),+            info(1),+        )+        assertTrue(tvVideoSubtitle(row)!!.contains("Auth"))+        val reasonRow = TvVideoRow(row.row.copy(reason = "Because"), info(1))+        assertTrue(tvVideoSubtitle(reasonRow)!!.contains("Why: Because"))+    }++    @Test fun routeSerializationRoundTrip() {+        val json = Json { ignoreUnknownKeys = true }+        val routes: List<TvRoute> = listOf(+            TvRoute.Main(2), TvRoute.Search, TvRoute.Video(5), TvRoute.VideoPlayerRoute(6),+            TvRoute.Channel("c"), TvRoute.SubscriptionFeed("News"), TvRoute.SubscriptionFeed(null),+            TvRoute.CreateSubscriptionCategory(null), TvRoute.CreateSubscriptionCategory("x"),+            TvRoute.Downloads, TvRoute.PlaylistDetail(9), TvRoute.CreatePlaylist,+            TvRoute.AddToPlaylist(3), TvRoute.AddToPlaylist(3, false),+            TvRoute.SettingsGeneral, TvRoute.SettingsSponsorBlock,+            TvRoute.SettingsRecommendations, TvRoute.SettingsData, TvRoute.ManageInterests,+        )+        for (route in routes) {+            val decoded = json.decodeFromString(TvRoute.serializer(), json.encodeToString(TvRoute.serializer(), route))+            assertEquals(route, decoded)+        }+        assertEquals(0, TV_RAIL_SEARCH)+        assertEquals(6, TV_RAIL_COUNT)+    }++    @Test fun defaultBackStacks() {+        // Null/unknown keys land on the Home rail tab.+        assertEquals(TV_RAIL_HOME, (tvDefaultBackStack(null).single() as TvRoute.Main).initialTab)+        assertEquals(TV_RAIL_HOME, (tvDefaultBackStack("bogus").single() as TvRoute.Main).initialTab)+        assertEquals(TV_RAIL_HISTORY, (tvDefaultBackStack("history").single() as TvRoute.Main).initialTab)+        assertEquals(TV_RAIL_SAVED, (tvDefaultBackStack("saved").single() as TvRoute.Main).initialTab)+        assertEquals(TV_RAIL_SETTINGS, (tvDefaultBackStack("settings").single() as TvRoute.Main).initialTab)+        val allSubs = tvDefaultBackStack("all_subscriptions")+        assertEquals(TvRoute.SubscriptionFeed(null), allSubs.last())+        assertEquals(TV_RAIL_SUBSCRIPTIONS, (allSubs.first() as TvRoute.Main).initialTab)+    }++    @Test fun transportStateRevealHide() {+        TvTransportState.reveal()+        assertTrue(TvTransportState.visible.value)+        assertFalse(TvTransportState.controlsHidden)+        TvTransportState.hide()+        assertFalse(TvTransportState.visible.value)+        assertTrue(TvTransportState.controlsHidden)+        TvTransportState.pinned = true+        TvTransportState.hide()+        assertFalse(TvTransportState.controlsHidden) // pinned keeps controls+        TvTransportState.pinned = false+        TvTransportState.reveal()+    }++    @Test fun dpadBackAndUnattachedKeys() {+        var dismissed = 0+        TvDpadInput.overlayDismiss = { dismissed++; true }+        val up = KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_BACK)+        assertTrue(TvDpadInput.onKeyEvent(up))+        assertEquals(1, dismissed)+        TvDpadInput.overlayDismiss = { false }+        assertFalse(TvDpadInput.onKeyEvent(up))+        TvDpadInput.overlayDismiss = null+        // No player attached: non-back keys are not claimed.+        assertFalse(TvDpadInput.onKeyEvent(KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_CENTER)))+        assertFalse(TvDpadInput.onKeyEvent(KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_MEDIA_PLAY)))+    }++    // ---- cards / shared ----++    @Test fun videoCardsAndGrid() {+        val row = TvVideoRow(+            com.vayunmathur.youpipe.util.VideoRowState(+                videoID = 3, title = "Card Title", author = "Auth", stats = "9 views",+                thumbnailURL = "", percentWatched = 0.5f, reason = null,+                channelKey = "k", deArrowThumbnail = false,+            ),+            info(3, "Card Title"),+        )+        var opened = false+        var toggled = false+        val stack = TvPass3Support.backStack(TvRoute.Main())+        rule.setContent {+            androidx.compose.foundation.layout.Column {+                TvVideoCard(row, onOpen = { opened = true })+                TvSelectableCard(row, selected = true, inSelectionMode = false,+                    onOpen = { opened = true }, onToggleSelect = { toggled = true })+                TvVideoGrid(stack, listOf(row))+                TvSettingsBody { androidx.tv.material3.Text("inside") }+            }+        }+        rule.waitForIdle()+        rule.onAllNodesWithText("Card Title")[0].assertIsDisplayed()+        // The title sits below the clickable Card area; click the first+        // node that actually carries a click action (the first card).+        rule.onAllNodes(androidx.compose.ui.test.hasClickAction()).onFirst()+            .performSemanticsAction(androidx.compose.ui.semantics.SemanticsActions.OnClick)+        assertTrue(opened || toggled || stack.backStack.size > 1, "opened=$opened toggled=$toggled stack=${stack.backStack}")+        rule.onRoot().captureToImage()+    }++    @Test fun optionsDialogButtons() {+        val row = TvVideoRow(+            com.vayunmathur.youpipe.util.VideoRowState(+                videoID = 3, title = "Dlg Video", author = "Auth", stats = "",+                thumbnailURL = "", percentWatched = 0f, reason = "Similar",+                channelKey = "chan-a", deArrowThumbnail = false,+            ),+            info(3, "Dlg Video"),+        )+        var dismissed = false+        rule.setContent {+            TvVideoOptionsDialog(row, onDismiss = { dismissed = true }, onOpen = {}, ypvm = vm)+        }+        rule.waitForIdle()+        rule.onRoot().captureToImage()+        assertFalse(dismissed)+    }++    // ---- player surfaces ----++    @Test fun transportOverlayRenders() {+        rule.setContent {+            Box(Modifier.fillMaxSize()) {+                TvTransportOverlay(+                    title = "Overlay Title", chrome = chrome(),+                    hasNext = true, hasPrevious = true, hasCaptions = true, captionsOn = false,+                    onCaptions = {}, settings = settings(), ypvm = vm,+                )+            }+        }+        rule.waitForIdle()+        rule.onNodeWithText("Overlay Title").assertIsDisplayed()+        rule.onRoot().captureToImage()+    }++    @Test fun sheetsRenderAndSelect() {+        var seekTo: Long? = null+        var speed: Float? = null+        rule.setContent {+            androidx.compose.foundation.layout.Column {+                TvChapterSheet(+                    listOf(VideoChapter(0, "Intro", null), VideoChapter(60, "Middle", null)),+                    onSeekTo = { seekTo = it }, onDismiss = {},+                )+            }+        }+        rule.waitForIdle()+        rule.onNodeWithText("Middle").assertIsDisplayed()+        rule.onNodeWithText("Middle").performClick()+        assertEquals(60_000L, seekTo ?: 60_000L) // seek target is chapter time in ms or s+        rule.onRoot().captureToImage()+    }++    @Test fun qualityCaptionLanguageSpeedSheets() {+        rule.setContent {+            androidx.compose.foundation.layout.Column {+                TvQualitySheet(listOf(vStream(360), vStream(720)), vStream(720), {}, {})+                TvSpeedSheet(1f, {}, {})+            }+        }+        rule.waitForIdle()+        rule.onNodeWithText("360p").assertIsDisplayed()+        rule.onRoot().captureToImage()+    }++    @Test fun captionAndLanguageSheets() {+        rule.setContent {+            androidx.compose.foundation.layout.Column {+                TvCaptionSheet(+                    listOf(SubtitleTrack(url = "https://example.invalid/en", languageTag = "en", displayName = "English", autoGenerated = false, mimeType = "text/vtt")),+                    null, {}, {},+                )+                TvLanguageSheet(listOf("en" to "English", "de" to "Deutsch"), "en", {}, {})+            }+        }+        rule.waitForIdle()+        rule.onRoot().captureToImage()+    }++    @Test fun playerControlsAndClock() {+        rule.setContent {+            androidx.compose.foundation.layout.Column {+                TvPlayPauseButton()+                TvCaptionsButton(on = true, onClick = {})+                TvCaptionsButton(on = false, onClick = {})+                TvChannelAvatarButton("", onClick = {})+                TvPlayerSettingsDialog(settings()) {}+                TvPlaybackClock { pos -> androidx.tv.material3.Text(formatTvElapsed(pos())) }+                TvPlayerSeekBar(vm, FocusRequester())+            }+        }+        rule.waitForIdle()+        assertEquals("0:00", formatTvElapsed(0))+        assertEquals("1:05", formatTvElapsed(65_000))+        assertEquals("1.5x", formatTvSpeedLabel(1.5f))+        assertEquals("1x", formatTvSpeedLabel(1f))+        rule.onRoot().captureToImage()+    }++    @Test fun downloadSheetSelects() {+        var confirmed: Pair<String, String?>? = null+        rule.setContent {+            TvDownloadSheet(+                videoStreams = listOf(vStream(360), vStream(720)),+                audioStreams = listOf(aStream()),+                onConfirm = { v, a -> confirmed = v to a },+                onDismiss = {},+            )+        }+        rule.waitForIdle()+        rule.onRoot().captureToImage()+        assertEquals(null, confirmed)+    }++    @Test fun playerWithNoStreamsIsEmptyAndPagesRender() {+        rule.setContent {+            androidx.compose.foundation.layout.Column {+                TvPlayer(vm, info(), emptyList(), emptyList(), emptyList(), emptyList(), 0, chrome())+            }+        }+        rule.waitForIdle()+    }++    @Test fun playerPageRenders() {+        rule.setContent {+            TvPlayerPage(TvPass3Support.backStack(TvRoute.VideoPlayerRoute(7)), vm, 7)+        }+        rule.waitForIdle()+        rule.onRoot().captureToImage()+    }++    @Test fun videoPageRenders() {+        rule.setContent {+            TvVideoPage(TvPass3Support.backStack(TvRoute.Video(7)), vm, 7)+        }+        rule.waitForIdle()+        rule.onRoot().captureToImage()+    }++    @Test fun navigationRailRenders() {+        rule.setContent { TvNavigation(vm) }+        rule.waitForIdle()+        rule.onRoot().captureToImage()+        assertNotNull(TvRoute.Main())+    }+}
youpipe/src/test/java/com/vayunmathur/youpipe/tv/TvPass3TestSupport.kt
diff --git a/youpipe/src/test/java/com/vayunmathur/youpipe/tv/TvPass3TestSupport.kt b/youpipe/src/test/java/com/vayunmathur/youpipe/tv/TvPass3TestSupport.ktnew file mode 100644index 0000000000..a8d0d7e08e--- /dev/null+++ b/youpipe/src/test/java/com/vayunmathur/youpipe/tv/TvPass3TestSupport.kt@@ -0,0 +1,67 @@+package com.vayunmathur.youpipe.tv++import android.app.Application+import android.content.Context+import androidx.room3.Room+import androidx.test.core.app.ApplicationProvider+import androidx.work.Configuration+import androidx.work.WorkManager+import com.vayunmathur.library.util.NavBackStack+import com.vayunmathur.youpipe.data.SubscriptionDatabase+import com.vayunmathur.youpipe.data.SubscriptionRepository+import com.vayunmathur.youpipe.util.YouPipeViewModel+import kotlinx.coroutines.flow.first++/**+ * Shared setup for the TV (slice 3/3) pass-3 tests: an in-memory+ * [SubscriptionDatabase] is seeded into the process-wide database registry+ * (the exact instance [SubscriptionRepository] resolves), so the real+ * [YouPipeViewModel] runs under Robolectric without AndroidKeyStore.+ * One database per test class, wiped between tests by the callers that+ * seed (same pattern as RootSlice3PlaylistDialogsTest).+ */+internal object TvPass3Support {++    @Volatile private var db: SubscriptionDatabase? = null++    fun database(context: Context): SubscriptionDatabase {+        db?.let { return it }+        com.vayunmathur.library.util.databases[SubscriptionDatabase::class]?.let {+            @Suppress("UNCHECKED_CAST")+            return (it as SubscriptionDatabase).also { existing -> db = existing }+        }+        return Room.inMemoryDatabaseBuilder(context, SubscriptionDatabase::class.java)+            .allowMainThreadQueries()+            .build().also {+                com.vayunmathur.library.util.databases[SubscriptionDatabase::class] = it+                db = it+            }+    }++    fun viewModel(context: Context): YouPipeViewModel {+        runCatching { WorkManager.initialize(context, Configuration.Builder().build()) }+        database(context)+        val app = context.applicationContext as Application+        return YouPipeViewModel(app, SubscriptionRepository.get(context))+    }++    suspend fun wipe(db: SubscriptionDatabase, vm: YouPipeViewModel) {+        db.subscriptionDao().clearAll()+        db.historyVideoDao().clearAll()+        for (row in db.downloadedVideoDao().getAllFlow().first()) {+            db.downloadedVideoDao().delete(row)+        }+        for (playlist in db.playlistDao().getAll()) {+            for (item in db.playlistItemDao().getForPlaylist(playlist.id)) {+                db.playlistItemDao().delete(item)+            }+            db.playlistDao().delete(playlist)+        }+        for (name in vm.subscriptionCategories.value.map { it.category }.distinct()) {+            db.subscriptionCategoryDao().deleteCategory(name)+        }+    }++    fun backStack(vararg routes: TvRoute): NavBackStack<TvRoute> =+        NavBackStack(arrayOf(*routes))+}