openassistant: A2UI vocabulary, host templates and render_ui (#assistant)
- Commit
d6766893f60ea4fa5a6cf13d4b0003a42d7ff645- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-16 22:47 UTC (19 days ago)
- Parents
ed1955f
Implements P1 only of the OpenAssistant design (/tmp/oa-design.md
section 3 and section 4, plus the searchResults template from
/tmp/oa-web-design.md section A2UI), on top of the P0 confirmation
foundation. Scope is openassistant/ only.
A2UI vocabulary (platform/AssistantCatalog.kt):
- Picker (label?, options {path}, value {path}, action): schema and
the prompt line come from the same Component, as before.
- QuantityStepper (label?, value {path}, min, max, action?).
- TextField gains a multiline boolean prop (no new component type).
- ui/A2uiSurfaceView.kt renders all three: Picker is a radio list
that updates the bound value and fires its action with the chosen
id in context; QuantityStepper is a -/value/+ row clamped to
min/max that mutates the data model only and never dispatches
unless an optional action prop is present (then it dispatches with
the new value in context); multiline TextField uses
singleLine=false with minLines=3.
Host templates (platform/A2uiTemplates.kt):
- listPicker, statusCard, resultCard and searchResults as pure
functions returning {"components","data"} JSON, typed by PickerItem
and SearchResultItem. searchResults is a Card > Column[Text query,
List template Row[Column[[n] title, snippet, domain], Read action
web.read {index}, Open action web.open {url}]].
- Every template is validated through buildA2uiEnvelope and against
the catalog processor in A2uiTemplatesTest.
render_ui tool:
- New READ spec in AssistantToolSpecs (components_json, optional
data_json); tool count 28 -> 29. AssistantTools validates with
buildA2uiEnvelope (temp surface), rejects payloads over 12000
chars, returns an error string on invalid input, and on success
stashes the envelope in AssistantTools.pendingRenderUi.
- AssistantTools cannot write the DB, so MamlChatEngine consumes
pendingRenderUi after a Finished outcome and appends it to the
reply as an a2ui fence; the existing storeReply/splitA2ui path then
persists it on the current assistant message.
a2uiData persistence:
- buildA2uiEnvelope gains a dataOverride param that augments and
overrides the block initial data. A2uiController feeds it from
Message.a2uiData (DB v5, from P0), snapshots the ComposeDataModel
root on outbound events through a new onSurfaceData callback, and
AssistantViewModel upserts that snapshot back onto the message.
- ComposeDataModel.snapshot() exposes the root tree for this.
Latest-surface-only interactivity:
- A2uiSurfaceView gains enabled: Boolean = true; disabled surfaces
ignore dispatch and disable Button/Picker/Stepper/TextField/
CheckBox. LiteRTChatScreen computes the latest message with an
a2ui block and passes a2uiEnabled through LiteRTChatBubble, so
older cards render as inert scrollback.
Prompt:
- AssistantCatalog.PROMPT_SECTION now prefers host templates and
the render_ui tool over a hand-written fence (kept as fallback,
EXAMPLE unchanged and still valid), documents the namespaced
action vocabulary (pick.*, confirm.tool, cancel.tool, web.read,
web.open), and states steppers/text fields only edit locally.
- NOTE: changing PROMPT_SECTION (and the catalog) invalidates the
baked gemma4_prefix.kv. Behaviour stays correct, but the prefix
must be rebaked with bake_gemma4_prefix, otherwise first turns
prefill until it is.
Tests: catalog prompt/render coverage for Picker, QuantityStepper
and multiline; template snapshot and catalog-validation tests;
envelope data-seeding tests; render_ui validation, size guard and
pending-stash tests; surface render tests for picker/stepper
(local mutation, clamping, no turn), disabled surfaces and the
onSurfaceData snapshot; and a fake-model golden scenario where a
scripted render_ui call lands as an a2ui fence on the reply.
Verified on devvm21958 with the jdk21 + proxy Gradle env:
./gradlew --max-workers=8 :openassistant:testDevUnitTest
:openassistant:compileDevKotlin - 220 tests, 0 failures.
Not pushed.Diff
openassistant/src/main/java/com/vayunmathur/openassistant/domain/A2uiEnvelope.kt
diff --git a/openassistant/src/main/java/com/vayunmathur/openassistant/domain/A2uiEnvelope.kt b/openassistant/src/main/java/com/vayunmathur/openassistant/domain/A2uiEnvelope.ktindex c30d63b00a..e0dbe3bc6b 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/domain/A2uiEnvelope.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/domain/A2uiEnvelope.kt@@ -25,19 +25,33 @@ fun a2uiSurfaceId(messageId: Long): String = "m$messageId" * envelope (`createSurface`, surface and catalog ids) is supplied here. A bare component array * is accepted too, since that is the commonest way a small model drops the wrapper. */-fun buildA2uiEnvelope(surfaceId: String, catalogId: String, json: String): List<A2uiServerToClientMessage>? {+fun buildA2uiEnvelope(+ surfaceId: String,+ catalogId: String,+ json: String,+ dataOverride: String? = null,+): List<A2uiServerToClientMessage>? { val root = runCatching { Json.parseToJsonElement(json) }.getOrNull() ?: return null val (componentsJson, dataJson) = when (root) { is JsonArray -> root to null is JsonObject -> (root["components"] as? JsonArray ?: return null) to root["data"] as? JsonObject else -> return null }+ // A persisted data-model snapshot (Message.a2uiData) seeds replay: its values+ // augment/replace the block's initial data, so typed/stepped state survives.+ val overrideJson = dataOverride?.let {+ runCatching { Json.parseToJsonElement(it) }.getOrNull() as? JsonObject+ }+ val seededData: JsonObject? = when {+ dataJson != null && overrideJson != null -> JsonObject(dataJson + overrideJson)+ else -> overrideJson ?: dataJson+ } val components = componentsJson.mapNotNull { toComponent(it) } if (components.isEmpty()) return null return buildList { add(A2uiCreateSurfaceMessage(surfaceId, catalogId)) add(A2uiUpdateComponentsMessage(surfaceId, components))- if (dataJson != null) add(A2uiUpdateDataModelMessage(surfaceId, "/", jsonToValue(dataJson)))+ if (seededData != null) add(A2uiUpdateDataModelMessage(surfaceId, "/", jsonToValue(seededData))) } }
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 f6937f624a..9988c27b2a 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/domain/AssistantToolSpecs.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/domain/AssistantToolSpecs.kt@@ -113,6 +113,16 @@ val ASSISTANT_TOOL_SPECS: List<ToolSpec> = listOf( "Get the current weather conditions for a named place (city, address, landmark).", listOf(p("location", description = "city or place name")), ),+ ToolSpec(+ "render_ui",+ "Render a rich UI card (A2UI) attached to your reply. Prefer this over writing a ```a2ui fence. " ++ "components_json is a JSON string: {\"components\":[...]} (or a bare component array) using the RICH UI types; " ++ "data_json is an optional JSON object string with initial data values.",+ listOf(+ p("components_json", description = "A2UI components as a JSON string"),+ p("data_json", description = "optional initial data model as a JSON object string", required = false),+ ),+ ), 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/A2uiComposeState.kt
diff --git a/openassistant/src/main/java/com/vayunmathur/openassistant/platform/A2uiComposeState.kt b/openassistant/src/main/java/com/vayunmathur/openassistant/platform/A2uiComposeState.ktindex bf98854e9f..9db017a9da 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/platform/A2uiComposeState.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/platform/A2uiComposeState.kt@@ -60,6 +60,9 @@ class ComposeDataModel : A2uiCoreDataModel { return node } + /** The whole data-model tree, for persisting a snapshot (Message.a2uiData). */+ fun snapshot(): Any? = synchronized(lock) { root }+ override fun close() { synchronized(lock) { root = emptyMap<String, Any?>() } }
openassistant/src/main/java/com/vayunmathur/openassistant/platform/A2uiController.kt
diff --git a/openassistant/src/main/java/com/vayunmathur/openassistant/platform/A2uiController.kt b/openassistant/src/main/java/com/vayunmathur/openassistant/platform/A2uiController.ktindex 3ecf70e799..48aa0ff072 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/platform/A2uiController.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/platform/A2uiController.kt@@ -14,6 +14,7 @@ import com.vayunmathur.openassistant.data.Message import com.vayunmathur.openassistant.domain.a2uiSurfaceId import com.vayunmathur.openassistant.domain.actionTurnText import com.vayunmathur.openassistant.domain.buildA2uiEnvelope+import com.vayunmathur.openassistant.domain.valueToJson import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.StateFlow@@ -26,8 +27,9 @@ import kotlinx.coroutines.launch * turns the events those surfaces fire into user turns via [onAction]. * * Surfaces are keyed by message ([a2uiSurfaceId]), so [sync] is idempotent and reopening a- * conversation recreates its surfaces from Room. Values typed into a surface are not stored;- * what matters reaches the model, and so the history, through the action turn.+ * conversation recreates its surfaces from Room. When an action fires, the surface's current+ * data model is snapshotted through [onSurfaceData] (when set) so the host can persist it as+ * Message.a2uiData and replay it via the envelope's data seeding. */ class A2uiController( context: Context,@@ -35,6 +37,7 @@ class A2uiController( private val onHostAction: ( (conversationId: Long, eventName: String, context: Map<String, Any?>) -> Boolean )? = null,+ private val onSurfaceData: ((messageId: Long, dataJson: String) -> Unit)? = null, private val onAction: (conversationId: Long, text: String) -> Unit, ) { private val appContext = context.applicationContext@@ -45,6 +48,7 @@ class A2uiController( ) private val fed = HashMap<Long, String>() private val conversationOf = HashMap<String, Long>()+ private val messageOf = HashMap<String, Long>() val surfaces: StateFlow<Map<String, A2uiCoreSurfaceModel>> = processor.activeSurfaces .map { list -> list.filterIsInstance<A2uiCoreSurfaceModel>().associateBy { it.id } }@@ -56,6 +60,14 @@ class A2uiController( processor.outboundEvents.collect { event -> when (event) { is A2uiClientEventMessage -> conversationOf[event.surfaceId]?.let { convId ->+ // Snapshot the surface data before the turn, so typed/stepped+ // values survive a restart even when they were not in the context.+ messageOf[event.surfaceId]?.let { messageId ->+ val data = surfaces.value[event.surfaceId]?.dataModel as? ComposeDataModel+ if (onSurfaceData != null && data != null) {+ onSurfaceData.invoke(messageId, valueToJson(data.snapshot()).toString())+ }+ } val handled = onHostAction?.invoke(convId, event.type, event.context) ?: false if (!handled) onAction(convId, actionTurnText(event.type, event.context)) }@@ -70,15 +82,18 @@ class A2uiController( fun sync(messages: List<Message>) { for (message in messages) { val json = message.a2ui- if (json != null && fed[message.id] != json) feed(message, json)+ val fedKey = json?.let { it + "\u0000" + (message.a2uiData ?: "") }+ if (json != null && fed[message.id] != fedKey) feed(message, json) } } private fun feed(message: Message, json: String) { val surfaceId = a2uiSurfaceId(message.id)- if (fed.put(message.id, json) != null) processor.processMessage(A2uiDeleteSurfaceMessage(surfaceId))+ val fedKey = json + "\u0000" + (message.a2uiData ?: "")+ if (fed.put(message.id, fedKey) != null) processor.processMessage(A2uiDeleteSurfaceMessage(surfaceId)) conversationOf[surfaceId] = message.conversationId- val envelope = buildA2uiEnvelope(surfaceId, AssistantCatalog.ID, json)+ messageOf[surfaceId] = message.id+ val envelope = buildA2uiEnvelope(surfaceId, AssistantCatalog.ID, json, dataOverride = message.a2uiData) if (envelope == null) { Log.status(TAG, "unusable a2ui block on message ${message.id}") return
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 42ba5472eb..55d1cfe46a 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/platform/A2uiTemplates.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/platform/A2uiTemplates.kt@@ -1,13 +1,32 @@ package com.vayunmathur.openassistant.platform import com.vayunmathur.openassistant.domain.PendingToolCall+import com.vayunmathur.openassistant.domain.valueToJson import kotlinx.serialization.json.JsonArray+import kotlinx.serialization.json.JsonElement import kotlinx.serialization.json.JsonObject import kotlinx.serialization.json.JsonPrimitive import kotlinx.serialization.json.buildJsonArray import kotlinx.serialization.json.buildJsonObject import kotlinx.serialization.json.put +/** One selectable item in a [A2uiTemplates.listPicker] card. */+data class PickerItem(+ val id: String,+ val title: String,+ val caption: String = "",+ val imageUrl: String? = null,+)++/** One web search result in a [A2uiTemplates.searchResults] card. */+data class SearchResultItem(+ val index: Int,+ val title: String,+ val snippet: String,+ val domain: String,+ val url: String,+)+ /** Host-generated A2UI cards. The model never authors these. */ object A2uiTemplates { @@ -21,35 +40,220 @@ object A2uiTemplates { "children" to JsonArray(listOf(s("title"), s("summary"), s("actions"))), ), )+ add(text("title", "Confirm ${pending.name}", "title"))+ add(text("summary", pending.summary, "body")) add( obj(- "id" to s("title"), "component" to s("Text"),- "text" to s("Confirm ${pending.name}"), "variant" to s("title"),+ "id" to s("actions"), "component" to s("Row"),+ "children" to JsonArray(listOf(s("btnCancel"), s("btnConfirm"))), ), )+ add(button("btnCancel", "Cancel", "cancel.tool", pending.id, primary = false))+ add(button("btnConfirm", "Confirm", "confirm.tool", pending.id, primary = true))+ }+ val data = buildJsonObject {+ put("id", pending.id)+ put("tool", pending.name)+ put("summary", pending.summary)+ }+ return envelope(components, data)+ }++ /** Single-pick card: a [Picker] over [items]; selecting fires [actionName] with the id. */+ fun listPicker(title: String, items: List<PickerItem>, actionName: String = "pick.item"): String {+ val components = buildJsonArray {+ add(obj("id" to s("root"), "component" to s("Card"), "child" to s("col"))) add( obj(- "id" to s("summary"), "component" to s("Text"),- "text" to s(pending.summary), "variant" to s("body"),+ "id" to s("col"), "component" to s("Column"),+ "children" to JsonArray(listOf(s("title"), s("picker"))), ), )+ add(text("title", title, "title")) add( obj(- "id" to s("actions"), "component" to s("Row"),- "children" to JsonArray(listOf(s("btnCancel"), s("btnConfirm"))),+ "id" to s("picker"), "component" to s("Picker"),+ "options" to path("/items"), "value" to path("/selected"),+ "action" to action(actionName, mapOf("id" to pathValue("/selected"))), ), )- add(button("btnCancel", "Cancel", "cancel.tool", pending.id, primary = false))- add(button("btnConfirm", "Confirm", "confirm.tool", pending.id, primary = true)) } val data = buildJsonObject {- put("id", pending.id)- put("tool", pending.name)- put("summary", pending.summary)+ put(+ "items",+ JsonArray(+ items.map { item ->+ buildJsonObject {+ put("id", item.id)+ put("title", item.title)+ put("caption", item.caption)+ item.imageUrl?.let { put("imageUrl", it) }+ }+ },+ ),+ )+ put("selected", "")+ }+ return envelope(components, data)+ }++ /** Small status/result card. [variant] is a host hint (e.g. "success"/"error"), kept in data. */+ fun statusCard(title: String, caption: String, variant: String? = null): 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("caption"))),+ ),+ )+ add(text("title", title, "title"))+ add(text("caption", caption, "caption"))+ }+ val data = buildJsonObject {+ put("title", title)+ put("caption", caption)+ variant?.let { put("variant", it) } }- return JsonObject(mapOf("components" to components, "data" to data)).toString()+ return envelope(components, data) } + /** Card with a title, body lines and one optional action button. */+ fun resultCard(+ title: String,+ lines: List<String>,+ actionLabel: String? = null,+ actionName: String? = null,+ actionContext: Map<String, Any?>? = null,+ ): String {+ val lineIds = lines.indices.map { "line$it" }+ val hasAction = actionLabel != null && actionName != null+ 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) } ++ if (hasAction) listOf(s("btnAction")) else emptyList(),+ ),+ ),+ )+ add(text("title", title, "title"))+ lines.forEachIndexed { i, line -> add(text("line$i", line, "body")) }+ if (hasAction) {+ add(+ obj(+ "id" to s("btnAction"), "component" to s("Button"), "label" to s(actionLabel),+ "primary" to JsonPrimitive(true),+ "action" to action(actionName, (actionContext ?: emptyMap()).mapValues { valueToJson(it.value) }),+ ),+ )+ }+ }+ val data = buildJsonObject {+ put("title", title)+ put("lines", JsonArray(lines.map { s(it) }))+ }+ return envelope(components, data)+ }++ /**+ * Web search results card (oa-web-design §A2UI): a List template repeating a+ * Row[Column["[n] title", snippet, domain], Read (web.read {index}), Open (web.open {url})].+ */+ fun searchResults(query: String, results: List<SearchResultItem>): 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("results"))),+ ),+ )+ add(text("title", query, "title"))+ add(+ obj(+ "id" to s("results"), "component" to s("List"),+ "children" to buildJsonObject {+ put("componentId", "result")+ put("path", "/results")+ },+ ),+ )+ add(+ obj(+ "id" to s("result"), "component" to s("Row"),+ "children" to JsonArray(listOf(s("resultBody"), s("btnRead"), s("btnOpen"))),+ ),+ )+ add(+ obj(+ "id" to s("resultBody"), "component" to s("Column"),+ "children" to JsonArray(listOf(s("resultTitle"), s("resultSnippet"), s("resultDomain"))),+ ),+ )+ add(boundText("resultTitle", "/displayTitle", "body"))+ add(boundText("resultSnippet", "/snippet", "caption"))+ add(boundText("resultDomain", "/domain", "caption"))+ add(+ obj(+ "id" to s("btnRead"), "component" to s("Button"), "label" to s("Read"),+ "action" to action("web.read", mapOf("index" to pathValue("/index"))),+ ),+ )+ add(+ obj(+ "id" to s("btnOpen"), "component" to s("Button"), "label" to s("Open"),+ "action" to action("web.open", mapOf("url" to pathValue("/url"))),+ ),+ )+ }+ val data = buildJsonObject {+ put("query", query)+ put(+ "results",+ JsonArray(+ results.map { r ->+ buildJsonObject {+ put("index", r.index)+ put("title", r.title)+ put("displayTitle", "[${r.index}] ${r.title}")+ put("snippet", r.snippet)+ put("domain", r.domain)+ put("url", r.url)+ }+ },+ ),+ )+ }+ return envelope(components, data)+ }++ private fun envelope(components: JsonArray, data: JsonObject): String =+ JsonObject(mapOf("components" to components, "data" to data)).toString()++ private fun text(id: String, value: String, variant: String): JsonObject =+ obj("id" to s(id), "component" to s("Text"), "text" to s(value), "variant" to s(variant))++ private fun boundText(id: String, path: String, variant: String): JsonObject =+ obj("id" to s(id), "component" to s("Text"), "text" to pathValue(path), "variant" to s(variant))++ private fun path(value: String): JsonObject = buildJsonObject { put("path", value) }++ private fun pathValue(value: String): JsonElement = path(value)++ private fun action(name: String, context: Map<String, JsonElement>): JsonObject =+ buildJsonObject {+ put(+ "event",+ buildJsonObject {+ put("name", name)+ put("context", JsonObject(context))+ },+ )+ }+ private fun button( id: String, label: String,@@ -59,18 +263,9 @@ object A2uiTemplates { ): JsonObject = obj( "id" to s(id), "component" to s("Button"), "label" to s(label), "primary" to JsonPrimitive(primary),- "action" to buildJsonObject {- put(- "event",- buildJsonObject {- put("name", event)- put("context", buildJsonObject { put("id", pendingId) })- },- )- },+ "action" to action(event, mapOf("id" to s(pendingId))), ) private fun s(value: String) = JsonPrimitive(value)- private fun obj(vararg pairs: Pair<String, kotlinx.serialization.json.JsonElement>) =- JsonObject(mapOf(*pairs))+ private fun obj(vararg pairs: Pair<String, JsonElement>) = JsonObject(mapOf(*pairs)) }
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 3c0fdf0a9f..9326e33d4b 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/platform/AssistantCatalog.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/platform/AssistantCatalog.kt@@ -8,6 +8,7 @@ import androidx.a2ui.model.catalog.basiccatalog.createBasicCatalogFunctions import androidx.a2ui.model.catalog.functions.A2uiMessageFormatter import androidx.a2ui.model.catalog.functions.A2uiUrlOpener import androidx.a2ui.model.schema.A2uiBooleanSchema+import androidx.a2ui.model.schema.A2uiNumberSchema import androidx.a2ui.model.schema.A2uiObjectSchema import androidx.a2ui.model.schema.A2uiSchema import androidx.a2ui.model.schema.A2uiSchemaKeyword@@ -83,10 +84,39 @@ class AssistantCatalog(urlOpener: A2uiUrlOpener, messageFormatter: A2uiMessageFo required = setOf("label", "action"), ), Component(- "TextField", "A single-line text input bound to the data model.", BINDING_PROPS,- mapOf("label" to text, "value" to binding),+ "TextField", "A text input bound to the data model.",+ "$BINDING_PROPS, multiline (true|false, optional)",+ mapOf(+ "label" to text, "value" to binding,+ "multiline" to A2uiBooleanSchema.INSTANCE,+ ), required = setOf("value"), ),+ Component(+ "Picker", "A single-select list bound to the data model; selecting fires its action.",+ "label (optional), options {\"path\":\"/items\"} (items are {\"id\",\"title\",\"caption\"}), " ++ "value {\"path\":\"/selected\"}, action {\"event\":{\"name\":\"pick...\",\"context\":{...}}}",+ mapOf(+ "label" to text,+ "options" to binding,+ "value" to binding,+ "action" to A2uiActionSchema.DEFAULT_INSTANCE,+ ),+ required = setOf("options", "value", "action"),+ ),+ Component(+ "QuantityStepper", "A -/value/+ stepper bound to a numeric data value.",+ "label (optional), value {\"path\":\"/qty\"}, min (number), max (number), " ++ "action (optional, same shape as Button action)",+ mapOf(+ "label" to text,+ "value" to binding,+ "min" to A2uiNumberSchema.INSTANCE,+ "max" to A2uiNumberSchema.INSTANCE,+ "action" to A2uiActionSchema.DEFAULT_INSTANCE,+ ),+ required = setOf("value", "min", "max"),+ ), Component( "CheckBox", "A checkbox bound to a boolean in the data model.", BINDING_PROPS, mapOf("label" to text, "value" to binding),@@ -115,8 +145,10 @@ class AssistantCatalog(urlOpener: A2uiUrlOpener, messageFormatter: A2uiMessageFo appendLine("RICH UI:") appendLine( "When a card, list, set of choices or form would help more than plain text " +- "(collecting details, offering options, showing structured results), " +- "add ONE block after your text:",+ "(collecting details, offering options, showing structured results), prefer the " ++ "render_ui tool (components_json, optional data_json) over writing UI in your reply. " ++ "The app also shows host-templated cards after some tool results; you do not write those. " ++ "Only when render_ui is unavailable, add ONE block after your text as a fallback:", ) appendLine(A2UI_FENCE_OPEN) appendLine("""{"components":[...],"data":{...}}""")@@ -125,9 +157,17 @@ class AssistantCatalog(urlOpener: A2uiUrlOpener, messageFormatter: A2uiMessageFo appendLine("""The component with id "root" is shown. Types:""") COMPONENTS.forEach { appendLine("- ${it.name}: ${it.promptProps}") } appendLine("""Any text may be {"path":"/field"} to show a data value. "data" sets initial values.""")- appendLine("""Button context values may be {"path":"/field"} to send what the user entered.""")- appendLine("""When the user taps a button you receive a turn like [UI action "name": {...}].""")- appendLine("Respond to it.")+ appendLine("""Button/Picker context values may be {"path":"/field"} to send what the user entered or picked.""")+ appendLine(+ "Steppers and text fields only edit the card's data; they do not send a turn. " ++ "Buttons and Picker selections do.",+ )+ appendLine("""When the user taps a control you receive a turn like [UI action "name": {...}]. Respond to it.""")+ appendLine(+ "Action names are namespaced: pick.* (a Picker/list choice, context has \"id\"), " ++ "confirm.tool / cancel.tool (host confirmation, do not invent these), " ++ "web.read ({\"index\": n}) and web.open ({\"url\": ...}). Use those names exactly.",+ ) appendLine("Keep blocks small (under 15 components). Never use a block for a plain answer. Example:") appendLine(A2UI_FENCE_OPEN) appendLine(EXAMPLE)
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 9d7c692145..1532bd1649 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/platform/AssistantTools.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/platform/AssistantTools.kt@@ -21,11 +21,15 @@ import com.vayunmathur.openassistant.domain.ToolArgs import com.vayunmathur.openassistant.domain.ToolArgsResult import com.vayunmathur.openassistant.domain.ToolRisk import com.vayunmathur.openassistant.domain.ToolSpec+import com.vayunmathur.openassistant.domain.buildA2uiEnvelope import com.vayunmathur.openassistant.domain.coerceToolArgs import com.vayunmathur.openassistant.domain.pendingToolSummary import com.vayunmathur.openassistant.util.AssistantDeviceTools import com.vayunmathur.openassistant.util.AssistantToolIntents import kotlinx.coroutines.CancellationException+import kotlinx.serialization.json.Json+import kotlinx.serialization.json.JsonArray+import kotlinx.serialization.json.JsonObject import java.util.UUID fun ToolSpec.toDeclaration(): Gemma4Handle.ToolDeclaration = Gemma4Handle.ToolDeclaration(@@ -50,6 +54,13 @@ class AssistantTools( val declarations: List<Gemma4Handle.ToolDeclaration> = ASSISTANT_TOOL_SPECS.map { it.toDeclaration() } + /**+ * Envelope JSON stashed by the last successful `render_ui` call. AssistantTools cannot+ * write the DB, so [MamlChatEngine] consumes this after the loop and appends it to the+ * reply as an a2ui fence, which the normal split/persist path then stores.+ */+ var pendingRenderUi: String? = null+ private val handlers: Map<String, (ToolArgs) -> String> = mapOf( "get_notes" to { _ -> intents.runTool { intents.getNotes() } }, "create_note" to { a ->@@ -137,6 +148,7 @@ class AssistantTools( intents.runTool { intents.getWeather(a.number("latitude"), a.number("longitude")) } }, "get_weather_by_name" to { a -> intents.runTool { intents.getWeatherByName(a.string("location")) } },+ "render_ui" to { a -> renderUi(a.string("components_json"), a.string("data_json")) }, "get_memories" to { _ -> intents.runTool { device.getMemories(memoryDao) } }, "remove_memory" to { a -> intents.runTool { device.removeMemory(memoryDao, a.number("id")) } }, "add_to_memory" to { a -> intents.runTool { device.addToMemory(memoryDao, a.string("content")) } },@@ -205,6 +217,57 @@ class AssistantTools( return execute(spec.name, coerced) } + /** Takes and clears the stashed [pendingRenderUi] envelope, if any. */+ fun consumePendingRenderUi(): String? {+ val pending = pendingRenderUi+ pendingRenderUi = null+ return pending+ }++ /**+ * Validates a `render_ui` payload and stashes it in [pendingRenderUi] for the engine+ * to attach to the current assistant message. Never throws; bad UI comes back as an+ * error string so the model can fix it.+ */+ private fun renderUi(componentsJson: String, dataJson: String): String {+ if (componentsJson.isBlank()) return "Error: render_ui needs components_json"+ val combined = buildRenderUiJson(componentsJson, dataJson)+ ?: return "Error: invalid A2UI: components_json/data_json is not valid JSON"+ if (combined.length > MAX_RENDER_UI_CHARS) {+ return "Error: render_ui payload too large (${combined.length} chars, max $MAX_RENDER_UI_CHARS)"+ }+ if (buildA2uiEnvelope(TEMP_SURFACE_ID, AssistantCatalog.ID, combined) == null) {+ return "Error: invalid A2UI: no usable components"+ }+ pendingRenderUi = combined+ return "UI rendered"+ }++ /** Merges components_json (+ optional data_json object) into one {"components","data"} string. */+ private fun buildRenderUiJson(componentsJson: String, dataJson: String): String? {+ val componentsRoot = runCatching { Json.parseToJsonElement(componentsJson) }.getOrNull() ?: return null+ val dataOverride = if (dataJson.isBlank()) {+ null+ } else {+ runCatching { Json.parseToJsonElement(dataJson) }.getOrNull() as? JsonObject ?: return null+ }+ return when (componentsRoot) {+ is JsonArray -> JsonObject(+ buildMap {+ put("components", componentsRoot)+ if (dataOverride != null) put("data", dataOverride)+ },+ ).toString()+ is JsonObject -> {+ if (componentsRoot["components"] !is JsonArray) return null+ val merged = LinkedHashMap(componentsRoot)+ if (dataOverride != null) merged["data"] = dataOverride+ JsonObject(merged).toString()+ }+ else -> null+ }+ }+ private fun execute(name: String, args: ToolArgs): String = try { handlers.getValue(name)(args) } catch (e: CancellationException) {@@ -212,4 +275,9 @@ class AssistantTools( } catch (expected: Exception) { "Error: ${expected.message}" }++ private companion object {+ const val TEMP_SURFACE_ID = "temp"+ const val MAX_RENDER_UI_CHARS = 12_000+ } }
openassistant/src/main/java/com/vayunmathur/openassistant/platform/MamlChatEngine.kt
diff --git a/openassistant/src/main/java/com/vayunmathur/openassistant/platform/MamlChatEngine.kt b/openassistant/src/main/java/com/vayunmathur/openassistant/platform/MamlChatEngine.ktindex 40fb9cb73e..e427f068f4 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/platform/MamlChatEngine.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/platform/MamlChatEngine.kt@@ -14,6 +14,7 @@ import com.vayunmathur.openassistant.domain.ToolLoopOutcome import com.vayunmathur.openassistant.domain.decodeWavMono16k import com.vayunmathur.openassistant.domain.fitConversation import com.vayunmathur.openassistant.domain.runToolLoop+import com.vayunmathur.openassistant.domain.withA2uiBlock import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job@@ -181,7 +182,14 @@ open class MamlChatEngine(private val modelDir: File) : AutoCloseable { onVisible = onText, ) when (outcome) {- is ToolLoopOutcome.Finished -> ChatResult.Reply(outcome.text, halted = false)+ is ToolLoopOutcome.Finished -> {+ // A render_ui call stashed its envelope on the tools (it cannot write+ // the DB); append it as an a2ui fence so storeReply/splitA2ui persists+ // it on this assistant message.+ val pendingUi = tools.consumePendingRenderUi()+ val text = if (pendingUi != null) withA2uiBlock(outcome.text, pendingUi) else outcome.text+ ChatResult.Reply(text, halted = false)+ } is ToolLoopOutcome.Halted -> ChatResult.Reply(outcome.text, halted = true) is ToolLoopOutcome.Failed -> ChatResult.Unavailable is ToolLoopOutcome.PendingConfirmation -> ChatResult.Pending(
openassistant/src/main/java/com/vayunmathur/openassistant/ui/A2uiSurfaceView.kt
diff --git a/openassistant/src/main/java/com/vayunmathur/openassistant/ui/A2uiSurfaceView.kt b/openassistant/src/main/java/com/vayunmathur/openassistant/ui/A2uiSurfaceView.ktindex e008c571c9..8363ab7ca9 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/ui/A2uiSurfaceView.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/ui/A2uiSurfaceView.kt@@ -10,6 +10,7 @@ import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.heightIn import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.widthIn import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.runtime.Composable@@ -29,6 +30,7 @@ import com.vayunmathur.library.ui.HorizontalDivider import com.vayunmathur.library.ui.MaterialTheme import com.vayunmathur.library.ui.OutlinedButton import com.vayunmathur.library.ui.OutlinedTextField+import com.vayunmathur.library.ui.RadioButton import com.vayunmathur.library.ui.Text import com.vayunmathur.openassistant.platform.ComposeComponentRegistry import com.vayunmathur.openassistant.platform.ComposeDataModel@@ -44,10 +46,10 @@ private const val MAX_DEPTH = 12 * state, so edits recompose whatever is bound to them. */ @Composable-fun A2uiSurfaceView(surface: A2uiCoreSurfaceModel, modifier: Modifier = Modifier) {+fun A2uiSurfaceView(surface: A2uiCoreSurfaceModel, modifier: Modifier = Modifier, enabled: Boolean = true) { val registry = surface.componentRegistry as? ComposeComponentRegistry ?: return val data = surface.dataModel as? ComposeDataModel ?: return- val renderer = remember(surface) { SurfaceRenderer(surface, registry, data) }+ val renderer = remember(surface, enabled) { SurfaceRenderer(surface, registry, data, enabled) } Box(modifier.widthIn(max = 400.dp)) { renderer.Node(ROOT_ID, A2uiDataPath("/"), 0) } } @@ -55,6 +57,7 @@ private class SurfaceRenderer( val surface: A2uiCoreSurfaceModel, val registry: ComposeComponentRegistry, val data: ComposeDataModel,+ val enabled: Boolean = true, ) { private val resolver = A2uiCoreValueResolver { data[it] } @@ -79,6 +82,7 @@ private class SurfaceRenderer( */ @Suppress("UNCHECKED_CAST") fun dispatch(componentId: String, dataPath: A2uiDataPath, action: Any?) {+ if (!enabled) return val map = action as? Map<String, Any?> ?: return val event = map["event"] as? Map<String, Any?> val context = event?.get("context") as? Map<String, Any?>@@ -91,6 +95,18 @@ private class SurfaceRenderer( surface.dispatchAction(componentId, resolved) } + /** [action] with one extra literal entry merged into its event context. */+ @Suppress("UNCHECKED_CAST")+ fun actionWith(action: Any?, key: String, value: Any?): Any? {+ val map = action as? Map<String, Any?> ?: return action+ val event = map["event"] as? Map<String, Any?> ?: return action+ val context = event["context"] as? Map<String, Any?> ?: emptyMap()+ return mapOf("event" to (event + ("context" to (context + (key to value)))))+ }++ fun formatNumber(value: Double): String =+ if (value % 1.0 == 0.0) value.toLong().toString() else value.toString()+ @Composable fun Node(id: String, dataPath: A2uiDataPath, depth: Int) { if (depth > MAX_DEPTH) return@@ -124,22 +140,91 @@ private class SurfaceRenderer( "Button" -> { val onClick = { dispatch(id, dataPath, props["action"]) } if (props["primary"] == true) {- Button(onClick) { Text(str("label")) }+ Button(onClick, enabled = enabled) { Text(str("label")) } } else {- OutlinedButton(onClick) { Text(str("label")) }+ OutlinedButton(onClick, enabled = enabled) { Text(str("label")) }+ }+ }+ "TextField" -> {+ val multiline = props["multiline"] == true+ OutlinedTextField(+ value = str("value"),+ onValueChange = { text -> if (enabled) boundPath(dataPath, props["value"])?.let { data.update(it, text) } },+ modifier = Modifier.fillMaxWidth(),+ enabled = enabled,+ label = props["label"]?.let { { Text(str("label")) } },+ singleLine = !multiline,+ minLines = if (multiline) 3 else 1,+ )+ }+ "Picker" -> {+ val options = evaluate(id, dataPath, props["options"]) as? List<*> ?: emptyList<Any?>()+ val selected = evaluate(id, dataPath, props["value"])?.toString().orEmpty()+ Column(verticalArrangement = Arrangement.spacedBy(4.dp)) {+ props["label"]?.let { Text(str("label"), style = MaterialTheme.typography.titleSmall) }+ options.forEach { option ->+ val map = option as? Map<*, *> ?: return@forEach+ val optionId = map["id"]?.toString().orEmpty()+ val optionTitle = (map["label"] ?: map["title"] ?: map["name"] ?: optionId).toString()+ val optionCaption = map["caption"]?.toString().orEmpty()+ Row(verticalAlignment = Alignment.CenterVertically) {+ RadioButton(+ selected = optionId == selected,+ onClick = {+ if (enabled) {+ // Update the bound value first, then fire the action+ // with the chosen id in its context.+ boundPath(dataPath, props["value"])?.let { data.update(it, optionId) }+ dispatch(id, dataPath, actionWith(props["action"], "id", optionId))+ }+ },+ enabled = enabled,+ )+ map["imageUrl"]?.toString()?.takeIf { it.isNotEmpty() }?.let { url ->+ AsyncImage(+ ImageRequest.Builder(LocalContext.current).data(url).build(),+ null,+ Modifier.size(40.dp).clip(RoundedCornerShape(8.dp)),+ contentScale = ContentScale.Crop,+ )+ }+ Column {+ Text(optionTitle)+ if (optionCaption.isNotEmpty()) {+ Text(optionCaption, style = MaterialTheme.typography.bodySmall)+ }+ }+ }+ }+ }+ }+ "QuantityStepper" -> {+ // Steppers mutate the surface data model locally only; they never+ // dispatch on their own. If an optional `action` prop is present it+ // is dispatched on change with the new value in its context.+ val current = (evaluate(id, dataPath, props["value"]) as? Number)?.toDouble() ?: 0.0+ val min = (props["min"] as? Number)?.toDouble() ?: 0.0+ val max = (props["max"] as? Number)?.toDouble() ?: current.coerceAtLeast(min)+ fun step(delta: Double) {+ if (!enabled) return+ val next = (current + delta).coerceIn(min, max)+ if (next == current) return+ val stored: Any = if (next % 1.0 == 0.0) next.toLong() else next+ boundPath(dataPath, props["value"])?.let { data.update(it, stored) }+ props["action"]?.let { dispatch(id, dataPath, actionWith(it, "value", stored)) }+ }+ Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {+ props["label"]?.let { Text(str("label")) }+ OutlinedButton({ step(-1.0) }, enabled = enabled && current > min) { Text("-") }+ Text(formatNumber(current))+ OutlinedButton({ step(1.0) }, enabled = enabled && current < max) { Text("+") } } }- "TextField" -> OutlinedTextField(- value = str("value"),- onValueChange = { text -> boundPath(dataPath, props["value"])?.let { data.update(it, text) } },- modifier = Modifier.fillMaxWidth(),- label = props["label"]?.let { { Text(str("label")) } },- singleLine = true,- ) "CheckBox" -> Row(verticalAlignment = Alignment.CenterVertically) { Checkbox( checked = evaluate(id, dataPath, props["value"]) == true,- onCheckedChange = { checked -> boundPath(dataPath, props["value"])?.let { data.update(it, checked) } },+ onCheckedChange = { checked -> if (enabled) boundPath(dataPath, props["value"])?.let { data.update(it, checked) } },+ enabled = enabled, ) Text(str("label")) }
openassistant/src/main/java/com/vayunmathur/openassistant/ui/LiteRTChatBubble.kt
diff --git a/openassistant/src/main/java/com/vayunmathur/openassistant/ui/LiteRTChatBubble.kt b/openassistant/src/main/java/com/vayunmathur/openassistant/ui/LiteRTChatBubble.ktindex 2d6c50568e..047fa43f78 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/ui/LiteRTChatBubble.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/ui/LiteRTChatBubble.kt@@ -52,7 +52,7 @@ import kotlinx.coroutines.launch */ @OptIn(ExperimentalMaterial3Api::class) @Composable-fun ChatBubble(message: Message, surface: A2uiCoreSurfaceModel? = null) {+fun ChatBubble(message: Message, surface: A2uiCoreSurfaceModel? = null, a2uiEnabled: Boolean = true) { val context = LocalContext.current val isUser = message.role == "user" val isTool = message.role == "tool"@@ -132,7 +132,7 @@ fun ChatBubble(message: Message, surface: A2uiCoreSurfaceModel? = null) { ) } if (surface != null && !isUser) {- A2uiSurfaceView(surface, Modifier.padding(vertical = 4.dp))+ A2uiSurfaceView(surface, Modifier.padding(vertical = 4.dp), enabled = a2uiEnabled) } if (message.text.isNotBlank() && !isTool) { IconButton(
openassistant/src/main/java/com/vayunmathur/openassistant/ui/LiteRTChatScreen.kt
diff --git a/openassistant/src/main/java/com/vayunmathur/openassistant/ui/LiteRTChatScreen.kt b/openassistant/src/main/java/com/vayunmathur/openassistant/ui/LiteRTChatScreen.ktindex f2672f483a..acaea14f25 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/ui/LiteRTChatScreen.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/ui/LiteRTChatScreen.kt@@ -81,8 +81,14 @@ fun ChatScreen( scrollBehavior = appBarScrollBehavior(), ) { padding -> SelectionContainer {+ // Only the latest A2UI surface stays interactive; older cards are inert scrollback.+ val latestA2uiMessageId = remember(state.messages) {+ state.messages.lastOrNull { it.a2ui != null }?.id+ } LazyColumn(state = listState, modifier = Modifier.padding(padding).fillMaxSize(), contentPadding = PaddingValues(16.dp), verticalArrangement = Arrangement.spacedBy(16.dp)) {- items(state.messages, key = { it.id }) { ChatBubble(it, state.surfaces[a2uiSurfaceId(it.id)]) }+ items(state.messages, key = { it.id }) {+ ChatBubble(it, state.surfaces[a2uiSurfaceId(it.id)], a2uiEnabled = it.id == latestA2uiMessageId)+ } } } }
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 be8c35352b..977a83eb00 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/util/AssistantViewModel.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/util/AssistantViewModel.kt@@ -102,6 +102,14 @@ class AssistantViewModel( onHostAction = { conversationId, eventName, context -> handleHostAction(conversationId, eventName, context) },+ onSurfaceData = { messageId, dataJson ->+ viewModelScope.launch {+ val existing = runCatching { repository.getMessage(messageId) }.getOrNull()+ if (existing != null && existing.a2uiData != dataJson) {+ upsertMessage(existing.copy(a2uiData = dataJson))+ }+ }+ }, ) /**
openassistant/src/test/java/com/vayunmathur/openassistant/domain/A2uiEnvelopeTest.kt
diff --git a/openassistant/src/test/java/com/vayunmathur/openassistant/domain/A2uiEnvelopeTest.kt b/openassistant/src/test/java/com/vayunmathur/openassistant/domain/A2uiEnvelopeTest.ktindex 9e5daba9c9..3c69e2cdae 100644--- a/openassistant/src/test/java/com/vayunmathur/openassistant/domain/A2uiEnvelopeTest.kt+++ b/openassistant/src/test/java/com/vayunmathur/openassistant/domain/A2uiEnvelopeTest.kt@@ -44,6 +44,28 @@ class A2uiEnvelopeTest { ) } + @Test+ fun dataOverrideSeedsAndMergesDataModel() {+ val json = """{"components":[{"id":"root","component":"Text","text":"x"}],"data":{"name":"Ada","qty":1}}"""+ val messages = buildA2uiEnvelope("m1", "cat", json, dataOverride = """{"qty":3,"extra":true}""")!!+ assertEquals(3, messages.size)+ assertEquals(+ A2uiUpdateDataModelMessage("m1", "/", mapOf("name" to "Ada", "qty" to 3L, "extra" to true)),+ messages[2],+ )+ // Override alone (no block data) still seeds; a bad override is ignored.+ val only = buildA2uiEnvelope(+ "m1", "cat", """{"components":[{"id":"root","component":"Text","text":"x"}]}""",+ dataOverride = """{"qty":2}""",+ )!!+ assertEquals(A2uiUpdateDataModelMessage("m1", "/", mapOf("qty" to 2L)), only[2])+ val bad = buildA2uiEnvelope("m1", "cat", json, dataOverride = "{nope")!!+ assertEquals(+ A2uiUpdateDataModelMessage("m1", "/", mapOf("name" to "Ada", "qty" to 1L)),+ bad[2],+ )+ }+ @Test fun acceptsBareComponentArrayAndSkipsBadEntries() { val messages = buildA2uiEnvelope("m1", "cat", """[{"id":"root","component":"Text","text":"x"},{"id":"bad"},3]""")!!
openassistant/src/test/java/com/vayunmathur/openassistant/platform/A2uiSurfaceRenderTest.kt
diff --git a/openassistant/src/test/java/com/vayunmathur/openassistant/platform/A2uiSurfaceRenderTest.kt b/openassistant/src/test/java/com/vayunmathur/openassistant/platform/A2uiSurfaceRenderTest.ktindex 959061e658..9e311a31ef 100644--- a/openassistant/src/test/java/com/vayunmathur/openassistant/platform/A2uiSurfaceRenderTest.kt+++ b/openassistant/src/test/java/com/vayunmathur/openassistant/platform/A2uiSurfaceRenderTest.kt@@ -87,6 +87,78 @@ class A2uiSurfaceRenderTest { } } + @Test fun pickerAndStepperRenderAndMutateData() {+ val ctx = ApplicationProvider.getApplicationContext<android.content.Context>()+ val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default)+ val actions = mutableListOf<Pair<Long, String>>()+ val dataSnapshots = mutableListOf<Pair<Long, String>>()+ val controller = A2uiController(+ ctx, scope,+ onSurfaceData = { id, data -> dataSnapshots.add(id to data) },+ ) { id, text -> actions.add(id to text) }+ val pickerJson = """+ {"components":[+ {"id":"root","component":"Column","children":["p","s"]},+ {"id":"p","component":"Picker","label":"Pick one",+ "options":{"path":"/items"},"value":{"path":"/selected"},+ "action":{"event":{"name":"pick.item","context":{"id":{"path":"/selected"}}}}},+ {"id":"s","component":"QuantityStepper","label":"Qty",+ "value":{"path":"/qty"},"min":1,"max":3}+ ],"data":{"items":[{"id":"a","title":"Alpha"},{"id":"b","title":"Beta"}],"selected":"a","qty":1}}+ """.trimIndent()+ try {+ controller.sync(listOf(Message(9L, "hi", "assistant", a2ui = pickerJson, id = 11L)))+ assertTrue(await { controller.surfaces.value.containsKey("m11") })+ val surface = controller.surfaces.value.getValue("m11")+ composeRule.setContent { DynamicTheme { A2uiSurfaceView(surface) } }+ composeRule.onNodeWithText("Pick one").assertIsDisplayed()+ composeRule.onNodeWithText("Alpha").assertIsDisplayed()+ composeRule.onNodeWithText("Beta").assertIsDisplayed()+ composeRule.onNodeWithText("Qty").assertIsDisplayed()+ // Stepper mutates the data model locally without firing an action.+ composeRule.onNodeWithText("+").performClick()+ assertEquals(2L, surface.dataModel[A2uiDataPath("/qty")])+ assertTrue(actions.isEmpty(), "stepper must not fire turns: $actions")+ // Clamped at max.+ composeRule.onNodeWithText("+").performClick()+ composeRule.onNodeWithText("+").performClick()+ assertEquals(3L, surface.dataModel[A2uiDataPath("/qty")])+ assertTrue(actions.isEmpty(), "$actions")+ // Firing the picker action snapshots the current data model for a2uiData.+ @Suppress("UNCHECKED_CAST")+ val pickerAction = (surface.componentRegistry as ComposeComponentRegistry)+ .components.getValue("p").properties["action"] as Map<String, Any?>+ surface.dispatchAction("p", pickerAction)+ assertTrue(await { actions.isNotEmpty() }, "actions=$actions")+ assertTrue(actions[0].second.contains("pick.item"), actions[0].second)+ assertTrue(await { dataSnapshots.isNotEmpty() }, "snapshots=$dataSnapshots")+ assertEquals(11L, dataSnapshots[0].first)+ assertTrue(dataSnapshots[0].second.contains("\"qty\":3"), dataSnapshots[0].second)+ } finally {+ scope.cancel()+ }+ }++ @Test fun disabledSurfaceIgnoresButtons() {+ val ctx = ApplicationProvider.getApplicationContext<android.content.Context>()+ val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default)+ val actions = mutableListOf<Pair<Long, String>>()+ val controller = A2uiController(ctx, scope) { id, text -> actions.add(id to text) }+ try {+ controller.sync(listOf(Message(9L, "hi", "assistant", a2ui = json, id = 12L)))+ assertTrue(await { controller.surfaces.value.containsKey("m12") })+ val surface = controller.surfaces.value.getValue("m12")+ composeRule.setContent { DynamicTheme { A2uiSurfaceView(surface, enabled = false) } }+ composeRule.onNodeWithText("RSVP").assertIsDisplayed()+ // Disabled controls do not dispatch (click is a no-op / not performed on disabled node).+ runCatching { composeRule.onNodeWithText("RSVP").performClick() }+ Thread.sleep(300)+ assertTrue(actions.isEmpty(), "disabled surface fired: $actions")+ } finally {+ scope.cancel()+ }+ }+ @Test fun dataModelPathWritesAndReads() { val model = ComposeDataModel() model.update(A2uiDataPath("/name"), "Ada")
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 4fa08ccf04..10a0242928 100644--- a/openassistant/src/test/java/com/vayunmathur/openassistant/platform/A2uiTemplatesTest.kt+++ b/openassistant/src/test/java/com/vayunmathur/openassistant/platform/A2uiTemplatesTest.kt@@ -3,6 +3,16 @@ package com.vayunmathur.openassistant.platform import com.vayunmathur.openassistant.domain.PendingToolCall import com.vayunmathur.openassistant.domain.buildA2uiEnvelope import com.vayunmathur.openassistant.domain.redactedArgsSummary+import androidx.a2ui.engine.model.A2uiCoreSurfaceModel+import androidx.a2ui.engine.processor.A2uiCoreMessageProcessor+import kotlinx.coroutines.delay+import kotlinx.coroutines.launch+import kotlinx.coroutines.runBlocking+import kotlinx.coroutines.withTimeout+import kotlinx.serialization.json.Json+import kotlinx.serialization.json.jsonArray+import kotlinx.serialization.json.jsonObject+import kotlinx.serialization.json.jsonPrimitive import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertNotNull@@ -28,6 +38,119 @@ class A2uiTemplatesTest { assertEquals(3, envelope.size) } + private fun componentsOf(json: String): Map<String, Map<String, String>> {+ val root = Json.parseToJsonElement(json).jsonObject+ return root.getValue("components").jsonArray.associate { el ->+ val obj = el.jsonObject+ obj.getValue("id").jsonPrimitive.content to+ obj.mapValues { it.value.toString().trim('"') }+ }+ }++ private fun assertEnvelopeValid(json: String) {+ val envelope = buildA2uiEnvelope("m1", AssistantCatalog.ID, json)+ assertNotNull(envelope, json)+ assertEquals(3, envelope.size, json)+ }++ @Test fun listPickerIsEnvelopeValid() {+ val json = A2uiTemplates.listPicker(+ "Choose a place",+ listOf(+ PickerItem("r1", "Sushi Place", "4.8 stars", "https://example.com/s.png"),+ PickerItem("r2", "Taco Place"),+ ),+ )+ assertEnvelopeValid(json)+ val comps = componentsOf(json)+ assertEquals("Card", comps.getValue("root")["component"])+ assertEquals("Picker", comps.getValue("picker")["component"])+ assertTrue(json.contains("pick.item"), json)+ assertTrue(json.contains("Sushi Place"), json)+ assertTrue(json.contains("/items"), json)+ // Custom action name is honoured.+ assertTrue(A2uiTemplates.listPicker("T", listOf(PickerItem("x", "X")), "pick.restaurant").contains("pick.restaurant"))+ }++ @Test fun statusAndResultCardsAreEnvelopeValid() {+ val status = A2uiTemplates.statusCard("Order placed", "Arriving at 7pm", variant = "success")+ assertEnvelopeValid(status)+ assertEquals("Text", componentsOf(status).getValue("title")["component"])+ assertTrue(status.contains("Order placed") && status.contains("success"), status)++ val plain = A2uiTemplates.resultCard("Done", listOf("Line one", "Line two"))+ assertEnvelopeValid(plain)+ assertTrue(plain.contains("Line one") && plain.contains("Line two"), plain)+ assertTrue(!plain.contains("btnAction"), plain)++ val withAction = A2uiTemplates.resultCard(+ "Done", listOf("Line"), actionLabel = "Open", actionName = "open.app",+ actionContext = mapOf("id" to "42"),+ )+ assertEnvelopeValid(withAction)+ val comps = componentsOf(withAction)+ assertEquals("Button", comps.getValue("btnAction")["component"])+ assertTrue(withAction.contains("open.app") && withAction.contains("42"), withAction)+ }++ @Test fun searchResultsAreEnvelopeValid() {+ val json = A2uiTemplates.searchResults(+ "best sushi",+ listOf(+ SearchResultItem(1, "Sushi Guide", "All about sushi", "example.com", "https://example.com/sushi"),+ SearchResultItem(2, "Taco Guide", "All about tacos", "tacos.example", "https://tacos.example/"),+ ),+ )+ assertEnvelopeValid(json)+ val comps = componentsOf(json)+ assertEquals("List", comps.getValue("results")["component"])+ assertEquals("Row", comps.getValue("result")["component"])+ assertEquals("Column", comps.getValue("resultBody")["component"])+ assertEquals("Button", comps.getValue("btnRead")["component"])+ assertEquals("Button", comps.getValue("btnOpen")["component"])+ assertTrue(json.contains("web.read"), json)+ assertTrue(json.contains("web.open"), json)+ assertTrue(json.contains("[1] Sushi Guide"), json)+ assertTrue(json.contains("best sushi"), json)+ }++ @Test fun templatesValidateAgainstCatalog() = runBlocking {+ val fixtures = listOf(+ A2uiTemplates.listPicker("Pick", listOf(PickerItem("a", "Alpha", "cap"))),+ A2uiTemplates.statusCard("Done", "All good", "success"),+ A2uiTemplates.resultCard("Done", listOf("One"), "Open", "open.app", mapOf("id" to "1")),+ A2uiTemplates.searchResults(+ "q",+ listOf(SearchResultItem(1, "T", "S", "example.com", "https://example.com/")),+ ),+ )+ for ((index, json) in fixtures.withIndex()) {+ val catalog = AssistantCatalog({}, { pattern, _, _ -> pattern })+ val processor = A2uiCoreMessageProcessor(listOf(catalog), ::ComposeDataModel, ::ComposeComponentRegistry)+ val loop = launch { processor.collectMessages() }+ try {+ val envelope = buildA2uiEnvelope("t$index", AssistantCatalog.ID, json)+ assertNotNull(envelope)+ envelope.forEach(processor::processMessage)+ withTimeout(5_000) {+ while (true) {+ val surfaces = processor.activeSurfaces.value+ val registry = (surfaces.firstOrNull() as? A2uiCoreSurfaceModel)+ ?.componentRegistry as? ComposeComponentRegistry+ if (registry != null && registry.components.isNotEmpty()) break+ delay(10)+ }+ }+ // Give validation a moment to report any per-component errors.+ delay(100)+ val registry = (processor.activeSurfaces.value.first() as A2uiCoreSurfaceModel).componentRegistry as ComposeComponentRegistry+ assertTrue(registry.errors.isEmpty(), "fixture $index errors: ${registry.errors} json=$json")+ } finally {+ loop.cancel()+ }+ }+ }+ @Test fun redactedSummaryShowsLengthsOnly() { assertEquals( "content(len=12), title(len=1)",
openassistant/src/test/java/com/vayunmathur/openassistant/platform/AssistantCatalogTest.kt
diff --git a/openassistant/src/test/java/com/vayunmathur/openassistant/platform/AssistantCatalogTest.kt b/openassistant/src/test/java/com/vayunmathur/openassistant/platform/AssistantCatalogTest.ktindex 04595180e5..30f56041b6 100644--- a/openassistant/src/test/java/com/vayunmathur/openassistant/platform/AssistantCatalogTest.kt+++ b/openassistant/src/test/java/com/vayunmathur/openassistant/platform/AssistantCatalogTest.kt@@ -95,6 +95,34 @@ class AssistantCatalogTest { loop.cancel() } + @Test+ fun pickerStepperAndMultilineTextFieldRenderWithoutErrors() = runBlocking {+ val processor = processor()+ val loop = launch { processor.collectMessages() }+ val json = """{"components":[+ {"id":"root","component":"Column","children":["p","s","t"]},+ {"id":"p","component":"Picker","label":"Pick one",+ "options":{"path":"/items"},"value":{"path":"/selected"},+ "action":{"event":{"name":"pick.item","context":{"id":{"path":"/selected"}}}}},+ {"id":"s","component":"QuantityStepper","label":"Qty",+ "value":{"path":"/qty"},"min":1,"max":5},+ {"id":"t","component":"TextField","label":"Notes","value":{"path":"/notes"},"multiline":true}+ ],"data":{"items":[{"id":"a","title":"A"},{"id":"b","title":"B"}],"selected":"a","qty":2,"notes":""}}"""+ buildA2uiEnvelope("m9", AssistantCatalog.ID, json)!!.forEach(processor::processMessage)+ val surface = processor.awaitSurface()+ val registry = surface.componentRegistry as ComposeComponentRegistry+ registry.awaitSettled(4)+ assertEquals(setOf("root", "p", "s", "t"), registry.components.keys)+ assertTrue(registry.errors.isEmpty(), "errors: ${registry.errors}")+ assertEquals(2L, surface.dataModel[A2uiDataPath("/qty")])+ // Prompt lines for the new components are generated from the same definitions.+ assertTrue(AssistantCatalog.PROMPT_SECTION.contains("- Picker: "))+ assertTrue(AssistantCatalog.PROMPT_SECTION.contains("- QuantityStepper: "))+ assertTrue(AssistantCatalog.PROMPT_SECTION.contains("multiline"))+ assertTrue(AssistantCatalog.PROMPT_SECTION.contains("render_ui"))+ loop.cancel()+ }+ @Test fun promptListsEveryComponentAndItsExampleParses() { AssistantCatalog.COMPONENT_NAMES.forEach {
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 fbb6ae310f..d75ea967fc 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(28, tools.declarations.size)+ assertEquals(29, tools.declarations.size) } @Test fun crossAppToolsReportMissingApps() {@@ -145,6 +145,37 @@ class AssistantToolsInvokeTest { assertEquals("Error: pending tool call expired", gated.invokeConfirmed(expired.id)) } + @Test fun renderUiValidatesAndStashesEnvelope() {+ // Invalid JSON and unusable components are errors and stash nothing.+ assertTrue(call("render_ui", "components_json" to "{not json").startsWith("Error:"), "bad json")+ assertEquals(null, tools.pendingRenderUi)+ assertTrue(+ call("render_ui", "components_json" to """{"components":[]}""").startsWith("Error: invalid A2UI"),+ )+ assertEquals(null, tools.pendingRenderUi)+ // Oversize payloads are rejected before stashing.+ val big = """{"components":[{"id":"root","component":"Text","text":"${"x".repeat(13_000)}"}]}"""+ assertTrue(call("render_ui", "components_json" to big).contains("too large"))+ assertEquals(null, tools.pendingRenderUi)+ // Valid UI succeeds, merges data_json, and is consumable exactly once by the engine.+ val ok = call(+ "render_ui",+ "components_json" to """{"components":[{"id":"root","component":"Text","text":"Hi"}]}""",+ "data_json" to """{"name":"Ada"}""",+ )+ assertEquals("UI rendered", ok)+ val stashed = tools.pendingRenderUi+ assertTrue(stashed != null && stashed.contains("Ada"), "$stashed")+ assertEquals(stashed, tools.consumePendingRenderUi())+ assertEquals(null, tools.consumePendingRenderUi())+ // Bare component arrays are accepted too.+ assertEquals(+ "UI rendered",+ call("render_ui", "components_json" to """[{"id":"root","component":"Text","text":"Yo"}]"""),+ )+ tools.consumePendingRenderUi()+ }+ @Test fun riskClassificationMatchesDesign() { val gated = setOf("create_note", "create_todo", "complete_todo", "create_contact", "create_calendar_event", "create_location_share_link", "play_music",
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 66f9219271..460f982af6 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(28, names.size)+ assertEquals(29, names.size) assertEquals(names.size, names.toSet().size) for (spec in ASSISTANT_TOOL_SPECS) { assertTrue(snake.matches(spec.name), spec.name)
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 0271b6888b..750a6dec47 100644--- a/openassistant/src/test/java/com/vayunmathur/openassistant/platform/MamlChatEngineFakeModelTest.kt+++ b/openassistant/src/test/java/com/vayunmathur/openassistant/platform/MamlChatEngineFakeModelTest.kt@@ -87,6 +87,32 @@ class MamlChatEngineFakeModelTest { e.close() } + @Test fun renderUiCallAttachesA2uiFenceToReply() = runBlocking {+ var calls = 0+ val uiJson = """{"components":[{"id":"root","component":"Text","text":"Pick one"}]}"""+ val quoted = "<|\"|>" + uiJson + "<|\"|>"+ val fake = FakeTextModel(script = { _, onToken ->+ calls+++ if (calls == 1) {+ "<|tool_call>call:render_ui{components_json:$quoted}<tool_call|>"+ } else {+ onToken("here you go"); "here you go"+ }+ })+ val e = engine(fake)+ val toolSet = tools()+ val result = e.chat(ChatRequest("sys", emptyList(), "show a card"), toolSet) { true }+ assertTrue(result is ChatResult.Reply, "$result")+ val text = (result as ChatResult.Reply).text+ assertTrue(text.contains("here you go"), text)+ assertTrue(text.contains("```a2ui"), text)+ assertTrue(text.contains("Pick one"), text)+ assertEquals(2, calls)+ // The stash was consumed by the engine, exactly once.+ assertEquals(null, toolSet.pendingRenderUi)+ e.close()+ }+ @Test fun haltedStreamAndTooLongAndUnavailable() = runBlocking { val fake = FakeTextModel() val e = engine(fake)