Modern Apps git

← Modern-Apps.git

fooddelivery: fix main-thread JSON parsing causing ANR

Commit
3d7db77148d97f53cf033c1ce53ee7695dbff9dd
Author
vayun-mathur <[email protected]>
When
2026-08-20 22:49 UTC (3 months ago)
Parents
19b3238

Diff

fooddelivery/src/main/AndroidManifest.xml
diff --git a/fooddelivery/src/main/AndroidManifest.xml b/fooddelivery/src/main/AndroidManifest.xmlindex a628af73b7..e14a7a89b3 100644--- a/fooddelivery/src/main/AndroidManifest.xml+++ b/fooddelivery/src/main/AndroidManifest.xml@@ -15,6 +15,7 @@         android:protectionLevel="signature" />      <application+        android:name=".FoodDeliveryApplication"         android:allowBackup="false"         android:dataExtractionRules="@xml/data_extraction_rules"         android:icon="@mipmap/ic_launcher"
fooddelivery/src/main/java/com/vayunmathur/fooddelivery/FoodDeliveryApplication.kt
diff --git a/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/FoodDeliveryApplication.kt b/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/FoodDeliveryApplication.ktnew file mode 100644index 0000000000..0fe097cd35--- /dev/null+++ b/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/FoodDeliveryApplication.kt@@ -0,0 +1,11 @@+package com.vayunmathur.fooddelivery++import android.app.Application+import com.vayunmathur.fooddelivery.platform.AppInit++class FoodDeliveryApplication : Application() {+    override fun onCreate() {+        super.onCreate()+        AppInit.start(this)+    }+}
fooddelivery/src/main/java/com/vayunmathur/fooddelivery/MainActivity.kt
diff --git a/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/MainActivity.kt b/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/MainActivity.ktindex 324c5ed75b..39d9afda57 100644--- a/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/MainActivity.kt+++ b/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/MainActivity.kt@@ -1,7 +1,6 @@ package com.vayunmathur.fooddelivery  import android.Manifest-import android.content.Context import android.content.Intent import android.content.pm.PackageManager import android.os.Build@@ -33,7 +32,6 @@ import com.vayunmathur.library.util.MainNavigation import com.vayunmathur.library.util.NavBackStack import com.vayunmathur.library.util.NavKey import com.vayunmathur.library.util.rememberNavBackStack-import com.vayunmathur.fooddelivery.api.BitesApi import com.vayunmathur.fooddelivery.data.CartItem import com.vayunmathur.fooddelivery.data.CartStore import com.vayunmathur.fooddelivery.ipc.OrderLookupContract@@ -47,8 +45,6 @@ import com.vayunmathur.fooddelivery.ui.OrderTrackingScreen import com.vayunmathur.fooddelivery.ui.OrdersScreen import com.vayunmathur.fooddelivery.ui.RestaurantScreen import kotlinx.serialization.Serializable-import com.vayunmathur.library.network.NetworkClient-import com.vayunmathur.library.network.TrustBundle  sealed interface Route : NavKey {     @Serializable data class Main(val initialTab: Int = 0) : Route@@ -76,19 +72,10 @@ class MainActivity : ComponentActivity() {         trackOrderId.value = intent.trackOrderIdOrNull()         openRestaurantId.value = intent.restaurantIdOrNull()         requestNotificationPermissionIfNeeded()-        // api.deliverycollective.com is on AWS Elastic Beanstalk and serves an ACM cert-        // chaining to Amazon Root CA 1, which FIRST_PARTY (ISRG + GTS only) doesn't carry —-        // pinning to it fails the handshake before any request goes out. STANDARD adds the-        // Amazon roots.-        NetworkClient.init(this, TrustBundle.STANDARD)+        // The TLS trust bundle and the saved auth token are warmed up off the main thread by+        // FoodDeliveryApplication / AppInit, so nothing here touches the network or disk.         enableEdgeToEdge() -        val prefs = getSharedPreferences("fooddelivery_prefs", Context.MODE_PRIVATE)-        val tokenJson = prefs.getString("token_json", null)-        if (tokenJson != null) {-            BitesApi.restoreToken(tokenJson)-        }-         PaymentConfiguration.init(             applicationContext,             "pk_live_51NQy7lFJFBMK4hv9KubgZcyH2Wy0MsXn9BtrtM7moEi762WE7pcmZ1JL9BrCKPRKw6ZJdGo9YJSA1pidb0KUthlJ00Wr4bcpVD"@@ -145,7 +132,17 @@ private fun FoodDeliveryApp(trackOrderId: MutableState<Int?>, openRestaurantId:         backStack.add(Route.Restaurant(id))         openRestaurantId.value = null     }-    val cart = remember { mutableStateListOf<CartItem>().also { it.addAll(CartStore.getAll(context)) } }+    // Restoring the cart is a prefs read plus a JSON decode, so it happens off the main+    // thread rather than in the remember initialiser. Anything added while the read was in+    // flight stays in the cart, and is re-persisted alongside the restored lines.+    val cart = remember { mutableStateListOf<CartItem>() }+    LaunchedEffect(Unit) {+        val saved = CartStore.getAll(context)+        if (saved.isEmpty()) return@LaunchedEffect+        val addedMeanwhile = cart.isNotEmpty()+        cart.addAll(0, saved)+        if (addedMeanwhile) CartStore.save(context, cart)+    }      MainNavigation(backStack) {         entry<Route.Main> { route ->@@ -159,7 +156,10 @@ private fun FoodDeliveryApp(trackOrderId: MutableState<Int?>, openRestaurantId:             RestaurantScreen(                 merchantId = route.id,                 onBack = { backStack.pop() },-                onAddToCart = { item -> cart.add(item); CartStore.save(context, cart) }+                onAddToCart = { item ->+                    cart.add(item)+                    CartStore.save(context, cart)+                }             )         }         entry<Route.Checkout> {@@ -191,30 +191,35 @@ private fun FoodDeliveryTabs( ) {     val context = LocalContext.current     val pagerState = rememberPagerState(initialPage = initialTab.coerceIn(0, 4), pageCount = { 5 })-    val tabs = listOf(-        PagerTab("Home", { IconHome() }) {-            HomeScreen(onMerchantClick = { id -> backStack.add(Route.Restaurant(id)) })-        },-        PagerTab("Cart", { IconShoppingCart() }) {-            CartScreen(-                items = cart,-                onRemoveItem = { cart.removeAt(it); CartStore.save(context, cart) },-                onCheckout = { backStack.add(Route.Checkout) },-                onEditModifiers = { index, modifiers ->-                    cart[index] = cart[index].copy(selectedModifiers = modifiers)-                    CartStore.save(context, cart)-                },-            )-        },-        PagerTab("Deals", { IconLocalOffer() }) {-            DealsScreen(onMerchantClick = { id -> backStack.add(Route.Restaurant(id)) })-        },-        PagerTab("Orders", { IconPackage() }) {-            OrdersScreen(onTrackOrder = { id -> backStack.add(Route.OrderTracking(id)) })-        },-        PagerTab("Account", { IconPerson() }) {-            AccountScreen()-        },-    )+    val tabs = remember(backStack, cart, context) {+        listOf(+            PagerTab("Home", { IconHome() }) {+                HomeScreen(onMerchantClick = { id -> backStack.add(Route.Restaurant(id)) })+            },+            PagerTab("Cart", { IconShoppingCart() }) {+                CartScreen(+                    items = cart,+                    onRemoveItem = {+                        cart.removeAt(it)+                        CartStore.save(context, cart)+                    },+                    onCheckout = { backStack.add(Route.Checkout) },+                    onEditModifiers = { index, modifiers ->+                        cart[index] = cart[index].copy(selectedModifiers = modifiers)+                        CartStore.save(context, cart)+                    },+                )+            },+            PagerTab("Deals", { IconLocalOffer() }) {+                DealsScreen(onMerchantClick = { id -> backStack.add(Route.Restaurant(id)) })+            },+            PagerTab("Orders", { IconPackage() }) {+                OrdersScreen(onTrackOrder = { id -> backStack.add(Route.OrderTracking(id)) })+            },+            PagerTab("Account", { IconPerson() }) {+                AccountScreen()+            },+        )+    }     TabbedPagerScaffold(tabs = tabs, pagerState = pagerState, tabStyle = TabStyle.BottomNav) }
fooddelivery/src/main/java/com/vayunmathur/fooddelivery/api/BitesApi.kt
diff --git a/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/api/BitesApi.kt b/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/api/BitesApi.ktindex bf0d0f9024..b4643bbae6 100644--- a/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/api/BitesApi.kt+++ b/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/api/BitesApi.kt@@ -3,6 +3,7 @@ package com.vayunmathur.fooddelivery.api import com.vayunmathur.library.network.NetworkClient import com.vayunmathur.library.network.SimpleResponse import android.util.Log+import com.vayunmathur.fooddelivery.BuildConfig import com.vayunmathur.fooddelivery.data.ApiResponse import com.vayunmathur.fooddelivery.data.AuthToken import com.vayunmathur.fooddelivery.data.CheckoutAddress@@ -23,14 +24,28 @@ import com.vayunmathur.fooddelivery.data.MerchantsWrapper import com.vayunmathur.fooddelivery.data.Order import com.vayunmathur.fooddelivery.data.OrderRewards import com.vayunmathur.fooddelivery.data.Reward-import kotlinx.serialization.encodeToString+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.sync.Mutex+import kotlinx.coroutines.sync.withLock+import kotlinx.coroutines.withContext+import kotlinx.serialization.KSerializer+import kotlinx.serialization.builtins.ListSerializer import kotlinx.serialization.json.Json+import kotlinx.serialization.json.JsonObject+import kotlinx.serialization.json.buildJsonObject+import kotlinx.serialization.json.jsonObject+import kotlinx.serialization.json.jsonPrimitive+import kotlinx.serialization.json.longOrNull+import kotlinx.serialization.json.put  object BitesApi {      private const val BASE = "https://api.deliverycollective.com"     private const val API = "$BASE/api/v1" +    /** Absolute expiry we persist alongside the token so a cold start knows if it is stale. */+    private const val EXPIRES_AT_KEY = "expires_at_ms"+     private val json = Json {         ignoreUnknownKeys = true         isLenient = true@@ -46,30 +61,51 @@ object BitesApi {         explicitNulls = false     } +    @Volatile     private var storedToken: AuthToken? = null++    @Volatile     private var expiresAtMs: Long = 0     var onTokenUpdated: ((String) -> Unit)? = null +    /** Serialises refreshes: the refresh token rotates, so two in flight invalidate each other. */+    private val refreshMutex = Mutex()++    private inline fun logd(message: () -> String) {+        if (BuildConfig.DEV_BUILD) Log.d("BitesApi", message())+    }+     fun setToken(token: AuthToken?) {         storedToken = token-        if (token != null && token.expires_in > 0) {+        if (token == null) return+        if (token.expires_in > 0) {             expiresAtMs = System.currentTimeMillis() + token.expires_in * 1000         }-        if (token != null) {-            Log.d("BitesApi", "setToken: access=${token.access_token.take(20)}... refresh=${token.refresh_token.take(20)}... expires_in=${token.expires_in}")-            onTokenUpdated?.invoke(json.encodeToString(token))-        }+        onTokenUpdated?.invoke(encodeTokenForStorage(token, expiresAtMs))     }      fun restoreToken(tokenJson: String) {         try {-            storedToken = json.decodeFromString<AuthToken>(tokenJson)-            Log.d("BitesApi", "restoreToken: access=${storedToken?.access_token?.take(20)}... refresh=${storedToken?.refresh_token?.take(20)}...")+            val root = json.parseToJsonElement(tokenJson).jsonObject+            storedToken = json.decodeFromJsonElement(AuthToken.serializer(), root)+            expiresAtMs = root[EXPIRES_AT_KEY]?.jsonPrimitive?.longOrNull ?: 0L         } catch (e: Exception) {             Log.e("BitesApi", "restoreToken failed", e)         }     } +    /**+     * The token plus its absolute expiry. Persisting only `expires_in` meant every cold+     * start treated the token as unknown-expiry and forced a refresh on the first request.+     */+    private fun encodeTokenForStorage(token: AuthToken, expiryMs: Long): String {+        val encoded = json.encodeToJsonElement(AuthToken.serializer(), token).jsonObject+        return buildJsonObject {+            encoded.forEach { (k, v) -> put(k, v) }+            put(EXPIRES_AT_KEY, expiryMs)+        }.toString()+    }+     fun isLoggedIn(): Boolean = storedToken != null && storedToken!!.access_token.isNotEmpty()      fun clearToken() {@@ -77,33 +113,38 @@ object BitesApi {         expiresAtMs = 0     } +    /**+     * One refresh at a time. Callers that queue behind the mutex re-check [storedToken]:+     * if it already moved on, the refresh someone else did is theirs to use.+     */+    private suspend fun refreshToken(stale: AuthToken): AuthToken? = refreshMutex.withLock {+        val current = storedToken+        if (current != null && current.access_token != stale.access_token) return@withLock current+        val refresh = current?.refresh_token+        if (refresh.isNullOrEmpty()) return@withLock null+        exchangeRefreshTokenForToken(refresh)?.also { setToken(it) }+    }+     private suspend fun getAccessToken(): String? {         val token = storedToken ?: return null         if (token.access_token.isEmpty()) return null         if (token.refresh_token.isNotEmpty() &&             (expiresAtMs == 0L || System.currentTimeMillis() > expiresAtMs)) {-            val refreshed = exchangeRefreshTokenForToken(token.refresh_token)-            if (refreshed != null) {-                setToken(refreshed)-                return refreshed.access_token-            }+            refreshToken(token)?.let { return it.access_token }         }         return token.access_token     }      private suspend fun authenticatedRequest(url: String, method: String = "GET", body: String? = null): SimpleResponse {         var resp = NetworkClient.performRequest(url, method, headers(), body)-        Log.d("BitesApi", "$method $url -> ${resp.status} body=${resp.body.take(200)}")-        if (resp.status == 401 && storedToken?.refresh_token?.isNotEmpty() == true) {-            Log.d("BitesApi", "Got 401, refreshing token...")-            val refreshed = exchangeRefreshTokenForToken(storedToken!!.refresh_token)-            if (refreshed != null) {-                Log.d("BitesApi", "Token refreshed, retrying...")-                setToken(refreshed)+        logd { "$method $url -> ${resp.status}" }+        val token = storedToken+        if (resp.status == 401 && token != null && token.refresh_token.isNotEmpty()) {+            if (refreshToken(token) != null) {                 resp = NetworkClient.performRequest(url, method, headers(), body)-                Log.d("BitesApi", "Retry -> ${resp.status} body=${resp.body.take(200)}")+                logd { "retry $method $url -> ${resp.status}" }             } else {-                Log.d("BitesApi", "Token refresh failed")+                logd { "token refresh failed" }             }         }         return resp@@ -120,18 +161,18 @@ object BitesApi {      // ---- Auth ---- -    suspend fun verifyPhone(phone: String): String? {-        return try {+    suspend fun verifyPhone(phone: String): String? = withContext(Dispatchers.Default) {+        try {             val cleanPhone = "+" + phone.replace(Regex("\\D"), "")             val body = """{"phoneNumber":"$cleanPhone","audience":"customer","scope":"openid email profile offline_access"}"""             val resp = NetworkClient.performRequest(                 "$BASE/auth/verify_phone", "POST",                 mapOf("Content-Type" to "application/json"), body             )-            Log.d("BitesApi", "verifyPhone -> ${resp.status} body=${resp.body.take(300)}")+            logd { "verifyPhone -> ${resp.status}" }             if (resp.isSuccess) {                 val parsed = json.parseToJsonElement(resp.body)-                if (parsed is kotlinx.serialization.json.JsonObject) {+                if (parsed is JsonObject) {                     (parsed["state_id"] ?: parsed["stateId"])?.toString()?.trim('"')                 } else null             } else null@@ -143,15 +184,15 @@ object BitesApi {         }     } -    suspend fun exchangeOtpCodeForToken(stateId: String, code: String): AuthToken? {-        return try {+    suspend fun exchangeOtpCodeForToken(stateId: String, code: String): AuthToken? = withContext(Dispatchers.Default) {+        try {             val body = "grant_type=phone_otp&state_id=$stateId&code=$code"             val resp = NetworkClient.performRequest(                 "$BASE/auth/token", "POST",                 mapOf("Content-Type" to "application/x-www-form-urlencoded", "Accept" to "application/json"),                 body             )-            Log.d("BitesApi", "exchangeOtp -> ${resp.status} body=${resp.body.take(300)}")+            logd { "exchangeOtp -> ${resp.status}" }             if (resp.isSuccess) json.decodeFromString<AuthToken>(resp.body) else null         } catch (e: Exception) {             Log.e("BitesApi", "exchangeOtp failed", e)@@ -159,15 +200,15 @@ object BitesApi {         }     } -    private suspend fun exchangeRefreshTokenForToken(refreshToken: String): AuthToken? {-        return try {+    private suspend fun exchangeRefreshTokenForToken(refreshToken: String): AuthToken? = withContext(Dispatchers.Default) {+        try {             val body = "grant_type=refresh_token&refresh_token=$refreshToken"             val resp = NetworkClient.performRequest(                 "$BASE/auth/token", "POST",                 mapOf("Content-Type" to "application/x-www-form-urlencoded", "Accept" to "application/json"),                 body             )-            Log.d("BitesApi", "refreshToken -> ${resp.status} body=${resp.body.take(300)}")+            logd { "refreshToken -> ${resp.status}" }             if (resp.isSuccess) json.decodeFromString<AuthToken>(resp.body) else null         } catch (e: Exception) {             Log.e("BitesApi", "refreshToken failed", e)@@ -177,8 +218,8 @@ object BitesApi {      // ---- Merchants ---- -    suspend fun getMerchants(lat: Double? = null, lng: Double? = null): List<Merchant> {-        return try {+    suspend fun getMerchants(lat: Double? = null, lng: Double? = null): List<Merchant> = withContext(Dispatchers.Default) {+        try {             val params = buildString {                 val parts = mutableListOf<String>()                 if (lat != null) parts.add("lat=$lat")@@ -193,8 +234,8 @@ object BitesApi {         } catch (_: Exception) { emptyList() }     } -    suspend fun getMerchantDetail(id: Int): MerchantDetail? {-        return try {+    suspend fun getMerchantDetail(id: Int): MerchantDetail? = withContext(Dispatchers.Default) {+        try {             val resp = authenticatedRequest("$API/merchants/$id")             if (resp.isSuccess) {                 val wrapper = json.decodeFromString<ApiResponse<MerchantDetail>>(resp.body)@@ -205,8 +246,8 @@ object BitesApi {      // ---- Deals ---- -    suspend fun getDeals(lat: Double? = null, lng: Double? = null): List<Deal> {-        return try {+    suspend fun getDeals(lat: Double? = null, lng: Double? = null): List<Deal> = withContext(Dispatchers.Default) {+        try {             val params = buildString {                 val parts = mutableListOf<String>()                 if (lat != null) parts.add("lat=$lat")@@ -217,33 +258,18 @@ object BitesApi {                 "$API/deals/active$params", headers = headers()             )             if (resp.isSuccess) {-                val parsed = json.parseToJsonElement(resp.body)-                if (parsed is kotlinx.serialization.json.JsonObject) {-                    val dataEl = parsed["data"]-                    if (dataEl is kotlinx.serialization.json.JsonArray) {-                        json.decodeFromString<List<Deal>>(dataEl.toString())-                    } else emptyList()-                } else emptyList()+                json.decodeFromString<ApiResponse<List<Deal>>>(resp.body).data ?: emptyList()             } else emptyList()         } catch (_: Exception) { emptyList() }     }      // ---- Orders ---- -    suspend fun getOrders(): List<Order> {-        return try {+    suspend fun getOrders(): List<Order> = withContext(Dispatchers.Default) {+        try {             val resp = authenticatedRequest("$API/orders/past/all")             if (resp.isSuccess) {-                val parsed = json.parseToJsonElement(resp.body)-                if (parsed is kotlinx.serialization.json.JsonObject) {-                    val dataEl = parsed["data"]-                    if (dataEl is kotlinx.serialization.json.JsonArray && dataEl.isNotEmpty()) {-                        val firstOrder = dataEl[0] as? kotlinx.serialization.json.JsonObject-                        val items = firstOrder?.get("orderItems")-                        Log.d("BitesApi", "order[0].orderItems[0]: ${(items as? kotlinx.serialization.json.JsonArray)?.firstOrNull().toString().take(1000)}")-                        json.decodeFromString<List<Order>>(dataEl.toString())-                    } else emptyList()-                } else emptyList()+                json.decodeFromString<ApiResponse<List<Order>>>(resp.body).data ?: emptyList()             } else emptyList()         } catch (e: Exception) {             Log.e("BitesApi", "getOrders failed", e)@@ -259,57 +285,43 @@ object BitesApi {     }      /** GET /orders/email/{token} — look an order up by its email link. */-    suspend fun getOrderByEmail(token: String): Order? = try {-        val resp = authenticatedRequest("$API/orders/email/$token")-        if (!resp.isSuccess) null else {-            val dataEl = (json.parseToJsonElement(resp.body) as? kotlinx.serialization.json.JsonObject)?.get("data")-            json.decodeFromString<Order>((dataEl ?: json.parseToJsonElement(resp.body)).toString())+    suspend fun getOrderByEmail(token: String): Order? = withContext(Dispatchers.Default) {+        try {+            val resp = authenticatedRequest("$API/orders/email/$token")+            if (!resp.isSuccess) null else unwrap(resp.body, Order.serializer())+        } catch (e: Exception) {+            Log.e("BitesApi", "getOrderByEmail failed", e); null         }-    } catch (e: Exception) {-        Log.e("BitesApi", "getOrderByEmail failed", e); null     }      /** POST /merchants/{id}/check-serviceability — can this merchant deliver to [address]? */-    suspend fun checkServiceability(merchantId: Int, address: CheckoutAddress): Boolean? = try {-        val resp = authenticatedRequest(-            "$API/merchants/$merchantId/check-serviceability", "POST",-            json.encodeToString(CheckoutAddress.serializer(), address),-        )-        if (resp.isSuccess) true else if (resp.status in 400..499) false else null-    } catch (e: Exception) {-        Log.e("BitesApi", "checkServiceability failed", e); null+    suspend fun checkServiceability(merchantId: Int, address: CheckoutAddress): Boolean? = withContext(Dispatchers.Default) {+        try {+            val resp = authenticatedRequest(+                "$API/merchants/$merchantId/check-serviceability", "POST",+                json.encodeToString(CheckoutAddress.serializer(), address),+            )+            if (resp.isSuccess) true else if (resp.status in 400..499) false else null+        } catch (e: Exception) {+            Log.e("BitesApi", "checkServiceability failed", e); null+        }     }      // ---- Customer ---- -    suspend fun getCustomer(): Customer? {-        return try {+    suspend fun getCustomer(): Customer? = withContext(Dispatchers.Default) {+        try {             val resp = authenticatedRequest("$API/customers/me")-            if (resp.isSuccess) {-                val parsed = json.parseToJsonElement(resp.body)-                if (parsed is kotlinx.serialization.json.JsonObject) {-                    val dataEl = parsed["data"]-                    if (dataEl != null) {-                        json.decodeFromString<Customer>(dataEl.toString())-                    } else json.decodeFromString<Customer>(resp.body)-                } else null-            } else null+            if (resp.isSuccess) unwrap(resp.body, Customer.serializer()) else null         } catch (_: Exception) { null }     }      // ---- Savings & Rewards ---- -    suspend fun getCustomerSavings(): CustomerSavings? {-        return try {+    suspend fun getCustomerSavings(): CustomerSavings? = withContext(Dispatchers.Default) {+        try {             val resp = authenticatedRequest("$API/orders/me/savings")-            if (resp.isSuccess) {-                val parsed = json.parseToJsonElement(resp.body)-                if (parsed is kotlinx.serialization.json.JsonObject) {-                    val dataEl = parsed["data"]-                    if (dataEl != null) json.decodeFromString<CustomerSavings>(dataEl.toString())-                    else json.decodeFromString<CustomerSavings>(resp.body)-                } else null-            } else null+            if (resp.isSuccess) unwrap(resp.body, CustomerSavings.serializer()) else null         } catch (_: Exception) { null }     } @@ -318,43 +330,35 @@ object BitesApi {      * calls this right before showing the total and subtracts `rewardsAvailable` from the      * order's component sum (bites-js-decompiled.js:1255938).      */-    suspend fun getOrderRewards(orderUuid: String): OrderRewards? {-        return try {+    suspend fun getOrderRewards(orderUuid: String): OrderRewards? = withContext(Dispatchers.Default) {+        try {             val resp = authenticatedRequest("$API/orders/$orderUuid/rewards")-            if (!resp.isSuccess) return null-            val parsed = json.parseToJsonElement(resp.body)-            val dataEl = (parsed as? kotlinx.serialization.json.JsonObject)?.get("data")-            if (dataEl != null) json.decodeFromString<OrderRewards>(dataEl.toString())-            else json.decodeFromString<OrderRewards>(resp.body)+            if (!resp.isSuccess) null else unwrap(resp.body, OrderRewards.serializer())         } catch (e: Exception) {             Log.e("BitesApi", "getOrderRewards failed", e)             null         }     } -    suspend fun getRewards(): List<Reward> {-        return try {+    suspend fun getRewards(): List<Reward> = withContext(Dispatchers.Default) {+        try {             val resp = authenticatedRequest("$API/rewards")             if (resp.isSuccess) {-                val parsed = json.parseToJsonElement(resp.body)-                if (parsed is kotlinx.serialization.json.JsonObject) {-                    val dataEl = parsed["data"]-                    if (dataEl is kotlinx.serialization.json.JsonArray) {-                        json.decodeFromString<List<Reward>>(dataEl.toString())-                    } else emptyList()-                } else emptyList()+                json.decodeFromString<ApiResponse<List<Reward>>>(resp.body).data ?: emptyList()             } else emptyList()         } catch (_: Exception) { emptyList() }     }      // ---- Feedback (POST/GET /orders/{uuid}/feedback) ---- -    suspend fun submitFeedback(orderUuid: String, request: FeedbackRequest): Boolean = try {-        authenticatedRequest(-            "$API/orders/$orderUuid/feedback", "POST",-            json.encodeToString(FeedbackRequest.serializer(), request),-        ).isSuccess-    } catch (e: Exception) { Log.e("BitesApi", "submitFeedback failed", e); false }+    suspend fun submitFeedback(orderUuid: String, request: FeedbackRequest): Boolean = withContext(Dispatchers.Default) {+        try {+            authenticatedRequest(+                "$API/orders/$orderUuid/feedback", "POST",+                json.encodeToString(FeedbackRequest.serializer(), request),+            ).isSuccess+        } catch (e: Exception) { Log.e("BitesApi", "submitFeedback failed", e); false }+    }      suspend fun getFeedback(orderUuid: String): Feedback? =         decodeData("$API/orders/$orderUuid/feedback", Feedback.serializer())@@ -385,13 +389,15 @@ object BitesApi {     // ---- Customer profile ----      /** POST /customers/me — create or update the signed-in customer. */-    suspend fun createOrUpdateCustomer(customer: Customer): Customer? = try {-        val resp = authenticatedRequest(-            "$API/customers/me", "POST",-            json.encodeToString(Customer.serializer(), customer),-        )-        if (!resp.isSuccess) null else unwrap(resp.body, Customer.serializer())-    } catch (e: Exception) { Log.e("BitesApi", "createOrUpdateCustomer failed", e); null }+    suspend fun createOrUpdateCustomer(customer: Customer): Customer? = withContext(Dispatchers.Default) {+        try {+            val resp = authenticatedRequest(+                "$API/customers/me", "POST",+                json.encodeToString(Customer.serializer(), customer),+            )+            if (!resp.isSuccess) null else unwrap(resp.body, Customer.serializer())+        } catch (e: Exception) { Log.e("BitesApi", "createOrUpdateCustomer failed", e); null }+    }      /** DELETE /customers/me — permanent account deletion. */     suspend fun deleteCustomer(): Boolean = try {@@ -458,46 +464,46 @@ object BitesApi {      // ---- Shared decoding helpers ---- -    /** Unwrap the `{message, data}` envelope these endpoints use, falling back to the root. */-    private fun <T> unwrap(body: String, serializer: kotlinx.serialization.KSerializer<T>): T? {+    /**+     * Unwrap the `{message, data}` envelope these endpoints use, falling back to the root.+     * The element is handed straight to the deserializer — re-serialising it to a String and+     * parsing that back is a third full pass plus a duplicate of the whole payload.+     */+    private fun <T> unwrap(body: String, serializer: KSerializer<T>): T? {         val root = json.parseToJsonElement(body)-        val el = (root as? kotlinx.serialization.json.JsonObject)?.get("data") ?: root-        return json.decodeFromString(serializer, el.toString())+        val el = (root as? JsonObject)?.get("data") ?: root+        return json.decodeFromJsonElement(serializer, el)     }      private suspend fun <T> decodeData(         url: String,-        serializer: kotlinx.serialization.KSerializer<T>,-    ): T? = try {-        val resp = authenticatedRequest(url)-        if (!resp.isSuccess) null else unwrap(resp.body, serializer)-    } catch (e: Exception) { Log.e("BitesApi", "GET $url failed", e); null }+        serializer: KSerializer<T>,+    ): T? = withContext(Dispatchers.Default) {+        try {+            val resp = authenticatedRequest(url)+            if (!resp.isSuccess) null else unwrap(resp.body, serializer)+        } catch (e: Exception) { Log.e("BitesApi", "GET $url failed", e); null }+    }      private suspend fun <T> decodeDataList(         url: String,-        serializer: kotlinx.serialization.KSerializer<T>,-    ): List<T> = try {-        val resp = authenticatedRequest(url)-        if (!resp.isSuccess) emptyList()-        else unwrap(resp.body, kotlinx.serialization.builtins.ListSerializer(serializer)) ?: emptyList()-    } catch (e: Exception) { Log.e("BitesApi", "GET $url failed", e); emptyList() }+        serializer: KSerializer<T>,+    ): List<T> = withContext(Dispatchers.Default) {+        try {+            val resp = authenticatedRequest(url)+            if (!resp.isSuccess) emptyList()+            else unwrap(resp.body, ListSerializer(serializer)) ?: emptyList()+        } catch (e: Exception) { Log.e("BitesApi", "GET $url failed", e); emptyList() }+    }      // ---- Checkout ---- -    suspend fun checkout(merchantId: Int, request: CheckoutRequest): CheckoutResponse? {-        return try {+    suspend fun checkout(merchantId: Int, request: CheckoutRequest): CheckoutResponse? = withContext(Dispatchers.Default) {+        try {             val body = json.encodeToString(CheckoutRequest.serializer(), request)-            Log.d("BitesApi", "checkout request body=$body")             val resp = authenticatedRequest("$API/merchants/$merchantId/checkout", "POST", body)-            Log.d("BitesApi", "checkout -> ${resp.status} body=${resp.body.take(2000)}")-            if (resp.isSuccess) {-                val parsed = json.parseToJsonElement(resp.body)-                if (parsed is kotlinx.serialization.json.JsonObject) {-                    val dataEl = parsed["data"]-                    if (dataEl != null) json.decodeFromString<CheckoutResponse>(dataEl.toString())-                    else json.decodeFromString<CheckoutResponse>(resp.body)-                } else null-            } else null+            logd { "checkout -> ${resp.status}" }+            if (resp.isSuccess) unwrap(resp.body, CheckoutResponse.serializer()) else null         } catch (e: Exception) {             Log.e("BitesApi", "checkout failed", e)             null
fooddelivery/src/main/java/com/vayunmathur/fooddelivery/data/AddressStore.kt
diff --git a/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/data/AddressStore.kt b/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/data/AddressStore.ktindex eae89eaf1b..2cfabfae8d 100644--- a/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/data/AddressStore.kt+++ b/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/data/AddressStore.kt@@ -2,9 +2,18 @@ package com.vayunmathur.fooddelivery.data  import android.content.Context import androidx.core.content.edit+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.ExperimentalCoroutinesApi+import kotlinx.coroutines.withContext import kotlinx.serialization.encodeToString import kotlinx.serialization.json.Json +/**+ * Saved delivery addresses. Every accessor is `suspend` and hops to [io]: each one is a+ * SharedPreferences read plus a JSON decode, which must not run on the main thread (and so+ * must not run inside a `remember { }` initialiser either).+ */+@OptIn(ExperimentalCoroutinesApi::class) object AddressStore {      private const val PREFS_NAME = "fooddelivery_addresses"@@ -12,16 +21,19 @@ object AddressStore {      private val json = Json { ignoreUnknownKeys = true } -    fun getAll(context: Context): List<SavedAddress> {-        val raw = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)-            .getString(KEY, null) ?: return emptyList()-        return try {-            json.decodeFromString<List<SavedAddress>>(raw)-        } catch (_: Exception) { emptyList() }+    /**+     * Single writer, so each accessor's read-modify-write runs to completion before the next+     * one starts: two concurrent deletes would otherwise both start from the same list and+     * the second write would put the first one's row back.+     */+    private val io = Dispatchers.IO.limitedParallelism(1)++    suspend fun getAll(context: Context): List<SavedAddress> = withContext(io) {+        read(context)     } -    fun save(context: Context, address: SavedAddress) {-        val list = getAll(context).toMutableList()+    suspend fun save(context: Context, address: SavedAddress) = withContext(io) {+        val list = read(context).toMutableList()         val idx = list.indexOfFirst { it.id == address.id }         val toSave = if (address.isDefault) {             list.map { it.copy(isDefault = false) }.toMutableList()@@ -30,16 +42,25 @@ object AddressStore {         write(context, toSave)     } -    fun delete(context: Context, id: String) {-        write(context, getAll(context).filter { it.id != id })+    suspend fun delete(context: Context, id: String) = withContext(io) {+        write(context, read(context).filter { it.id != id })     } -    fun setDefault(context: Context, id: String) {-        write(context, getAll(context).map { it.copy(isDefault = it.id == id) })+    suspend fun setDefault(context: Context, id: String) = withContext(io) {+        write(context, read(context).map { it.copy(isDefault = it.id == id) })     } -    fun getDefault(context: Context): SavedAddress? {-        return getAll(context).firstOrNull { it.isDefault } ?: getAll(context).firstOrNull()+    suspend fun getDefault(context: Context): SavedAddress? = withContext(io) {+        val all = read(context)+        all.firstOrNull { it.isDefault } ?: all.firstOrNull()+    }++    private fun read(context: Context): List<SavedAddress> {+        val raw = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)+            .getString(KEY, null) ?: return emptyList()+        return try {+            json.decodeFromString<List<SavedAddress>>(raw)+        } catch (_: Exception) { emptyList() }     }      private fun write(context: Context, list: List<SavedAddress>) {
fooddelivery/src/main/java/com/vayunmathur/fooddelivery/data/CartStore.kt
diff --git a/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/data/CartStore.kt b/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/data/CartStore.ktindex 9141b4140b..e3cae05ba5 100644--- a/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/data/CartStore.kt+++ b/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/data/CartStore.kt@@ -2,9 +2,16 @@ package com.vayunmathur.fooddelivery.data  import android.content.Context import androidx.core.content.edit+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.ExperimentalCoroutinesApi+import kotlinx.coroutines.SupervisorJob+import kotlinx.coroutines.launch+import kotlinx.coroutines.withContext import kotlinx.serialization.encodeToString import kotlinx.serialization.json.Json +@OptIn(ExperimentalCoroutinesApi::class) object CartStore {      private const val PREFS_NAME = "fooddelivery_cart"@@ -20,21 +27,37 @@ object CartStore {      private val json = Json { ignoreUnknownKeys = true } -    fun getAll(context: Context): List<CartItem> {+    /**+     * Single writer, so back-to-back mutations commit in the order they were made — a save+     * must not overtake the clear that follows a placed order.+     */+    private val io = Dispatchers.IO.limitedParallelism(1)++    /** Outlives composition: a cart edit has to be persisted even if the screen goes away. */+    private val scope = CoroutineScope(SupervisorJob() + io)++    suspend fun getAll(context: Context): List<CartItem> = withContext(io) {         val raw = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)-            .getString(KEY, null) ?: return emptyList()-        return try {+            .getString(KEY, null) ?: return@withContext emptyList()+        try {             json.decodeFromString<List<CartItem>>(raw)         } catch (_: Exception) { emptyList() }     }      fun save(context: Context, items: List<CartItem>) {-        context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)-            .edit { putString(KEY, json.encodeToString(items)) }+        val appCtx = context.applicationContext+        val snapshot = items.toList()+        scope.launch {+            appCtx.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)+                .edit { putString(KEY, json.encodeToString(snapshot)) }+        }     }      fun clear(context: Context) {-        context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)-            .edit { remove(KEY) }+        val appCtx = context.applicationContext+        scope.launch {+            appCtx.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)+                .edit { remove(KEY) }+        }     } }
fooddelivery/src/main/java/com/vayunmathur/fooddelivery/data/Models.kt
diff --git a/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/data/Models.kt b/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/data/Models.ktindex 9072faf36c..1b48de1b04 100644--- a/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/data/Models.kt+++ b/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/data/Models.kt@@ -334,6 +334,16 @@ data class Order(             return 3958.8 * 2 * Math.atan2(Math.sqrt(h), Math.sqrt(1 - h))         } +    /**+     * The ISO timestamps this order's stage and ETA are derived from, parsed once. Parsing is+     * the expensive part and it does not depend on the clock, so it is what gets memoised —+     * [stage] and [etaMillis] stay recomputed so a wall-clock transition still surfaces on a+     * list that isn't re-fetched. Delegated properties are not part of the serialized form.+     */+    private val pickupReadyAtMillis: Long? by lazy { parseIsoMillis(pickupReadyAt) }+    private val dueAtMillis: Long? by lazy { parseIsoMillis(dueAt) }+    private val liveDeliveryEtaMillis: Long? by lazy { parseIsoMillis(liveDeliveryEta) }+     /** Mirrors the reference's status ladder, including its ordering. */     val stage: OrderStage         get() {@@ -348,9 +358,9 @@ data class Order(             if (pickedupAt != null) return OrderStage.DRIVING             if (driverReachedMerchantAt != null) return OrderStage.READY             val now = System.currentTimeMillis()-            val ready = parseIsoMillis(pickupReadyAt)+            val ready = pickupReadyAtMillis             if (ready != null && ready <= now) return OrderStage.READY-            val due = parseIsoMillis(dueAt)+            val due = dueAtMillis             // More than 30 minutes out, the reference shows "Preparing Soon".             if (due != null && due - now > 1_800_000L) return OrderStage.PREPARING_SOON             return OrderStage.PREPARING@@ -363,8 +373,8 @@ data class Order(      */     val etaMillis: Long?         get() {-            val live = parseIsoMillis(liveDeliveryEta)-            val due = parseIsoMillis(dueAt)+            val live = liveDeliveryEtaMillis+            val due = dueAtMillis             return when {                 live != null && due != null -> max(live, due)                 else -> live ?: due@@ -434,6 +444,12 @@ data class CartItem(     val merchantId: Int = 0,     val merchantName: String = "",     val specialInstructions: String? = null,+    /**+     * Per-line identity so a lazy list can key on it: two cart lines can otherwise be+     * entirely equal, and keying on position makes a mid-list removal shift every later+     * row's identity. Only has to be stable while the cart is on screen.+     */+    val lineId: String = java.util.UUID.randomUUID().toString(), ) {     /** Modifier prices count per unit of the modifier, then the whole line by item quantity. */     val totalPrice: Double@@ -661,12 +677,61 @@ data class CheckoutResponse( /**  * Parse an ISO-8601 timestamp to epoch millis, tolerating the `Z` suffix and fractional  * seconds the API returns. Returns null for null/blank/malformed input.+ *+ * The common `yyyy-MM-ddTHH:mm:ss[.fff][Z]` shape is parsed by hand so a well-formed+ * timestamp never goes through exception-driven control flow; anything else falls back to+ * java.time.  */ internal fun parseIsoMillis(iso: String?): Long? {     if (iso.isNullOrBlank()) return null+    fastParseIsoMillis(iso)?.let { return it }     return runCatching { java.time.Instant.parse(iso).toEpochMilli() }.getOrNull()         ?: runCatching {             java.time.LocalDateTime.parse(iso.substringBefore('Z'))                 .toInstant(java.time.ZoneOffset.UTC).toEpochMilli()         }.getOrNull() }++/** `yyyy-MM-ddTHH:mm:ss[.fff][Z]`, UTC, with no exceptions on the way through. */+private fun fastParseIsoMillis(iso: String): Long? {+    if (iso.length < 19) return null+    if (iso[4] != '-' || iso[7] != '-' || iso[10] != 'T' || iso[13] != ':' || iso[16] != ':') return null+    val year = iso.digits(0, 4) ?: return null+    val month = iso.digits(5, 7) ?: return null+    val day = iso.digits(8, 10) ?: return null+    val hour = iso.digits(11, 13) ?: return null+    val minute = iso.digits(14, 16) ?: return null+    val second = iso.digits(17, 19) ?: return null+    if (month !in 1..12 || hour !in 0..23 || minute !in 0..59 || second !in 0..59) return null+    val isLeap = year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)+    val daysInMonth = when (month) {+        1, 3, 5, 7, 8, 10, 12 -> 31+        4, 6, 9, 11 -> 30+        else -> if (isLeap) 29 else 28+    }+    if (day !in 1..daysInMonth) return null++    var millis = 0+    var rest = iso.substring(19)+    if (rest.startsWith('.')) {+        val fraction = rest.drop(1).takeWhile { it in '0'..'9' }+        if (fraction.isEmpty()) return null+        millis = fraction.take(3).padEnd(3, '0').toInt()+        rest = rest.drop(1 + fraction.length)+    }+    // Only UTC (or an absent zone, which the API means as UTC) takes the fast path.+    if (rest.isNotEmpty() && rest != "Z") return null++    val epochDay = java.time.LocalDate.of(year, month, day).toEpochDay()+    return (epochDay * 86_400L + hour * 3_600L + minute * 60L + second) * 1_000L + millis+}++private fun String.digits(from: Int, to: Int): Int? {+    var value = 0+    for (i in from until to) {+        val c = this[i]+        if (c < '0' || c > '9') return null+        value = value * 10 + (c - '0')+    }+    return value+}
fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ipc/OrderLookupProvider.kt
diff --git a/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ipc/OrderLookupProvider.kt b/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ipc/OrderLookupProvider.ktindex 824bc69472..c879f1788f 100644--- a/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ipc/OrderLookupProvider.kt+++ b/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ipc/OrderLookupProvider.kt@@ -2,15 +2,19 @@ package com.vayunmathur.fooddelivery.ipc  import android.content.ContentProvider import android.content.ContentValues-import android.content.Context import android.database.Cursor import android.database.MatrixCursor import android.net.Uri import com.vayunmathur.fooddelivery.api.BitesApi import com.vayunmathur.fooddelivery.data.Merchant-import com.vayunmathur.library.network.NetworkClient-import com.vayunmathur.library.network.TrustBundle+import com.vayunmathur.fooddelivery.platform.AppInit+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.ExperimentalCoroutinesApi+import kotlinx.coroutines.SupervisorJob+import kotlinx.coroutines.async import kotlinx.coroutines.runBlocking+import kotlinx.coroutines.withTimeoutOrNull import kotlin.math.atan2 import kotlin.math.cos import kotlin.math.sin@@ -33,20 +37,15 @@ import kotlin.math.sqrt  * row rather than throwing across the binder — the caller then simply shows no  * Order button.  */+@OptIn(ExperimentalCoroutinesApi::class) class OrderLookupProvider : ContentProvider() {      override fun onCreate(): Boolean {-        // A provider can be created before any Activity runs, so make sure the-        // network stack (TLS trust bundle) and any saved auth token are ready —-        // MainActivity does the same on its own launch path.+        // A provider is created on the main thread before Application.onCreate and before+        // any Activity, so kick the network/token warm-up off to a background thread and+        // return immediately rather than paying for it here. [findMatch] awaits it.         val ctx = context ?: return false-        try {-            NetworkClient.init(ctx, TrustBundle.STANDARD)-            val prefs = ctx.getSharedPreferences("fooddelivery_prefs", Context.MODE_PRIVATE)-            prefs.getString("token_json", null)?.let { BitesApi.restoreToken(it) }-        } catch (_: Exception) {-            // Best-effort; a lookup that then fails just returns not-orderable.-        }+        AppInit.start(ctx)         return true     } @@ -86,8 +85,21 @@ class OrderLookupProvider : ContentProvider() {         val target = normalize(name)         if (target.isEmpty()) return null -        val merchants = runBlocking { BitesApi.getMerchants(lat, lng) }-        if (merchants.isEmpty()) return null+        // This runs on a binder thread out of a 16-strong pool, and the request underneath+        // can take the engine's full 30s connect / 60s read budget (three times over, if the+        // auth path retries). Bound the wait: query() degrades to orderable=0 on a null match,+        // so giving up is strictly better than holding the transaction open. The fetch runs on+        // a scope of its own — cancelling a coroutine parked in a blocking socket read does not+        // unblock it, so the timeout has to sit on a separate, cancellable suspension point.+        val fetch = lookupScope.async {+            AppInit.awaitReady()+            BitesApi.getMerchants(lat, lng)+        }+        val merchants = runBlocking {+            withTimeoutOrNull(LOOKUP_TIMEOUT_MS) { fetch.await() }+        }+        if (merchants == null) fetch.cancel()+        if (merchants.isNullOrEmpty()) return null          // Keep only merchants that are plausibly the same place: close enough AND         // whose normalised name matches (equal / prefix / containment). Pick the@@ -128,5 +140,17 @@ class OrderLookupProvider : ContentProvider() {     companion object {         /** How close a merchant must be to the queried point to be the same place. */         private const val MATCH_RADIUS_METERS = 800.0++        /** Total budget for warm-up plus catalog fetch on the binder thread. */+        private const val LOOKUP_TIMEOUT_MS = 3_000L++        private val lookupScope =+            CoroutineScope(SupervisorJob() + Dispatchers.IO.limitedParallelism(MAX_INFLIGHT_LOOKUPS))++        /**+         * A timed-out fetch keeps its thread until the engine's own timeouts fire, so cap how+         * many can be in flight rather than letting a chatty caller drain [Dispatchers.IO].+         */+        private const val MAX_INFLIGHT_LOOKUPS = 4     } }
fooddelivery/src/main/java/com/vayunmathur/fooddelivery/notifications/OrderTrackingService.kt
diff --git a/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/notifications/OrderTrackingService.kt b/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/notifications/OrderTrackingService.ktindex 682fd576dc..32bbbd2731 100644--- a/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/notifications/OrderTrackingService.kt+++ b/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/notifications/OrderTrackingService.kt@@ -11,6 +11,7 @@ import android.util.Log import androidx.core.app.NotificationManagerCompat import com.vayunmathur.fooddelivery.api.BitesApi import com.vayunmathur.fooddelivery.data.Order+import com.vayunmathur.fooddelivery.platform.AppInit import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job@@ -64,6 +65,8 @@ class OrderTrackingService : Service() {     }      private suspend fun pollLoop(orderId: Int) {+        // The saved auth token is restored by the background warm-up.+        AppInit.awaitReady()         while (true) {             val order = runCatching {                 BitesApi.getOrders().firstOrNull { it.id == orderId }
fooddelivery/src/main/java/com/vayunmathur/fooddelivery/platform/AppInit.kt
diff --git a/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/platform/AppInit.kt b/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/platform/AppInit.ktnew file mode 100644index 0000000000..b60980fb0e--- /dev/null+++ b/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/platform/AppInit.kt@@ -0,0 +1,70 @@+package com.vayunmathur.fooddelivery.platform++import android.content.Context+import android.util.Log+import androidx.core.content.edit+import com.vayunmathur.fooddelivery.api.BitesApi+import com.vayunmathur.library.network.NetworkClient+import com.vayunmathur.library.network.TrustBundle+import kotlinx.coroutines.CompletableDeferred+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.SupervisorJob+import kotlinx.coroutines.launch+import java.util.concurrent.atomic.AtomicBoolean++/**+ * Process-wide warm-up, run off the main thread.+ *+ * [NetworkClient.init] opens and X.509-parses the bundled DER roots, fills a KeyStore and+ * initialises an SSLContext, and the saved auth token has to be read out of+ * SharedPreferences and JSON-decoded — none of which may happen on the main thread or a+ * binder thread. Both process entry points ([com.vayunmathur.fooddelivery.FoodDeliveryApplication]+ * and [com.vayunmathur.fooddelivery.ipc.OrderLookupProvider], which is created first) call+ * [start], which is idempotent; anything that needs the token or the pinned trust anchors+ * awaits [awaitReady] from a coroutine instead of blocking.+ */+object AppInit {++    private const val PREFS_NAME = "fooddelivery_prefs"+    private const val KEY_TOKEN = "token_json"++    private val started = AtomicBoolean(false)+    private val ready = CompletableDeferred<Unit>()+    private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)++    fun start(context: Context) {+        if (!started.compareAndSet(false, true)) return+        val appCtx = context.applicationContext+        scope.launch {+            // Kept in separate try blocks: a trust-bundle failure must not also skip the token+            // restore, or one bad DER root would silently sign the user out and — because+            // onTokenUpdated would never be installed — stop the next login from persisting.+            try {+                // api.deliverycollective.com is on AWS Elastic Beanstalk and serves an ACM cert+                // chaining to Amazon Root CA 1, which FIRST_PARTY (ISRG + GTS only) doesn't carry —+                // pinning to it fails the handshake before any request goes out. STANDARD adds the+                // Amazon roots.+                NetworkClient.init(appCtx, TrustBundle.STANDARD)+            } catch (e: Exception) {+                Log.w("AppInit", "network warm-up failed", e)+            }+            try {+                val prefs = appCtx.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)+                // The application context, not an Activity: BitesApi outlives every Activity.+                BitesApi.onTokenUpdated = { tokenJson ->+                    prefs.edit { putString(KEY_TOKEN, tokenJson) }+                }+                prefs.getString(KEY_TOKEN, null)?.let { BitesApi.restoreToken(it) }+            } catch (e: Exception) {+                Log.w("AppInit", "token warm-up failed", e)+            } finally {+                ready.complete(Unit)+            }+        }+    }++    suspend fun awaitReady() {+        ready.await()+    }+}
fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/AccountScreen.kt
diff --git a/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/AccountScreen.kt b/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/AccountScreen.ktindex c0a7cb9864..b708d839d8 100644--- a/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/AccountScreen.kt+++ b/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/AccountScreen.kt@@ -59,6 +59,7 @@ import com.vayunmathur.fooddelivery.data.CustomerSavings import com.vayunmathur.fooddelivery.data.PlatformSavings import com.vayunmathur.fooddelivery.data.Referral import com.vayunmathur.fooddelivery.data.SavedAddress+import com.vayunmathur.fooddelivery.platform.AppInit import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext@@ -80,6 +81,9 @@ fun AccountScreen() {     var editingProfile by remember { mutableStateOf(false) }     var loading by remember { mutableStateOf(true) }     var loggedIn by remember { mutableStateOf(BitesApi.isLoggedIn()) }+    // The saved token is restored by the background warm-up, so "signed out" isn't known to+    // be true until that has landed — don't offer the sign-in card before then.+    var authResolved by remember { mutableStateOf(BitesApi.isLoggedIn()) }      var stateId by remember { mutableStateOf<String?>(null) }     var phone by remember { mutableStateOf("") }@@ -87,7 +91,8 @@ fun AccountScreen() {     var codeSent by remember { mutableStateOf(false) }     var authLoading by remember { mutableStateOf(false) } -    var addresses by remember { mutableStateOf(AddressStore.getAll(context)) }+    var addresses by remember { mutableStateOf<List<SavedAddress>>(emptyList()) }+    var addressesLoaded by remember { mutableStateOf(false) }     var showAddAddress by remember { mutableStateOf(false) }     var editingAddress by remember { mutableStateOf<SavedAddress?>(null) }     var addrLabel by remember { mutableStateOf("") }@@ -130,6 +135,19 @@ fun AccountScreen() {         showAddAddress = true     } +    LaunchedEffect(Unit) {+        addresses = AddressStore.getAll(context)+        addressesLoaded = true+    }++    // The saved token is restored by the background warm-up, so re-read the login state once+    // it has landed instead of assuming the initial (possibly pre-restore) answer.+    LaunchedEffect(Unit) {+        AppInit.awaitReady()+        if (!loggedIn) loggedIn = BitesApi.isLoggedIn()+        authResolved = true+    }+     LaunchedEffect(loggedIn) {         if (loggedIn) {             customer = BitesApi.getCustomer()@@ -140,18 +158,13 @@ fun AccountScreen() {         loading = false     } -    BitesApi.onTokenUpdated = { tokenJson ->-        context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)-            .edit { putString(KEY_TOKEN, tokenJson) }-    }-     Scaffold { padding ->         Column(             Modifier.fillMaxSize().padding(padding)                 .verticalScroll(rememberScrollState()).padding(16.dp),             verticalArrangement = Arrangement.spacedBy(16.dp)         ) {-            if (!loggedIn) {+            if (!loggedIn && authResolved) {                 Card(Modifier.fillMaxWidth()) {                     Column(Modifier.padding(16.dp),                         horizontalAlignment = Alignment.CenterHorizontally) {@@ -219,7 +232,7 @@ fun AccountScreen() {                         }                     }                 }-            } else {+            } else if (loggedIn) {                 if (editingProfile) {                     customer?.let { c ->                         EditProfileDialog(@@ -426,7 +439,7 @@ fun AccountScreen() {                 }             } -            if (addresses.isEmpty() && !showAddAddress) {+            if (addressesLoaded && addresses.isEmpty() && !showAddAddress) {                 Text(stringResource(R.string.no_saved_addresses_tap_to_add_one),                     style = MaterialTheme.typography.bodyMedium,                     color = MaterialTheme.colorScheme.onSurfaceVariant)@@ -466,8 +479,10 @@ fun AccountScreen() {                                 }                             }                             IconButton(onClick = {-                                AddressStore.delete(context, addr.id)-                                addresses = AddressStore.getAll(context)+                                scope.launch {+                                    AddressStore.delete(context, addr.id)+                                    addresses = AddressStore.getAll(context)+                                }                             }) {                                 IconDelete(modifier = Modifier.size(20.dp),                                     tint = MaterialTheme.colorScheme.error)@@ -476,8 +491,10 @@ fun AccountScreen() {                         Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {                             if (!addr.isDefault) {                                 TextButton(onClick = {-                                    AddressStore.setDefault(context, addr.id)-                                    addresses = AddressStore.getAll(context)+                                    scope.launch {+                                        AddressStore.setDefault(context, addr.id)+                                        addresses = AddressStore.getAll(context)+                                    }                                 }) {                                     Text(stringResource(R.string.set_default), style = MaterialTheme.typography.labelMedium)                                 }
fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/CartScreen.kt
diff --git a/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/CartScreen.kt b/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/CartScreen.ktindex bbd4c4aa7c..676fe8a17e 100644--- a/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/CartScreen.kt+++ b/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/CartScreen.kt@@ -15,7 +15,7 @@ import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.foundation.lazy.LazyColumn-import androidx.compose.foundation.lazy.items+import androidx.compose.foundation.lazy.itemsIndexed import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf@@ -85,8 +85,7 @@ fun CartScreen(                     verticalArrangement = Arrangement.spacedBy(8.dp),                     modifier = Modifier.weight(1f)                 ) {-                    items(items.size) { index ->-                        val item = items[index]+                    itemsIndexed(items, key = { _, item -> item.lineId }) { index, item ->                         CartItemRow(                             item = item,                             onRemove = { onRemoveItem(index) },
fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/CheckoutScreen.kt
diff --git a/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/CheckoutScreen.kt b/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/CheckoutScreen.ktindex 1cd599eff3..c9a553e257 100644--- a/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/CheckoutScreen.kt+++ b/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/CheckoutScreen.kt@@ -14,6 +14,7 @@ import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.foundation.lazy.LazyColumn+import androidx.compose.foundation.lazy.itemsIndexed import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect@@ -47,6 +48,7 @@ import com.vayunmathur.library.ui.SegmentedButton import com.vayunmathur.library.ui.SingleChoiceSegmentedButtonRow import com.vayunmathur.library.ui.Text import com.vayunmathur.fooddelivery.api.BitesApi+import com.vayunmathur.fooddelivery.BuildConfig import com.vayunmathur.fooddelivery.data.AddressStore import com.vayunmathur.fooddelivery.data.CartItem import com.vayunmathur.fooddelivery.data.CheckoutAddress@@ -55,8 +57,10 @@ import com.vayunmathur.fooddelivery.data.CheckoutRequest import com.vayunmathur.fooddelivery.data.Customer import com.vayunmathur.fooddelivery.data.Deal import com.vayunmathur.fooddelivery.data.OrderRewards+import com.vayunmathur.fooddelivery.data.SavedAddress import com.vayunmathur.fooddelivery.data.CheckoutResponse import com.vayunmathur.fooddelivery.notifications.OrderTrackingService+import com.vayunmathur.fooddelivery.platform.AppInit import android.util.Log import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.delay@@ -72,7 +76,7 @@ fun CheckoutScreen(      var isPickup by remember { mutableStateOf(false) }     var tipCents by remember { mutableIntStateOf(300) }-    var deliveryInstructions by remember { mutableStateOf(AddressStore.getDefault(context)?.deliveryInstructions ?: "") }+    var deliveryInstructions by remember { mutableStateOf("") }     var paying by remember { mutableStateOf(false) }     var fetchingPrices by remember { mutableStateOf(false) }     var error by remember { mutableStateOf<String?>(null) }@@ -88,11 +92,29 @@ fun CheckoutScreen(     var lastOrderUuid by remember { mutableStateOf<String?>(null) }     var selectedDealId by remember { mutableStateOf<Int?>(null) } -    val addresses = remember { AddressStore.getAll(context) }-    var selectedAddress by remember { mutableStateOf(AddressStore.getDefault(context)) }+    // One prefs read plus one JSON decode, off the main thread — the default address is+    // picked out of the list already in hand rather than re-reading the store for it.+    var addresses by remember { mutableStateOf<List<SavedAddress>>(emptyList()) }+    var addressesLoaded by remember { mutableStateOf(false) }+    var selectedAddress by remember { mutableStateOf<SavedAddress?>(null) }++    LaunchedEffect(Unit) {+        val all = AddressStore.getAll(context)+        val default = all.firstOrNull { it.isDefault } ?: all.firstOrNull()+        addresses = all+        selectedAddress = default+        // Don't overwrite anything typed while the read was in flight.+        if (deliveryInstructions.isEmpty()) {+            deliveryInstructions = default?.deliveryInstructions ?: ""+        }+        addressesLoaded = true+    }      // The reference sends the customer's identity with every checkout.-    LaunchedEffect(Unit) { customer = BitesApi.getCustomer() }+    LaunchedEffect(Unit) {+        AppInit.awaitReady()+        customer = BitesApi.getCustomer()+    }      val subtotalCents = items.sumOf {         (it.menuItem.price + it.selectedModifiers.sumOf { m -> m.price * m.quantity }) * it.quantity@@ -108,11 +130,13 @@ fun CheckoutScreen(      // Deals the merchant currently has running; picking one sends its dealId with checkout.     LaunchedEffect(merchantId) {+        AppInit.awaitReady()         deals = if (merchantId != 0) BitesApi.getActiveDealsByMerchant(merchantId) else emptyList()     }      LaunchedEffect(isPickup, tipCents, selectedAddress?.id, promoCode, customer?.uuid, selectedDealId) {         if (!canFetch) return@LaunchedEffect+        AppInit.awaitReady()         checkoutResponse = null         error = null         fetchingPrices = true@@ -154,12 +178,13 @@ fun CheckoutScreen(             phone = customer?.phone?.ifBlank { null },         )         val response = BitesApi.checkout(merchantId, request)-        Log.d("Checkout", "response.order=${response?.order}")-        Log.d("Checkout", "response.clientSecret=${response?.clientSecret?.take(20)}")-        Log.d("Checkout", "response.serviceable=${response?.serviceable}")-        if (response?.order != null) {-            val o = response.order-            Log.d("Checkout", "order: foodTotal=${o.foodTotal} taxes=${o.taxes} deliveryFee=${o.deliveryFee} fees=${o.fees} tips=${o.tips} displayTotal=${o.displayTotal}")+        if (BuildConfig.DEV_BUILD) {+            Log.d("Checkout", "response.order=${response?.order}")+            Log.d("Checkout", "response.clientSecret=${response?.clientSecret?.take(20)}")+            Log.d("Checkout", "response.serviceable=${response?.serviceable}")+            response?.order?.let { o ->+                Log.d("Checkout", "order: foodTotal=${o.foodTotal} taxes=${o.taxes} deliveryFee=${o.deliveryFee} fees=${o.fees} tips=${o.tips} displayTotal=${o.displayTotal}")+            }         }         // Reuse the draft order on the next re-price; drop it if this call failed so we         // don't keep asking the server to update an order it can't find.@@ -184,7 +209,9 @@ fun CheckoutScreen(         val orderUuid = confirmedOrder?.uuid?.takeIf { it.isNotBlank() }         rewards = if (customer == null || orderUuid == null) null         else BitesApi.getOrderRewards(orderUuid)-        Log.d("Checkout", "rewardsAvailable=${rewards?.rewardsAvailable} rate=${rewards?.rewardsRate}")+        if (BuildConfig.DEV_BUILD) {+            Log.d("Checkout", "rewardsAvailable=${rewards?.rewardsAvailable} rate=${rewards?.rewardsRate}")+        }     }      // Cross-check against what Stripe will really charge; UI follows the reference formula,@@ -198,7 +225,7 @@ fun CheckoutScreen(             }.onFailure { Log.w("Checkout", "PaymentIntent lookup failed", it) }.getOrNull()         } ?: return@LaunchedEffect         val shown = payTotal ?: return@LaunchedEffect-        if (kotlin.math.abs(amount / 100.0 - shown) > 0.005) {+        if (kotlin.math.abs(amount / 100.0 - shown) > 0.005 && BuildConfig.DEV_BUILD) {             Log.w("Checkout", "MISMATCH: stripe=${amount / 100.0} shown=$shown " +                 "componentTotal=${confirmedOrder.componentTotal} rewards=${rewards?.rewardsAvailable}")         }@@ -256,8 +283,7 @@ fun CheckoutScreen(                     Spacer(Modifier.height(8.dp))                 } -                items(items.size) { index ->-                    val item = items[index]+                itemsIndexed(items, key = { _, item -> item.lineId }) { _, item ->                     Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween) {                         Column(Modifier.weight(1f)) {                             Text("${item.quantity}x ${item.menuItem.name}",@@ -304,9 +330,11 @@ fun CheckoutScreen(                         Spacer(Modifier.height(8.dp))                          if (addresses.isEmpty()) {-                            Text(stringResource(R.string.no_saved_addresses_add_one_in_account_se),-                                style = MaterialTheme.typography.bodyMedium,-                                color = MaterialTheme.colorScheme.onSurfaceVariant)+                            if (addressesLoaded) {+                                Text(stringResource(R.string.no_saved_addresses_add_one_in_account_se),+                                    style = MaterialTheme.typography.bodyMedium,+                                    color = MaterialTheme.colorScheme.onSurfaceVariant)+                            }                         } else {                             addresses.forEach { addr ->                                 val isSelected = selectedAddress?.id == addr.id
fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/DealsScreen.kt
diff --git a/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/DealsScreen.kt b/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/DealsScreen.ktindex 3d2a8a05aa..dc0b0bf254 100644--- a/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/DealsScreen.kt+++ b/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/DealsScreen.kt@@ -42,6 +42,15 @@ import com.vayunmathur.fooddelivery.R import com.vayunmathur.fooddelivery.api.BitesApi import com.vayunmathur.fooddelivery.data.Deal import com.vayunmathur.fooddelivery.data.DealProgress+import com.vayunmathur.fooddelivery.platform.AppInit+import kotlinx.coroutines.async+import kotlinx.coroutines.awaitAll+import kotlinx.coroutines.coroutineScope+import kotlinx.coroutines.sync.Semaphore+import kotlinx.coroutines.sync.withPermit++/** Concurrent per-deal progress requests in flight at once. */+private const val MAX_PARALLEL_PROGRESS = 6  /**  * Browse every active deal on the platform. Tapping one opens its merchant so the deal@@ -54,10 +63,17 @@ fun DealsScreen(onMerchantClick: (Int) -> Unit) {     var loading by remember { mutableStateOf(true) }      LaunchedEffect(Unit) {+        AppInit.awaitReady()         deals = BitesApi.getAllDeals().filter { it.isActive }         loading = false-        // Progress is per-deal; fetch after the list so the deals render immediately.-        progress = deals.mapNotNull { d -> BitesApi.getDealProgress(d.id)?.let { d.id to it } }.toMap()+        // Progress is per-deal; fetch after the list so the deals render immediately, and+        // fan the round trips out rather than paying for them one after another.+        val gate = Semaphore(MAX_PARALLEL_PROGRESS)+        progress = coroutineScope {+            deals.map { d ->+                async { gate.withPermit { BitesApi.getDealProgress(d.id)?.let { d.id to it } } }+            }.awaitAll().filterNotNull().toMap()+        }     }      Scaffold { padding ->@@ -79,6 +95,9 @@ fun DealsScreen(onMerchantClick: (Int) -> Unit) {                 verticalArrangement = Arrangement.spacedBy(12.dp),                 modifier = Modifier.padding(padding),             ) {+                // Deliberately unkeyed: Deal.id is its only identity and decodes to 0 for any+                // row the server sends without one, so a key risks the duplicate-key crash. It+                // would buy nothing anyway — `deals` is assigned once and never replaced.                 items(deals) { deal ->                     DealCard(                         deal = deal,
fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/HomeScreen.kt
diff --git a/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/HomeScreen.kt b/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/HomeScreen.ktindex f2f359d69d..a506c16db9 100644--- a/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/HomeScreen.kt+++ b/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/HomeScreen.kt@@ -45,6 +45,7 @@ import com.vayunmathur.library.ui.Text import com.vayunmathur.fooddelivery.api.BitesApi import com.vayunmathur.fooddelivery.data.AddressStore import com.vayunmathur.fooddelivery.data.Merchant+import com.vayunmathur.fooddelivery.platform.AppInit  @Composable fun HomeScreen(onMerchantClick: (Int) -> Unit) {@@ -54,6 +55,9 @@ fun HomeScreen(onMerchantClick: (Int) -> Unit) {     var noAddress by remember { mutableStateOf(false) }      LaunchedEffect(Unit) {+        // The saved token is restored by the background warm-up; wait for it so a signed-in+        // session isn't asked for the catalog anonymously.+        AppInit.awaitReady()         val defaultAddr = AddressStore.getDefault(context)         if (defaultAddr != null) {             merchants = BitesApi.getMerchants(lat = defaultAddr.latitude, lng = defaultAddr.longitude)@@ -121,6 +125,10 @@ fun HomeContent(                 horizontalArrangement = Arrangement.spacedBy(12.dp),                 modifier = Modifier.padding(padding)             ) {+                // Deliberately unkeyed: /merchants/all/stores can return several store rows+                // per merchant and Merchant has no id-independent identity, so a key risks the+                // duplicate-key crash. It would buy nothing anyway — `merchants` is assigned+                // once and never replaced while the grid is on screen.                 items(merchants) { merchant ->                     MerchantCard(merchant) { onMerchantClick(merchant.id) }                 }
fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/OrderTrackingScreen.kt
diff --git a/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/OrderTrackingScreen.kt b/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/OrderTrackingScreen.ktindex 045fb5d844..be75f38212 100644--- a/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/OrderTrackingScreen.kt+++ b/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/OrderTrackingScreen.kt@@ -60,6 +60,7 @@ import com.vayunmathur.fooddelivery.api.BitesApi import com.vayunmathur.fooddelivery.data.Order import com.vayunmathur.fooddelivery.data.OrderStage import com.vayunmathur.fooddelivery.notifications.OrderTrackingService+import com.vayunmathur.fooddelivery.platform.AppInit import kotlinx.coroutines.delay import kotlin.time.Instant import com.vayunmathur.library.ui.DateString@@ -84,6 +85,7 @@ fun OrderTrackingScreen(orderId: Int, onBack: () -> Unit) {     var loading by remember { mutableStateOf(true) }      LaunchedEffect(orderId) {+        AppInit.awaitReady()         // Keep the background Live Update tracker running for this order too, so tracking         // opened from the Orders tab (or a re-opened app) is covered. Idempotent.         OrderTrackingService.start(context, orderId)
fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/OrdersScreen.kt
diff --git a/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/OrdersScreen.kt b/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/OrdersScreen.ktindex 30cf0c425d..4ddf635f98 100644--- a/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/OrdersScreen.kt+++ b/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/OrdersScreen.kt@@ -15,7 +15,7 @@ import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.foundation.lazy.LazyColumn-import androidx.compose.foundation.lazy.items+import androidx.compose.foundation.lazy.itemsIndexed import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.runtime.Composable@@ -52,6 +52,7 @@ import com.vayunmathur.library.ui.TextButton import com.vayunmathur.fooddelivery.api.BitesApi import com.vayunmathur.fooddelivery.data.FeedbackRequest import com.vayunmathur.fooddelivery.data.Order+import com.vayunmathur.fooddelivery.platform.AppInit import java.util.Locale import kotlinx.coroutines.launch import kotlinx.datetime.LocalDateTime@@ -63,10 +64,10 @@ import com.vayunmathur.library.ui.rememberIs24Hour  @Composable fun OrdersScreen(onTrackOrder: (Int) -> Unit = {}) {-    val isLoggedIn = remember { BitesApi.isLoggedIn() }+    var isLoggedIn by remember { mutableStateOf(false) }      var orders by remember { mutableStateOf<List<Order>>(emptyList()) }-    var loading by remember { mutableStateOf(isLoggedIn) }+    var loading by remember { mutableStateOf(true) }     var ratingOrder by remember { mutableStateOf<Order?>(null) }     val scope = rememberCoroutineScope() @@ -94,14 +95,22 @@ fun OrdersScreen(onTrackOrder: (Int) -> Unit = {}) {     }      LaunchedEffect(Unit) {+        // The saved token is restored by the background warm-up, so wait for it before+        // deciding whether this is a signed-in session.+        AppInit.awaitReady()+        isLoggedIn = BitesApi.isLoggedIn()         if (isLoggedIn) {             orders = BitesApi.getOrders()-            loading = false         }+        loading = false     }      Scaffold { padding ->-        if (!isLoggedIn) {+        if (loading) {+            Box(Modifier.fillMaxSize().padding(padding), contentAlignment = Alignment.Center) {+                CircularProgressIndicator()+            }+        } else if (!isLoggedIn) {             Box(Modifier.fillMaxSize().padding(padding), contentAlignment = Alignment.Center) {                 Column(horizontalAlignment = Alignment.CenterHorizontally) {                     IconPerson(modifier = Modifier.size(48.dp),@@ -114,10 +123,6 @@ fun OrdersScreen(onTrackOrder: (Int) -> Unit = {}) {                         color = MaterialTheme.colorScheme.onSurfaceVariant)                 }             }-        } else if (loading) {-            Box(Modifier.fillMaxSize().padding(padding), contentAlignment = Alignment.Center) {-                CircularProgressIndicator()-            }         } else if (orders.isEmpty()) {             Box(Modifier.fillMaxSize().padding(padding), contentAlignment = Alignment.Center) {                 Column(horizontalAlignment = Alignment.CenterHorizontally) {@@ -132,12 +137,28 @@ fun OrdersScreen(onTrackOrder: (Int) -> Unit = {}) {                 }             }         } else {+            // uuid is the server's per-order key (every /orders/{uuid}/... endpoint is keyed by+            // it) and the id is already load-bearing as a unique lookup elsewhere+            // (OrderTrackingScreen/Service re-find an order by id in this very list), so the pair+            // identifies a row. Rows that decode without either — both fields have lenient+            // defaults — would still collide, and Compose throws on a duplicate key, so any+            // repeat gets an ordinal. Keying is worth it here because marking a pickup collected+            // replaces the whole list.+            val orderKeys = remember(orders) {+                val seen = mutableMapOf<String, Int>()+                orders.map { order ->+                    val base = "${order.uuid.orEmpty()}#${order.id}"+                    val n = (seen[base] ?: 0) + 1+                    seen[base] = n+                    if (n == 1) base else "$base~$n"+                }+            }             LazyColumn(                 contentPadding = PaddingValues(16.dp),                 verticalArrangement = Arrangement.spacedBy(12.dp),                 modifier = Modifier.padding(padding)             ) {-                items(orders) { order ->+                itemsIndexed(orders, key = { index, _ -> orderKeys[index] }) { _, order ->                     OrderCard(                         order = order,                         // Only in-flight deliveries have anything to track.
fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/RestaurantScreen.kt
diff --git a/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/RestaurantScreen.kt b/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/RestaurantScreen.ktindex cbf2152257..db54895a9f 100644--- a/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/RestaurantScreen.kt+++ b/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/RestaurantScreen.kt@@ -27,6 +27,7 @@ import androidx.compose.runtime.mutableStateMapOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue+import androidx.compose.runtime.snapshotFlow import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip@@ -61,9 +62,15 @@ import com.vayunmathur.fooddelivery.data.MerchantDetail import com.vayunmathur.fooddelivery.data.MenuItem import com.vayunmathur.fooddelivery.data.MerchantRewards import com.vayunmathur.fooddelivery.data.SelectedModifier+import com.vayunmathur.fooddelivery.platform.AppInit import androidx.compose.runtime.rememberCoroutineScope+import kotlinx.coroutines.FlowPreview+import kotlinx.coroutines.flow.debounce import kotlinx.coroutines.launch +/** How long typing has to settle before the menu is re-filtered. */+private const val FILTER_DEBOUNCE_MS = 150L+ @Composable fun RestaurantScreen(     merchantId: Int,@@ -76,6 +83,7 @@ fun RestaurantScreen(     val scope = rememberCoroutineScope()      LaunchedEffect(merchantId) {+        AppInit.awaitReady()         merchant = BitesApi.getMerchantDetail(merchantId)         loading = false         rewards = BitesApi.getCustomerMerchantRewards().firstOrNull { it.merchantId == merchantId }@@ -115,6 +123,7 @@ fun RestaurantScreen(  * The menu, with no API call of its own so it can be rendered from a `@Preview` — see  * `src/screenshotTest`, which is where the store listing images come from.  */+@OptIn(FlowPreview::class) @Composable fun RestaurantContent(     merchant: MerchantDetail?,@@ -127,6 +136,12 @@ fun RestaurantContent( ) {     var customizeItem by remember { mutableStateOf<MenuItem?>(null) }     var query by remember { mutableStateOf("") }+    // The field itself stays instant; the menu is only re-filtered once typing settles, so a+    // keystroke no longer re-walks and re-sorts every category.+    var appliedQuery by remember { mutableStateOf("") }+    LaunchedEffect(Unit) {+        snapshotFlow { query }.debounce(FILTER_DEBOUNCE_MS).collect { appliedQuery = it }+    }      customizeItem?.let { item ->         ModifierDialog(@@ -151,7 +166,24 @@ fun RestaurantContent(             )         } else {             val m = merchant-            val itemsById = m.items.associateBy { it.id }+            val q = appliedQuery.trim()+            // Rebuilding the id index and the filtered menu on every recomposition is what made+            // typing in the search field lag, so both are kept until their inputs change.+            val itemsById = remember(m.items) { m.items.associateBy { it.id } }+            val activeCategories = remember(m.categories) {+                m.categories.filter { it.isActive }.sortedBy { it.sortOrder }+            }+            val sections = remember(m.items, m.categories, q) {+                activeCategories.mapNotNull { category ->+                    val categoryItems = category.itemIds.mapNotNull { itemsById[it] }+                        .filter {+                            it.isAvailable && it.isInStock && (q.isEmpty() ||+                                it.name.contains(q, ignoreCase = true) ||+                                it.description.contains(q, ignoreCase = true))+                        }+                    if (categoryItems.isEmpty()) null else category to categoryItems+                }+            }              LazyColumn(                 contentPadding = PaddingValues(bottom = 16.dp),@@ -238,21 +270,7 @@ fun RestaurantContent(                     )                 } -                val q = query.trim()-                // Match on name or description; an empty query leaves the menu untouched.-                fun matches(mi: MenuItem) = q.isEmpty() ||-                    mi.name.contains(q, ignoreCase = true) ||-                    mi.description.contains(q, ignoreCase = true)--                val activeCategories = m.categories-                    .filter { it.isActive }-                    .sortedBy { it.sortOrder }--                val anyMatch = activeCategories.any { category ->-                    category.itemIds.mapNotNull { itemsById[it] }-                        .any { it.isAvailable && it.isInStock && matches(it) }-                }-                if (!anyMatch) {+                if (sections.isEmpty()) {                     item {                         Text(                             stringResource(R.string.no_menu_items_match, q),@@ -263,26 +281,24 @@ fun RestaurantContent(                     }                 } -                activeCategories.forEach { category ->-                    val categoryItems = category.itemIds.mapNotNull { itemsById[it] }-                        .filter { it.isAvailable && it.isInStock && matches(it) }-                    if (categoryItems.isNotEmpty()) {-                        item {-                            HorizontalDivider(Modifier.padding(horizontal = 16.dp))-                            Spacer(Modifier.height(12.dp))-                            Text(category.name,-                                style = MaterialTheme.typography.titleMedium,-                                fontWeight = FontWeight.Bold,-                                modifier = Modifier.padding(horizontal = 16.dp))-                            Spacer(Modifier.height(8.dp))-                        }-                        items(categoryItems) { menuItem ->-                            MenuItemRow(menuItem) {-                                if (menuItem.modifierGroups.isNotEmpty()) {-                                    customizeItem = menuItem-                                } else {-                                    onAddItem(menuItem, emptyList())-                                }+                sections.forEach { (category, categoryItems) ->+                    item {+                        HorizontalDivider(Modifier.padding(horizontal = 16.dp))+                        Spacer(Modifier.height(12.dp))+                        Text(category.name,+                            style = MaterialTheme.typography.titleMedium,+                            fontWeight = FontWeight.Bold,+                            modifier = Modifier.padding(horizontal = 16.dp))+                        Spacer(Modifier.height(8.dp))+                    }+                    // An item can sit in more than one category, so the key has to include the+                    // category to stay unique across the whole list.+                    items(categoryItems, key = { "${category.id}-${it.id}" }) { menuItem ->+                        MenuItemRow(menuItem) {+                            if (menuItem.modifierGroups.isNotEmpty()) {+                                customizeItem = menuItem+                            } else {+                                onAddItem(menuItem, emptyList())                             }                         }                     }@@ -309,12 +325,9 @@ fun ModifierDialog(             initialSelection.forEach { sel ->                 getOrPut(sel.modifierGroupId) { mutableSetOf() }.add(sel.modifierId)             }-        }-    }--    item.modifierGroups.forEach { group ->-        if (group.id !in selections) {-            selections[group.id] = mutableSetOf()+            // Seeded here rather than written back during composition, which would dirty the+            // map it had just been read from and force another pass.+            item.modifierGroups.forEach { group -> getOrPut(group.id) { mutableSetOf() } }         }     } 
library/network/src/main/java/com/vayunmathur/library/network/NetworkClient.kt
diff --git a/library/network/src/main/java/com/vayunmathur/library/network/NetworkClient.kt b/library/network/src/main/java/com/vayunmathur/library/network/NetworkClient.ktindex 8babf954bd..791f58e882 100644--- a/library/network/src/main/java/com/vayunmathur/library/network/NetworkClient.kt+++ b/library/network/src/main/java/com/vayunmathur/library/network/NetworkClient.kt@@ -206,12 +206,17 @@ object NetworkClient {         sslSocketFactory: SSLSocketFactory? = null,         useSystemTrust: Boolean = false,     ): SimpleResponse {-        val r = HttpUrlEngine.internalExecute(-            url, method, headers, HttpUrlEngine.toBodyBytes(body),-            followRedirects = true, connectTimeoutMs = null,-            sslSocketFactory = resolveFactory(sslSocketFactory, useSystemTrust),-        )-        return SimpleResponse(r.status, r.statusMessage, r.bodyBytes.toString(Charsets.UTF_8), r.headers, r.finalUrl)+        // internalExecute suspends on Dispatchers.IO but returns to the caller's dispatcher,+        // so decoding the body here would run the (potentially hundreds of MB) UTF-8+        // conversion on whatever thread called us — the main thread, for Compose callers.+        return withContext(Dispatchers.IO) {+            val r = HttpUrlEngine.internalExecute(+                url, method, headers, HttpUrlEngine.toBodyBytes(body),+                followRedirects = true, connectTimeoutMs = null,+                sslSocketFactory = resolveFactory(sslSocketFactory, useSystemTrust),+            )+            SimpleResponse(r.status, r.statusMessage, r.bodyBytes.toString(Charsets.UTF_8), r.headers, r.finalUrl)+        }     }      /**