Modern Apps git

← Modern-Apps.git

shop: leaving a store's scope can no longer be overwritten by its late search results

Commit
170943d2abe64df8b7edcd5e3f24f9ceec247b15
Author
Vayun Mathur <[email protected]>
When
2026-12-01 04:01 UTC (5 days ago)
Parents
8947d8e
search() launched a coroutine that wrote results/searchError
and reset searching unconditionally on completion, with no
check that its launching scope was still current. clearScope
cleared the scope and called search(), which early-returned
on searching == true — so the dismissed store's in-flight
search was never invalidated or replaced: when the Kitchen
response landed, Kitchen-only products repopulated the grid
presented as global results (and an empty stale response left
the 'start searching' state up for a submitted query). The
same hole fired on store-to-store scopedSearch switches.

A monotonic searchGeneration owns the search now: search()
captures ++generation and applies results/error and the
searching reset only while still current (also skipping the
backend call if invalidated during awaitReady); clearScope
and scopedSearch invalidate first, so a replacement search
starts immediately and a late completion can neither
repopulate results nor steal the newer search's flag. Two
regression tests with a gated fake backend failed pre-fix on
exactly this. Cart, money math, checkout idempotency and
order staleness were audited and cleared. Verified:
:shop:testDevUnitTest 159 tests pass; lint errors are
pre-existing on untouched files.

Diff

shop/src/main/java/com/vayunmathur/shop/platform/ShopViewModel.kt
diff --git a/shop/src/main/java/com/vayunmathur/shop/platform/ShopViewModel.kt b/shop/src/main/java/com/vayunmathur/shop/platform/ShopViewModel.ktindex babbced3d0..33c87cffc0 100644--- a/shop/src/main/java/com/vayunmathur/shop/platform/ShopViewModel.kt+++ b/shop/src/main/java/com/vayunmathur/shop/platform/ShopViewModel.kt@@ -188,6 +188,7 @@ class ShopViewModel(     fun updateQuery(value: String) { query = value }      fun clearScope() {+        invalidateSearch()         scopeDomain = null         scopeName = null         results = emptyList()@@ -232,6 +233,7 @@ class ShopViewModel(     }      private fun scopedSearch(domain: String, name: String, scopedQuery: String, navigate: (Route) -> Unit) {+        invalidateSearch()         scopeDomain = domain         scopeName = name         query = scopedQuery@@ -284,10 +286,24 @@ class ShopViewModel(         }     } +    /**+     * Monotonic search generation. Scope changes (dismissing the store chip, opening+     * another store's link) invalidate any in-flight search: its late completion must+     * never repopulate results for a store/query the user has already left, and must+     * not clear the [searching] flag a newer search now owns.+     */+    private var searchGeneration = 0++    private fun invalidateSearch() {+        searchGeneration+++        searching = false+    }+     fun search() {         val q = query.trim()         if (q.isEmpty() || searching) return         val shop = scopeDomain+        val generation = ++searchGeneration         searching = true         searchError = null         searchedQuery = q@@ -295,12 +311,13 @@ class ShopViewModel(         viewModelScope.launch {             try {                 AppInit.awaitReady()+                if (generation != searchGeneration) return@launch                 backend.search(q, shop, limit = SEARCH_LIMIT).fold(-                    onSuccess = { results = it },-                    onFailure = { searchError = it.toBackendMessage() },+                    onSuccess = { if (generation == searchGeneration) results = it },+                    onFailure = { if (generation == searchGeneration) searchError = it.toBackendMessage() },                 )             } finally {-                searching = false+                if (generation == searchGeneration) searching = false             }         }     }
shop/src/test/java/com/vayunmathur/shop/platform/ShopViewModelTest.kt
diff --git a/shop/src/test/java/com/vayunmathur/shop/platform/ShopViewModelTest.kt b/shop/src/test/java/com/vayunmathur/shop/platform/ShopViewModelTest.ktindex c5fbb7d9ad..1ff2c3f199 100644--- a/shop/src/test/java/com/vayunmathur/shop/platform/ShopViewModelTest.kt+++ b/shop/src/test/java/com/vayunmathur/shop/platform/ShopViewModelTest.kt@@ -38,6 +38,9 @@ class ShopViewModelTest {      private class FakeBackend : ShopBackend {         var searchResult: Result<List<UcpProduct>> = Result.success(emptyList())+        var searchResultForShop: ((String?) -> Result<List<UcpProduct>>)? = null+        var searchGate: kotlinx.coroutines.CompletableDeferred<Unit>? = null+        var completedSearches = 0         var productResult: Result<UcpProduct> = Result.failure(IllegalStateException("none"))         var merchant: MerchantListing? = null         val searches = mutableListOf<Triple<String, String?, Int>>()@@ -45,7 +48,9 @@ class ShopViewModelTest {          override suspend fun search(query: String, shop: String?, limit: Int, country: String): Result<List<UcpProduct>> {             searches += Triple(query, shop, limit)-            return searchResult+            searchGate?.await()+            completedSearches+++            return searchResultForShop?.invoke(shop) ?: searchResult         }          override suspend fun getProduct(@@ -143,6 +148,53 @@ class ShopViewModelTest {         assertNull(vm.searchError)     } +    @Test+    fun search_inFlightScopedResultIsDroppedAfterClearScope() {+        backend.merchant = MerchantListing("m1", "Kitchen Co", "kitchen.example", "https://kitchen.example")+        vm.openLink("https://kitchen.example/collections/all")+        await { vm.scopeDomain == "kitchen.example" }+        val gate = kotlinx.coroutines.CompletableDeferred<Unit>()+        backend.searchGate = gate+        backend.searchResultForShop = { shop ->+            Result.success(listOf(product(title = if (shop == null) "Global Shoes" else "Kitchen Shoes")))+        }+        vm.updateQuery("shoes")+        vm.search()+        await { backend.searches.size == 1 }+        assertEquals("kitchen.example", backend.searches[0].second)+        // Dismissing the store mid-search invalidates it; the unscoped search replaces it.+        vm.clearScope()+        await { backend.searches.size == 2 }+        assertEquals(null, backend.searches[1].second)+        gate.complete(Unit)+        await { backend.completedSearches == 2 && !vm.searching }+        assertNull(vm.scopeDomain)+        assertEquals(listOf("Global Shoes"), vm.results.map { it.title })+        assertEquals("shoes", vm.searchedQuery)+    }++    @Test+    fun search_inFlightResultIsDroppedWhenSwitchingStores() {+        backend.merchant = MerchantListing("m1", "Kitchen Co", "kitchen.example", "https://kitchen.example")+        vm.openLink("https://kitchen.example/collections/all")+        await { vm.scopeDomain == "kitchen.example" }+        val gate = kotlinx.coroutines.CompletableDeferred<Unit>()+        backend.searchGate = gate+        backend.searchResult = Result.success(listOf(product(title = "Kitchen Shoes")))+        vm.updateQuery("shoes")+        vm.search()+        await { backend.searches.size == 1 }+        // Opening another store's link invalidates the in-flight Kitchen search.+        backend.merchant = MerchantListing("m2", "Trail Co", "trail.example", "https://trail.example")+        vm.openLink("https://trail.example/collections/all")+        await { vm.scopeDomain == "trail.example" }+        gate.complete(Unit)+        await { backend.completedSearches == 1 }+        assertTrue(vm.results.isEmpty())+        assertNull(vm.searchedQuery)+        assertEquals("", vm.query)+    }+     @Test     fun addToCart_mergesSameVariantCapsAt99AndRejectsInvalid() {         val p = product()