Modern Apps git

← Modern-Apps.git

openassistant: shop prepare-only tools with cart handoff (#assistant)

Commit
428a82e90c790ae46cdecb012a721a526fdace78
Author
Vayun Mathur <[email protected]>
When
2026-11-16 23:19 UTC (19 days ago)
Parents
47b4e7c
Wire the consumer side of the shop assistant intents (P5),
prepare-only per shop's own rules: search_products,
get_product_detail, shop_get_cart and get_shop_orders are READ
tools returning host-truncated summaries (one line per purchasable
variant, exact prices/availability, per-store cart). Search and
detail render the product card (variant Picker, quantity stepper,
Add button) for the first/detail product; the model is told to
confirm the exact variant before adding.

shop_add_to_cart and shop_remove_from_cart are light writes
(WWRITE_LIGHT): they execute exactly once (the provider re-verifies
the exact variant and there is no auto-retry on an uncertain error,
which surfaces as a typed cart error), and always render the grouped
cart back.

start_shop_checkout is HANDOFF_PREP: it reads the per-store cart,
renders the summary card whose button is handoff.shop_checkout,
intercepted in AssistantViewModel to deep-link shop://cart, where
Shop's one-tap checkout remains the only checkout. There is
deliberately no checkout, create_checkout or profile-reading tool:
a test asserts those specs do not exist. Opening the cart is never
reported as a paid order, in both tool result text and prompt.

Prompt sections (SHOPPING block, shop.add/handoff.shop_checkout
action vocabulary) teach this; they invalidate the baked gemma
prefix, which rebakes on first use.

Tests: product/cart/summary template snapshots, spec parity and
risk classification, missing-app paths, summaries, and a fake-model
golden shop script (search, detail, add, cart, handoff).
Verified: :openassistant:testDevUnitTest and compileDevKotlin green
(245 tests, 0 failures).

Diff

openassistant/src/main/java/com/vayunmathur/openassistant/domain/AssistantToolSpecs.kt
diff --git a/openassistant/src/main/java/com/vayunmathur/openassistant/domain/AssistantToolSpecs.kt b/openassistant/src/main/java/com/vayunmathur/openassistant/domain/AssistantToolSpecs.ktindex d246070669..1a049b2afa 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/domain/AssistantToolSpecs.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/domain/AssistantToolSpecs.kt@@ -274,6 +274,51 @@ val ASSISTANT_TOOL_SPECS: List<ToolSpec> = listOf(         risk = HANDOFF_PREP,     ),     ToolSpec("get_food_orders", "Get the user's past FoodDelivery orders"),+    ToolSpec(+        "search_products",+        "Search the Shop catalog. Each result is one purchasable variant with its variant_id, " ++            "store and exact price.",+        listOf(+            p("query", description = "search text"),+            p("limit", NUMBER, "optional max results (default 5)", required = false),+        ),+    ),+    ToolSpec(+        "get_product_detail",+        "Get one product's variants with exact prices and availability. Confirm the exact " ++            "variant with the user before adding it to the cart.",+        listOf(+            p("shop_domain", description = "store domain from search_products"),+            p("product_id", description = "product id from search_products"),+            p("variant_id", description = "optional variant to price", required = false),+        ),+    ),+    ToolSpec("shop_get_cart", "Get the current Shop cart, grouped by store"),+    ToolSpec(+        "shop_add_to_cart",+        "Add an exact variant to the Shop cart. The variant is re-verified before writing " ++            "and the cart is shown back to the user; no checkout is started.",+        listOf(+            p("shop_domain", description = "store domain from search_products"),+            p("variant_id", description = "exact variant id from get_product_detail"),+            p("quantity", NUMBER, "quantity 1-99 (default 1)", required = false),+        ), risk = WRITE_LIGHT,+    ),+    ToolSpec(+        "shop_remove_from_cart",+        "Remove a variant from the Shop cart; the cart is shown back to the user.",+        listOf(p("variant_id", description = "variant id to remove")),+        risk = WRITE_LIGHT,+    ),+    ToolSpec(+        "start_shop_checkout",+        "Show the per-store cart summary for one store. The user checks out in the Shop app " ++            "itself; this never creates a checkout or charges anything, and opening the cart " ++            "is not a paid order.",+        listOf(p("shop_domain", description = "store domain to check out")),+        risk = HANDOFF_PREP,+    ),+    ToolSpec("get_shop_orders", "Get the user's Shop order summaries"),     ToolSpec("get_memories", "Get a list of all memories"),     ToolSpec("remove_memory", "Remove a memory by its id (requires confirmation)", listOf(p("id", NUMBER)), risk = WRITE_CONFIRM),     ToolSpec("add_to_memory", "Add a new memory to the list of memories", listOf(p("content"))),
openassistant/src/main/java/com/vayunmathur/openassistant/platform/A2uiTemplates.kt
diff --git a/openassistant/src/main/java/com/vayunmathur/openassistant/platform/A2uiTemplates.kt b/openassistant/src/main/java/com/vayunmathur/openassistant/platform/A2uiTemplates.ktindex 5dc56b8dce..f6d1567465 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/platform/A2uiTemplates.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/platform/A2uiTemplates.kt@@ -27,6 +27,19 @@ data class MenuItemRow(     val qty: Int = 0, ) +/** One selectable variant in a [A2uiTemplates.productCard]. */+data class ProductVariantRow(+    val variantId: String,+    val title: String,+    val price: Long,+    val currency: String = "USD",+    val available: Boolean = true,+)++/** Formats minor-unit money as $x.xx for the USD shop catalog. */+fun formatMoney(amount: Long, currency: String = "USD"): String =+    if (currency == "USD") formatCents(amount.toInt()) else "$amount $currency"+ /** One cart/order line row in the food and order-summary cards. */ data class CartLineRow(     val itemId: Int,@@ -370,6 +383,129 @@ object A2uiTemplates {         return envelope(components, data)     } +    /**+     * Product card (design §3.2): image/title/store, a variant [Picker],+     * a quantity stepper and one Add button (`shop.add`) whose context+     * snapshots the picked variant and qty. Picking/stepping alone sends+     * no turn.+     */+    fun productCard(+        title: String,+        storeName: String,+        shopDomain: String,+        imageUrl: String,+        variants: List<ProductVariantRow>,+    ): String {+        val hasImage = imageUrl.isNotBlank()+        val children = listOf("title", "store") ++            (if (hasImage) listOf("image") else emptyList()) ++            listOf("variants", "stepper", "btnAdd")+        val components = buildJsonArray {+            add(obj("id" to s("root"), "component" to s("Card"), "child" to s("col")))+            add(+                obj(+                    "id" to s("col"), "component" to s("Column"),+                    "children" to JsonArray(children.map { s(it) }),+                ),+            )+            add(text("title", title, "title"))+            add(text("store", storeName, "caption"))+            if (hasImage) {+                add(obj("id" to s("image"), "component" to s("Image"), "url" to s(imageUrl), "description" to s(title)))+            }+            add(+                obj(+                    "id" to s("variants"), "component" to s("Picker"),+                    "options" to path("/variants"), "value" to path("/variant"),+                    "action" to action("shop.variant", mapOf("id" to pathValue("/variant"))),+                ),+            )+            add(+                obj(+                    "id" to s("stepper"), "component" to s("QuantityStepper"),+                    "label" to s("Quantity"), "value" to path("/qty"),+                    "min" to JsonPrimitive(1), "max" to JsonPrimitive(99),+                ),+            )+            add(+                actionButton(+                    "btnAdd", "Add to cart", "shop.add",+                    mapOf(+                        "shop_domain" to s(shopDomain),+                        "variant_id" to pathValue("/variant"),+                        "quantity" to pathValue("/qty"),+                    ),+                    primary = true,+                ),+            )+        }+        val data = buildJsonObject {+            put("shopDomain", shopDomain)+            put(+                "variants",+                JsonArray(+                    variants.map { v ->+                        buildJsonObject {+                            put("id", v.variantId)+                            put("title", v.title)+                            put(+                                "caption",+                                formatMoney(v.price, v.currency) + if (v.available) "" else " · unavailable",+                            )+                        }+                    },+                ),+            )+            put("variant", variants.firstOrNull()?.variantId ?: "")+            put("qty", 1)+        }+        return envelope(components, data)+    }++    /** Shop cart card: every store's lines and per-store totals. */+    fun shopCart(stores: List<Pair<String, List<String>>>, totalItems: Int): String {+        val lines = stores.flatMap { (store, storeLines) -> listOf(store) + storeLines }+        return cartCard(+            title = "Shop cart ($totalItems items)",+            lines = lines,+            totalLine = if (lines.isEmpty()) "Cart is empty" else "$totalItems item(s) in cart",+            dataExtra = emptyMap(),+        )+    }++    /** Per-store checkout summary; the button deep-links the store's Shop cart. */+    fun shopCheckoutSummary(+        storeName: String,+        shopDomain: String,+        lines: List<String>,+        checkoutDeepLink: String = "shop://cart",+    ): String {+        val lineIds = lines.indices.map { "line$it" }+        val components = buildJsonArray {+            add(obj("id" to s("root"), "component" to s("Card"), "child" to s("col")))+            add(+                obj(+                    "id" to s("col"), "component" to s("Column"),+                    "children" to JsonArray(listOf(s("title")) + lineIds.map { s(it) } + listOf(s("btnCheckout"))),+                ),+            )+            add(text("title", storeName.ifBlank { "Checkout" }, "title"))+            lines.forEachIndexed { i, line -> add(text("line$i", line, "body")) }+            add(+                actionButton(+                    "btnCheckout", "Open $storeName checkout in Shop", "handoff.shop_checkout",+                    mapOf("deepLink" to s(checkoutDeepLink), "shopDomain" to s(shopDomain)),+                    primary = true,+                ),+            )+        }+        val data = buildJsonObject {+            put("shopDomain", shopDomain)+            put("checkoutDeepLink", checkoutDeepLink)+        }+        return envelope(components, data)+    }+     private fun cartCard(         title: String,         lines: List<String>,
openassistant/src/main/java/com/vayunmathur/openassistant/platform/AssistantCatalog.kt
diff --git a/openassistant/src/main/java/com/vayunmathur/openassistant/platform/AssistantCatalog.kt b/openassistant/src/main/java/com/vayunmathur/openassistant/platform/AssistantCatalog.ktindex 11650c149d..52c8e48a00 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/platform/AssistantCatalog.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/platform/AssistantCatalog.kt@@ -170,6 +170,8 @@ class AssistantCatalog(urlOpener: A2uiUrlOpener, messageFormatter: A2uiMessageFo                     "msg.send (composer Send; host-gated, do not invent) and msg.cancel, " +                     "cart.food.update ({\"merchantId\": n, \"items\": [...]}) after stepping menu quantities, " +                     "handoff.food_checkout (opens FoodDelivery checkout; host action, do not invent), " ++                    "shop.add ({\"shop_domain\": ..., \"variant_id\": ..., \"quantity\": n}) from the product card, " ++                    "handoff.shop_checkout (opens the Shop cart; host action, do not invent), " +                     "open.conversation (opens a message thread in Communicate), " +                     "web.read ({\"index\": n}) and web.open ({\"url\": ...}). Use those names exactly.",             )
openassistant/src/main/java/com/vayunmathur/openassistant/platform/AssistantTools.kt
diff --git a/openassistant/src/main/java/com/vayunmathur/openassistant/platform/AssistantTools.kt b/openassistant/src/main/java/com/vayunmathur/openassistant/platform/AssistantTools.ktindex 5c1f388724..73072fda80 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/platform/AssistantTools.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/platform/AssistantTools.kt@@ -341,6 +341,119 @@ class AssistantTools(                 com.vayunmathur.openassistant.util.summarizeFoodOrders(intents.getFoodOrders())             }         },+        "search_products" to { a ->+            intents.runTool {+                val limit = a.number("limit").toInt().takeIf { it > 0 } ?: 5+                val list = intents.searchProducts(a.string("query"), limit)+                // One product card per call would flood the chat; the first hit's card+                // demonstrates variants/stepper, the rest stay model-readable text.+                list.firstOrNull()?.let { first ->+                    intents.getProductDetail(first.shopDomain, first.productId, first.variantId)+                        .takeIf { it.error == null && it.variants.isNotEmpty() }+                        ?.let { detail ->+                            pendingRenderUi = A2uiTemplates.productCard(+                                detail.title, detail.storeName, detail.shopDomain, detail.imageUrl,+                                detail.variants.map {+                                    ProductVariantRow(it.variantId, it.title, it.price, it.currency, it.available)+                                },+                            )+                        }+                }+                com.vayunmathur.openassistant.util.summarizeProducts(list)+            }+        },+        "get_product_detail" to { a ->+            intents.runTool {+                val detail = intents.getProductDetail(+                    a.string("shop_domain"), a.string("product_id"),+                    a.string("variant_id").takeIf { it.isNotBlank() },+                )+                if (detail.error == null && detail.variants.isNotEmpty()) {+                    pendingRenderUi = A2uiTemplates.productCard(+                        detail.title, detail.storeName, detail.shopDomain, detail.imageUrl,+                        detail.variants.map {+                            ProductVariantRow(it.variantId, it.title, it.price, it.currency, it.available)+                        },+                    )+                }+                com.vayunmathur.openassistant.util.summarizeProductDetail(detail)+            }+        },+        "shop_get_cart" to { _ ->+            intents.runTool {+                val cart = intents.getShopCart()+                if (cart.error == null && cart.totalItems > 0) {+                    pendingRenderUi = A2uiTemplates.shopCart(+                        cart.stores.map { store ->+                            store.storeName to store.lines.map {+                                "${it.title} ${it.variantTitle} × ${it.quantity} — ${formatMoney(it.price * it.quantity, it.currency)}"+                            }+                        },+                        cart.totalItems,+                    )+                }+                com.vayunmathur.openassistant.util.summarizeShopCart(cart)+            }+        },+        "shop_add_to_cart" to { a ->+            val quantity = a.number("quantity").toInt().takeIf { it > 0 } ?: 1+            intents.runTool {+                val cart = intents.addToShopCart(+                    com.vayunmathur.library.intents.shop.AddToCartRequest(+                        a.string("shop_domain"), a.string("variant_id"), quantity,+                    ),+                )+                // Light write: executed once, cart rendered back, never auto-retried.+                if (cart.error == null) {+                    pendingRenderUi = A2uiTemplates.shopCart(+                        cart.stores.map { store ->+                            store.storeName to store.lines.map {+                                "${it.title} ${it.variantTitle} × ${it.quantity} — ${formatMoney(it.price * it.quantity, it.currency)}"+                            }+                        },+                        cart.totalItems,+                    )+                }+                com.vayunmathur.openassistant.util.summarizeShopCart(cart)+            }+        },+        "shop_remove_from_cart" to { a ->+            intents.runTool {+                val cart = intents.removeFromShopCart(a.string("variant_id"))+                if (cart.error == null) {+                    pendingRenderUi = A2uiTemplates.shopCart(+                        cart.stores.map { store ->+                            store.storeName to store.lines.map {+                                "${it.title} ${it.variantTitle} × ${it.quantity} — ${formatMoney(it.price * it.quantity, it.currency)}"+                            }+                        },+                        cart.totalItems,+                    )+                }+                com.vayunmathur.openassistant.util.summarizeShopCart(cart)+            }+        },+        "start_shop_checkout" to { a ->+            intents.runTool {+                val cart = intents.getShopCart()+                val store = cart.stores.firstOrNull { it.shopDomain == a.string("shop_domain") }+                if (cart.error == null && store != null && store.lines.isNotEmpty()) {+                    pendingRenderUi = A2uiTemplates.shopCheckoutSummary(+                        store.storeName, store.shopDomain,+                        store.lines.map {+                            "${it.title} ${it.variantTitle} × ${it.quantity} — ${formatMoney(it.price * it.quantity, it.currency)}"+                        },+                    )+                }+                com.vayunmathur.openassistant.util.summarizeShopCart(cart) ++                    " Show the user this summary; they check out in Shop. This is not a paid order."+            }+        },+        "get_shop_orders" to { _ ->+            intents.runTool {+                com.vayunmathur.openassistant.util.summarizeShopOrders(intents.getShopOrders())+            }+        },         "web_search" to { a ->             val count = a.number("count").toInt().takeIf { it > 0 } ?: 5             val result = runBlocking { webTools.webSearch(a.string("query"), count, a.string("kind", "text")) }
openassistant/src/main/java/com/vayunmathur/openassistant/util/AssistantToolIntents.kt
diff --git a/openassistant/src/main/java/com/vayunmathur/openassistant/util/AssistantToolIntents.kt b/openassistant/src/main/java/com/vayunmathur/openassistant/util/AssistantToolIntents.ktindex efe01604da..99f7d364bd 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/util/AssistantToolIntents.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/util/AssistantToolIntents.kt@@ -40,6 +40,14 @@ import com.vayunmathur.library.intents.fooddelivery.RestaurantData import com.vayunmathur.library.intents.fooddelivery.SetCart import com.vayunmathur.library.intents.fooddelivery.SetCartItem import com.vayunmathur.library.intents.maps.DirectionsRequest+import com.vayunmathur.library.intents.shop.AddToCartRequest+import com.vayunmathur.library.intents.shop.CartData as ShopCartData+import com.vayunmathur.library.intents.shop.GetProductQuery+import com.vayunmathur.library.intents.shop.OrderData as ShopOrderData+import com.vayunmathur.library.intents.shop.ProductData+import com.vayunmathur.library.intents.shop.ProductDetailData+import com.vayunmathur.library.intents.shop.RemoveFromCartRequest+import com.vayunmathur.library.intents.shop.SearchProductsQuery import com.vayunmathur.library.intents.maps.DirectionsResult import com.vayunmathur.library.intents.taxi.RideEstimateRequest import com.vayunmathur.library.intents.taxi.RideEstimateResult@@ -359,6 +367,48 @@ internal class AssistantToolIntents(private val context: Context) {         FoodGetOrders(),     ) +    suspend fun searchProducts(query: String, limit: Int): List<ProductData> = launchIntent(+        context,+        "com.vayunmathur.shop",+        "com.vayunmathur.shop.intents.SearchProductsIntent",+        SearchProductsQuery(query, limit),+    )++    suspend fun getProductDetail(shopDomain: String, productId: String, variantId: String?): ProductDetailData = launchIntent(+        context,+        "com.vayunmathur.shop",+        "com.vayunmathur.shop.intents.GetProductIntent",+        GetProductQuery(shopDomain, productId, variantId),+    )++    suspend fun getShopCart(): ShopCartData = launchIntent(+        context,+        "com.vayunmathur.shop",+        "com.vayunmathur.shop.intents.GetCartIntent",+        Unit,+    )++    suspend fun addToShopCart(request: AddToCartRequest): ShopCartData = launchIntent(+        context,+        "com.vayunmathur.shop",+        "com.vayunmathur.shop.intents.AddToCartIntent",+        request,+    )++    suspend fun removeFromShopCart(variantId: String): ShopCartData = launchIntent(+        context,+        "com.vayunmathur.shop",+        "com.vayunmathur.shop.intents.RemoveFromCartIntent",+        RemoveFromCartRequest(variantId),+    )++    suspend fun getShopOrders(): List<ShopOrderData> = launchIntent(+        context,+        "com.vayunmathur.shop",+        "com.vayunmathur.shop.intents.GetOrdersIntent",+        Unit,+    )+     suspend fun getContactsList(): List<ContactData> = launchIntent<Unit, List<ContactData>>(         context,         "com.vayunmathur.contacts",@@ -550,6 +600,47 @@ fun parseSetCartItems(itemsJson: String): List<SetCartItem>? {     } } +/** Host-truncated product hits for the model: one line per purchasable variant. */+fun summarizeProducts(list: List<ProductData>): String =+    if (list.isEmpty()) {+        "No products found"+    } else {+        list.joinToString("\n") { p ->+            "variant_id=${p.variantId} product_id=${p.productId} ${p.title} ${p.price} ${p.currency} @ ${p.storeName} (${p.shopDomain}) checkout=${p.checkoutEligible}"+        }+    }++/** Product detail for the model: every variant's exact price/availability. */+fun summarizeProductDetail(detail: ProductDetailData): String {+    if (detail.error != null) return "Error: product unavailable (${detail.error})"+    val variants = detail.variants.joinToString("\n") { v ->+        "variant_id=${v.variantId} ${v.title} ${v.price} ${v.currency} ${if (v.available) "available" else "unavailable"}"+    }+    return "Product ${detail.title} @ ${detail.storeName} (${detail.shopDomain}) from ${detail.price} ${detail.currency}:\n$variants"+}++/** Shop cart for the model, grouped per store; a refused write leaves it unchanged. */+fun summarizeShopCart(cart: ShopCartData): String {+    if (cart.error != null) return "Error: cart not updated (${cart.error})"+    if (cart.stores.isEmpty() || cart.totalItems == 0) return "Shop cart is empty"+    return cart.stores.joinToString("\n") { store ->+        val lines = store.lines.joinToString("\n") { l ->+            "variant_id=${l.variantId} ${l.title} ${l.variantTitle} x${l.quantity} ${l.price} ${l.currency}"+        }+        "Store ${store.storeName} (${store.shopDomain}):\n$lines"+    }+}++/** Host-truncated shop order summaries; a pending handoff is never a paid order. */+fun summarizeShopOrders(list: List<ShopOrderData>, cap: Int = 10): String =+    if (list.isEmpty()) {+        "No shop orders"+    } else {+        list.take(cap).joinToString("\n") { o ->+            "order_id=${o.orderId} ${o.storeName} ${o.status} ${o.total} ${o.currency} items=${o.itemCount}"+        }+    }+ /** Maps a provider send outcome to the model-facing string; GV is typed. */ fun summarizeSendResult(result: SendMessageResult): String = when {     result.success -> "Success: Message sent"
openassistant/src/main/java/com/vayunmathur/openassistant/util/AssistantViewModel.kt
diff --git a/openassistant/src/main/java/com/vayunmathur/openassistant/util/AssistantViewModel.kt b/openassistant/src/main/java/com/vayunmathur/openassistant/util/AssistantViewModel.ktindex ca0ce20894..2e6f858b5c 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/util/AssistantViewModel.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/util/AssistantViewModel.kt@@ -148,6 +148,12 @@ class AssistantViewModel(                 }                 return true             }+            "handoff.shop_checkout" -> {+                val link = context["deepLink"]?.toString().orEmpty()+                if (link.isBlank()) return false+                openUrl(link)+                return true+            }             "handoff.food_checkout" -> {                 val link = context["deepLink"]?.toString().orEmpty()                 if (link.isBlank()) return false
openassistant/src/main/java/com/vayunmathur/openassistant/util/InferenceService.kt
diff --git a/openassistant/src/main/java/com/vayunmathur/openassistant/util/InferenceService.kt b/openassistant/src/main/java/com/vayunmathur/openassistant/util/InferenceService.ktindex 9835814a48..9b9cb27466 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/util/InferenceService.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/util/InferenceService.kt@@ -122,6 +122,11 @@ class InferenceService : Service() {             FOOD (FoodDelivery app):             - find_restaurants needs a latitude/longitude; get_restaurant_menu shows items with ids and prices in cents. Build carts only from menu item ids, with modifier ids from that item's groups.             - food_set_cart replaces the cart and is shown back to the user immediately; then food_prepare_order prices it. place_food_order only shows the summary: the user taps Place order in FoodDelivery to pay. Never claim an order was placed or paid for from here.++            SHOPPING (Shop app, prepare-only):+            - search_products returns one row per variant; get_product_detail confirms the exact variant, price and availability before any cart add. Ask the user to confirm the exact variant when more than one fits.+            - shop_add_to_cart / shop_remove_from_cart write the local cart and are shown back immediately. A failed add is uncertain: report it, never retry it automatically.+            - start_shop_checkout only shows a per-store summary and opens the cart in Shop; checkout happens there. Never call the handoff a placed or paid order, and never invent profile details: Shop handles checkout inputs itself.             """.trimIndent()     } 
openassistant/src/test/java/com/vayunmathur/openassistant/platform/A2uiTemplatesTest.kt
diff --git a/openassistant/src/test/java/com/vayunmathur/openassistant/platform/A2uiTemplatesTest.kt b/openassistant/src/test/java/com/vayunmathur/openassistant/platform/A2uiTemplatesTest.ktindex cbfd2af19d..99c76a878e 100644--- a/openassistant/src/test/java/com/vayunmathur/openassistant/platform/A2uiTemplatesTest.kt+++ b/openassistant/src/test/java/com/vayunmathur/openassistant/platform/A2uiTemplatesTest.kt@@ -189,6 +189,27 @@ class A2uiTemplatesTest {         assertTrue(summary.contains("fooddelivery://checkout"), summary)     } +    @Test fun shopTemplatesAreEnvelopeValid() {+        val product = A2uiTemplates.productCard(+            "Enamel Mug", "Kitchen Co", "kitchen.example", "https://example.com/mug.png",+            listOf(ProductVariantRow("v1", "Blue", 1500), ProductVariantRow("v2", "Red", 1600, available = false)),+        )+        assertEnvelopeValid(product)+        assertEquals("Picker", componentsOf(product).getValue("variants")["component"])+        assertEquals("QuantityStepper", componentsOf(product).getValue("stepper")["component"])+        assertTrue(product.contains("shop.add") && product.contains("Enamel Mug"), product)++        val cart = A2uiTemplates.shopCart(listOf("Kitchen Co" to listOf("Enamel Mug Blue × 1 — $15.00")), 1)+        assertEnvelopeValid(cart)+        assertTrue(cart.contains("Kitchen Co"), cart)++        val summary = A2uiTemplates.shopCheckoutSummary(+            "Kitchen Co", "kitchen.example", listOf("Enamel Mug Blue × 1 — $15.00"))+        assertEnvelopeValid(summary)+        assertTrue(summary.contains("handoff.shop_checkout"), summary)+        assertTrue(summary.contains("shop://cart"), summary)+    }+     @Test fun redactedSummaryShowsLengthsOnly() {         assertEquals(             "content(len=12), title(len=1)",
openassistant/src/test/java/com/vayunmathur/openassistant/platform/AssistantToolsInvokeTest.kt
diff --git a/openassistant/src/test/java/com/vayunmathur/openassistant/platform/AssistantToolsInvokeTest.kt b/openassistant/src/test/java/com/vayunmathur/openassistant/platform/AssistantToolsInvokeTest.ktindex 46c1a0972b..2a54f6f3aa 100644--- a/openassistant/src/test/java/com/vayunmathur/openassistant/platform/AssistantToolsInvokeTest.kt+++ b/openassistant/src/test/java/com/vayunmathur/openassistant/platform/AssistantToolsInvokeTest.kt@@ -44,7 +44,7 @@ class AssistantToolsInvokeTest {         assertEquals("Error: create_note needs title", call("create_note", "content" to "x"))         assertTrue(             call("set_timer", "seconds" to "abc").contains("must be a number"))-        assertEquals(47, tools.declarations.size)+        assertEquals(54, tools.declarations.size)     }      @Test fun crossAppToolsReportMissingApps() {@@ -246,12 +246,26 @@ class AssistantToolsInvokeTest {         assertTrue(call("place_food_order", "merchant_id" to "3").startsWith("The FoodDelivery app is required"))     } +    @Test fun shopToolsMissingAppAndPrepareOnly() {+        assertTrue(call("search_products", "query" to "mug").startsWith("The Shop app is required"))+        assertTrue(call("get_product_detail", "shop_domain" to "s.example", "product_id" to "p1").startsWith("The Shop app is required"))+        assertTrue(call("shop_get_cart").startsWith("The Shop app is required"))+        assertTrue(call("get_shop_orders").startsWith("The Shop app is required"))+        // Light writes execute without a gate (missing app surfaces here).+        assertTrue(call("shop_add_to_cart", "shop_domain" to "s.example", "variant_id" to "v1").startsWith("The Shop app is required"))+        assertTrue(call("shop_remove_from_cart", "variant_id" to "v1").startsWith("The Shop app is required"))+        // Handoff reads the cart only; there is no checkout tool at all.+        assertTrue(call("start_shop_checkout", "shop_domain" to "s.example").startsWith("The Shop app is required"))+        assertEquals(null, tools.specFor("shop_checkout"))+        assertEquals(null, tools.specFor("create_checkout"))+    }+     @Test fun riskClassificationMatchesDesign() {         val gated = setOf("create_note", "create_todo", "complete_todo", "create_contact",             "create_calendar_event", "create_location_share_link", "play_music",             "set_alarm", "set_timer", "remove_memory", "send_message_v2")-        val light = setOf("food_set_cart")-        val handoff = setOf("place_food_order")+        val light = setOf("food_set_cart", "shop_add_to_cart", "shop_remove_from_cart")+        val handoff = setOf("place_food_order", "start_shop_checkout")         for (spec in com.vayunmathur.openassistant.domain.ASSISTANT_TOOL_SPECS) {             val expected = when (spec.name) {                 in gated -> com.vayunmathur.openassistant.domain.ToolRisk.WRITE_CONFIRM
openassistant/src/test/java/com/vayunmathur/openassistant/platform/AssistantToolsTest.kt
diff --git a/openassistant/src/test/java/com/vayunmathur/openassistant/platform/AssistantToolsTest.kt b/openassistant/src/test/java/com/vayunmathur/openassistant/platform/AssistantToolsTest.ktindex 7dcd518591..fbf2e89d30 100644--- a/openassistant/src/test/java/com/vayunmathur/openassistant/platform/AssistantToolsTest.kt+++ b/openassistant/src/test/java/com/vayunmathur/openassistant/platform/AssistantToolsTest.kt@@ -14,7 +14,7 @@ class AssistantToolsTest {     @Test     fun namesAreUniqueSnakeCase() {         val names = ASSISTANT_TOOL_SPECS.map { it.name }-        assertEquals(47, names.size)+        assertEquals(54, names.size)         assertEquals(names.size, names.toSet().size)         for (spec in ASSISTANT_TOOL_SPECS) {             assertTrue(snake.matches(spec.name), spec.name)@@ -67,6 +67,7 @@ class AssistantToolsTest {                 "get_restaurant_menu.merchant_id", "food_set_cart.merchant_id",                 "food_prepare_order.merchant_id", "food_prepare_order.is_pickup",                 "food_prepare_order.tip_cents", "place_food_order.merchant_id",+                "search_products.limit", "shop_add_to_cart.quantity",             ),             numeric,         )
openassistant/src/test/java/com/vayunmathur/openassistant/platform/MamlChatEngineFakeModelTest.kt
diff --git a/openassistant/src/test/java/com/vayunmathur/openassistant/platform/MamlChatEngineFakeModelTest.kt b/openassistant/src/test/java/com/vayunmathur/openassistant/platform/MamlChatEngineFakeModelTest.ktindex 3d3988952c..3712a3e45c 100644--- a/openassistant/src/test/java/com/vayunmathur/openassistant/platform/MamlChatEngineFakeModelTest.kt+++ b/openassistant/src/test/java/com/vayunmathur/openassistant/platform/MamlChatEngineFakeModelTest.kt@@ -169,6 +169,27 @@ class MamlChatEngineFakeModelTest {         e.close()     } +    @Test fun shopScriptSearchesAddsAndHandsOff() = runBlocking {+        var calls = 0+        val quoted = { s: String -> "<|\"|>" + s + "<|\"|>" }+        val script = listOf(+            "<|tool_call>call:search_products{query:${quoted("mug")}}<tool_call|>",+            "<|tool_call>call:get_product_detail{shop_domain:${quoted("kitchen.example")},product_id:${quoted("p1")}}<tool_call|>",+            "<|tool_call>call:shop_add_to_cart{shop_domain:${quoted("kitchen.example")},variant_id:${quoted("v1")},quantity:1}<tool_call|>",+            "<|tool_call>call:shop_get_cart{}<tool_call|>",+            "<|tool_call>call:start_shop_checkout{shop_domain:${quoted("kitchen.example")}}<tool_call|>",+        )+        val fake = FakeTextModel(script = { _, onToken ->+            calls+++            if (calls <= script.size) script[calls - 1] else { onToken("done"); "done" }+        })+        val e = engine(fake)+        val result = e.chat(ChatRequest("sys", emptyList(), "buy a mug"), tools()) { true }+        assertEquals(ChatResult.Reply("done", halted = false), result)+        assertEquals(6, calls)+        e.close()+    }+     @Test fun haltedStreamAndTooLongAndUnavailable() = runBlocking {         val fake = FakeTextModel()         val e = engine(fake)
openassistant/src/test/java/com/vayunmathur/openassistant/util/AssistantToolIntentsTest.kt
diff --git a/openassistant/src/test/java/com/vayunmathur/openassistant/util/AssistantToolIntentsTest.kt b/openassistant/src/test/java/com/vayunmathur/openassistant/util/AssistantToolIntentsTest.ktindex 3471d0bdf9..e0400509a1 100644--- a/openassistant/src/test/java/com/vayunmathur/openassistant/util/AssistantToolIntentsTest.kt+++ b/openassistant/src/test/java/com/vayunmathur/openassistant/util/AssistantToolIntentsTest.kt@@ -184,6 +184,32 @@ class AssistantToolIntentsTest {             com.vayunmathur.library.intents.fooddelivery.MenuData(error = "DOWN")).contains("DOWN"))     } +    @Test fun shopToolsThrowMissingAppAndSummaries() = runTest {+        assertFailsWith<MissingAppException> { tools.searchProducts("mug", 5) }+        assertFailsWith<MissingAppException> { tools.getProductDetail("s.example", "p1", null) }+        assertFailsWith<MissingAppException> { tools.getShopCart() }+        assertFailsWith<MissingAppException> { tools.getShopOrders() }+        assertTrue(+            AssistantToolIntents.getMissingAppMessage("com.vayunmathur.shop").contains("The Shop app"))+        val products = summarizeProducts(+            listOf(+                com.vayunmathur.library.intents.shop.ProductData(+                    "Mug", "p1", "v1", "s.example", "Store", 1500, "USD", "", true)))+        assertTrue(products.contains("variant_id=v1"), products)+        val cart = summarizeShopCart(+            com.vayunmathur.library.intents.shop.CartData(+                stores = listOf(+                    com.vayunmathur.library.intents.shop.CartStoreData(+                        "s.example", "Store",+                        listOf(+                            com.vayunmathur.library.intents.shop.CartLineData(+                                "Mug", "Blue", "v1", "s.example", "Store", 1500, "USD", 2)))),+                totalItems = 2))+        assertTrue(cart.contains("Mug") && cart.contains("Store"), cart)+        assertEquals("Shop cart is empty", summarizeShopCart(+            com.vayunmathur.library.intents.shop.CartData()))+    }+     @Test fun requestPayloadShapes() {         assertEquals(3.5, WeatherLatLonRequest(3.5, -1.25).latitude)         assertEquals("Lisbon", WeatherNameRequest("Lisbon").name)