Modern Apps git

← Modern-Apps.git

openassistant: food ordering tools with checkout handoff (#assistant)

Commit
47b4e7c45718d72a72683123e1ff4a896979b9b8
Author
Vayun Mathur <[email protected]>
When
2026-11-16 23:16 UTC (19 days ago)
Parents
fd78573
Wire the consumer side of the fooddelivery assistant intents (P4):
find_restaurants, get_restaurant_menu, food_get_cart and
get_food_orders are READ tools returning host-truncated summaries
(top-N, field whitelist, capped menu) so menus never blow the reply
cap, and each renders a host card: restaurant list-picker, menu card
with per-item QuantitySteppers, and the cart card.

food_set_cart is the design's light write (new ToolRisk.WRITE_LIGHT):
it parses items_json host-side, executes immediately since the
provider cart is reversible and moves no money, and always renders
the resulting cart back as a card. Invalid items_json is rejected
before any IPC. food_prepare_order prices the cart without creating
an order.

place_food_order is HANDOFF_PREP: it re-prices the cart, renders an
order-summary card whose Place order button is the host action
handoff.food_checkout, intercepted in AssistantViewModel to deep-link
fooddelivery://checkout, where FoodDelivery's own Stripe flow is the
payment confirmation. No assistant code path creates an order or
sees a clientSecret.

Prompt sections (FOOD system-prompt block, A2UI action vocabulary
with cart.food.update and handoff.food_checkout) teach the flow;
they invalidate the baked gemma prefix, which rebakes on first use.

Tests: menu/cart/summary template snapshots incl. formatCents,
spec parity and risk classification (light vs handoff vs gated),
items_json parsing, missing-app paths, and a fake-model golden
order-food script (find, menu, set cart, prepare, handoff) proving
the exact sequence with no gate and no order placed.
Verified: :openassistant:testDevUnitTest and compileDevKotlin green.

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 17380c3c14..d246070669 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/domain/AssistantToolSpecs.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/domain/AssistantToolSpecs.kt@@ -227,6 +227,53 @@ val ASSISTANT_TOOL_SPECS: List<ToolSpec> = listOf(             p("thread_remote_id", description = "optional existing thread id to reply into", required = false),         ), risk = WRITE_CONFIRM,     ),+    ToolSpec(+        "find_restaurants",+        "Find restaurants near a location via the FoodDelivery app, optionally filtered by name or tag.",+        listOf(+            p("query", description = "optional name or tag filter", required = false),+            p("lat", NUMBER, "latitude"),+            p("lng", NUMBER, "longitude"),+            p("limit", NUMBER, "optional max results (default 5)", required = false),+        ),+    ),+    ToolSpec(+        "get_restaurant_menu",+        "Get the menu of a restaurant (merchant_id from find_restaurants). Items carry ids, " ++            "prices in cents, availability and modifier groups.",+        listOf(p("merchant_id", NUMBER, "merchant id from find_restaurants")),+    ),+    ToolSpec("food_get_cart", "Get the current FoodDelivery cart (items and total)"),+    ToolSpec(+        "food_set_cart",+        "Replace the FoodDelivery cart with items_json: a JSON array like " ++            "[{\"itemId\":1,\"qty\":2,\"modifierIds\":[]}]. The cart is re-validated and shown " ++            "back to the user right away; no order is placed and no money moves.",+        listOf(+            p("merchant_id", NUMBER, "merchant id the items belong to"),+            p("items_json", description = "JSON array of {itemId, qty, modifierIds}"),+        ), risk = WRITE_LIGHT,+    ),+    ToolSpec(+        "food_prepare_order",+        "Price the current cart for an order (pickup or delivery) without creating an order. " ++            "Returns the summary the user will confirm in the FoodDelivery app.",+        listOf(+            p("merchant_id", NUMBER, "merchant id of the cart"),+            p("is_pickup", NUMBER, "1 for pickup, 0 (default) for delivery", required = false),+            p("address_id", description = "optional saved address id", required = false),+            p("tip_cents", NUMBER, "optional tip in cents", required = false),+            p("promo", description = "optional promo code", required = false),+        ),+    ),+    ToolSpec(+        "place_food_order",+        "Show the order summary for the current cart. The user places and pays for the order " ++            "in the FoodDelivery app itself; this never creates an order or charges a card.",+        listOf(p("merchant_id", NUMBER, "merchant id of the cart")),+        risk = HANDOFF_PREP,+    ),+    ToolSpec("get_food_orders", "Get the user's past FoodDelivery orders"),     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 6ef3737a52..5dc56b8dce 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/platform/A2uiTemplates.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/platform/A2uiTemplates.kt@@ -18,6 +18,30 @@ data class PickerItem(     val imageUrl: String? = null, ) +/** One menu row in a [A2uiTemplates.foodMenu] card. */+data class MenuItemRow(+    val id: Int,+    val name: String,+    val priceCents: Int,+    val available: Boolean,+    val qty: Int = 0,+)++/** One cart/order line row in the food and order-summary cards. */+data class CartLineRow(+    val itemId: Int,+    val name: String,+    val qty: Int,+    val lineTotalCents: Int,+)++/** Formats integer cents as a dollar string ($12.34, -$1.00). */+fun formatCents(cents: Int): String {+    val sign = if (cents < 0) "-" else ""+    val abs = kotlin.math.abs(cents)+    return "$sign\$${abs / 100}.${(abs % 100).toString().padStart(2, '0')}"+}+ /** One web search result in a [A2uiTemplates.searchResults] card. */ data class SearchResultItem(     val index: Int,@@ -219,6 +243,159 @@ object A2uiTemplates {         return envelope(components, data)     } +    /**+     * Menu card (design §3.2 item card): one row per item with a+     * [QuantityStepper] bound to that item's qty. Steppers only edit card+     * data; the single Update cart button (`cart.food.update`) snapshots+     * every qty back to the model in one turn.+     */+    fun foodMenu(merchantName: String, merchantId: Int, items: List<MenuItemRow>): String {+        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"), s("items"), s("btnUpdate"))),+                ),+            )+            add(text("title", merchantName, "title"))+            add(+                obj(+                    "id" to s("items"), "component" to s("List"),+                    "children" to buildJsonObject {+                        put("componentId", "item")+                        put("path", "/items")+                    },+                ),+            )+            add(+                obj(+                    "id" to s("item"), "component" to s("Row"),+                    "children" to JsonArray(listOf(s("itemBody"), s("stepper"))),+                ),+            )+            add(+                obj(+                    "id" to s("itemBody"), "component" to s("Column"),+                    "children" to JsonArray(listOf(s("itemName"), s("itemPrice"))),+                ),+            )+            add(boundText("itemName", "/name", "body"))+            add(boundText("itemPrice", "/priceText", "caption"))+            add(+                obj(+                    "id" to s("stepper"), "component" to s("QuantityStepper"),+                    "value" to path("/qty"),+                    "min" to JsonPrimitive(0), "max" to JsonPrimitive(99),+                ),+            )+            add(+                actionButton(+                    "btnUpdate", "Update cart", "cart.food.update",+                    mapOf("merchantId" to JsonPrimitive(merchantId), "items" to pathValue("/items")),+                    primary = true,+                ),+            )+        }+        val data = buildJsonObject {+            put("merchantId", merchantId)+            put(+                "items",+                JsonArray(+                    items.map { item ->+                        buildJsonObject {+                            put("id", item.id)+                            put("name", item.name)+                            put("priceCents", item.priceCents)+                            put("priceText", formatCents(item.priceCents) + if (item.available) "" else " · unavailable")+                            put("qty", item.qty)+                        }+                    },+                ),+            )+        }+        return envelope(components, data)+    }++    /** Cart card: lines, total, and (when non-empty) a checkout handoff button. */+    fun foodCart(merchantName: String, merchantId: Int, items: List<CartLineRow>, totalCents: Int): String =+        cartCard(+            title = merchantName.ifBlank { "Your cart" },+            lines = items.map { "${it.name} × ${it.qty} — ${formatCents(it.lineTotalCents)}" },+            totalLine = "Total ${formatCents(totalCents)}",+            dataExtra = mapOf("merchantId" to JsonPrimitive(merchantId)),+        )++    /** Order-summary card: the primary button is the food checkout host handoff. */+    fun foodOrderSummary(+        merchantName: String,+        lines: List<String>,+        subtotalCents: Int,+        tipCents: Int,+        totalCents: Int,+        checkoutDeepLink: String,+        merchantId: Int,+    ): String {+        val allLines = lines + listOf(+            "Subtotal ${formatCents(subtotalCents)}",+            "Tip ${formatCents(tipCents)}",+            "Total ${formatCents(totalCents)} (final total confirmed in FoodDelivery)",+        )+        val lineIds = allLines.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", merchantName.ifBlank { "Order" }, "title"))+            allLines.forEachIndexed { i, line -> add(text("line$i", line, "body")) }+            add(+                actionButton(+                    "btnCheckout", "Place order in FoodDelivery", "handoff.food_checkout",+                    mapOf("deepLink" to s(checkoutDeepLink), "merchantId" to JsonPrimitive(merchantId)),+                    primary = true,+                ),+            )+        }+        val data = buildJsonObject {+            put("merchantId", merchantId)+            put("checkoutDeepLink", checkoutDeepLink)+            put("totalCents", totalCents)+        }+        return envelope(components, data)+    }++    private fun cartCard(+        title: String,+        lines: List<String>,+        totalLine: String,+        dataExtra: Map<String, JsonElement>,+    ): 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("total"))),+                ),+            )+            add(text("title", title, "title"))+            lines.forEachIndexed { i, line -> add(text("line$i", line, "body")) }+            add(text("total", totalLine, "title"))+        }+        val data = buildJsonObject {+            put("title", title)+            dataExtra.forEach { (k, v) -> put(k, v) }+        }+        return envelope(components, data)+    }+     private fun actionButton(         id: String,         label: 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 5f3553668d..11650c149d 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/platform/AssistantCatalog.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/platform/AssistantCatalog.kt@@ -168,6 +168,8 @@ class AssistantCatalog(urlOpener: A2uiUrlOpener, messageFormatter: A2uiMessageFo                     "pick.conversation carries a thread_key), " +                     "confirm.tool / cancel.tool (host confirmation, do not invent these), " +                     "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), " +                     "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 8157712e17..5c1f388724 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/platform/AssistantTools.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/platform/AssistantTools.kt@@ -238,6 +238,109 @@ class AssistantTools(                 com.vayunmathur.openassistant.util.summarizeSendResult(result)             }         },+        "find_restaurants" to { a ->+            intents.runTool {+                val limit = a.number("limit").toInt().takeIf { it > 0 } ?: 5+                val list = intents.findRestaurants(+                    a.string("query"), a.number("lat"), a.number("lng"), limit)+                if (list.isNotEmpty()) {+                    pendingRenderUi = A2uiTemplates.listPicker(+                        "Restaurants",+                        list.map {+                            PickerItem(+                                it.id.toString(), it.name,+                                "${if (it.isOpen) "Open" else "Closed"} · ${it.address.take(50)}",+                                it.imageUrl.takeIf { u -> u.isNotBlank() },+                            )+                        },+                        actionName = "pick.restaurant",+                    )+                }+                com.vayunmathur.openassistant.util.summarizeRestaurants(list)+            }+        },+        "get_restaurant_menu" to { a ->+            intents.runTool {+                val menu = intents.getRestaurantMenu(a.number("merchant_id").toInt())+                if (menu.error == null && menu.items.isNotEmpty()) {+                    pendingRenderUi = A2uiTemplates.foodMenu(+                        menu.merchantName, menu.merchantId,+                        menu.items.take(24).map {+                            MenuItemRow(it.id, it.name, it.priceCents, it.available)+                        },+                    )+                }+                com.vayunmathur.openassistant.util.summarizeMenu(menu)+            }+        },+        "food_get_cart" to { _ ->+            intents.runTool {+                val cart = intents.getFoodCart()+                if (cart.error == null && cart.items.isNotEmpty()) {+                    pendingRenderUi = A2uiTemplates.foodCart(+                        cart.merchantName, cart.merchantId,+                        cart.items.map { CartLineRow(it.itemId, it.name, it.qty, it.lineTotalCents) },+                        cart.totalCents,+                    )+                }+                com.vayunmathur.openassistant.util.summarizeFoodCart(cart)+            }+        },+        "food_set_cart" to { a ->+            val items = com.vayunmathur.openassistant.util.parseSetCartItems(a.string("items_json"))+                ?: return@to "Error: items_json must be a JSON array of {itemId, qty, modifierIds}"+            intents.runTool {+                val cart = intents.setFoodCart(a.number("merchant_id").toInt(), items)+                // Light write (design §2): executed immediately, always rendered back.+                if (cart.error == null) {+                    pendingRenderUi = A2uiTemplates.foodCart(+                        cart.merchantName, cart.merchantId,+                        cart.items.map { CartLineRow(it.itemId, it.name, it.qty, it.lineTotalCents) },+                        cart.totalCents,+                    )+                }+                com.vayunmathur.openassistant.util.summarizeFoodCart(cart)+            }+        },+        "food_prepare_order" to { a ->+            intents.runTool {+                com.vayunmathur.openassistant.util.summarizeOrderSummary(+                    intents.prepareFoodOrder(+                        com.vayunmathur.library.intents.fooddelivery.PrepareOrder(+                            merchantId = a.number("merchant_id").toInt(),+                            isPickup = a.number("is_pickup").toInt() == 1,+                            addressId = a.string("address_id").takeIf { it.isNotBlank() },+                            tipCents = a.number("tip_cents").toInt(),+                            promo = a.string("promo").takeIf { it.isNotBlank() },+                        ),+                    ),+                )+            }+        },+        "place_food_order" to { a ->+            intents.runTool {+                val summary = intents.prepareFoodOrder(+                    com.vayunmathur.library.intents.fooddelivery.PrepareOrder(+                        merchantId = a.number("merchant_id").toInt(),+                    ),+                )+                if (summary.error == null) {+                    pendingRenderUi = A2uiTemplates.foodOrderSummary(+                        summary.merchantName,+                        summary.items.map { "${it.name} × ${it.qty} — ${formatCents(it.lineTotalCents)}" },+                        summary.subtotalCents, summary.tipCents, summary.totalCents,+                        summary.checkoutDeepLink, summary.merchantId,+                    )+                }+                com.vayunmathur.openassistant.util.summarizeOrderSummary(summary) ++                    " Show the user this summary; they place the order in FoodDelivery."+            }+        },+        "get_food_orders" to { _ ->+            intents.runTool {+                com.vayunmathur.openassistant.util.summarizeFoodOrders(intents.getFoodOrders())+            }+        },         "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 924d0bdfa9..efe01604da 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/util/AssistantToolIntents.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/util/AssistantToolIntents.kt@@ -25,8 +25,20 @@ import com.vayunmathur.library.intents.communicate.FindConversationsQuery import com.vayunmathur.library.intents.communicate.GetMessagesQuery import com.vayunmathur.library.intents.communicate.SendMessageRequest import com.vayunmathur.library.intents.communicate.SendMessageResult+import com.vayunmathur.library.intents.fooddelivery.CartData as FoodCartData+import com.vayunmathur.library.intents.fooddelivery.FindRestaurants+import com.vayunmathur.library.intents.fooddelivery.GetCart as FoodGetCart+import com.vayunmathur.library.intents.fooddelivery.GetMenu+import com.vayunmathur.library.intents.fooddelivery.GetOrders as FoodGetOrders+import com.vayunmathur.library.intents.fooddelivery.MenuData+import com.vayunmathur.library.intents.fooddelivery.OrderData as FoodOrderData import com.vayunmathur.library.intents.fooddelivery.OrderLookupRequest import com.vayunmathur.library.intents.fooddelivery.OrderLookupResult+import com.vayunmathur.library.intents.fooddelivery.OrderSummaryData+import com.vayunmathur.library.intents.fooddelivery.PrepareOrder+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.maps.DirectionsResult import com.vayunmathur.library.intents.taxi.RideEstimateRequest@@ -42,6 +54,7 @@ import kotlinx.coroutines.runBlocking import com.vayunmathur.openassistant.MainActivity import kotlinx.serialization.ExperimentalSerializationApi import kotlinx.serialization.json.Json+import kotlinx.serialization.json.JsonPrimitive import kotlinx.serialization.serializer  /**@@ -304,6 +317,48 @@ internal class AssistantToolIntents(private val context: Context) {         request,     ) +    suspend fun findRestaurants(query: String, lat: Double, lng: Double, limit: Int): List<RestaurantData> = launchIntent(+        context,+        "com.vayunmathur.fooddelivery",+        "com.vayunmathur.fooddelivery.intents.FindRestaurantsIntent",+        FindRestaurants(query.takeIf { it.isNotBlank() }, lat, lng, limit),+    )++    suspend fun getRestaurantMenu(merchantId: Int): MenuData = launchIntent(+        context,+        "com.vayunmathur.fooddelivery",+        "com.vayunmathur.fooddelivery.intents.GetMenuIntent",+        GetMenu(merchantId),+    )++    suspend fun getFoodCart(): FoodCartData = launchIntent(+        context,+        "com.vayunmathur.fooddelivery",+        "com.vayunmathur.fooddelivery.intents.GetCartIntent",+        FoodGetCart(),+    )++    suspend fun setFoodCart(merchantId: Int, items: List<SetCartItem>): FoodCartData = launchIntent(+        context,+        "com.vayunmathur.fooddelivery",+        "com.vayunmathur.fooddelivery.intents.SetCartIntent",+        SetCart(merchantId, items),+    )++    suspend fun prepareFoodOrder(request: PrepareOrder): OrderSummaryData = launchIntent(+        context,+        "com.vayunmathur.fooddelivery",+        "com.vayunmathur.fooddelivery.intents.PrepareOrderIntent",+        request,+    )++    suspend fun getFoodOrders(): List<FoodOrderData> = launchIntent(+        context,+        "com.vayunmathur.fooddelivery",+        "com.vayunmathur.fooddelivery.intents.GetOrdersIntent",+        FoodGetOrders(),+    )+     suspend fun getContactsList(): List<ContactData> = launchIntent<Unit, List<ContactData>>(         context,         "com.vayunmathur.contacts",@@ -428,6 +483,73 @@ fun summarizeConversationMessages(list: List<ConversationMessageData>): String =         }     } +/** Host-truncated restaurant list for the model. */+fun summarizeRestaurants(list: List<RestaurantData>): String =+    if (list.isEmpty()) {+        "No restaurants found"+    } else {+        list.joinToString("\n") { r ->+            val rating = r.rating?.let { " ★$it" } ?: ""+            "merchant_id=${r.id} ${r.name}$rating ${if (r.isOpen) "open" else "closed"} ${r.address.take(60)}"+        }+    }++/** Host-truncated menu for the model: ids, names, cents, availability, modifier rules. */+fun summarizeMenu(menu: MenuData, cap: Int = 24): String {+    if (menu.error != null) return "Error: menu unavailable (${menu.error})"+    if (menu.items.isEmpty()) return "No menu items for ${menu.merchantName}"+    val shown = menu.items.take(cap)+    val lines = shown.joinToString("\n") { item ->+        val mods = item.modifierGroups.joinToString(";") { g ->+            "${g.name}[${g.modifiers.joinToString(",") { "${it.id}:${it.name}" }}] req=${g.required} min=${g.minSelections} max=${g.maxSelections}"+        }+        "item_id=${item.id} ${item.name} ${item.priceCents}c ${if (item.available) "available" else "unavailable"} ${item.category}${if (mods.isBlank()) "" else " $mods"}"+    }+    val more = if (menu.items.size > cap) "\n(${menu.items.size - cap} more items not shown)" else ""+    return "Menu ${menu.merchantName} (merchant_id=${menu.merchantId}):\n$lines$more"+}++/** Cart summary for the model; also the success string of every cart write. */+fun summarizeFoodCart(cart: FoodCartData): String {+    if (cart.error != null) return "Error: cart not updated (${cart.error})"+    if (cart.items.isEmpty()) return "Cart is empty"+    val lines = cart.items.joinToString("\n") { "item_id=${it.itemId} ${it.name} x${it.qty} ${it.lineTotalCents}c" }+    return "Cart ${cart.merchantName} (merchant_id=${cart.merchantId}):\n$lines\nTotal ${cart.totalCents}c"+}++/** Priced-order summary for the model; taxes/fee unknown until in-app checkout. */+fun summarizeOrderSummary(summary: OrderSummaryData): String {+    if (summary.error != null) return "Error: order not priced (${summary.error})"+    val lines = summary.items.joinToString("\n") { "${it.name} x${it.qty} ${it.lineTotalCents}c" }+    return "Order summary ${summary.merchantName} (${if (summary.isPickup) "pickup" else "delivery"}):\n$lines\n" ++        "subtotal=${summary.subtotalCents}c tip=${summary.tipCents}c total=${summary.totalCents}c " ++        "(taxes/delivery fee confirmed in FoodDelivery) checkout=${summary.checkoutDeepLink}"+}++/** Host-truncated past orders for the model. */+fun summarizeFoodOrders(list: List<FoodOrderData>, cap: Int = 10): String =+    if (list.isEmpty()) {+        "No past orders"+    } else {+        list.take(cap).joinToString("\n") { o ->+            "order_id=${o.id} ${o.merchantName} ${o.status} ${o.totalCents}c items=${o.itemCount}"+        }+    }++/** Parses the food_set_cart items_json arg ([{itemId, qty, modifierIds}]). */+fun parseSetCartItems(itemsJson: String): List<SetCartItem>? {+    val root = runCatching { Json.parseToJsonElement(itemsJson) }.getOrNull() ?: return null+    val array = root as? kotlinx.serialization.json.JsonArray ?: return null+    return array.map { element ->+        val obj = element as? kotlinx.serialization.json.JsonObject ?: return null+        val itemId = (obj["itemId"] as? JsonPrimitive)?.content?.toIntOrNull() ?: return null+        val qty = (obj["qty"] as? JsonPrimitive)?.content?.toIntOrNull() ?: return null+        val mods = (obj["modifierIds"] as? kotlinx.serialization.json.JsonArray)+            ?.map { (it as? JsonPrimitive)?.content?.toIntOrNull() ?: return null } ?: emptyList()+        SetCartItem(itemId, qty, mods)+    }+}+ /** 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 33b39a9fee..ca0ce20894 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.food_checkout" -> {+                val link = context["deepLink"]?.toString().orEmpty()+                if (link.isBlank()) return false+                openUrl(link)+                return true+            }             "open.conversation" -> {                 val address = context["address"]?.toString().orEmpty()                 if (address.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 a7a42f5769..9835814a48 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/util/InferenceService.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/util/InferenceService.kt@@ -118,6 +118,10 @@ class InferenceService : Service() {             - find_conversations searches conversations (thread_key identifies each); get_conversation_messages reads one.             - To compose a message, prefer draft_message: it shows an editable composer card and sends nothing. When the user taps Send (msg.send) or confirms send_message_v2, the app shows a confirmation card first — never claim a message was sent until the tool result says so.             - send_message_v2 requires explicit user confirmation; GoogleVoice cannot send here, so offer to open the conversation instead. The legacy send_message only opens a pre-filled SMS screen.++            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.             """.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 702b368e80..cbfd2af19d 100644--- a/openassistant/src/test/java/com/vayunmathur/openassistant/platform/A2uiTemplatesTest.kt+++ b/openassistant/src/test/java/com/vayunmathur/openassistant/platform/A2uiTemplatesTest.kt@@ -164,6 +164,31 @@ class A2uiTemplatesTest {         assertTrue(!A2uiTemplates.messageComposer("Ann", "+1", "Sim", "Hi").contains("thread_remote_id"))     } +    @Test fun foodTemplatesAreEnvelopeValid() {+        assertEquals("$12.34", formatCents(1234))+        assertEquals("$0.05", formatCents(5))+        val menu = A2uiTemplates.foodMenu(+            "Sushi Place", 7,+            listOf(MenuItemRow(1, "Salmon Roll", 1200, true, 1), MenuItemRow(2, "Miso Soup", 400, false)),+        )+        assertEnvelopeValid(menu)+        assertEquals("QuantityStepper", componentsOf(menu).getValue("stepper")["component"])+        assertTrue(menu.contains("cart.food.update") && menu.contains("Salmon Roll"), menu)+        assertTrue(menu.contains("unavailable"), menu)++        val cart = A2uiTemplates.foodCart("Sushi Place", 7, listOf(CartLineRow(1, "Salmon Roll", 2, 2400)), 2400)+        assertEnvelopeValid(cart)+        assertTrue(cart.contains("Total $24.00"), cart)++        val summary = A2uiTemplates.foodOrderSummary(+            "Sushi Place", listOf("Salmon Roll × 2 — $24.00"), 2400, 200, 2600,+            "fooddelivery://checkout", 7,+        )+        assertEnvelopeValid(summary)+        assertTrue(summary.contains("handoff.food_checkout"), summary)+        assertTrue(summary.contains("fooddelivery://checkout"), 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 23263873b8..46c1a0972b 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(40, tools.declarations.size)+        assertEquals(47, tools.declarations.size)     }      @Test fun crossAppToolsReportMissingApps() {@@ -231,15 +231,33 @@ class AssistantToolsInvokeTest {         assertTrue(card != null && card.contains("msg.send") && card.contains("Running late"), "$card")     } +    @Test fun foodToolsMissingAppAndLightWriteExecutes() {+        assertTrue(call("find_restaurants", "lat" to "1.0", "lng" to "2.0").startsWith("The FoodDelivery app is required"))+        assertTrue(call("get_restaurant_menu", "merchant_id" to "3").startsWith("The FoodDelivery app is required"))+        assertTrue(call("food_get_cart").startsWith("The FoodDelivery app is required"))+        assertTrue(call("get_food_orders").startsWith("The FoodDelivery app is required"))+        // Light write: no confirmation gate — it executes (and reports the missing app here).+        val light = call("food_set_cart", "merchant_id" to "3", "items_json" to "[{\"itemId\":1,\"qty\":2}]")+        assertTrue(light.startsWith("The FoodDelivery app is required"), light)+        assertEquals(+            "Error: items_json must be a JSON array of {itemId, qty, modifierIds}",+            call("food_set_cart", "merchant_id" to "3", "items_json" to "not json"))+        // Handoff-prep executes its read side only; it never gates and never orders.+        assertTrue(call("place_food_order", "merchant_id" to "3").startsWith("The FoodDelivery app is required"))+    }+     @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")         for (spec in com.vayunmathur.openassistant.domain.ASSISTANT_TOOL_SPECS) {-            val expected = if (spec.name in gated) {-                com.vayunmathur.openassistant.domain.ToolRisk.WRITE_CONFIRM-            } else {-                com.vayunmathur.openassistant.domain.ToolRisk.READ+            val expected = when (spec.name) {+                in gated -> com.vayunmathur.openassistant.domain.ToolRisk.WRITE_CONFIRM+                in light -> com.vayunmathur.openassistant.domain.ToolRisk.WRITE_LIGHT+                in handoff -> com.vayunmathur.openassistant.domain.ToolRisk.HANDOFF_PREP+                else -> com.vayunmathur.openassistant.domain.ToolRisk.READ             }             assertEquals(expected, spec.risk, spec.name)         }
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 034cdf21d1..7dcd518591 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(40, names.size)+        assertEquals(47, names.size)         assertEquals(names.size, names.toSet().size)         for (spec in ASSISTANT_TOOL_SPECS) {             assertTrue(snake.matches(spec.name), spec.name)@@ -63,6 +63,10 @@ class AssistantToolsTest {                 "food_order_lookup.lat", "food_order_lookup.lng",                 "web_search.count", "web_read_result.index", "web_read_result.offset",                 "find_conversations.limit", "get_conversation_messages.limit",+                "find_restaurants.lat", "find_restaurants.lng", "find_restaurants.limit",+                "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",             ),             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 1a7f480efe..3d3988952c 100644--- a/openassistant/src/test/java/com/vayunmathur/openassistant/platform/MamlChatEngineFakeModelTest.kt+++ b/openassistant/src/test/java/com/vayunmathur/openassistant/platform/MamlChatEngineFakeModelTest.kt@@ -147,6 +147,28 @@ class MamlChatEngineFakeModelTest {         e.close()     } +    @Test fun orderFoodScriptRunsFindMenuCartPrepareHandoff() = runBlocking {+        var calls = 0+        val quoted = { s: String -> "<|\"|>" + s + "<|\"|>" }+        val script = listOf(+            "<|tool_call>call:find_restaurants{query:${quoted("sushi")},lat:37.0,lng:-122.0}<tool_call|>",+            "<|tool_call>call:get_restaurant_menu{merchant_id:7}<tool_call|>",+            "<|tool_call>call:food_set_cart{merchant_id:7,items_json:${quoted("[{\"itemId\":1,\"qty\":2}]")}}<tool_call|>",+            "<|tool_call>call:food_prepare_order{merchant_id:7}<tool_call|>",+            "<|tool_call>call:place_food_order{merchant_id:7}<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(), "order sushi"), tools()) { true }+        assertEquals(ChatResult.Reply("done", halted = false), result)+        // 5 tool rounds + the final prose round; no round gated or placed an order.+        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 226b7cba98..3471d0bdf9 100644--- a/openassistant/src/test/java/com/vayunmathur/openassistant/util/AssistantToolIntentsTest.kt+++ b/openassistant/src/test/java/com/vayunmathur/openassistant/util/AssistantToolIntentsTest.kt@@ -161,6 +161,29 @@ class AssistantToolIntentsTest {                 .contains("Google Voice"))     } +    @Test fun foodToolsThrowMissingAppAndSummariesParse() = runTest {+        assertFailsWith<MissingAppException> { tools.findRestaurants("sushi", 1.0, 2.0, 5) }+        assertFailsWith<MissingAppException> { tools.getRestaurantMenu(7) }+        assertFailsWith<MissingAppException> { tools.getFoodCart() }+        assertFailsWith<MissingAppException> { tools.getFoodOrders() }+        val parsed = parseSetCartItems("[{\"itemId\":1,\"qty\":2,\"modifierIds\":[3]}]")+        assertEquals(1, parsed?.size)+        assertEquals(3, parsed?.first()?.modifierIds?.first())+        assertEquals(null, parseSetCartItems("nope"))+        assertEquals(null, parseSetCartItems("[{\"qty\":2}]"))+        val cart = summarizeFoodCart(+            com.vayunmathur.library.intents.fooddelivery.CartData(+                merchantId = 7, merchantName = "Sushi",+                items = listOf(+                    com.vayunmathur.library.intents.fooddelivery.CartItemData(1, "Roll", 2, emptyList(), 2400)),+                totalCents = 2400))+        assertTrue(cart.contains("Roll") && cart.contains("2400c"), cart)+        assertEquals("Cart is empty", summarizeFoodCart(+            com.vayunmathur.library.intents.fooddelivery.CartData()))+        assertTrue(summarizeMenu(+            com.vayunmathur.library.intents.fooddelivery.MenuData(error = "DOWN")).contains("DOWN"))+    }+     @Test fun requestPayloadShapes() {         assertEquals(3.5, WeatherLatLonRequest(3.5, -1.25).latitude)         assertEquals("Lisbon", WeatherNameRequest("Lisbon").name)