shop: assistant provider intents + cart deep link (#assistant)
- Commit
7b295b494ead9e14a8dbe2d541ce3bde03a688ad- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-16 22:54 UTC (19 days ago)
- Parents
81c6589
Add the provider side of the OpenAssistant shop tools (P5 provider side only; the assistant-side tool registrations land separately), prepare-only per shop/AGENTS.md. Library: new com.vayunmathur.library.intents.shop DTOs (ShopData.kt), following the existing library.intents.* convention. SearchProductsQuery/ProductData carry title, productId, variantId, shopDomain, storeName, price (ISO minor units) + currency, imageUrl and checkoutEligible; GetProductQuery/ProductDetailData/ProductVariantData read one product with all its variants; CartData/CartStoreData/ CartLineData return the local cart grouped by store; AddToCartRequest/RemoveFromCartRequest mutate only that local cart; OrderData summarises placed/handoff records. Every field is defaulted so older and newer callers decode each other. Shop: SearchProductsIntent, GetProductIntent, GetCartIntent, AddToCartIntent, RemoveFromCartIntent and GetOrdersIntent as NoDisplay AssistantIntent activities, exported in the manifest behind the new signature permission com.vayunmathur.shop.permissions.ACCESS_SHOP. A ShopAssistantBackend seam delegates catalog reads to ShopBackend (awaiting AppInit trust-bundle readiness first) and cart/order reads to ShopCartStore/OrderStore in production, and lets tests install a fake. AddToCart re-fetches the product and confirms the exact variant exists, is available and is checkout-eligible before any cart write (the variant id doubles as the product id, as in ProductScreen); quantities are integers in 1..99, merged lines cap at 99, and failed/uncertain verification returns a typed error code in CartData with the cart unchanged and no retry. No intent can create/update/complete a checkout, hold an idempotency key, treat a handoff as paid, or read the buyer profile: GetOrders reports a pending handoff as pending and prefers live tracking status only when one is already stored. Deep link: shop://cart now opens Route.Cart — MainActivity counts cart handoffs like orders handoffs and Navigation resets to the Cart tab once the profile gate lifts — for the assistant checkout handoff. Checkout itself remains a one-tap user action in the app. Tests: ShopAssistantIntentsTest against a fake backend covers search variant expansion and limits, product detail pricing, cart grouping by store, exact-variant re-fetch asserted via backend call records, merge capping, refusal with zero cart writes for invalid quantity / missing / unavailable / ineligible variants and backend failure, removal, order summaries that never claim payment, and DTO round-trip / default decoding. Verified: ./gradlew :shop:testDevUnitTest (full suite, existing tests green), :shop:compileDevKotlin, :shop:lint and :library:lint all pass. No pushes.
Diff
library/src/main/java/com/vayunmathur/library/intents/shop/ShopData.kt
diff --git a/library/src/main/java/com/vayunmathur/library/intents/shop/ShopData.kt b/library/src/main/java/com/vayunmathur/library/intents/shop/ShopData.ktnew file mode 100644index 0000000000..b1eae8fadb--- /dev/null+++ b/library/src/main/java/com/vayunmathur/library/intents/shop/ShopData.kt@@ -0,0 +1,165 @@+package com.vayunmathur.library.intents.shop++import kotlinx.serialization.Serializable++/**+ * Shared wire DTOs for shop's cross-app assistant intents+ * ([com.vayunmathur.library.util.AssistantIntent]): `SearchProductsIntent`,+ * `GetProductIntent`, `GetCartIntent`, `AddToCartIntent`,+ * `RemoveFromCartIntent` and `GetOrdersIntent` in+ * `com.vayunmathur.shop.intents`, answered only for a co-signed caller behind+ * `com.vayunmathur.shop.permissions.ACCESS_SHOP`.+ *+ * Prepare-only by design (see shop/AGENTS.md): these DTOs can search the+ * catalog, read the local cart and order summaries, and add/remove local cart+ * lines. They cannot create, update or complete a checkout, hold an+ * idempotency key, or read the buyer profile; checkout stays a one-tap user+ * action in the shop app (the assistant hands off via the `shop://cart` deep+ * link), and a cart/browser handoff is never reported as a paid order.+ *+ * Every field has a default so older/newer callers can omit fields without+ * breaking decode (library DTO-compat rule). Prices are ISO minor units+ * (e.g. cents) in [currency], exactly as the shop backend reports them.+ */++/** Search the catalog for [query] (blank returns nothing provider-side). */+@Serializable+data class SearchProductsQuery(+ val query: String = "",+ val limit: Int = 10,+)++/**+ * One purchasable variant of a product: a search hit expands to one row per+ * variant so [variantId] can be handed verbatim to [AddToCartRequest].+ *+ * @property productId catalog product id; pass it back to [GetProductQuery].+ * @property price variant price in minor units of [currency].+ */+@Serializable+data class ProductData(+ val title: String = "",+ val productId: String = "",+ val variantId: String = "",+ val shopDomain: String = "",+ val storeName: String = "",+ val price: Long = 0L,+ val currency: String = "USD",+ val imageUrl: String = "",+ val checkoutEligible: Boolean = false,+)++/** Read one product; [variantId] optionally names the variant to price. */+@Serializable+data class GetProductQuery(+ val shopDomain: String = "",+ val productId: String = "",+ val variantId: String? = null,+)++/** One variant of a [ProductDetailData]. */+@Serializable+data class ProductVariantData(+ val variantId: String = "",+ val title: String = "",+ val price: Long = 0L,+ val currency: String = "USD",+ val available: Boolean = false,+ val sku: String? = null,+)++/**+ * Product detail plus every variant. [price] is the requested variant's+ * price when [GetProductQuery.variantId] matched, else the product's+ * starting price. [error] is a stable machine-readable code when the lookup+ * failed (`INVALID_REQUEST`, `BACKEND_FAILED`); never thrown.+ */+@Serializable+data class ProductDetailData(+ val title: String = "",+ val productId: String = "",+ val shopDomain: String = "",+ val storeName: String = "",+ val description: String = "",+ val price: Long = 0L,+ val currency: String = "USD",+ val imageUrl: String = "",+ val checkoutEligible: Boolean = false,+ val variants: List<ProductVariantData> = emptyList(),+ val error: String? = null,+)++/** One local cart line. [price] is the unit price in minor units. */+@Serializable+data class CartLineData(+ val title: String = "",+ val variantTitle: String = "",+ val variantId: String = "",+ val shopDomain: String = "",+ val storeName: String = "",+ val price: Long = 0L,+ val currency: String = "USD",+ val quantity: Int = 1,+)++/** The cart lines of one store; checkout is per-store in the shop app. */+@Serializable+data class CartStoreData(+ val shopDomain: String = "",+ val storeName: String = "",+ val lines: List<CartLineData> = emptyList(),+)++/**+ * The whole local cart, grouped by store. [error] is a stable+ * machine-readable code when a cart write was refused+ * (`INVALID_REQUEST`, `INVALID_QUANTITY`, `VARIANT_NOT_FOUND`,+ * `VARIANT_UNAVAILABLE`, `NOT_CHECKOUT_ELIGIBLE`, `BACKEND_FAILED`); the+ * cart is left unchanged in that case.+ */+@Serializable+data class CartData(+ val stores: List<CartStoreData> = emptyList(),+ val totalItems: Int = 0,+ val error: String? = null,+)++/**+ * Add [quantity] (integer, 1..99) of [variantId] from [shopDomain] to the+ * local cart. The provider re-fetches the product and confirms that exact+ * variant exists and is available before writing; it never creates a+ * checkout and never auto-retries an uncertain result.+ */+@Serializable+data class AddToCartRequest(+ val shopDomain: String = "",+ val variantId: String = "",+ val quantity: Int = 1,+)++/** Remove every local cart line with [variantId]. Local-only, no network. */+@Serializable+data class RemoveFromCartRequest(+ val variantId: String = "",+)++/**+ * One placed-order / pending-handoff summary. [status] is the latest local+ * tracking status when one is known, else the stored record status+ * (`pending` for a browser handoff — never proof of payment — or+ * `completed` once the merchant's `ec.complete` signal arrived).+ *+ * @property total order total in minor units of [currency].+ */+@Serializable+data class OrderData(+ val orderId: String = "",+ val checkoutId: String = "",+ val shopDomain: String = "",+ val storeName: String = "",+ val status: String = "",+ val total: Long = 0L,+ val currency: String = "USD",+ val itemCount: Int = 0,+ val placedAtMs: Long = 0L,+)
shop/src/main/AndroidManifest.xml
diff --git a/shop/src/main/AndroidManifest.xml b/shop/src/main/AndroidManifest.xmlindex 89ae396000..055f2d755a 100644--- a/shop/src/main/AndroidManifest.xml+++ b/shop/src/main/AndroidManifest.xml@@ -7,6 +7,12 @@ <!-- Sensors permission at install instead of auto-granting it. --> <uses-permission android:name="com.vayunmathur.permission.SENSORS_OPTOUT" /> + <!-- Assistant tools (search / product / cart / orders) for openassistant.+ Signature-level: only apps signed with the Modern Apps key can call. -->+ <permission+ android:name="com.vayunmathur.shop.permissions.ACCESS_SHOP"+ android:protectionLevel="signature" />+ <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <!-- Delivery updates for placed orders (shipped, out for delivery, delivered). -->@@ -42,7 +48,46 @@ <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter>+ <!-- Assistant checkout handoff: prepare-only, opens the cart;+ checkout itself remains a one-tap user action in the app. -->+ <intent-filter>+ <action android:name="android.intent.action.VIEW" />+ <category android:name="android.intent.category.DEFAULT" />+ <category android:name="android.intent.category.BROWSABLE" />+ <data android:scheme="shop" android:host="cart" />+ </intent-filter> </activity>++ <activity+ android:name=".intents.SearchProductsIntent"+ android:exported="true"+ android:permission="com.vayunmathur.shop.permissions.ACCESS_SHOP"+ android:theme="@android:style/Theme.NoDisplay" />+ <activity+ android:name=".intents.GetProductIntent"+ android:exported="true"+ android:permission="com.vayunmathur.shop.permissions.ACCESS_SHOP"+ android:theme="@android:style/Theme.NoDisplay" />+ <activity+ android:name=".intents.GetCartIntent"+ android:exported="true"+ android:permission="com.vayunmathur.shop.permissions.ACCESS_SHOP"+ android:theme="@android:style/Theme.NoDisplay" />+ <activity+ android:name=".intents.AddToCartIntent"+ android:exported="true"+ android:permission="com.vayunmathur.shop.permissions.ACCESS_SHOP"+ android:theme="@android:style/Theme.NoDisplay" />+ <activity+ android:name=".intents.RemoveFromCartIntent"+ android:exported="true"+ android:permission="com.vayunmathur.shop.permissions.ACCESS_SHOP"+ android:theme="@android:style/Theme.NoDisplay" />+ <activity+ android:name=".intents.GetOrdersIntent"+ android:exported="true"+ android:permission="com.vayunmathur.shop.permissions.ACCESS_SHOP"+ android:theme="@android:style/Theme.NoDisplay" /> </application> </manifest>
shop/src/main/java/com/vayunmathur/shop/MainActivity.kt
diff --git a/shop/src/main/java/com/vayunmathur/shop/MainActivity.kt b/shop/src/main/java/com/vayunmathur/shop/MainActivity.ktindex 79c53e830c..a3f2f6ce56 100644--- a/shop/src/main/java/com/vayunmathur/shop/MainActivity.kt+++ b/shop/src/main/java/com/vayunmathur/shop/MainActivity.kt@@ -23,6 +23,9 @@ class MainActivity : MaActivity() { */ private var ordersRequest by mutableIntStateOf(0) + /** Counts `shop://cart` handoffs, sequenced like [ordersRequest]. */+ private var cartRequest by mutableIntStateOf(0)+ /** Latest merchant link to open, sequenced so re-delivering the same URL re-navigates. */ private var linkRequest by mutableStateOf<Pair<Int, String>?>(null) private var linkSequence = 0@@ -48,6 +51,13 @@ class MainActivity : MaActivity() { ordersRequest++ return }+ // Assistant checkout handoff (shop://cart): open the cart only;+ // preparing a cart is not a checkout and never a paid order.+ val data = intent?.data+ if (intent?.action == Intent.ACTION_VIEW && data?.scheme == "shop" && data.host == "cart") {+ cartRequest+++ return+ } if (intent?.action != Intent.ACTION_VIEW) return intent.dataString?.let { linkRequest = ++linkSequence to it } }@@ -59,6 +69,11 @@ class MainActivity : MaActivity() { @Composable override fun Content() {- Navigation(viewModel, ordersRequest = ordersRequest, linkRequest = linkRequest)+ Navigation(+ viewModel,+ ordersRequest = ordersRequest,+ cartRequest = cartRequest,+ linkRequest = linkRequest,+ ) } }
shop/src/main/java/com/vayunmathur/shop/Navigation.kt
diff --git a/shop/src/main/java/com/vayunmathur/shop/Navigation.kt b/shop/src/main/java/com/vayunmathur/shop/Navigation.ktindex fa038149da..75bd70ec18 100644--- a/shop/src/main/java/com/vayunmathur/shop/Navigation.kt+++ b/shop/src/main/java/com/vayunmathur/shop/Navigation.kt@@ -72,6 +72,7 @@ internal fun applyShopPendingRoute( fun Navigation( viewModel: ShopViewModel, ordersRequest: Int = 0,+ cartRequest: Int = 0, linkRequest: Pair<Int, String>? = null, ) { val context = LocalContext.current@@ -95,6 +96,14 @@ fun Navigation( backStack.reset(Route.Orders) } }+ // Assistant cart handoff (shop://cart): same deferred-until-ungated reset.+ LaunchedEffect(cartRequest, backStack.backStack.lastOrNull()) {+ if (cartRequest > 0 && backStack.last() != Route.Cart &&+ backStack.backStack.lastOrNull() != Route.ProfileSetup+ ) {+ backStack.reset(Route.Cart)+ }+ } // Merchant links resolve in the ViewModel, which calls back with the destination; // this is the direct backStack call that replaces the old pendingRoute effect. // While gated, the link is left unconsumed and applies after the gate lifts.
shop/src/main/java/com/vayunmathur/shop/intents/AddToCartIntent.kt
diff --git a/shop/src/main/java/com/vayunmathur/shop/intents/AddToCartIntent.kt b/shop/src/main/java/com/vayunmathur/shop/intents/AddToCartIntent.ktnew file mode 100644index 0000000000..2799ff6ece--- /dev/null+++ b/shop/src/main/java/com/vayunmathur/shop/intents/AddToCartIntent.kt@@ -0,0 +1,21 @@+package com.vayunmathur.shop.intents++import com.vayunmathur.library.intents.shop.AddToCartRequest+import com.vayunmathur.library.intents.shop.CartData+import com.vayunmathur.library.util.AssistantIntent++/**+ * Assistant tool: add an exact, re-verified variant to the local cart.+ * Prepare-only — this never creates/updates a checkout, never holds an+ * idempotency key, and the user still checks out in the shop app+ * (`shop://cart` handoff). A failed verification leaves the cart unchanged.+ */+class AddToCartIntent : AssistantIntent<AddToCartRequest, CartData>(+ AddToCartRequest.serializer(),+ CartData.serializer(),+) {+ override suspend fun performCalculation(input: AddToCartRequest): CartData {+ awaitShopReady(this)+ return addToCart(this, input, shopAssistantBackend())+ }+}
shop/src/main/java/com/vayunmathur/shop/intents/GetCartIntent.kt
diff --git a/shop/src/main/java/com/vayunmathur/shop/intents/GetCartIntent.kt b/shop/src/main/java/com/vayunmathur/shop/intents/GetCartIntent.ktnew file mode 100644index 0000000000..df9178f293--- /dev/null+++ b/shop/src/main/java/com/vayunmathur/shop/intents/GetCartIntent.kt@@ -0,0 +1,14 @@+package com.vayunmathur.shop.intents++import com.vayunmathur.library.intents.shop.CartData+import com.vayunmathur.library.util.AssistantIntent+import kotlinx.serialization.builtins.serializer++/** Assistant tool: local cart, grouped by store. */+class GetCartIntent : AssistantIntent<Unit, CartData>(+ Unit.serializer(),+ CartData.serializer(),+) {+ override suspend fun performCalculation(input: Unit): CartData =+ getCart(this, shopAssistantBackend())+}
shop/src/main/java/com/vayunmathur/shop/intents/GetOrdersIntent.kt
diff --git a/shop/src/main/java/com/vayunmathur/shop/intents/GetOrdersIntent.kt b/shop/src/main/java/com/vayunmathur/shop/intents/GetOrdersIntent.ktnew file mode 100644index 0000000000..c7ddc471bf--- /dev/null+++ b/shop/src/main/java/com/vayunmathur/shop/intents/GetOrdersIntent.kt@@ -0,0 +1,18 @@+package com.vayunmathur.shop.intents++import com.vayunmathur.library.intents.shop.OrderData+import com.vayunmathur.library.util.AssistantIntent+import kotlinx.serialization.builtins.ListSerializer+import kotlinx.serialization.builtins.serializer++/**+ * Assistant tool: placed-order / handoff summaries from the local store.+ * A `pending` handoff is not a paid order; merchant pages stay authoritative.+ */+class GetOrdersIntent : AssistantIntent<Unit, List<OrderData>>(+ Unit.serializer(),+ ListSerializer(OrderData.serializer()),+) {+ override suspend fun performCalculation(input: Unit): List<OrderData> =+ getOrders(this, shopAssistantBackend())+}
shop/src/main/java/com/vayunmathur/shop/intents/GetProductIntent.kt
diff --git a/shop/src/main/java/com/vayunmathur/shop/intents/GetProductIntent.kt b/shop/src/main/java/com/vayunmathur/shop/intents/GetProductIntent.ktnew file mode 100644index 0000000000..e6fde0adca--- /dev/null+++ b/shop/src/main/java/com/vayunmathur/shop/intents/GetProductIntent.kt@@ -0,0 +1,16 @@+package com.vayunmathur.shop.intents++import com.vayunmathur.library.intents.shop.GetProductQuery+import com.vayunmathur.library.intents.shop.ProductDetailData+import com.vayunmathur.library.util.AssistantIntent++/** Assistant tool: product detail + variants for one catalog product. */+class GetProductIntent : AssistantIntent<GetProductQuery, ProductDetailData>(+ GetProductQuery.serializer(),+ ProductDetailData.serializer(),+) {+ override suspend fun performCalculation(input: GetProductQuery): ProductDetailData {+ awaitShopReady(this)+ return getProductDetail(input, shopAssistantBackend())+ }+}
shop/src/main/java/com/vayunmathur/shop/intents/RemoveFromCartIntent.kt
diff --git a/shop/src/main/java/com/vayunmathur/shop/intents/RemoveFromCartIntent.kt b/shop/src/main/java/com/vayunmathur/shop/intents/RemoveFromCartIntent.ktnew file mode 100644index 0000000000..a7f87e141c--- /dev/null+++ b/shop/src/main/java/com/vayunmathur/shop/intents/RemoveFromCartIntent.kt@@ -0,0 +1,14 @@+package com.vayunmathur.shop.intents++import com.vayunmathur.library.intents.shop.CartData+import com.vayunmathur.library.intents.shop.RemoveFromCartRequest+import com.vayunmathur.library.util.AssistantIntent++/** Assistant tool: remove a variant from the local cart. Local-only. */+class RemoveFromCartIntent : AssistantIntent<RemoveFromCartRequest, CartData>(+ RemoveFromCartRequest.serializer(),+ CartData.serializer(),+) {+ override suspend fun performCalculation(input: RemoveFromCartRequest): CartData =+ removeFromCart(this, input, shopAssistantBackend())+}
shop/src/main/java/com/vayunmathur/shop/intents/SearchProductsIntent.kt
diff --git a/shop/src/main/java/com/vayunmathur/shop/intents/SearchProductsIntent.kt b/shop/src/main/java/com/vayunmathur/shop/intents/SearchProductsIntent.ktnew file mode 100644index 0000000000..7de850a642--- /dev/null+++ b/shop/src/main/java/com/vayunmathur/shop/intents/SearchProductsIntent.kt@@ -0,0 +1,17 @@+package com.vayunmathur.shop.intents++import com.vayunmathur.library.intents.shop.ProductData+import com.vayunmathur.library.intents.shop.SearchProductsQuery+import com.vayunmathur.library.util.AssistantIntent+import kotlinx.serialization.builtins.ListSerializer++/** Assistant tool: catalog search. Prepare-only; never starts checkout. */+class SearchProductsIntent : AssistantIntent<SearchProductsQuery, List<ProductData>>(+ SearchProductsQuery.serializer(),+ ListSerializer(ProductData.serializer()),+) {+ override suspend fun performCalculation(input: SearchProductsQuery): List<ProductData> {+ awaitShopReady(this)+ return searchProducts(input, shopAssistantBackend())+ }+}
shop/src/main/java/com/vayunmathur/shop/intents/ShopAssistantBackend.kt
diff --git a/shop/src/main/java/com/vayunmathur/shop/intents/ShopAssistantBackend.kt b/shop/src/main/java/com/vayunmathur/shop/intents/ShopAssistantBackend.ktnew file mode 100644index 0000000000..66f916f819--- /dev/null+++ b/shop/src/main/java/com/vayunmathur/shop/intents/ShopAssistantBackend.kt@@ -0,0 +1,260 @@+package com.vayunmathur.shop.intents++import android.content.Context+import com.vayunmathur.library.intents.shop.AddToCartRequest+import com.vayunmathur.library.intents.shop.CartData+import com.vayunmathur.library.intents.shop.CartLineData+import com.vayunmathur.library.intents.shop.CartStoreData+import com.vayunmathur.library.intents.shop.GetProductQuery+import com.vayunmathur.library.intents.shop.OrderData+import com.vayunmathur.library.intents.shop.ProductData+import com.vayunmathur.library.intents.shop.ProductDetailData+import com.vayunmathur.library.intents.shop.ProductVariantData+import com.vayunmathur.library.intents.shop.RemoveFromCartRequest+import com.vayunmathur.library.intents.shop.SearchProductsQuery+import com.vayunmathur.shop.data.CartLine+import com.vayunmathur.shop.data.OrderStore+import com.vayunmathur.shop.data.PlacedOrder+import com.vayunmathur.shop.data.ShopCartStore+import com.vayunmathur.shop.data.UcpProduct+import com.vayunmathur.shop.network.ShopBackend+import com.vayunmathur.shop.network.ShopHttpBackend+import com.vayunmathur.shop.platform.AppInit++/** Typed failure codes returned in DTO `error` fields (never thrown). */+internal const val ERROR_INVALID_REQUEST = "INVALID_REQUEST"+internal const val ERROR_INVALID_QUANTITY = "INVALID_QUANTITY"+internal const val ERROR_VARIANT_NOT_FOUND = "VARIANT_NOT_FOUND"+internal const val ERROR_VARIANT_UNAVAILABLE = "VARIANT_UNAVAILABLE"+internal const val ERROR_NOT_CHECKOUT_ELIGIBLE = "NOT_CHECKOUT_ELIGIBLE"+internal const val ERROR_BACKEND_FAILED = "BACKEND_FAILED"++internal const val DEFAULT_SEARCH_LIMIT = 10+internal const val MAX_SEARCH_LIMIT = 50+internal const val MAX_QUANTITY = 99++/**+ * Seam behind the shop assistant intents. Production delegates catalog reads+ * to [ShopBackend] and cart/order reads to the local stores; tests install a+ * fake so provider logic (exact-variant verification, grouping, limits) is+ * asserted without network or live checkout (shop/AGENTS.md sanctions fake+ * transports, never live checkout).+ *+ * Prepare-only: this seam deliberately exposes no checkout call, no+ * idempotency key and no buyer-profile access.+ */+internal interface ShopAssistantBackend {+ suspend fun search(query: String, limit: Int): Result<List<UcpProduct>>+ suspend fun getProduct(shop: String, productId: String, variantId: String?): Result<UcpProduct>+ suspend fun cartLines(context: Context): List<CartLine>+ suspend fun saveCart(context: Context, lines: List<CartLine>)+ suspend fun orders(context: Context): List<PlacedOrder>+}++internal class RealShopAssistantBackend(+ private val backend: ShopBackend = ShopHttpBackend,+) : ShopAssistantBackend {+ override suspend fun search(query: String, limit: Int): Result<List<UcpProduct>> =+ backend.search(query, limit = limit)++ override suspend fun getProduct(+ shop: String,+ productId: String,+ variantId: String?,+ ): Result<UcpProduct> = backend.getProduct(shop, productId, variantId)++ override suspend fun cartLines(context: Context): List<CartLine> =+ ShopCartStore.getAll(context)++ override suspend fun saveCart(context: Context, lines: List<CartLine>) {+ ShopCartStore.save(context, lines)+ }++ override suspend fun orders(context: Context): List<PlacedOrder> =+ OrderStore.getAll(context)+}++/** Test seam, mirroring the `overrideForTest` singletons elsewhere. */+internal var shopAssistantBackendForTest: ShopAssistantBackend? = null++internal fun shopAssistantBackend(): ShopAssistantBackend =+ shopAssistantBackendForTest ?: RealShopAssistantBackend()++/**+ * Network calls must await the trust bundle (shop/AGENTS.md). Only the+ * production backend touches the network, so tests with a fake skip this —+ * [AppInit.start] is also what a NoDisplay intent entry point must call,+ * since MainActivity may never have run in this process.+ */+internal suspend fun awaitShopReady(context: Context) {+ if (shopAssistantBackendForTest != null) return+ AppInit.start(context)+ AppInit.awaitReady()+}++internal fun UcpProduct.toProductDataList(): List<ProductData> {+ val image = images.firstOrNull()?.url.orEmpty()+ if (variants.isEmpty()) {+ return listOf(+ ProductData(+ title = title, productId = id, variantId = "",+ shopDomain = shopDomain, storeName = storeName,+ price = priceRange.amount, currency = priceRange.currency,+ imageUrl = image, checkoutEligible = checkoutEligible,+ ),+ )+ }+ return variants.map { variant ->+ ProductData(+ title = title, productId = id, variantId = variant.id,+ shopDomain = variant.shopDomain.ifBlank { shopDomain },+ storeName = variant.storeName.ifBlank { storeName },+ price = variant.price.amount, currency = variant.price.currency,+ imageUrl = image, checkoutEligible = checkoutEligible,+ )+ }+}++internal suspend fun searchProducts(+ input: SearchProductsQuery,+ backend: ShopAssistantBackend,+): List<ProductData> {+ val query = input.query.trim()+ if (query.isEmpty()) return emptyList()+ val limit = if (input.limit <= 0) DEFAULT_SEARCH_LIMIT else input.limit.coerceAtMost(MAX_SEARCH_LIMIT)+ val products = backend.search(query, limit).getOrElse { return emptyList() }+ return products.flatMap { it.toProductDataList() }.take(limit)+}++internal suspend fun getProductDetail(+ input: GetProductQuery,+ backend: ShopAssistantBackend,+): ProductDetailData {+ val shop = input.shopDomain.trim()+ val productId = input.productId.trim()+ if (shop.isEmpty() || productId.isEmpty()) {+ return ProductDetailData(error = ERROR_INVALID_REQUEST)+ }+ val product = backend.getProduct(shop, productId, input.variantId?.takeIf { it.isNotBlank() })+ .getOrElse { return ProductDetailData(error = ERROR_BACKEND_FAILED) }+ val selected = input.variantId?.let { id -> product.variants.firstOrNull { it.id == id } }+ val price = selected?.price ?: product.priceRange+ return ProductDetailData(+ title = product.title,+ productId = product.id.ifBlank { productId },+ shopDomain = product.shopDomain.ifBlank { shop },+ storeName = product.storeName,+ description = product.description,+ price = price.amount,+ currency = price.currency,+ imageUrl = product.images.firstOrNull()?.url.orEmpty(),+ checkoutEligible = product.checkoutEligible,+ variants = product.variants.map { variant ->+ ProductVariantData(+ variantId = variant.id, title = variant.title,+ price = variant.price.amount, currency = variant.price.currency,+ available = variant.available, sku = variant.sku,+ )+ },+ )+}++internal fun List<CartLine>.toCartData(error: String? = null): CartData {+ val stores = groupBy { it.shopDomain }.map { (domain, lines) ->+ CartStoreData(+ shopDomain = domain,+ storeName = lines.firstOrNull()?.displayName.orEmpty(),+ lines = lines.map { line ->+ CartLineData(+ title = line.productTitle, variantTitle = line.variantTitle,+ variantId = line.variantId, shopDomain = line.shopDomain,+ storeName = line.displayName,+ price = line.unitPrice.amount, currency = line.unitPrice.currency,+ quantity = line.quantity,+ )+ },+ )+ }+ return CartData(stores = stores, totalItems = sumOf { it.quantity }, error = error)+}++internal suspend fun getCart(context: Context, backend: ShopAssistantBackend): CartData =+ backend.cartLines(context).toCartData()++internal suspend fun addToCart(+ context: Context,+ input: AddToCartRequest,+ backend: ShopAssistantBackend,+): CartData {+ val current = backend.cartLines(context)+ val shop = input.shopDomain.trim()+ val variantId = input.variantId.trim()+ if (shop.isEmpty() || variantId.isEmpty()) return current.toCartData(ERROR_INVALID_REQUEST)+ if (input.quantity !in 1..MAX_QUANTITY) return current.toCartData(ERROR_INVALID_QUANTITY)+ // Exact-variant verification before any cart write (shop/AGENTS.md):+ // re-fetch the product and confirm this variant exists in the live+ // response. As in ProductScreen, the variant id doubles as the product+ // id when no separate product id is carried by the request. Cached+ // snapshots are not verification, and a failed/uncertain read is never+ // retried automatically — the cart is simply left unchanged.+ val product = backend.getProduct(shop, variantId, variantId)+ .getOrElse { return current.toCartData(ERROR_BACKEND_FAILED) }+ val variant = product.variants.firstOrNull { it.id == variantId }+ ?: return current.toCartData(ERROR_VARIANT_NOT_FOUND)+ if (!variant.available) return current.toCartData(ERROR_VARIANT_UNAVAILABLE)+ if (!product.checkoutEligible) return current.toCartData(ERROR_NOT_CHECKOUT_ELIGIBLE)+ val lineShop = variant.shopDomain.ifBlank { product.shopDomain }.ifBlank { shop }+ val existing = current.indexOfFirst {+ it.variantId == variantId && it.platformId == product.platformId && it.shopDomain == lineShop+ }+ val next = if (existing >= 0) {+ current.toMutableList().also {+ it[existing] = it[existing].copy(+ quantity = (it[existing].quantity + input.quantity).coerceAtMost(MAX_QUANTITY),+ )+ }+ } else {+ current + CartLine(+ variantId = variant.id,+ productTitle = product.title,+ variantTitle = variant.title,+ unitPrice = variant.price,+ platformId = product.platformId,+ shopDomain = lineShop,+ quantity = input.quantity,+ storeName = variant.storeName.ifBlank { product.storeName },+ )+ }+ backend.saveCart(context, next)+ return next.toCartData()+}++internal suspend fun removeFromCart(+ context: Context,+ input: RemoveFromCartRequest,+ backend: ShopAssistantBackend,+): CartData {+ val current = backend.cartLines(context)+ val variantId = input.variantId.trim()+ if (variantId.isEmpty()) return current.toCartData(ERROR_INVALID_REQUEST)+ val next = current.filterNot { it.variantId == variantId }+ if (next.size != current.size) backend.saveCart(context, next)+ return next.toCartData()+}++internal suspend fun getOrders(+ context: Context,+ backend: ShopAssistantBackend,+): List<OrderData> = backend.orders(context).map { order ->+ OrderData(+ orderId = order.orderId,+ checkoutId = order.checkoutId,+ shopDomain = order.shopDomain,+ storeName = order.displayName,+ status = order.tracking?.status?.takeIf { it.isNotBlank() } ?: order.status,+ total = order.total.amount,+ currency = order.total.currency,+ itemCount = order.itemCount,+ placedAtMs = order.placedAtMs,+ )+}
shop/src/test/java/com/vayunmathur/shop/intents/ShopAssistantIntentsTest.kt
diff --git a/shop/src/test/java/com/vayunmathur/shop/intents/ShopAssistantIntentsTest.kt b/shop/src/test/java/com/vayunmathur/shop/intents/ShopAssistantIntentsTest.ktnew file mode 100644index 0000000000..8bcad1c879--- /dev/null+++ b/shop/src/test/java/com/vayunmathur/shop/intents/ShopAssistantIntentsTest.kt@@ -0,0 +1,340 @@+package com.vayunmathur.shop.intents++import android.content.Context+import com.vayunmathur.library.intents.shop.AddToCartRequest+import com.vayunmathur.library.intents.shop.CartData+import com.vayunmathur.library.intents.shop.GetProductQuery+import com.vayunmathur.library.intents.shop.RemoveFromCartRequest+import com.vayunmathur.library.intents.shop.SearchProductsQuery+import com.vayunmathur.shop.data.CartLine+import com.vayunmathur.shop.data.Money+import com.vayunmathur.shop.data.OrderTracking+import com.vayunmathur.shop.data.PlacedOrder+import com.vayunmathur.shop.data.ProductImage+import com.vayunmathur.shop.data.ProductVariant+import com.vayunmathur.shop.data.UcpProduct+import kotlinx.coroutines.runBlocking+import kotlinx.serialization.json.Json+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config+import kotlin.test.AfterTest+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNull+import kotlin.test.assertTrue++/**+ * Shop assistant provider intents against a fake [ShopAssistantBackend]+ * (fake transport sanctioned by shop/AGENTS.md; never live checkout).+ * Asserts exact-variant re-verification before cart writes, integer+ * quantities, grouping, and that no intent can create a checkout — the+ * seam exposes no checkout/profile call at all.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class ShopAssistantIntentsTest {++ private class FakeBackend(+ var searchResult: Result<List<UcpProduct>> = Result.success(emptyList()),+ var productResult: Result<UcpProduct> = Result.success(UcpProduct()),+ var cart: List<CartLine> = emptyList(),+ var orders: List<PlacedOrder> = emptyList(),+ ) : ShopAssistantBackend {+ var searchCalls = 0+ var getProductCalls = 0+ var saveCalls = 0+ var lastGetProduct: Triple<String, String, String?>? = null++ override suspend fun search(query: String, limit: Int): Result<List<UcpProduct>> {+ searchCalls+++ return searchResult+ }++ override suspend fun getProduct(+ shop: String,+ productId: String,+ variantId: String?,+ ): Result<UcpProduct> {+ getProductCalls+++ lastGetProduct = Triple(shop, productId, variantId)+ return productResult+ }++ override suspend fun cartLines(context: Context): List<CartLine> = cart++ override suspend fun saveCart(context: Context, lines: List<CartLine>) {+ saveCalls+++ cart = lines+ }++ override suspend fun orders(context: Context): List<PlacedOrder> = orders+ }++ private fun product(+ id: String = "p1",+ shop: String = "shop.example.com",+ eligible: Boolean = true,+ variants: List<ProductVariant> = listOf(+ ProductVariant(+ id = "v1", title = "9 / Blue", price = Money(12_999, "USD"),+ available = true, sku = "SKU-1", storeName = "Trail Store",+ shopDomain = shop,+ ),+ ProductVariant(+ id = "v2", title = "10 / Blue", price = Money(13_999, "USD"),+ available = false, storeName = "Trail Store", shopDomain = shop,+ ),+ ),+ ) = UcpProduct(+ id = id, title = "Trail Runner", description = "Grippy",+ priceRange = Money(12_999, "USD"), platformId = "shopify",+ shopDomain = shop, images = listOf(ProductImage("https://img.example/x.png")),+ variants = variants, checkoutEligible = eligible, storeName = "Trail Store",+ )++ private fun line(+ variantId: String = "v1",+ shop: String = "shop.example.com",+ store: String = "Trail Store",+ qty: Int = 2,+ ) = CartLine(+ variantId = variantId, productTitle = "Trail Runner", variantTitle = "9 / Blue",+ unitPrice = Money(12_999, "USD"), platformId = "shopify", shopDomain = shop,+ quantity = qty, storeName = store,+ )++ private var fake = FakeBackend()++ @BeforeTest+ fun setUp() {+ fake = FakeBackend()+ shopAssistantBackendForTest = fake+ }++ @AfterTest+ fun tearDown() {+ shopAssistantBackendForTest = null+ }++ // --- SearchProductsIntent ---++ @Test+ fun searchExpandsVariantsAndCapsLimit() = runBlocking {+ fake.searchResult = Result.success(listOf(product()))+ val out = SearchProductsIntent().performCalculation(SearchProductsQuery(query = "runner"))+ assertEquals(listOf("v1", "v2"), out.map { it.variantId })+ assertEquals("p1", out[0].productId)+ assertEquals(12_999L, out[0].price)+ assertEquals("Trail Store", out[0].storeName)+ assertTrue(out[0].checkoutEligible)+ assertEquals(1, SearchProductsIntent().performCalculation(+ SearchProductsQuery(query = "runner", limit = 1),+ ).size)+ assertTrue(SearchProductsIntent().performCalculation(SearchProductsQuery(query = " ")).isEmpty())+ // Blank query is refused provider-side, without a backend call.+ assertEquals(2, fake.searchCalls)+ }++ @Test+ fun searchFailureReturnsEmpty() = runBlocking {+ fake.searchResult = Result.failure(RuntimeException("boom"))+ assertTrue(SearchProductsIntent().performCalculation(SearchProductsQuery(query = "x")).isEmpty())+ }++ // --- GetProductIntent ---++ @Test+ fun getProductReturnsDetailAndSelectedVariantPrice() = runBlocking {+ fake.productResult = Result.success(product())+ val out = GetProductIntent().performCalculation(+ GetProductQuery(shopDomain = "shop.example.com", productId = "p1", variantId = "v2"),+ )+ assertNull(out.error)+ assertEquals(13_999L, out.price)+ assertEquals(listOf("v1", "v2"), out.variants.map { it.variantId })+ assertEquals("SKU-1", out.variants[0].sku)+ }++ @Test+ fun getProductInvalidAndFailureAreTyped() = runBlocking {+ assertEquals(+ ERROR_INVALID_REQUEST,+ GetProductIntent().performCalculation(GetProductQuery()).error,+ )+ fake.productResult = Result.failure(RuntimeException("boom"))+ assertEquals(+ ERROR_BACKEND_FAILED,+ GetProductIntent().performCalculation(+ GetProductQuery(shopDomain = "shop.example.com", productId = "p1"),+ ).error,+ )+ }++ // --- GetCartIntent ---++ @Test+ fun getCartGroupsLinesByStore() = runBlocking {+ fake.cart = listOf(+ line(),+ line(variantId = "v9", shop = "other.example.com", store = "", qty = 1),+ )+ val out = GetCartIntent().performCalculation(Unit)+ assertNull(out.error)+ assertEquals(3, out.totalItems)+ assertEquals(listOf("shop.example.com", "other.example.com"), out.stores.map { it.shopDomain })+ assertEquals("Trail Store", out.stores[0].storeName)+ // Domain fallback when no store name is known (shop/AGENTS.md).+ assertEquals("other.example.com", out.stores[1].storeName)+ assertEquals(12_999L, out.stores[0].lines[0].price)+ }++ // --- AddToCartIntent ---++ @Test+ fun addToCartReFetchesExactVariantBeforeWriting() = runBlocking {+ fake.productResult = Result.success(product())+ val out = AddToCartIntent().performCalculation(+ AddToCartRequest(shopDomain = "shop.example.com", variantId = "v1", quantity = 2),+ )+ assertNull(out.error)+ assertEquals(1, fake.getProductCalls)+ assertEquals(+ Triple("shop.example.com", "v1", "v1"),+ fake.lastGetProduct,+ )+ assertEquals(1, fake.saveCalls)+ assertEquals(2, out.totalItems)+ assertEquals("v1", out.stores.single().lines.single().variantId)+ assertEquals("Trail Store", out.stores.single().storeName)+ }++ @Test+ fun addToCartMergesAndCapsAt99() = runBlocking {+ fake.cart = listOf(line(qty = 98))+ fake.productResult = Result.success(product())+ val out = AddToCartIntent().performCalculation(+ AddToCartRequest(shopDomain = "shop.example.com", variantId = "v1", quantity = 5),+ )+ assertNull(out.error)+ assertEquals(99, out.totalItems)+ }++ @Test+ fun addToCartRefusesUnverifiedUnavailableAndInvalidWithoutWriting() = runBlocking {+ fake.cart = listOf(line(qty = 1))+ // Invalid quantity / blank ids: no re-fetch, no write.+ assertEquals(+ ERROR_INVALID_QUANTITY,+ AddToCartIntent().performCalculation(+ AddToCartRequest(shopDomain = "shop.example.com", variantId = "v1", quantity = 0),+ ).error,+ )+ assertEquals(+ ERROR_INVALID_QUANTITY,+ AddToCartIntent().performCalculation(+ AddToCartRequest(shopDomain = "shop.example.com", variantId = "v1", quantity = 100),+ ).error,+ )+ assertEquals(+ ERROR_INVALID_REQUEST,+ AddToCartIntent().performCalculation(AddToCartRequest()).error,+ )+ assertEquals(0, fake.getProductCalls)+ assertEquals(0, fake.saveCalls)+ // Exact variant absent from the live detail response.+ fake.productResult = Result.success(product(variants = listOf(+ ProductVariant(id = "other", price = Money(1, "USD"), available = true),+ )))+ assertEquals(+ ERROR_VARIANT_NOT_FOUND,+ AddToCartIntent().performCalculation(+ AddToCartRequest(shopDomain = "shop.example.com", variantId = "v1", quantity = 1),+ ).error,+ )+ // Present but unavailable.+ fake.productResult = Result.success(product())+ assertEquals(+ ERROR_VARIANT_UNAVAILABLE,+ AddToCartIntent().performCalculation(+ AddToCartRequest(shopDomain = "shop.example.com", variantId = "v2", quantity = 1),+ ).error,+ )+ // Not checkout-eligible.+ fake.productResult = Result.success(product(eligible = false))+ assertEquals(+ ERROR_NOT_CHECKOUT_ELIGIBLE,+ AddToCartIntent().performCalculation(+ AddToCartRequest(shopDomain = "shop.example.com", variantId = "v1", quantity = 1),+ ).error,+ )+ // Backend failure is not retried and leaves the cart untouched.+ fake.productResult = Result.failure(RuntimeException("boom"))+ val failed = AddToCartIntent().performCalculation(+ AddToCartRequest(shopDomain = "shop.example.com", variantId = "v1", quantity = 1),+ )+ assertEquals(ERROR_BACKEND_FAILED, failed.error)+ assertEquals(1, failed.totalItems)+ assertEquals(0, fake.saveCalls)+ }++ // --- RemoveFromCartIntent ---++ @Test+ fun removeFromCartRemovesOnlyThatVariant() = runBlocking {+ fake.cart = listOf(line(), line(variantId = "v9"))+ val out = RemoveFromCartIntent().performCalculation(RemoveFromCartRequest(variantId = "v1"))+ assertNull(out.error)+ assertEquals(listOf("v9"), out.stores.single().lines.map { it.variantId })+ assertEquals(1, fake.saveCalls)+ assertEquals(+ ERROR_INVALID_REQUEST,+ RemoveFromCartIntent().performCalculation(RemoveFromCartRequest()).error,+ )+ }++ // --- GetOrdersIntent ---++ @Test+ fun getOrdersSummarisesLocalRecordsWithoutClaimingPayment() = runBlocking {+ fake.orders = listOf(+ PlacedOrder(+ checkoutId = "c1", placedAtMs = 7L, total = Money(2_000, "USD"),+ itemCount = 2, status = "pending", shopDomain = "shop.example.com",+ storeName = "Trail Store", orderId = "",+ ),+ PlacedOrder(+ checkoutId = "c2", placedAtMs = 9L, total = Money(3_000, "USD"),+ itemCount = 1, status = "completed", shopDomain = "shop.example.com",+ orderId = "o2", tracking = OrderTracking(orderId = "o2", status = "in_transit"),+ ),+ )+ val out = GetOrdersIntent().performCalculation(Unit)+ // A pending browser handoff stays "pending"; tracking wins when known.+ assertEquals(listOf("pending", "in_transit"), out.map { it.status })+ assertEquals("Trail Store", out[0].storeName)+ assertEquals(2_000L, out[0].total)+ assertEquals("o2", out[1].orderId)+ }++ // --- DTO wire compat ---++ @Test+ fun shopDtosRoundTripAndDecodeWithDefaults() {+ val json = Json { ignoreUnknownKeys = true }+ val cart = CartData(totalItems = 2)+ assertEquals(+ cart,+ json.decodeFromString(CartData.serializer(), json.encodeToString(CartData.serializer(), cart)),+ )+ assertEquals(+ SearchProductsQuery(),+ json.decodeFromString(SearchProductsQuery.serializer(), "{}"),+ )+ assertEquals(+ AddToCartRequest(variantId = "v1"),+ json.decodeFromString(AddToCartRequest.serializer(), """{"variantId":"v1"}"""),+ )+ }+}