Modern Apps git

← Modern-Apps.git

appstore: bind detail and browse to route args (#nav)

Commit
87837a925dccb3945d530ac3bde9b91fda62133a
Author
Vayun Mathur <[email protected]>
When
2026-11-16 19:33 UTC (19 days ago)
Parents
9565d36
Phone Detail was a data object while AppStoreViewModel.selectedAppFlow
decided which app the detail screen showed, and Browse(sectionId) had
an entry that ignored its argument and read browseSectionFlow /
browseTitleFlow instead. On TV, TvStoreRoute.Detail(packageName) and
Browse(sectionId) already carried arguments, but TvStoreBrowse and
TvStoreDetail still read the TvStoreViewModel selection/browse flows,
with selectApp/openBrowse called before the push and clearSelection/
clearBrowse hand-called on pop. That is selection-as-navigation: a
restored back stack shows whatever the flow currently holds, which may
be a different app or section from the one the top entry names.

Phone: Route.Detail is now data class Detail(packageName). The Detail
entry binds AppDetailPage to route.packageName; the page reloads via
the new AppStoreViewModel.loadDetail(packageName) whenever its argument
changes, and loadDetail drops the previous listing synchronously so a
new destination never renders the last ones app. Resolution keeps the
old tap semantics by package alone: the catalogue row wins, then
Accrescents allowlist, then Play details, with a Play shell for a
package none of them knows (e.g. a market:// link, which now just
pushes Route.Detail(pkg)). selectApp, selectPackage and clearSelection
are deleted, and popping Detail is a plain backStack.pop().

Phone Browse: the Browse entry now passes route.sectionId to
BrowsePage, which loads via loadBrowse(sectionId). The section is
resolved from the home state that produced the id (title, source apps
and the Play cluster fallback all key off the argument), with known
offline ids resolving even if home has not rebuilt the row.
browseSectionFlow, browseTitleFlow, browseAppsFlow and
isLoadingBrowseFlow collapse into one loaded browseContentFlow that
carries its sectionId, so stale browse content cannot be read under a
different section. Category browse falls back to the home rows own
apps when a mid-load sync prunes the cache, instead of emptying a
section the user is already in. The pager-tabs host in Route.Main is
untouched; this batch is only the selection flows.

TV: TvStoreBrowse and TvStoreDetail take sectionId/packageName and
load via TvStoreViewModel.loadBrowse/loadDetail, mirroring the phone
resolution (catalogue, Accrescent allowlist, Play, shell; offline /
Accrescent / Play-cluster browse by section id). selectApp, openBrowse,
clearBrowse, clearSelection and the setSourceEnabled clearBrowse call
are deleted; every push is now just backStack.add(TvStoreRoute.Detail/
Browse(arg)) and every pop a plain pop, so BACK lands on the rail or
browse destination that opened the page with no stale selection.

Tests: RouteSerializerTest round-trips the new Route.Detail arg;
DetailAndBrowseOpsTest is rewritten around loadDetail/loadBrowse by
argument, including a second package replacing the first detail
without a stale frame and browse-by-category through the home section;
TvStoreViewModelTest covers loadDetail replacement and browse by
route id; TvDetailWrapperAndActionsTest renders the detail wrapper
from its package argument alone (catalogue-seeded, after the startup
sync settles); TvWrapperScreensTest and AccrescentVmOpsW5Test are
moved to the route-argument APIs.

Verified: ./gradlew :appstore:testDevUnitTest and
:appstore:compileDevKotlin (with compileDevUnitTestKotlin) green -
670 unit tests, 0 failures.

Diff

appstore/src/main/java/com/vayunmathur/appstore/MainActivity.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/MainActivity.kt b/appstore/src/main/java/com/vayunmathur/appstore/MainActivity.ktindex 381277b9a0..83d8be32f3 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/MainActivity.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/MainActivity.kt@@ -30,10 +30,6 @@ import com.vayunmathur.appstore.util.AppSection import com.vayunmathur.appstore.util.AppStoreViewModel import com.vayunmathur.appstore.util.AppStoreViewModelFactory import com.vayunmathur.appstore.util.RemoteImageFetchers-import com.vayunmathur.appstore.util.clearSelection-import com.vayunmathur.appstore.util.openBrowse-import com.vayunmathur.appstore.util.selectApp-import com.vayunmathur.appstore.util.selectPackage import com.vayunmathur.library.image.ImageLoader import com.vayunmathur.library.network.NetworkClient import com.vayunmathur.library.network.TrustBundle@@ -119,8 +115,8 @@ sealed interface Route : NavKey {     @Serializable data object Main : Route     /** Destination showing source trust information. */     @Serializable data object Trust : Route-    /** Destination showing one app's detail page. */-    @Serializable data object Detail : Route+    /** Destination showing one app's detail page, named by its package. */+    @Serializable data class Detail(val packageName: String) : Route     /** Destination browsing one home-page section by its ID. */     @Serializable data class Browse(val sectionId: String) : Route @@ -150,18 +146,20 @@ private fun AppRoot(      LaunchedEffect(externalPackage) {         val pkg = externalPackage ?: return@LaunchedEffect-        viewModel.selectPackage(pkg)-        if (backStack.last() !is Route.Detail) backStack.add(Route.Detail)+        // The route carries the package; the Detail entry loads it. No+        // ViewModel selection is set here, so a restored stack cannot show+        // a different app from the one its top entry names.+        if (backStack.last() != Route.Detail(pkg)) backStack.add(Route.Detail(pkg))         onExternalPackageHandled()     }      fun openDetail(app: UnifiedApp) {-        viewModel.selectApp(app)-        if (backStack.last() !is Route.Detail) backStack.add(Route.Detail)+        if (backStack.last() != Route.Detail(app.packageName)) {+            backStack.add(Route.Detail(app.packageName))+        }     }      fun openBrowse(section: AppSection) {-        viewModel.openBrowse(section)         backStack.add(Route.Browse(section.id))     } @@ -174,9 +172,10 @@ private fun AppRoot(                 onOpenBrowse = ::openBrowse,             )         }-        entry<Route.Browse> {+        entry<Route.Browse> { route ->             BrowsePage(                 viewModel = viewModel,+                sectionId = route.sectionId,                 onAppClick = ::openDetail,                 onBack = { backStack.pop() },             )@@ -187,13 +186,11 @@ private fun AppRoot(                 onBack = { backStack.pop() },             )         }-        entry<Route.Detail>(metadata = MorphPage()) {+        entry<Route.Detail>(metadata = MorphPage()) { route ->             AppDetailPage(                 viewModel = viewModel,-                onBack = {-                    backStack.pop()-                    viewModel.clearSelection()-                },+                packageName = route.packageName,+                onBack = { backStack.pop() },                 onOpenTrust = { backStack.add(Route.Trust) },                 onOpenScreenshot = { index ->                     val app = viewModel.detail.value.app
appstore/src/main/java/com/vayunmathur/appstore/tv/TvMainActivity.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/tv/TvMainActivity.kt b/appstore/src/main/java/com/vayunmathur/appstore/tv/TvMainActivity.ktindex 7890d653e1..aaf4714893 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/tv/TvMainActivity.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/tv/TvMainActivity.kt@@ -91,10 +91,11 @@ class TvMainActivity : MaActivity() { /**  * The TV navigation host: [rememberNavBackStack] + [MainNavigation] over [TvStoreRoute].  *- * The browse and detail destinations read the selection the rail already set via- * [TvStoreViewModel.openBrowse]/[TvStoreViewModel.selectApp] — popping clears them,- * so BACK from either always lands on the destination that opened it with no stale- * selection behind it.+ * The browse and detail destinations bind to their route arguments+ * ([TvStoreRoute.Browse.sectionId] / [TvStoreRoute.Detail.packageName]);+ * their entries load exactly the section/app they name, so BACK and a+ * restored stack always land on the destination that opened them with no+ * ViewModel selection behind it.  */ @Composable private fun TvStoreNavigation(viewModel: TvStoreViewModel) {@@ -103,26 +104,21 @@ private fun TvStoreNavigation(viewModel: TvStoreViewModel) {         entry<TvStoreRoute.Main> {             TvStoreRail(backStack = backStack, viewModel = viewModel)         }-        entry<TvStoreRoute.Browse> {+        entry<TvStoreRoute.Browse> { route ->             TvStoreBrowse(                 viewModel = viewModel,+                sectionId = route.sectionId,                 onAppClick = { app ->-                    viewModel.selectApp(app)                     backStack.add(TvStoreRoute.Detail(app.packageName))                 },-                onBack = {-                    backStack.pop()-                    viewModel.clearBrowse()-                },+                onBack = { backStack.pop() },             )         }-        entry<TvStoreRoute.Detail> {+        entry<TvStoreRoute.Detail> { route ->             TvStoreDetail(                 viewModel = viewModel,-                onBack = {-                    backStack.pop()-                    viewModel.clearSelection()-                },+                packageName = route.packageName,+                onBack = { backStack.pop() },             )         }     }@@ -173,7 +169,6 @@ private fun TvStoreRail(     var selectedIndex by rememberSaveable { mutableIntStateOf(0) }      fun openDetail(app: UnifiedApp) {-        viewModel.selectApp(app)         backStack.add(TvStoreRoute.Detail(app.packageName))     } @@ -199,7 +194,6 @@ private fun TvStoreRail(                 onAppClick = ::openDetail,                 onOpenUpdates = { selectedIndex = TV_DEST_UPDATES },                 onOpenBrowse = { section ->-                    viewModel.openBrowse(section)                     backStack.add(TvStoreRoute.Browse(section.id))                 },             )
appstore/src/main/java/com/vayunmathur/appstore/tv/TvStoreBrowse.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/tv/TvStoreBrowse.kt b/appstore/src/main/java/com/vayunmathur/appstore/tv/TvStoreBrowse.ktindex 132537971a..7aa2adc0b3 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/tv/TvStoreBrowse.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/tv/TvStoreBrowse.kt@@ -4,6 +4,7 @@ import androidx.activity.compose.BackHandler import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.lazy.grid.items import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.ui.Modifier@@ -25,10 +26,14 @@ import com.vayunmathur.library.ui.IconPackage @Composable fun TvStoreBrowse(     viewModel: TvStoreViewModel,+    sectionId: String,     onAppClick: (UnifiedApp) -> Unit,     onBack: () -> Unit,     modifier: Modifier = Modifier, ) {+    // The Browse route's argument, reloaded whenever it changes so a+    // restored entry shows its own section.+    LaunchedEffect(sectionId) { viewModel.loadBrowse(sectionId) }     val state by viewModel.browse.collectAsState()     BackHandler(onBack = onBack)     TvStoreBrowseScreen(
appstore/src/main/java/com/vayunmathur/appstore/tv/TvStoreDetail.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/tv/TvStoreDetail.kt b/appstore/src/main/java/com/vayunmathur/appstore/tv/TvStoreDetail.ktindex eaa1fb67f8..1ede41107a 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/tv/TvStoreDetail.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/tv/TvStoreDetail.kt@@ -12,6 +12,7 @@ import androidx.compose.foundation.layout.padding import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf@@ -56,9 +57,13 @@ private const val DETAIL_IDENTITY_WEIGHT = 0.65f @Composable fun TvStoreDetail(     viewModel: TvStoreViewModel,+    packageName: String,     onBack: () -> Unit,     modifier: Modifier = Modifier, ) {+    // The Detail route's argument, reloaded whenever it changes so a+    // restored entry shows its own app.+    LaunchedEffect(packageName) { viewModel.loadDetail(packageName) }     val state by viewModel.detail.collectAsState()     BackHandler(onBack = onBack)     TvStoreDetailScreen(
appstore/src/main/java/com/vayunmathur/appstore/tv/TvStoreViewModel.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/tv/TvStoreViewModel.kt b/appstore/src/main/java/com/vayunmathur/appstore/tv/TvStoreViewModel.ktindex 959cefa789..f396506645 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/tv/TvStoreViewModel.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/tv/TvStoreViewModel.kt@@ -79,15 +79,14 @@ class TvStoreViewModel(     internal val categoryAppsFlow = MutableStateFlow<List<UnifiedApp>>(emptyList())     internal val isLoadingFlow = MutableStateFlow(true)     internal val statusMessageFlow = MutableStateFlow("")-    internal val selectedAppFlow = MutableStateFlow<UnifiedApp?>(null)+    /** The listing loaded for the package the Detail route names; see loadDetail. */+    internal val detailAppFlow = MutableStateFlow<UnifiedApp?>(null)     internal val isLoadingDetailsFlow = MutableStateFlow(false)     internal var detailJob: Job? = null      // --- Browse (one home section's full catalogue) ------------------------------------    internal val browseSectionFlow = MutableStateFlow("")-    internal val browseTitleFlow = MutableStateFlow("")-    internal val browseAppsFlow = MutableStateFlow<List<UnifiedApp>>(emptyList())-    internal val isLoadingBrowseFlow = MutableStateFlow(false)+    /** Loaded Browse content for the section the Browse route names; see loadBrowse. */+    internal val browseContentFlow = MutableStateFlow(TvBrowseUiState())     internal var browseJob: Job? = null      // --- Search hub state -----------------------------------------------------------@@ -122,7 +121,7 @@ class TvStoreViewModel(      val detail: StateFlow<TvDetailUiState> = combine(         combine(-            selectedAppFlow,+            detailAppFlow,             isLoadingDetailsFlow,             combine(installedRepo.apps, installedRepo.icons) { installed, icons -> installed to icons },         ) { app, loading, installedPair -> Triple(app, loading, installedPair) },@@ -287,18 +286,12 @@ class TvStoreViewModel(      /** One home section's full catalogue, A–Z. Same shape as the phone's `BrowseUiState`. */     val browse: StateFlow<TvBrowseUiState> = combine(-        combine(browseSectionFlow, browseTitleFlow) { sectionId, title -> sectionId to title },-        browseAppsFlow,-        isLoadingBrowseFlow,+        browseContentFlow,         combine(installedRepo.apps, installedRepo.icons, installer.stages) { installed, icons, stages ->             Triple(installed, icons, stages)         },-    ) { (sectionId, title), apps, loading, (installed, icons, stages) ->-        TvBrowseUiState(-            sectionId = sectionId,-            title = title,-            apps = apps,-            isLoading = loading,+    ) { content, (installed, icons, stages) ->+        content.copy(             installedPackages = installed.map { it.packageName }.toSet(),             installedIcons = icons,             stages = stages,@@ -380,78 +373,113 @@ class TvStoreViewModel(     }      /**-     * Fill the Browse screen with one home section's full catalogue, A–Z.-     * Mirrors the phone's `openBrowse`: the whole offline repo for an offline row,-     * the whole paged catalogue for Accrescent, the uncapped cluster for a Play row.+     * Fill the Browse screen with the full catalogue behind [sectionId] —+     * the argument of `TvStoreRoute.Browse`. Mirrors the phone's loadBrowse:+     * the whole offline repo for an offline row, the whole paged catalogue+     * for Accrescent, the uncapped cluster for a Play row.+     *+     * The section is looked up in the home state that produced it (title,+     * source and capped apps), so the entry binds only to its route+     * argument: a restored Browse entry re-resolves the section it names+     * instead of reading whatever section a ViewModel flow last held.      */-    fun openBrowse(section: TvSection) {+    fun loadBrowse(sectionId: String) {         browseJob?.cancel()-        browseSectionFlow.value = section.id-        browseTitleFlow.value = section.title-        browseAppsFlow.value = emptyList()-        isLoadingBrowseFlow.value = true+        val section = home.value.sections.find { it.id == sectionId }+            ?: sectionsFlow.value.find { it.id == sectionId }+        val title = section?.title ?: browseFallbackTitle(sectionId)+        browseContentFlow.value = TvBrowseUiState(+            sectionId = sectionId,+            title = title,+            apps = emptyList(),+            isLoading = true,+        )         browseJob = viewModelScope.launch {             val apps = when {-                section.id == "category" -> catalog.allByCategory(section.title)-                section.source != null && section.source != AppSource.PLAYSTORE &&+                sectionId == "category" ->+                    section?.let { catalog.allByCategory(it.title).ifEmpty { it.apps } }+                        ?: emptyList()+                section?.source != null && section.source != AppSource.PLAYSTORE &&                     section.source != AppSource.ACCRESCENT ->                     catalog.allBySource(section.source)-                section.id == "accrescent" -> accrescent.allListings()-                else -> playFullClustersFlow.value[section.id] ?: section.apps+                sectionId == "modern" || sectionId == "modern-recent" ->+                    catalog.allBySource(AppSource.MODERN_APPS)+                sectionId == "proprietary-recent" ->+                    catalog.allBySource(AppSource.PROPRIETARY)+                sectionId == "fdroid-recent" ->+                    catalog.allBySource(AppSource.FDROID)+                sectionId == "izzy-recent" ->+                    catalog.allBySource(AppSource.IZZY)+                sectionId == "accrescent" -> accrescent.allListings()+                else -> playFullClustersFlow.value[sectionId] ?: section?.apps ?: emptyList()             }-            browseAppsFlow.value = apps.sortedBy { it.name.lowercase() }-            isLoadingBrowseFlow.value = false+            browseContentFlow.value = TvBrowseUiState(+                sectionId = sectionId,+                title = title,+                apps = apps.sortedBy { it.name.lowercase() },+                isLoading = false,+            )         }     } -    fun clearBrowse() {-        browseJob?.cancel()-        browseSectionFlow.value = ""-        browseTitleFlow.value = ""-        browseAppsFlow.value = emptyList()+    /** Title for a known section id when home has not (re)built its row yet. */+    private fun browseFallbackTitle(sectionId: String): String = when (sectionId) {+        "modern", "modern-recent" -> context.getString(R.string.section_modern_apps_recent)+        "proprietary-recent" -> context.getString(R.string.section_proprietary_recent)+        "fdroid-recent" -> context.getString(R.string.section_fdroid_recent)+        "izzy-recent" -> context.getString(R.string.section_izzy_recent)+        "accrescent" -> context.getString(R.string.section_accrescent)+        "play-top" -> context.getString(R.string.section_play_top_charts)+        else -> sectionId.removePrefix("play-")     } -    fun selectApp(app: UnifiedApp) {+    /**+     * Load the detail page for [packageName] — the argument of+     * `TvStoreRoute.Detail`. The route, not a ViewModel selection, decides+     * which app is on screen, and the previous listing is dropped+     * synchronously so a new destination never renders the last one's app.+     *+     * Resolution mirrors the phone's loadDetail: the catalogue row wins+     * whenever there is one (it carries the signer and hash an install would+     * use), then Accrescent's allowlist, then Play, with a Play shell for a+     * package none of them knows.+     */+    fun loadDetail(packageName: String) {         detailJob?.cancel()-        selectedAppFlow.value = app+        detailAppFlow.value = null+        isLoadingDetailsFlow.value = true         detailJob = viewModelScope.launch {-            // The catalogue row wins whenever there is one, even if the user tapped a Play-            // tile for the same package. It is the row an install would actually use — it-            // carries the signer and hash an authenticated index published — so showing-            // the Play listing here would describe a download this store is not going to-            // make. Mirrors the phone's selectApp.-            val cached = catalog.byPackage(app.packageName)+            val cached = catalog.byPackage(packageName)             if (cached != null) {-                selectedAppFlow.value = cached-                return@launch-            }-            // Accrescent listings from the home carousel are shells (no version code, no-            // signer yet); fetch the full listing before the page settles.-            if (app.source == AppSource.ACCRESCENT) {-                isLoadingDetailsFlow.value = true-                val details = accrescent.details(app.packageName)-                if (details != null) selectedAppFlow.value = details+                detailAppFlow.value = cached                 isLoadingDetailsFlow.value = false                 return@launch             }-            // Play listings from a cluster are shells: no description, no screenshots, no-            // version code. Fill them in before the page settles.-            if (app.source == AppSource.PLAYSTORE && app.screenshots.isEmpty() &&-                AppSource.PLAYSTORE in enabledSourcesFlow.value+            if (AppSource.ACCRESCENT in enabledSourcesFlow.value &&+                packageName in accrescentPackagesFlow.value             ) {-                isLoadingDetailsFlow.value = true-                val details = play.details(app.packageName)-                if (details != null) selectedAppFlow.value = details+                val details = accrescent.details(packageName)+                detailAppFlow.value = details ?: UnifiedApp(+                    packageName = packageName,+                    source = AppSource.ACCRESCENT,+                    name = packageName.substringAfterLast('.'),+                )                 isLoadingDetailsFlow.value = false+                return@launch             }+            detailAppFlow.value = UnifiedApp(+                packageName = packageName,+                source = AppSource.PLAYSTORE,+                name = packageName.substringAfterLast('.'),+            )+            if (AppSource.PLAYSTORE in enabledSourcesFlow.value) {+                val details = play.details(packageName)+                if (details != null) detailAppFlow.value = details+            }+            isLoadingDetailsFlow.value = false         }     } -    fun clearSelection() {-        detailJob?.cancel()-        selectedAppFlow.value = null-    }-     // --- Search hub: body in TvStoreOps.kt -------------------------------------------------     fun setSearch(query: String) = setSearchImpl(query) @@ -479,7 +507,6 @@ class TvStoreViewModel(             val next = if (enabled) enabledSourcesFlow.value + source else enabledSourcesFlow.value - source             enabledSourcesFlow.value = next             if (!enabled) forgetSource(source)-            clearBrowse()             settings.setSourceEnabled(source, enabled)             catalog.purgeDisabled(next)             categoriesFlow.value = catalog.categories()
appstore/src/main/java/com/vayunmathur/appstore/ui/AppDetailPage.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/ui/AppDetailPage.kt b/appstore/src/main/java/com/vayunmathur/appstore/ui/AppDetailPage.ktindex 8125678755..2d1a00d8a2 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/ui/AppDetailPage.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/ui/AppDetailPage.kt@@ -7,6 +7,7 @@ import androidx.compose.foundation.layout.padding import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf@@ -20,6 +21,7 @@ import com.vayunmathur.appstore.R import com.vayunmathur.appstore.util.AppDetailActions import com.vayunmathur.appstore.util.AppDetailUiState import com.vayunmathur.appstore.util.AppStoreViewModel+import com.vayunmathur.appstore.util.loadDetail import com.vayunmathur.library.ui.AppBarAlignment import com.vayunmathur.library.ui.AppScaffold import com.vayunmathur.library.ui.ConfirmDialog@@ -29,14 +31,20 @@ import com.vayunmathur.library.ui.R as UiR import com.vayunmathur.library.ui.Text import com.vayunmathur.library.ui.appBarScrollBehavior -/** Binds [AppStoreViewModel] to the stateless [AppDetailScreen]. */+/**+ * Binds [AppStoreViewModel] to the stateless [AppDetailScreen] for+ * [packageName] — the `Route.Detail` argument, reloaded whenever it changes+ * so a restored entry shows its own app.+ */ @Composable fun AppDetailPage(     viewModel: AppStoreViewModel,+    packageName: String,     onBack: () -> Unit,     onOpenTrust: () -> Unit = {},     onOpenScreenshot: (Int) -> Unit = {}, ) {+    LaunchedEffect(packageName) { viewModel.loadDetail(packageName) }     val state by viewModel.detail.collectAsState()     AppDetailScreen(         state = state,
appstore/src/main/java/com/vayunmathur/appstore/ui/BrowsePage.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/ui/BrowsePage.kt b/appstore/src/main/java/com/vayunmathur/appstore/ui/BrowsePage.ktindex 2e1cd70921..479c64383b 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/ui/BrowsePage.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/ui/BrowsePage.kt@@ -7,6 +7,7 @@ import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.ui.Alignment@@ -17,6 +18,7 @@ import com.vayunmathur.appstore.R import com.vayunmathur.appstore.data.UnifiedApp import com.vayunmathur.appstore.util.AppStoreViewModel import com.vayunmathur.appstore.util.BrowseUiState+import com.vayunmathur.appstore.util.loadBrowse import com.vayunmathur.library.ui.AppBarAlignment import com.vayunmathur.library.ui.AppScaffold import com.vayunmathur.library.ui.CircularProgressIndicator@@ -24,13 +26,19 @@ import com.vayunmathur.library.ui.EmptyState import com.vayunmathur.library.ui.IconSearch import com.vayunmathur.library.ui.appBarScrollBehavior -/** Binds [AppStoreViewModel] to the stateless [BrowseScreen]. */+/**+ * Binds [AppStoreViewModel] to the stateless [BrowseScreen] for the section+ * [sectionId] — the `Route.Browse` argument, reloaded whenever it changes so+ * a restored entry shows its own section.+ */ @Composable fun BrowsePage(     viewModel: AppStoreViewModel,+    sectionId: String,     onAppClick: (UnifiedApp) -> Unit,     onBack: () -> Unit, ) {+    LaunchedEffect(sectionId) { viewModel.loadBrowse(sectionId) }     val state by viewModel.browse.collectAsState()     BrowseScreen(         state = state,
appstore/src/main/java/com/vayunmathur/appstore/util/AppStoreDetailOps.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/util/AppStoreDetailOps.kt b/appstore/src/main/java/com/vayunmathur/appstore/util/AppStoreDetailOps.ktindex dd253b337e..f39916dcd2 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/util/AppStoreDetailOps.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/util/AppStoreDetailOps.kt@@ -6,68 +6,66 @@ import com.vayunmathur.appstore.data.UnifiedApp import kotlinx.coroutines.launch  // ---- Detail -----// Moved from AppStoreViewModel.kt (FileLength split); behavior identical.+// Moved from AppStoreViewModel.kt (FileLength split); behaviour identical apart+// from the route-driven entry point below. -fun AppStoreViewModel.selectApp(app: UnifiedApp) {+/**+ * Load the detail page for [packageName] — the argument of `Route.Detail`.+ *+ * The route, not a ViewModel selection, decides which app is on screen: the+ * Detail entry calls this with its own argument, so a restored back stack+ * shows the app its entry names instead of whatever a stale flow last held.+ * The previous listing is dropped synchronously, before the fetch starts, so+ * a new destination never renders the app the last one loaded.+ *+ * Resolution order mirrors what a tap used to do: the catalogue row wins+ * whenever there is one, even for a package Play also lists. It is the row an+ * install would actually use — it carries the signer and hash an authenticated+ * index published — so showing the Play listing here would describe a download+ * this store is not going to make. Only F-Droid and Modern Apps rows are ever+ * cached, so this never replaces one Play listing with another. Next,+ * Accrescent's signed allowlist decides whether its full listing is fetched,+ * then Play fills in a listing for anything it hosts. A package none of them+ * knows (e.g. a `market://` link) settles as a Play shell named by its last+ * segment while Play is asked, and stays that shell if Play cannot answer.+ */+fun AppStoreViewModel.loadDetail(packageName: String) {     detailJob?.cancel()-    selectedAppFlow.value = app+    detailAppFlow.value = null+    isLoadingDetailsFlow.value = true     detailJob = viewModelScope.launch {-        // The catalogue row wins whenever there is one, even if the user tapped a Play-        // tile for the same package. It is the row an install would actually use — it-        // carries the signer and hash an authenticated index published — so showing-        // the Play listing here would describe a download this store is not going to-        // make. Only F-Droid and Modern Apps rows are ever cached, so this never-        // replaces one Play listing with another.-        val cached = catalog.byPackage(app.packageName)+        val cached = catalog.byPackage(packageName)         if (cached != null) {-            selectedAppFlow.value = cached-            return@launch-        }-        // Accrescent listings from the home carousel are shells (no version code, no signer-        // yet); fetch the full listing + package info + trust anchor before the page settles.-        if (app.source == AppSource.ACCRESCENT) {-            isLoadingDetailsFlow.value = true-            val details = accrescent.details(app.packageName)-            if (details != null) selectedAppFlow.value = details+            detailAppFlow.value = cached             isLoadingDetailsFlow.value = false             return@launch         }-        // Play listings from a cluster are shells: no description, no-        // screenshots, no version code. Fill them in before the page settles.-        if (app.source == AppSource.PLAYSTORE && app.screenshots.isEmpty() &&-            AppSource.PLAYSTORE in enabledSources.value+        // Accrescent listings from the home carousel are shells (no version+        // code, no signer yet); fetch the full listing before the page settles.+        if (AppSource.ACCRESCENT in enabledSources.value &&+            packageName in accrescentPackagesFlow.value         ) {-            isLoadingDetailsFlow.value = true-            val details = play.details(app.packageName)-            if (details != null) selectedAppFlow.value = details+            val details = accrescent.details(packageName)+            detailAppFlow.value = details ?: UnifiedApp(+                packageName = packageName,+                source = AppSource.ACCRESCENT,+                name = packageName.substringAfterLast('.'),+            )             isLoadingDetailsFlow.value = false-        }-    }-}--/** Open a package the store only knows by name, e.g. from a `market://` link. */-fun AppStoreViewModel.selectPackage(packageName: String) {-    viewModelScope.launch {-        val known = catalog.byPackage(packageName)-        if (known != null) {-            selectApp(known)             return@launch         }-        isLoadingDetailsFlow.value = true-        selectedAppFlow.value = UnifiedApp(+        // Play listings from a cluster are shells: no description, no+        // screenshots, no version code. Fill them in before the page settles;+        // the shell keeps the page addressable by its package while it loads.+        detailAppFlow.value = UnifiedApp(             packageName = packageName,             source = AppSource.PLAYSTORE,             name = packageName.substringAfterLast('.'),         )         if (AppSource.PLAYSTORE in enabledSources.value) {             val details = play.details(packageName)-            if (details != null) selectedAppFlow.value = details+            if (details != null) detailAppFlow.value = details         }         isLoadingDetailsFlow.value = false     } }--fun AppStoreViewModel.clearSelection() {-    detailJob?.cancel()-    selectedAppFlow.value = null-}
appstore/src/main/java/com/vayunmathur/appstore/util/AppStoreHomeOps.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/util/AppStoreHomeOps.kt b/appstore/src/main/java/com/vayunmathur/appstore/util/AppStoreHomeOps.ktindex 6706409e01..a45c584342 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/util/AppStoreHomeOps.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/util/AppStoreHomeOps.kt@@ -172,43 +172,75 @@ internal fun AppStoreViewModel.syncIfNeverSynced(enabled: Set<AppSource>) { }  /**- * Fill the Browse page with one home section's full catalogue.+ * Fill the Browse page with the full catalogue behind [sectionId] — the+ * argument of `Route.Browse`.  *- * Each home carousel is a capped slice — the 20 newest builds, the first 20 tiles.- * Browse lists literally every app behind that section, A–Z: the whole offline repo- * for an offline row, the whole paged catalogue for Accrescent, the uncapped cluster- * for a Play row. The rows use the same [AppRow] as search.+ * Each home carousel is a capped slice — the 20 newest builds, the first 20+ * tiles. Browse lists literally every app behind that section, A–Z: the whole+ * offline repo for an offline row, the whole paged catalogue for Accrescent,+ * the uncapped cluster for a Play row. The rows use the same [AppRow] as+ * search.+ *+ * The section the id names is looked up in the home state that produced it+ * (its title and, for a Play row, its capped apps are the fallback), so the+ * entry binds only to its route argument: a restored Browse entry re-resolves+ * the section it names instead of reading whatever section a ViewModel flow+ * last held. Known offline ids also resolve if home has not rebuilt the row+ * yet; a category section's name is its title, which only the home row knows,+ * so an unrestorable category id settles empty rather than guessing.  */-fun AppStoreViewModel.openBrowse(section: AppSection) {+fun AppStoreViewModel.loadBrowse(sectionId: String) {     browseJob?.cancel()-    browseSectionFlow.value = section.id-    browseTitleFlow.value = section.title-    browseAppsFlow.value = emptyList()-    isLoadingBrowseFlow.value = true+    val section = home.value.sections.find { it.id == sectionId }+    val title = section?.title ?: browseFallbackTitle(sectionId)+    browseContentFlow.value = BrowseUiState(+        sectionId = sectionId,+        title = title,+        apps = emptyList(),+        isLoading = true,+    )     browseJob = viewModelScope.launch {         val apps = when {-            section.id == "category" ->-                catalog.allByCategory(section.title)-            section.id == "modern" || section.id == "modern-recent" ->+            sectionId == "category" ->+                // The row's own list is the fallback: a sync pruning the+                // cache mid-load must not empty a section the user is in.+                section?.let { catalog.allByCategory(it.title).ifEmpty { it.apps } }+                    ?: emptyList()+            sectionId == "modern" || sectionId == "modern-recent" ->                 catalog.allBySource(AppSource.MODERN_APPS)-            section.id == "proprietary-recent" ->+            sectionId == "proprietary-recent" ->                 catalog.allBySource(AppSource.PROPRIETARY)-            section.id == "fdroid-recent" ->+            sectionId == "fdroid-recent" ->                 catalog.allBySource(AppSource.FDROID)-            section.id == "izzy-recent" ->+            sectionId == "izzy-recent" ->                 catalog.allBySource(AppSource.IZZY)-            section.id == "accrescent" ->+            sectionId == "accrescent" ->                 accrescent.allListings()             else ->-                playFullClustersFlow.value[section.id] ?: section.apps+                playFullClustersFlow.value[sectionId] ?: section?.apps ?: emptyList()         }         // A section tapped twice in a row re-resolves: the visible row may predate a         // sync, and stale full lists are worse than a re-read.-        browseAppsFlow.value = apps.sortedBy { it.name.lowercase() }-        isLoadingBrowseFlow.value = false+        browseContentFlow.value = BrowseUiState(+            sectionId = sectionId,+            title = title,+            apps = apps.sortedBy { it.name.lowercase() },+            isLoading = false,+        )     } } +/** Title for a known section id when home has not (re)built its row yet. */+private fun AppStoreViewModel.browseFallbackTitle(sectionId: String): String = when (sectionId) {+    "modern", "modern-recent" -> context.getString(R.string.section_modern_apps_recent)+    "proprietary-recent" -> context.getString(R.string.section_proprietary_recent)+    "fdroid-recent" -> context.getString(R.string.section_fdroid_recent)+    "izzy-recent" -> context.getString(R.string.section_izzy_recent)+    "accrescent" -> context.getString(R.string.section_accrescent)+    "play-top" -> context.getString(R.string.section_play_top_charts)+    else -> sectionId.removePrefix("play-")+}+ /** Re-download both offline catalogues, then reload the home rows from them. */ fun AppStoreViewModel.syncSources() {     if (isSyncingFlow.value) return
appstore/src/main/java/com/vayunmathur/appstore/util/AppStoreViewModel.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/util/AppStoreViewModel.kt b/appstore/src/main/java/com/vayunmathur/appstore/util/AppStoreViewModel.ktindex f3daf699ec..2d4dfac8e7 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/util/AppStoreViewModel.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/util/AppStoreViewModel.kt@@ -131,10 +131,8 @@ class AppStoreViewModel(     internal val categoriesFlow = MutableStateFlow<List<String>>(emptyList())     internal val selectedCategoryFlow = MutableStateFlow<String?>(null)     internal val categoryAppsFlow = MutableStateFlow<List<UnifiedApp>>(emptyList())-    internal val browseSectionFlow = MutableStateFlow<String?>(null)-    internal val browseTitleFlow = MutableStateFlow("")-    internal val browseAppsFlow = MutableStateFlow<List<UnifiedApp>>(emptyList())-    internal val isLoadingBrowseFlow = MutableStateFlow(false)+    /** Loaded Browse content for the section the Browse route names; see loadBrowse. */+    internal val browseContentFlow = MutableStateFlow(BrowseUiState())      internal val queryFlow = MutableStateFlow("")     internal val searchResultsFlow = MutableStateFlow<List<UnifiedApp>>(emptyList())@@ -144,7 +142,8 @@ class AppStoreViewModel(     /** Play's half of the last search failed (e.g. 429, issue #797); shown above the list. */     internal val searchPlayErrorFlow = MutableStateFlow("") -    internal val selectedAppFlow = MutableStateFlow<UnifiedApp?>(null)+    /** The listing loaded for the package the Detail route names; see loadDetail. */+    internal val detailAppFlow = MutableStateFlow<UnifiedApp?>(null)     internal val isLoadingDetailsFlow = MutableStateFlow(false)      internal val catalogUpdatesFlow = MutableStateFlow<List<UnifiedApp>>(emptyList())@@ -285,17 +284,10 @@ class AppStoreViewModel(     }.stateIn(viewModelScope, SharingStarted.Eagerly, HomeUiState())      val browse: StateFlow<BrowseUiState> = combine(-        browseSectionFlow,-        browseTitleFlow,-        browseAppsFlow,-        isLoadingBrowseFlow,+        browseContentFlow,         chrome,-    ) { sectionId, title, apps, loading, rows ->-        BrowseUiState(-            sectionId = sectionId.orEmpty(),-            title = title,-            apps = apps,-            isLoading = loading,+    ) { content, rows ->+        content.copy(             installedPackages = rows.installedPackages,             installedIcons = rows.icons,             stages = rows.stages,@@ -327,7 +319,7 @@ class AppStoreViewModel(     }.stateIn(viewModelScope, SharingStarted.Eagerly, SearchUiState())      val detail: StateFlow<AppDetailUiState> = combine(-        selectedAppFlow,+        detailAppFlow,         isLoadingDetailsFlow,         chrome,         installer.verification,
appstore/src/test/java/com/vayunmathur/appstore/RouteSerializerTest.kt
diff --git a/appstore/src/test/java/com/vayunmathur/appstore/RouteSerializerTest.kt b/appstore/src/test/java/com/vayunmathur/appstore/RouteSerializerTest.ktindex 9741102997..4b6b7bcbcd 100644--- a/appstore/src/test/java/com/vayunmathur/appstore/RouteSerializerTest.kt+++ b/appstore/src/test/java/com/vayunmathur/appstore/RouteSerializerTest.kt@@ -34,7 +34,15 @@ class RouteSerializerTest {         assertEquals(shots, restoredShots)         assertEquals(1, assertIs<Route.Screenshots>(restoredShots).index) -        for (route in listOf<Route>(Route.Main, Route.Trust, Route.Detail)) {+        val detail: Route = Route.Detail("com.example.app")+        val restoredDetail = json.decodeFromString(+            Route.serializer(),+            json.encodeToString(Route.serializer(), detail),+        )+        assertEquals(detail, restoredDetail)+        assertEquals("com.example.app", assertIs<Route.Detail>(restoredDetail).packageName)++        for (route in listOf<Route>(Route.Main, Route.Trust)) {             val restored = json.decodeFromString(                 Route.serializer(),                 json.encodeToString(Route.serializer(), route),
appstore/src/test/java/com/vayunmathur/appstore/tv/TvDetailWrapperAndActionsTest.kt
diff --git a/appstore/src/test/java/com/vayunmathur/appstore/tv/TvDetailWrapperAndActionsTest.kt b/appstore/src/test/java/com/vayunmathur/appstore/tv/TvDetailWrapperAndActionsTest.ktindex 65e64f2adc..54b2d02b13 100644--- a/appstore/src/test/java/com/vayunmathur/appstore/tv/TvDetailWrapperAndActionsTest.kt+++ b/appstore/src/test/java/com/vayunmathur/appstore/tv/TvDetailWrapperAndActionsTest.kt@@ -5,6 +5,7 @@ import android.content.Intent import android.os.Looper import androidx.compose.ui.test.assertIsDisplayed import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onAllNodesWithText import androidx.compose.ui.test.onNodeWithText import androidx.room3.Room import androidx.sqlite.driver.bundled.BundledSQLiteDriver@@ -12,6 +13,7 @@ import androidx.test.core.app.ApplicationProvider import com.vayunmathur.appstore.data.AppDatabase import com.vayunmathur.appstore.data.AppSource import com.vayunmathur.appstore.data.UnifiedApp+import com.vayunmathur.appstore.data.toEntity import com.vayunmathur.appstore.data.installer.InstallStage import kotlin.test.BeforeTest import kotlin.test.Test@@ -65,16 +67,28 @@ class TvDetailWrapperAndActionsTest {     private fun nextStarted(): Intent? = Shadows.shadowOf(app).nextStartedActivity      @Test-    fun `detail wrapper renders the selected app`() {-        vm.selectApp(-            UnifiedApp(-                packageName = "com.example.wrapper",-                source = AppSource.FDROID,-                name = "Wrapper App",-            ),-        )-        await("selected") { vm.detail.value.app?.packageName == "com.example.wrapper" }-        rule.setContent { TvStoreDetail(viewModel = vm, onBack = {}) }+    fun `detail wrapper renders the app its package argument names`() {+        // Seed the catalogue the way the store would: the wrapper binds to+        // its route argument and resolves that package, with no selection+        // set on the ViewModel first. Seeding waits out the startup sync,+        // whose offline repo refresh would otherwise prune the row.+        await("startup settled") { !vm.isLoadingFlow.value }+        kotlinx.coroutines.runBlocking {+            db.cachedAppDao().upsert(+                UnifiedApp(+                    packageName = "com.example.wrapper",+                    source = AppSource.FDROID,+                    name = "Wrapper App",+                ).toEntity(),+            )+        }+        rule.setContent {+            TvStoreDetail(viewModel = vm, packageName = "com.example.wrapper", onBack = {})+        }+        await("loaded") { vm.detail.value.app?.name == "Wrapper App" }+        rule.waitUntil(timeoutMillis = 10_000) {+            rule.onAllNodesWithText("Wrapper App").fetchSemanticsNodes().isNotEmpty()+        }         rule.onNodeWithText("Wrapper App").assertIsDisplayed()     } 
appstore/src/test/java/com/vayunmathur/appstore/tv/TvStoreViewModelTest.kt
diff --git a/appstore/src/test/java/com/vayunmathur/appstore/tv/TvStoreViewModelTest.kt b/appstore/src/test/java/com/vayunmathur/appstore/tv/TvStoreViewModelTest.ktindex 290f29675b..904bb97762 100644--- a/appstore/src/test/java/com/vayunmathur/appstore/tv/TvStoreViewModelTest.kt+++ b/appstore/src/test/java/com/vayunmathur/appstore/tv/TvStoreViewModelTest.kt@@ -12,7 +12,6 @@ import com.vayunmathur.appstore.util.SourceFilter import kotlin.test.BeforeTest import kotlin.test.Test import kotlin.test.assertEquals-import kotlin.test.assertNull import kotlin.test.assertTrue import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner@@ -73,29 +72,37 @@ class TvStoreViewModelTest {     }      @Test-    fun `select and clear an app drives the detail state`() {-        val selected = app("com.example.detail", name = "Detail")-        vm.selectApp(selected)-        await("detail selected") { vm.detail.value.app?.packageName == "com.example.detail" }-        vm.clearSelection()-        await("detail cleared") { vm.detail.value.app == null }-        assertNull(vm.detail.value.app)+    fun `loadDetail by package drives the detail state, replacing the previous app`() {+        // Detail is loaded by the route's package argument: a second+        // argument replaces the first instead of rendering a stale app.+        vm.loadDetail("com.example.detail")+        await("detail loaded") { vm.detail.value.app?.packageName == "com.example.detail" }+        vm.loadDetail("com.example.other")+        await("detail replaced") { vm.detail.value.app?.packageName == "com.example.other" }+        assertEquals("com.example.other", vm.detail.value.app?.packageName)     }      @Test-    fun `browse opens a section and clears`() {+    fun `browse loads the section the route argument names`() {         val section = TvSection(             id = "play-cluster",             title = "Top apps",             apps = listOf(app("com.example.b", name = "Beta"), app("com.example.a", name = "Alpha")),         )-        vm.openBrowse(section)+        vm.sectionsFlow.value = listOf(section)+        vm.loadBrowse("play-cluster")         await("browse apps sorted") {             vm.browse.value.apps.map { it.name } == listOf("Alpha", "Beta")         }+        assertEquals("play-cluster", vm.browse.value.sectionId)         assertEquals("Top apps", vm.browse.value.title)-        vm.clearBrowse()-        await("browse cleared") { vm.browse.value.apps.isEmpty() && vm.browse.value.title.isEmpty() }++        // A different argument loads its own (empty) section, not the last one.+        vm.loadBrowse("modern")+        await("browse replaced") {+            vm.browse.value.sectionId == "modern" && !vm.browse.value.isLoading+        }+        assertTrue(vm.browse.value.apps.none { it.name == "Alpha" })     }      @Test
appstore/src/test/java/com/vayunmathur/appstore/tv/TvWrapperScreensTest.kt
diff --git a/appstore/src/test/java/com/vayunmathur/appstore/tv/TvWrapperScreensTest.kt b/appstore/src/test/java/com/vayunmathur/appstore/tv/TvWrapperScreensTest.ktindex bd1a0b234c..06756aef5b 100644--- a/appstore/src/test/java/com/vayunmathur/appstore/tv/TvWrapperScreensTest.kt+++ b/appstore/src/test/java/com/vayunmathur/appstore/tv/TvWrapperScreensTest.kt@@ -13,6 +13,7 @@ import com.vayunmathur.appstore.data.UnifiedApp import com.vayunmathur.appstore.data.toEntity import kotlin.test.BeforeTest import kotlin.test.Test+import kotlin.test.assertEquals import kotlin.test.assertTrue import kotlinx.coroutines.runBlocking import org.junit.Rule@@ -101,20 +102,15 @@ class TvWrapperScreensTest {     }      @Test-    fun `browse wrapper renders the opened section`() {-        vm.openBrowse(-            TvSection(-                id = "modern",-                title = "Modern Row",-                apps = listOf(-                    UnifiedApp(ownPackage, AppSource.MODERN_APPS, "This Store"),-                ),-            ),-        )+    fun `browse wrapper renders the section its argument names`() {+        // "modern" is a known offline section id: the wrapper resolves it+        // from its route argument against the catalogue (which holds this+        // store) without any ViewModel browse state set first.         rule.setContent {-            TvStoreBrowse(viewModel = vm, onAppClick = {}, onBack = {})+            TvStoreBrowse(viewModel = vm, sectionId = "modern", onAppClick = {}, onBack = {})         }         rule.waitForIdle()-        assertTrue(exists("Modern Row") || exists("This Store"))+        assertTrue(exists("This Store") || exists("Modern"))+        assertEquals("modern", vm.browse.value.sectionId)     } }
appstore/src/test/java/com/vayunmathur/appstore/util/AccrescentVmOpsW5Test.kt
diff --git a/appstore/src/test/java/com/vayunmathur/appstore/util/AccrescentVmOpsW5Test.kt b/appstore/src/test/java/com/vayunmathur/appstore/util/AccrescentVmOpsW5Test.ktindex f4cdefbce4..b149c7baf9 100644--- a/appstore/src/test/java/com/vayunmathur/appstore/util/AccrescentVmOpsW5Test.kt+++ b/appstore/src/test/java/com/vayunmathur/appstore/util/AccrescentVmOpsW5Test.kt@@ -163,8 +163,7 @@ class AccrescentVmOpsW5Test {         await("accrescent search") {             vm.search.value.results.any { it.packageName == "app.alpha" }         }-        val alpha = UnifiedApp(packageName = "app.alpha", source = AppSource.ACCRESCENT, name = "Alpha")-        vm.selectApp(alpha)+        vm.loadDetail("app.alpha")         await("accrescent detail") { vm.detail.value.app?.versionCode == 999_999L }         assertEquals(999_999L, vm.detail.value.app?.versionCode) @@ -196,8 +195,7 @@ class AccrescentVmOpsW5Test {         await("tv accrescent search") {             vm.search.value.results.any { it.packageName == "app.beta" }         }-        val alpha = UnifiedApp(packageName = "app.alpha", source = AppSource.ACCRESCENT, name = "Alpha")-        vm.selectApp(alpha)+        vm.loadDetail("app.alpha")         await("tv detail") { vm.detail.value.app?.packageName == "app.alpha" }         vm.checkForUpdates()         await("tv update check settles") { !vm.isCheckingUpdatesFlow.value }@@ -209,7 +207,7 @@ class AccrescentVmOpsW5Test {     fun phoneVmInstallAccrescentAppAttemptsDownloadAndSettles() {         val vm = AppStoreViewModel(app, db, accrescentOverride = repo)         val alpha = UnifiedApp(packageName = "app.alpha", source = AppSource.ACCRESCENT, name = "Alpha", versionCode = 999_999L)-        vm.selectApp(alpha)+        vm.loadDetail(alpha.packageName)         await("detail") { vm.detail.value.app?.packageName == "app.alpha" }         vm.install(alpha)         // Download from example.org fails offline; the install state must@@ -231,13 +229,12 @@ class AccrescentVmOpsW5Test {         }         val section = vm.home.value.sections.firstOrNull()         if (section != null) {-            vm.openBrowse(section)+            vm.loadBrowse(section.id)             await("browse") { vm.browse.value.apps.isNotEmpty() || vm.browse.value.title == section.title }+            assertEquals(section.id, vm.browse.value.sectionId)         }-        vm.selectPackage("app.alpha")+        vm.loadDetail("app.alpha")         await("package detail") { vm.detail.value.app?.packageName == "app.alpha" }-        vm.clearSelection()-        await("detail cleared") { vm.detail.value.app == null }         vm.refreshInstalled()         vm.refreshUpdateCheckStatus()         vm.setSearchFilter(com.vayunmathur.appstore.util.SourceFilter.ACCRESCENT)@@ -255,15 +252,19 @@ class AccrescentVmOpsW5Test {         vm.home.value.categories.firstOrNull()?.let { vm.selectCategory(it) }         vm.selectCategory(null)         val section = vm.home.value.sections.firstOrNull() ?: com.vayunmathur.appstore.tv.TvSection(id = "w5", title = "W5 Picks", apps = listOf(UnifiedApp(packageName = "app.alpha", source = AppSource.ACCRESCENT, name = "Alpha")))-        vm.openBrowse(section)-        await("tv browse settles") { !vm.isLoadingBrowseFlow.value }+        // Browse loads by route id, so the section must be the home state+        // that produced it (as a real home row would be).+        if (vm.home.value.sections.none { it.id == section.id }) {+            vm.sectionsFlow.value = listOf(section)+        }+        vm.loadBrowse(section.id)+        await("tv browse settles") { !vm.browse.value.isLoading }         assertTrue(vm.browse.value.apps.isNotEmpty() || vm.browse.value.title == section.title,             "browse=${vm.browse.value}")-        vm.clearBrowse()-        assertTrue(vm.browse.value.apps.isEmpty() || vm.browseSectionFlow.value.isEmpty())+        assertEquals(section.id, vm.browse.value.sectionId)          val alpha = UnifiedApp(packageName = "app.alpha", source = AppSource.ACCRESCENT, name = "Alpha", versionCode = 999_999L)-        vm.selectApp(alpha)+        vm.loadDetail(alpha.packageName)         await("tv detail for install") { vm.detail.value.app?.packageName == "app.alpha" }         vm.install(alpha)         await("tv install settles") {@@ -271,8 +272,6 @@ class AccrescentVmOpsW5Test {             stage == null || stage.toString().contains("Fail", ignoreCase = true)         }         vm.dismissInstallFailure("app.alpha")-        vm.clearSelection()-        await("tv detail cleared") { vm.detail.value.app == null }          // Installed-app actions should be safe no-ops/records under Robolectric.         vm.openApp(ownPackage)
appstore/src/test/java/com/vayunmathur/appstore/util/AppStoreViewModelTest.kt
diff --git a/appstore/src/test/java/com/vayunmathur/appstore/util/AppStoreViewModelTest.kt b/appstore/src/test/java/com/vayunmathur/appstore/util/AppStoreViewModelTest.ktindex b72f78d502..856c802bde 100644--- a/appstore/src/test/java/com/vayunmathur/appstore/util/AppStoreViewModelTest.kt+++ b/appstore/src/test/java/com/vayunmathur/appstore/util/AppStoreViewModelTest.kt@@ -107,14 +107,17 @@ class AppStoreViewModelTest {     @Test     fun `detail and browse states follow their flows`() {         val selected = app("com.example.detail", name = "Detail App")-        vm.selectedAppFlow.value = selected+        vm.detailAppFlow.value = selected         vm.isLoadingDetailsFlow.value = true         await("detail") { vm.detail.value.app?.packageName == "com.example.detail" }         assertTrue(vm.detail.value.isLoadingDetails) -        vm.browseSectionFlow.value = "games"-        vm.browseTitleFlow.value = "Games"-        vm.browseAppsFlow.value = listOf(selected)+        vm.browseContentFlow.value = BrowseUiState(+            sectionId = "games",+            title = "Games",+            apps = listOf(selected),+            isLoading = false,+        )         await("browse") { vm.browse.value.title == "Games" }         assertEquals("games", vm.browse.value.sectionId)         assertEquals(listOf(selected), vm.browse.value.apps)
appstore/src/test/java/com/vayunmathur/appstore/util/DetailAndBrowseOpsTest.kt
diff --git a/appstore/src/test/java/com/vayunmathur/appstore/util/DetailAndBrowseOpsTest.kt b/appstore/src/test/java/com/vayunmathur/appstore/util/DetailAndBrowseOpsTest.ktindex 7db09b5063..89dd5bd3d5 100644--- a/appstore/src/test/java/com/vayunmathur/appstore/util/DetailAndBrowseOpsTest.kt+++ b/appstore/src/test/java/com/vayunmathur/appstore/util/DetailAndBrowseOpsTest.kt@@ -13,7 +13,6 @@ import com.vayunmathur.appstore.data.toEntity import kotlin.test.BeforeTest import kotlin.test.Test import kotlin.test.assertEquals-import kotlin.test.assertNull import kotlin.test.assertTrue import kotlinx.coroutines.runBlocking import org.junit.runner.RunWith@@ -21,9 +20,12 @@ import org.robolectric.RobolectricTestRunner import org.robolectric.Shadows  /**- * Detail selection and Browse resolution: the catalogue row wins over- * a tapped shell listing, an unknown package becomes a Play shell,- * and Browse expands a home section to its full A–Z catalogue.+ * Route-argument loading for Detail and Browse: `loadDetail` resolves a+ * package name against the catalogue (the catalogue row wins), Accrescent+ * and Play, shelling an unknown package; `loadBrowse` expands the section+ * a `Route.Browse` argument names to its full A–Z catalogue. This is what+ * the Detail/Browse entries call with their route arguments, so a restored+ * entry shows the app/section it names.  */ @RunWith(RobolectricTestRunner::class) class DetailAndBrowseOpsTest {@@ -81,71 +83,60 @@ class DetailAndBrowseOpsTest {     }      @Test-    fun `the catalogue row wins over a tapped play shell`() {-        vm.selectApp(-            UnifiedApp(-                packageName = "com.example.cached",-                source = AppSource.PLAYSTORE,-                name = "Shell Name",-            ),-        )+    fun `loadDetail by package resolves the catalogue row`() {+        // Even a package Play also lists: the catalogue row an install+        // would use wins over any shell listing.+        vm.loadDetail("com.example.cached")         await("cached detail") { vm.detail.value.app?.name == "Cached Name" }         assertEquals(9L, vm.detail.value.app?.versionCode)         assertEquals(AppSource.FDROID, vm.detail.value.app?.source)     }      @Test-    fun `an uncached offline listing stays as tapped`() {-        val tapped = UnifiedApp(-            packageName = "com.example.uncached",-            source = AppSource.FDROID,-            name = "Uncached",-        )-        vm.selectApp(tapped)-        await("tapped detail") { vm.detail.value.app?.packageName == "com.example.uncached" }-        assertEquals("Uncached", vm.detail.value.app?.name)-    }--    @Test-    fun `selectPackage resolves cached apps and shells unknown ones`() {-        vm.selectPackage("com.example.cached")-        await("cached by package") { vm.detail.value.app?.name == "Cached Name" }--        vm.selectPackage("com.example.unknown")+    fun `loadDetail shells an unknown package by its last segment`() {+        vm.loadDetail("com.example.unknown")         await("shell by package") { vm.detail.value.app?.packageName == "com.example.unknown" }         assertEquals("unknown", vm.detail.value.app?.name)         assertEquals(AppSource.PLAYSTORE, vm.detail.value.app?.source)     }      @Test-    fun `clearSelection empties the detail`() {-        vm.selectApp(-            UnifiedApp(-                packageName = "com.example.uncached",-                source = AppSource.FDROID,-                name = "Uncached",-            ),+    fun `loading a second package replaces the first detail`() {+        // The route-argument contract in one test: the entry for package B+        // must never render package A's listing, not even briefly from a+        // stale flow — loadDetail drops the old app synchronously.+        vm.loadDetail("com.example.cached")+        await("first detail") { vm.detail.value.app?.packageName == "com.example.cached" }+        vm.loadDetail("com.example.zmodern")+        assertTrue(+            vm.detail.value.app?.packageName != "com.example.cached",+            "stale detail survived a new route argument: ${vm.detail.value}",         )-        await("selected") { vm.detail.value.app != null }-        vm.clearSelection()-        await("cleared") { vm.detail.value.app == null }-        assertNull(vm.detail.value.app)+        await("second detail") { vm.detail.value.app?.packageName == "com.example.zmodern" }+        assertEquals("Zulu Modern", vm.detail.value.app?.name)     }      @Test     fun `browse expands an offline section to its full sorted catalogue`() {-        vm.openBrowse(AppSection(id = "modern-recent", title = "Modern", apps = emptyList()))+        vm.loadBrowse("modern-recent")         await("browse loaded") { vm.browse.value.apps.size == 2 && !vm.browse.value.isLoading }+        assertEquals("modern-recent", vm.browse.value.sectionId)         assertEquals(             listOf("Alpha Modern", "Zulu Modern"),             vm.browse.value.apps.map { it.name },         )-        assertEquals("Modern", vm.browse.value.title)+        assertTrue(vm.browse.value.title.isNotBlank())     }      @Test     fun `browse by category and by play cluster fallback`() {-        vm.openBrowse(AppSection(id = "category", title = "Games", apps = emptyList()))+        // A category's name lives only in the home row's title: browse the+        // category home is currently showing.+        vm.selectCategory("Games")+        await("category section on home") {+            vm.home.value.sections.any { it.id == "category" && it.title == "Games" }+        }+        vm.loadBrowse("category")         await("category browse") {             vm.browse.value.apps.map { it.packageName } == listOf("com.example.cached")         }@@ -154,10 +145,12 @@ class DetailAndBrowseOpsTest {             UnifiedApp("com.example.b", AppSource.PLAYSTORE, "Beta"),             UnifiedApp("com.example.a", AppSource.PLAYSTORE, "Alpha"),         )-        vm.openBrowse(AppSection(id = "play-cluster", title = "Play", apps = clusterApps))+        vm.playFullClustersFlow.value = mapOf("play-cluster" to clusterApps)+        vm.loadBrowse("play-cluster")         await("play browse") {             vm.browse.value.apps.map { it.name } == listOf("Alpha", "Beta")         }+        assertEquals("play-cluster", vm.browse.value.sectionId)         assertTrue(vm.browse.value.apps.all { it.source == AppSource.PLAYSTORE })     }