Modern Apps git

← Modern-Apps.git

openassistant: render A2UI surfaces the model writes in its replies

Commit
92003c049e3c217c27b246b0eebdb04b5f94eb68
Author
Vayun Mathur <[email protected]>
When
2026-10-30 21:35 UTC (1 month ago)
Parents
2c8878a
Gemma can now answer with an interactive card, form or set of buttons
instead of only markdown, using androidx.a2ui (a2ui-model + a2ui-engine
1.0.0-alpha02, protocol v0.9). The library provides the protocol types,
message processor, schema validation, data binding and catalog
functions, but no renderer and no component catalog, so both live here.

- The model writes one ```a2ui {"components":[...],"data":{...}} block
  after its prose. domain/A2uiEnvelope supplies the protocol envelope
  (createSurface, surface id m<messageId>, catalog id) so the block
  stays small under the 1024-token reply cap. domain/A2uiBlocks splits
  the block from the visible text and hides it while streaming.
- platform/AssistantCatalog defines Text, Column, Row, List, Card,
  Button, TextField, CheckBox, Image and Divider. Each prompt line is
  generated from the same definition that carries its schema, so the
  model is never taught a prop the validator rejects.
- ui/A2uiSurfaceView renders from "root" through the engine's
  evaluator, backed by snapshot-state registry and data model
  (platform/A2uiComposeState); invalid components fail alone.
- platform/A2uiController owns the processor. Button events become a
  user turn ([UI action "name": {...}]) sent through the normal path.
- Message gains an a2ui column (DB v3 -> v4); surfaces are replayed
  when a conversation is reopened, and the block is restored into the
  history the model sees.
- AssistantCatalog.PROMPT_SECTION is appended to every system prompt,
  custom ones included. That changes the system block, so the baked
  gemma4_prefix.kv no longer matches and first turns prefill until it
  is rebaked.

Verified: :openassistant:testDevUnitTest (16 new tests, including the
prompt example, per-component validation failures and a button event's
resolved context run through a real A2uiCoreMessageProcessor),
:openassistant:compileDevKotlin and :openassistant:lint pass. detekt
reports no findings in the new code; its pre-existing findings in
InferenceService, MamlChatEngine and WavDecoder are unchanged. Not yet
exercised on a device.

Diff

gradle/libs.versions.toml
diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.tomlindex d20091c6d4..e296f5bb0f 100644--- a/gradle/libs.versions.toml+++ b/gradle/libs.versions.toml@@ -50,6 +50,9 @@ wearComposeMaterial = "1.7.0-alpha05" # TV Material: Material Design for a ten-foot UI, where Material 3's focus handling does not reach. tv = "1.1.0" +# AndroidX – A2UI (agent-to-UI protocol v0.9: model + engine; no renderer is published)+a2ui = "1.0.0-alpha02"+ # AndroidX – navigation navigation3 = "1.3.0-alpha02" adaptiveNavigation3 = "1.3.0"@@ -211,6 +214,10 @@ androidx-sqlite-framework = { module = "androidx.sqlite:sqlite-framework", versi androidx-work-runtime-ktx = { module = "androidx.work:work-runtime-ktx", version.ref = "workRuntimeKtx" } androidx-datastore-preferences = { group = "androidx.datastore", name = "datastore-preferences", version.ref = "datastorePreferences" } +# AndroidX – A2UI+androidx-a2ui-model = { group = "androidx.a2ui", name = "a2ui-model", version.ref = "a2ui" }+androidx-a2ui-engine = { group = "androidx.a2ui", name = "a2ui-engine", version.ref = "a2ui" }+ # AndroidX – Compose & UI (unversioned entries come from the BOM) androidx-compose-bom = { group = "androidx.compose", name = "compose-bom", version.ref = "composeBom" } androidx-compose-ui = { group = "androidx.compose.ui", name = "ui" }
metadata_data/openassistant.md
diff --git a/metadata_data/openassistant.md b/metadata_data/openassistant.mdindex f0dc63708b..2fb19451fe 100644--- a/metadata_data/openassistant.md+++ b/metadata_data/openassistant.md@@ -5,6 +5,7 @@ Features: - Multiple chats with streaming responses - Multimodal input (photo upload and audio recording) - Markdown formatted text output+- Interactive cards and forms in replies (A2UI) - Tool calling into other Modern Apps over local IPC - A memory the model manages itself, and an editable system prompt - Can be set as the device's default digital assistant
openassistant/AGENTS.md
diff --git a/openassistant/AGENTS.md b/openassistant/AGENTS.mdindex abbe29eda6..085e910fdf 100644--- a/openassistant/AGENTS.md+++ b/openassistant/AGENTS.md@@ -7,7 +7,7 @@ _Install: ./install openassistant (dev by default)._ - Gradle: :openassistant / dir: openassistant/ - Package roots present: ui, data, domain, platform - Entry files: MainActivity.kt (no Route.kt — `Route` + `Navigation` are inline)-- Deps: :library:room, :library:image, :library:ml, :library:downloadservice+- Deps: :library:room, :library:image, :library:ml, :library:downloadservice, androidx.a2ui (model + engine) - Metadata: metadata_data/openassistant.md (present) - Rust: no / screenshotTest: yes @@ -18,6 +18,7 @@ _Install: ./install openassistant (dev by default)._ - Multimodal input: photo upload and audio recording, read by Gemma 4's vision and audio towers - Tool calling into other Modern Apps over local IPC, with JSON-schema validation - A model-managed memory plus an editable system prompt; can be set as the device's default digital assistant (Assist API + voice interaction service)+- Generative UI: replies can carry an A2UI block (cards, forms, buttons) rendered natively; button events come back to the model as user turns **Architecture / data-flow:** `ui/LiteRTChatUi` → `util/AssistantViewModel` → `data/OpenAssistantRepository` (Room) + `util/InferenceService` → `platform/MamlChatEngine` (Gemma 4 on `:library:ml`'s `Gemma4Handle`; own tool loop, max 6 rounds) with `platform/AssistantTools` (explicit registry over `domain/AssistantToolSpecs`) dispatching IPC tool calls. Pure logic (tool-call parsing/markup stripping, tool loop, WAV decode, history fitting) lives in `domain/` with unit tests. `onCreateBeforeContent` only wires the `IntentLauncher` and picks up Assist-API screen context; `Content()` gates on the initial model download before the chat renders. **Entry points + reading order:** `Route` (`ConversationPage(id)` / `SettingsPage`, inline) → `MainActivity.kt` → `ui/LiteRTChatUi.kt` → `util/AssistantViewModel.kt` → `util/InferenceService.kt` → `platform/MamlChatEngine.kt` → `data/OpenAssistantRepository.kt`. **Gotchas:**@@ -27,6 +28,8 @@ _Install: ./install openassistant (dev by default)._ - Tool names are snake_case (`get_notes`, `add_to_memory`), matching what LiteRT-LM exposed; the system prompt references them. Add a tool in `domain/AssistantToolSpecs.kt` AND `platform/AssistantTools.kt` (an init check fails if they disagree) - Model files live in `getExternalFilesDir(null)/gemma4/` (text, embed, head, vision, audio, tokenizer); the vision/audio towers load lazily and unload after 3 idle minutes - Extra non-conforming dirs (`assist/`, `util/`) hold real code — closed-roots migration pending+- A2UI: the model writes only ```` ```a2ui {"components":[...],"data":{...}} ```` and `domain/A2uiEnvelope` adds the protocol envelope. Surface id is `m<messageId>`; the block is stored in `Message.a2ui` (DB v4) and replayed by `platform/A2uiController.sync`. androidx.a2ui ships no renderer — `ui/A2uiSurfaceView` is ours. Add a component in `platform/AssistantCatalog` (schema + prompt line together) AND the `when` in `A2uiSurfaceView`+- `AssistantCatalog.PROMPT_SECTION` is appended to every system prompt, so changing it (or the catalog) invalidates the baked `gemma4_prefix.kv`: still correct, but first turns prefill until it is rebaked with `bake_gemma4_prefix`  ## Key files ### Root — entry + inline navigation@@ -45,15 +48,21 @@ _Install: ./install openassistant (dev by default)._ - com/vayunmathur/openassistant/ui/LiteRTChatBubble.kt - com/vayunmathur/openassistant/ui/LiteRTChatInput.kt - com/vayunmathur/openassistant/ui/SettingsPage.kt+- com/vayunmathur/openassistant/ui/A2uiSurfaceView.kt — Compose renderer for A2UI surfaces ### domain/ — pure, unit-tested - com/vayunmathur/openassistant/domain/AssistantToolSpecs.kt — tool names/descriptions/params - com/vayunmathur/openassistant/domain/ToolCalls.kt — call parsing, markup stripping, arg coercion - com/vayunmathur/openassistant/domain/ToolLoop.kt — generate/call/respond loop - com/vayunmathur/openassistant/domain/WavDecoder.kt - com/vayunmathur/openassistant/domain/HistoryFit.kt+- com/vayunmathur/openassistant/domain/A2uiBlocks.kt — split/restore ```a2ui blocks, streaming-safe+- com/vayunmathur/openassistant/domain/A2uiEnvelope.kt — block → A2UI protocol messages, action → user turn ### platform/ — engine + tool registry - com/vayunmathur/openassistant/platform/MamlChatEngine.kt - com/vayunmathur/openassistant/platform/AssistantTools.kt+- com/vayunmathur/openassistant/platform/AssistantCatalog.kt — A2UI component catalog + its prompt section+- com/vayunmathur/openassistant/platform/A2uiController.kt — owns the A2UI engine; events → user turns+- com/vayunmathur/openassistant/platform/A2uiComposeState.kt — snapshot-state registry + data model ### util/ — ViewModel, inference, tools, audio (migration pending) - com/vayunmathur/openassistant/util/AssistantViewModel.kt - com/vayunmathur/openassistant/util/AssistantUiContract.kt
openassistant/build.gradle.kts
diff --git a/openassistant/build.gradle.kts b/openassistant/build.gradle.ktsindex df44de70a7..d858e351cb 100644--- a/openassistant/build.gradle.kts+++ b/openassistant/build.gradle.kts@@ -40,4 +40,9 @@ dependencies {     implementation(libs.kotlinx.coroutines.android)      implementation(project(":library:downloadservice"))++    // generative UI: the model emits A2UI components, rendered natively in chat+    implementation(libs.androidx.a2ui.model)+    implementation(libs.androidx.a2ui.engine)+    implementation(libs.kotlinx.serialization.json) }
openassistant/src/main/java/com/vayunmathur/openassistant/data/Database.kt
diff --git a/openassistant/src/main/java/com/vayunmathur/openassistant/data/Database.kt b/openassistant/src/main/java/com/vayunmathur/openassistant/data/Database.ktindex 126fd53f90..f033d357c2 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/data/Database.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/data/Database.kt@@ -30,6 +30,8 @@ data class Message(     val imagePaths: List<String> = emptyList(), // Store as paths for better persistence     val hasAudio: Boolean = false,     val missingAppPackage: String? = null,+    /** The A2UI block the model attached to this reply, as written (see domain/A2uiBlocks). */+    val a2ui: String? = null,     val timestamp: Long = System.currentTimeMillis(),     @PrimaryKey(autoGenerate = true)     override val id: Long = 0,@@ -100,7 +102,7 @@ interface MemoryDao { }  @ColumnTypeConverters(DefaultConverters::class)-@Database(entities = [Conversation::class, Message::class, Memory::class], version = 3, exportSchema = false)+@Database(entities = [Conversation::class, Message::class, Memory::class], version = 4, exportSchema = false) abstract class AppDatabase: RoomDatabase() {     abstract fun conversationDao(): ConversationDao     abstract fun messageDao(): MessageDao@@ -115,6 +117,7 @@ abstract class AppDatabase: RoomDatabase() {                         "(`content` TEXT NOT NULL, `id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL)",                 )             },+            Migration(3, 4) { it.execSQL("ALTER TABLE Message ADD COLUMN a2ui TEXT") },         )     } }
openassistant/src/main/java/com/vayunmathur/openassistant/domain/A2uiBlocks.kt
diff --git a/openassistant/src/main/java/com/vayunmathur/openassistant/domain/A2uiBlocks.kt b/openassistant/src/main/java/com/vayunmathur/openassistant/domain/A2uiBlocks.ktnew file mode 100644index 0000000000..6927f6a48f--- /dev/null+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/domain/A2uiBlocks.kt@@ -0,0 +1,50 @@+package com.vayunmathur.openassistant.domain++const val A2UI_FENCE_OPEN = "```a2ui"+private const val FENCE_CLOSE = "```"++/** A reply split into the prose to show and the raw JSON of its first A2UI block, if any. */+data class A2uiSplit(val visible: String, val json: String?)++/**+ * Cuts every ```` ```a2ui ```` block out of [text]; the first complete one becomes [A2uiSplit.json].+ *+ * An unclosed block hides everything after its opener. With [streaming], a trailing fragment+ * that could still grow into the opener (` ``` `, ` ```a2 `) is hidden too, so the fence never+ * flashes on screen while it is being written.+ */+fun splitA2ui(text: String, streaming: Boolean = true): A2uiSplit {+    val out = StringBuilder()+    var json: String? = null+    var at = 0+    while (at < text.length) {+        val open = text.indexOf(A2UI_FENCE_OPEN, at)+        if (open < 0) {+            out.append(text, at, text.length)+            break+        }+        out.append(text, at, open)+        val bodyStart = open + A2UI_FENCE_OPEN.length+        val close = text.indexOf(FENCE_CLOSE, bodyStart)+        if (close < 0) {+            at = text.length+            break+        }+        if (json == null) json = text.substring(bodyStart, close).trim().takeIf { it.isNotEmpty() }+        at = close + FENCE_CLOSE.length+    }+    if (streaming) trimPartialOpener(out)+    return A2uiSplit(out.toString().trim(), json)+}++/** [text] with [json] restored as a fenced block, as the model originally wrote it. */+fun withA2uiBlock(text: String, json: String?): String =+    if (json == null) text else "$text\n$A2UI_FENCE_OPEN\n$json\n$FENCE_CLOSE".trimStart()++private fun trimPartialOpener(out: StringBuilder) {+    val tick = out.lastIndexOf("`")+    if (tick < 0) return+    val start = generateSequence(tick) { i -> (i - 1).takeIf { it >= 0 && out[it] == '`' } }.last()+    val tail = out.substring(start)+    if (tail.length < A2UI_FENCE_OPEN.length && A2UI_FENCE_OPEN.startsWith(tail)) out.setLength(start)+}
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.ktnew file mode 100644index 0000000000..c30d63b00a--- /dev/null+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/domain/A2uiEnvelope.kt@@ -0,0 +1,80 @@+package com.vayunmathur.openassistant.domain++import androidx.a2ui.model.protocol.A2uiComponentPayload+import androidx.a2ui.model.protocol.A2uiCreateSurfaceMessage+import androidx.a2ui.model.protocol.A2uiServerToClientMessage+import androidx.a2ui.model.protocol.A2uiUpdateComponentsMessage+import androidx.a2ui.model.protocol.A2uiUpdateDataModelMessage+import kotlinx.serialization.json.Json+import kotlinx.serialization.json.JsonArray+import kotlinx.serialization.json.JsonElement+import kotlinx.serialization.json.JsonNull+import kotlinx.serialization.json.JsonObject+import kotlinx.serialization.json.JsonPrimitive+import kotlinx.serialization.json.booleanOrNull+import kotlinx.serialization.json.doubleOrNull+import kotlinx.serialization.json.longOrNull++/** One surface per assistant message, so replaying a conversation recreates each in place. */+fun a2uiSurfaceId(messageId: Long): String = "m$messageId"++/**+ * The protocol messages for a block the model wrote, or null when it is not usable.+ *+ * The model writes only `{"components": [...], "data": {...}}` to keep its reply short; the+ * 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>? {+    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+    }+    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)))+    }+}++/** The user turn sent back to the model when a surface fires an event. */+fun actionTurnText(eventName: String, context: Map<String, Any?>): String =+    if (context.isEmpty()) {+        "[UI action \"$eventName\"]"+    } else {+        "[UI action \"$eventName\": ${valueToJson(context)}]"+    }++private fun toComponent(element: JsonElement): A2uiComponentPayload? {+    val obj = element as? JsonObject ?: return null+    val id = (obj["id"] as? JsonPrimitive)?.takeIf { it.isString }?.content ?: return null+    val type = (obj["component"] as? JsonPrimitive)?.takeIf { it.isString }?.content ?: return null+    val properties = obj.filterKeys { it != "id" && it != "component" }.mapValues { jsonToValue(it.value) }+    return A2uiComponentPayload(id, type, properties)+}++/** JSON as the plain types A2UI's data model and payloads use: Map, List, String, Number, Boolean, null. */+fun jsonToValue(element: JsonElement): Any? = when (element) {+    is JsonNull -> null+    is JsonObject -> element.mapValues { jsonToValue(it.value) }+    is JsonArray -> element.map { jsonToValue(it) }+    is JsonPrimitive -> when {+        element.isString -> element.content+        else -> element.booleanOrNull ?: element.longOrNull ?: element.doubleOrNull+    }+}++fun valueToJson(value: Any?): JsonElement = when (value) {+    null -> JsonNull+    is JsonElement -> value+    is String -> JsonPrimitive(value)+    is Number -> JsonPrimitive(value)+    is Boolean -> JsonPrimitive(value)+    is Map<*, *> -> JsonObject(value.entries.associate { (k, v) -> k.toString() to valueToJson(v) })+    is Iterable<*> -> JsonArray(value.map { valueToJson(it) })+    else -> JsonPrimitive(value.toString())+}
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.ktnew file mode 100644index 0000000000..bf98854e9f--- /dev/null+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/platform/A2uiComposeState.kt@@ -0,0 +1,83 @@+package com.vayunmathur.openassistant.platform++import androidx.a2ui.engine.platform.A2uiCoreComponentRegistry+import androidx.a2ui.engine.platform.A2uiCoreDataModel+import androidx.a2ui.model.protocol.A2uiComponentPayload+import androidx.a2ui.model.protocol.A2uiDataPath+import androidx.a2ui.model.protocol.A2uiException+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateMapOf+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.setValue+import androidx.compose.runtime.snapshots.Snapshot++/** Components and per-component errors in snapshot state, so composition follows engine updates. */+class ComposeComponentRegistry : A2uiCoreComponentRegistry {+    val components = mutableStateMapOf<String, A2uiComponentPayload>()+    val errors = mutableStateMapOf<String, String>()++    override fun update(components: List<A2uiComponentPayload>) = Snapshot.withMutableSnapshot {+        for (component in components) {+            this.components[component.id] = component+            errors.remove(component.id)+        }+    }++    override fun reportError(id: String, exception: A2uiException) {+        errors[id] = exception.message ?: exception.code+    }++    override fun close() = Snapshot.withMutableSnapshot {+        components.clear()+        errors.clear()+    }+}++/**+ * The surface's JSON tree as one immutable value in snapshot state.+ *+ * Every write copies the path it touches, so a reader in composition always sees a+ * consistent tree. Writes come from both the engine's actor and the UI thread (text+ * fields, checkboxes), hence the lock around read-modify-write.+ */+class ComposeDataModel : A2uiCoreDataModel {+    private var root: Any? by mutableStateOf(emptyMap<String, Any?>())+    private val lock = Any()++    override fun update(path: A2uiDataPath, value: Any?) {+        synchronized(lock) { root = setAt(root, path.segments, 0, value) ?: emptyMap<String, Any?>() }+    }++    override fun get(path: A2uiDataPath): Any? {+        var node = root+        for (segment in path.segments) {+            node = when (node) {+                is Map<*, *> -> node[segment]+                is List<*> -> segment.toIntOrNull()?.let { node.getOrNull(it) }+                else -> null+            } ?: return null+        }+        return node+    }++    override fun close() {+        synchronized(lock) { root = emptyMap<String, Any?>() }+    }++    private fun setAt(node: Any?, segments: List<String>, at: Int, value: Any?): Any? {+        if (at == segments.size) return value+        val key = segments[at]+        val index = key.toIntOrNull()+        if (node is List<*> && index != null && index >= 0) {+            val list = node.toMutableList()+            while (list.size <= index) list.add(null)+            list[index] = setAt(list[index], segments, at + 1, value)+            return list+        }+        val map = (node as? Map<*, *>)?.entries?.associateTo(LinkedHashMap()) { (k, v) -> k.toString() to v }+            ?: LinkedHashMap()+        val child = setAt(map[key], segments, at + 1, value)+        if (child == null && at + 1 == segments.size) map.remove(key) else map[key] = child+        return map+    }+}
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.ktnew file mode 100644index 0000000000..fb7019e560--- /dev/null+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/platform/A2uiController.kt@@ -0,0 +1,99 @@+package com.vayunmathur.openassistant.platform++import android.content.Context+import android.content.Intent+import android.icu.text.MessageFormat+import androidx.a2ui.engine.model.A2uiCoreSurfaceModel+import androidx.a2ui.engine.processor.A2uiCoreMessageProcessor+import androidx.a2ui.model.protocol.A2uiClientErrorMessage+import androidx.a2ui.model.protocol.A2uiClientEventMessage+import androidx.a2ui.model.protocol.A2uiDeleteSurfaceMessage+import androidx.core.net.toUri+import com.vayunmathur.library.log.Log+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 kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.flow.SharingStarted+import kotlinx.coroutines.flow.StateFlow+import kotlinx.coroutines.flow.map+import kotlinx.coroutines.flow.stateIn+import kotlinx.coroutines.launch++/**+ * Owns the A2UI engine for the app: feeds it the surfaces stored on assistant messages and+ * 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.+ */+class A2uiController(+    context: Context,+    scope: CoroutineScope,+    private val onAction: (conversationId: Long, text: String) -> Unit,+) {+    private val appContext = context.applicationContext+    private val processor = A2uiCoreMessageProcessor(+        catalogs = listOf(AssistantCatalog(::openUrl, ::formatMessage)),+        dataModelFactory = ::ComposeDataModel,+        componentRegistryFactory = ::ComposeComponentRegistry,+    )+    private val fed = HashMap<Long, String>()+    private val conversationOf = HashMap<String, Long>()++    val surfaces: StateFlow<Map<String, A2uiCoreSurfaceModel>> = processor.activeSurfaces+        .map { list -> list.filterIsInstance<A2uiCoreSurfaceModel>().associateBy { it.id } }+        .stateIn(scope, SharingStarted.Eagerly, emptyMap())++    init {+        scope.launch { processor.collectMessages() }+        scope.launch {+            processor.outboundEvents.collect { event ->+                when (event) {+                    is A2uiClientEventMessage -> conversationOf[event.surfaceId]?.let {+                        onAction(it, actionTurnText(event.type, event.context))+                    }+                    is A2uiClientErrorMessage ->+                        Log.status(TAG, "${event.code} on ${event.surfaceId}: ${event.message}")+                }+            }+        }+    }++    /** Feeds any surface in [messages] the engine has not seen yet. Main thread only. */+    fun sync(messages: List<Message>) {+        for (message in messages) {+            val json = message.a2ui+            if (json != null && fed[message.id] != json) 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))+        conversationOf[surfaceId] = message.conversationId+        val envelope = buildA2uiEnvelope(surfaceId, AssistantCatalog.ID, json)+        if (envelope == null) {+            Log.status(TAG, "unusable a2ui block on message ${message.id}")+            return+        }+        envelope.forEach(processor::processMessage)+    }++    private fun openUrl(url: String) {+        try {+            appContext.startActivity(Intent(Intent.ACTION_VIEW, url.toUri()).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))+        } catch (expected: Exception) {+            Log.status(TAG, "Failed to open $url", expected)+        }+    }++    private fun formatMessage(pattern: String, locale: java.util.Locale, arguments: Map<String, Any>): String =+        MessageFormat(pattern, locale).format(arguments)++    private companion object {+        const val TAG = "A2uiController"+    }+}
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.ktnew file mode 100644index 0000000000..486dafe285--- /dev/null+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/platform/AssistantCatalog.kt@@ -0,0 +1,136 @@+package com.vayunmathur.openassistant.platform++import androidx.a2ui.engine.catalog.A2uiCoreCatalog+import androidx.a2ui.engine.catalog.A2uiCoreComponentDefinition+import androidx.a2ui.engine.catalog.A2uiCoreComponentDefinitionCollection+import androidx.a2ui.model.catalog.A2uiFunctionCollection+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.A2uiObjectSchema+import androidx.a2ui.model.schema.A2uiSchema+import androidx.a2ui.model.schema.A2uiSchemaKeyword+import androidx.a2ui.model.schema.A2uiStringSchema+import androidx.a2ui.model.schema.commontypes.A2uiActionSchema+import androidx.a2ui.model.schema.commontypes.A2uiChildListSchema+import androidx.a2ui.model.schema.commontypes.A2uiComponentIdSchema+import androidx.a2ui.model.schema.commontypes.A2uiDataBindingSchema+import androidx.a2ui.model.schema.commontypes.A2uiDynamicStringSchema+import com.vayunmathur.openassistant.domain.A2UI_FENCE_OPEN++/**+ * The components the model may put in an A2UI block, and the prompt that teaches them.+ *+ * Each prompt line is generated from the same [Component] that carries the schema, so the+ * model is never told about a prop the validator would reject. Extra props are allowed:+ * a small model adds stray ones, and failing a whole component over them helps nobody.+ */+class AssistantCatalog(urlOpener: A2uiUrlOpener, messageFormatter: A2uiMessageFormatter) : A2uiCoreCatalog {+    override val id: String = ID+    override val title: String = "OpenAssistant"+    override val componentDefinitions: A2uiCoreComponentDefinitionCollection =+        A2uiCoreComponentDefinitionCollection(COMPONENTS)+    override val functions: A2uiFunctionCollection =+        A2uiFunctionCollection(createBasicCatalogFunctions(urlOpener, messageFormatter))++    private class Component(+        override val name: String,+        override val description: String,+        val promptProps: String,+        props: Map<String, A2uiSchema> = emptyMap(),+        required: Set<String> = props.keys,+    ) : A2uiCoreComponentDefinition {+        override val propertySchema: A2uiSchema = A2uiObjectSchema(properties = props, required = required)+    }++    companion object {+        const val ID = "https://vayunmathur.com/openassistant/a2ui/catalog/v1"++        private val text = A2uiDynamicStringSchema.DEFAULT_INSTANCE+        private val children = mapOf("children" to A2uiChildListSchema.DEFAULT_INSTANCE)+        private val binding = A2uiDataBindingSchema.DEFAULT_INSTANCE+        private val variant = A2uiStringSchema(+            keywords = listOf(A2uiSchemaKeyword.Enum(listOf("title", "body", "caption"))),+        )+        private const val BINDING_PROPS = "label, value {\"path\":\"/field\"}"++        private val COMPONENTS: List<Component> = listOf(+            Component(+                "Text", "A run of text.", "text, variant (\"title\"|\"body\"|\"caption\")",+                mapOf(+                    "text" to text,+                    "variant" to variant,+                ),+                required = setOf("text"),+            ),+            Component("Column", "Children stacked vertically.", "children (array of ids)", children),+            Component("Row", "Children side by side.", "children (array of ids)", children),+            Component("List", "A vertical list of items.", "children (array of ids)", children),+            Component(+                "Card", "A raised container around one child.", "child (one id)",+                mapOf("child" to A2uiComponentIdSchema.DEFAULT_INSTANCE),+            ),+            Component(+                "Button", "A tappable button that sends an event back to the assistant.",+                "label, action {\"event\":{\"name\":\"...\",\"context\":{...}}}, primary (true|false)",+                mapOf(+                    "label" to text,+                    "action" to A2uiActionSchema.DEFAULT_INSTANCE,+                    "primary" to A2uiBooleanSchema.INSTANCE,+                ),+                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),+                required = setOf("value"),+            ),+            Component(+                "CheckBox", "A checkbox bound to a boolean in the data model.", BINDING_PROPS,+                mapOf("label" to text, "value" to binding),+            ),+            Component(+                "Image", "An image from a URL.", "url, description",+                mapOf("url" to text, "description" to text),+                required = setOf("url"),+            ),+            Component("Divider", "A thin horizontal rule.", "(no props)"),+        )++        val COMPONENT_NAMES: List<String> = COMPONENTS.map { it.name }++        const val EXAMPLE = """{"components":[{"id":"root","component":"Card","child":"c"},""" ++            """{"id":"c","component":"Column","children":["q","n","v","b"]},""" ++            """{"id":"q","component":"Text","text":"Who's coming?","variant":"title"},""" ++            """{"id":"n","component":"TextField","label":"Name","value":{"path":"/name"}},""" ++            """{"id":"v","component":"CheckBox","label":"Vegetarian","value":{"path":"/veg"}},""" ++            """{"id":"b","component":"Button","label":"RSVP","primary":true,""" ++            """"action":{"event":{"name":"rsvp","context":{"name":{"path":"/name"},"veg":{"path":"/veg"}}}}}],""" ++            """"data":{"name":"","veg":false}}"""++        /** Appended to the system prompt; describes exactly [COMPONENTS]. */+        val PROMPT_SECTION: String = buildString {+            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:",+            )+            appendLine(A2UI_FENCE_OPEN)+            appendLine("""{"components":[...],"data":{...}}""")+            appendLine("```")+            appendLine("""Each component is {"id":"...","component":"<Type>", ...props}.""")+            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("Keep blocks small (under 15 components). Never use a block for a plain answer. Example:")+            appendLine(A2UI_FENCE_OPEN)+            appendLine(EXAMPLE)+            append("```")+        }+    }+}
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.ktnew file mode 100644index 0000000000..e008c571c9--- /dev/null+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/ui/A2uiSurfaceView.kt@@ -0,0 +1,169 @@+package com.vayunmathur.openassistant.ui++import androidx.a2ui.engine.model.A2uiCoreSurfaceModel+import androidx.a2ui.engine.model.A2uiCoreValueResolver+import androidx.a2ui.model.protocol.A2uiDataPath+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Column+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.widthIn+import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.runtime.Composable+import androidx.compose.runtime.remember+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.draw.clip+import androidx.compose.ui.layout.ContentScale+import androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.unit.dp+import com.vayunmathur.library.image.ImageRequest+import com.vayunmathur.library.image.compose.AsyncImage+import com.vayunmathur.library.ui.Button+import com.vayunmathur.library.ui.Card+import com.vayunmathur.library.ui.Checkbox+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.Text+import com.vayunmathur.openassistant.platform.ComposeComponentRegistry+import com.vayunmathur.openassistant.platform.ComposeDataModel++private const val ROOT_ID = "root"+private const val MAX_DEPTH = 12++/**+ * Draws an A2UI surface from its `root` component.+ *+ * Props are evaluated through the engine, so `{"path": ...}` bindings and catalog function+ * calls work anywhere a string is accepted; reads go through [ComposeDataModel]'s snapshot+ * state, so edits recompose whatever is bound to them.+ */+@Composable+fun A2uiSurfaceView(surface: A2uiCoreSurfaceModel, modifier: Modifier = Modifier) {+    val registry = surface.componentRegistry as? ComposeComponentRegistry ?: return+    val data = surface.dataModel as? ComposeDataModel ?: return+    val renderer = remember(surface) { SurfaceRenderer(surface, registry, data) }+    Box(modifier.widthIn(max = 400.dp)) { renderer.Node(ROOT_ID, A2uiDataPath("/"), 0) }+}++private class SurfaceRenderer(+    val surface: A2uiCoreSurfaceModel,+    val registry: ComposeComponentRegistry,+    val data: ComposeDataModel,+) {+    private val resolver = A2uiCoreValueResolver { data[it] }++    fun evaluate(componentId: String, dataPath: A2uiDataPath, payload: Any?): Any? =+        surface.evaluatePayload(componentId, resolver, dataPath, payload)++    fun string(componentId: String, dataPath: A2uiDataPath, payload: Any?): String =+        when (val value = evaluate(componentId, dataPath, payload)) {+            null -> ""+            is Double -> if (value % 1.0 == 0.0) value.toLong().toString() else value.toString()+            else -> value.toString()+        }++    fun boundPath(dataPath: A2uiDataPath, binding: Any?): A2uiDataPath? =+        ((binding as? Map<*, *>)?.get("path") as? String)?.let { dataPath / it }++    /**+     * Fires [action] with its event context already resolved at [dataPath].+     *+     * The engine resolves context at the surface root, which would point a button inside a+     * list template at the wrong item; resolving here first leaves it only literals.+     */+    @Suppress("UNCHECKED_CAST")+    fun dispatch(componentId: String, dataPath: A2uiDataPath, action: Any?) {+        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?>+        val resolved = if (event == null || context == null) {+            map+        } else {+            val literal = context.mapValues { evaluate(componentId, dataPath, it.value) }+            mapOf("event" to event + ("context" to literal))+        }+        surface.dispatchAction(componentId, resolved)+    }++    @Composable+    fun Node(id: String, dataPath: A2uiDataPath, depth: Int) {+        if (depth > MAX_DEPTH) return+        registry.errors[id]?.let {+            Text(it, color = MaterialTheme.colorScheme.error, style = MaterialTheme.typography.bodySmall)+            return+        }+        val component = registry.components[id] ?: return+        val props = component.properties+        val str = { key: String -> string(id, dataPath, props[key]) }+        when (component.type) {+            "Text" -> Text(+                str("text"),+                style = when (props["variant"]) {+                    "title" -> MaterialTheme.typography.titleMedium+                    "caption" -> MaterialTheme.typography.bodySmall+                    else -> MaterialTheme.typography.bodyMedium+                },+            )+            "Column", "List" -> Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {+                Children(props["children"], dataPath, depth)+            }+            "Row" -> Row(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalAlignment = Alignment.CenterVertically) {+                Children(props["children"], dataPath, depth)+            }+            "Card" -> Card(Modifier.fillMaxWidth()) {+                Box(Modifier.padding(16.dp)) {+                    (props["child"] as? String)?.let { Node(it, dataPath, depth + 1) }+                }+            }+            "Button" -> {+                val onClick = { dispatch(id, dataPath, props["action"]) }+                if (props["primary"] == true) {+                    Button(onClick) { Text(str("label")) }+                } else {+                    OutlinedButton(onClick) { Text(str("label")) }+                }+            }+            "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) } },+                )+                Text(str("label"))+            }+            "Image" -> AsyncImage(+                ImageRequest.Builder(LocalContext.current).data(str("url")).build(),+                str("description").ifEmpty { null },+                Modifier.fillMaxWidth().heightIn(max = 240.dp).clip(RoundedCornerShape(12.dp)),+                contentScale = ContentScale.Crop,+            )+            "Divider" -> HorizontalDivider()+        }+    }++    /** A static id list, or a `{componentId, path}` template repeated per item of a data list. */+    @Composable+    fun Children(children: Any?, dataPath: A2uiDataPath, depth: Int) {+        when (children) {+            is List<*> -> children.forEach { child -> (child as? String)?.let { Node(it, dataPath, depth + 1) } }+            is Map<*, *> -> {+                val template = children["componentId"] as? String ?: return+                val listPath = (children["path"] as? String)?.let { dataPath / it } ?: return+                val items = data[listPath] as? List<*> ?: return+                items.indices.forEach { Node(template, listPath / it.toString(), depth + 1) }+            }+        }+    }+}
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 8254e129bd..2d6c50568e 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/ui/LiteRTChatBubble.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/ui/LiteRTChatBubble.kt@@ -2,6 +2,7 @@ package com.vayunmathur.openassistant.ui  import android.content.ClipData import android.content.Intent+import androidx.a2ui.engine.model.A2uiCoreSurfaceModel import com.vayunmathur.library.log.Log import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row@@ -51,7 +52,7 @@ import kotlinx.coroutines.launch  */ @OptIn(ExperimentalMaterial3Api::class) @Composable-fun ChatBubble(message: Message) {+fun ChatBubble(message: Message, surface: A2uiCoreSurfaceModel? = null) {     val context = LocalContext.current     val isUser = message.role == "user"     val isTool = message.role == "tool"@@ -130,6 +131,9 @@ fun ChatBubble(message: Message) {                 style = LocalTextStyle.current.copy(fontSize = 16.sp, lineHeight = 22.sp)             )         }+        if (surface != null && !isUser) {+            A2uiSurfaceView(surface, Modifier.padding(vertical = 4.dp))+        }         if (message.text.isNotBlank() && !isTool) {             IconButton(                 onClick = { scope.launch { clipboard.setClipEntry(ClipEntry(ClipData.newPlainText("message", message.text))) } },
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 adf9f42cc5..f2672f483a 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/ui/LiteRTChatScreen.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/ui/LiteRTChatScreen.kt@@ -30,6 +30,7 @@ import com.vayunmathur.library.ui.SnackbarHostState import com.vayunmathur.library.ui.Text import com.vayunmathur.library.ui.appBarScrollBehavior import com.vayunmathur.openassistant.R+import com.vayunmathur.openassistant.domain.a2uiSurfaceId import com.vayunmathur.openassistant.util.ChatActions import com.vayunmathur.openassistant.util.ChatUiState @@ -81,7 +82,7 @@ fun ChatScreen(     ) { padding ->         SelectionContainer {             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) }+                items(state.messages, key = { it.id }) { ChatBubble(it, state.surfaces[a2uiSurfaceId(it.id)]) }             }         }     }
openassistant/src/main/java/com/vayunmathur/openassistant/ui/LiteRTChatUi.kt
diff --git a/openassistant/src/main/java/com/vayunmathur/openassistant/ui/LiteRTChatUi.kt b/openassistant/src/main/java/com/vayunmathur/openassistant/ui/LiteRTChatUi.ktindex a748abc4d6..c1e5cc43de 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/ui/LiteRTChatUi.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/ui/LiteRTChatUi.kt@@ -65,6 +65,8 @@ fun LiteRTChatUi(     val filteredMessages by assistantViewModel.messagesFor(conversationId).collectAsState(initial = emptyList())     val isRecording by assistantViewModel.isRecording.collectAsState()     val recordedAudioPath by assistantViewModel.recordedAudioPath.collectAsState()+    val surfaces by assistantViewModel.a2ui.surfaces.collectAsState()+    LaunchedEffect(filteredMessages) { assistantViewModel.a2ui.sync(filteredMessages) }      val context = LocalContext.current     val resources = LocalResources.current@@ -188,6 +190,7 @@ fun LiteRTChatUi(                 state = ChatUiState(                     title = activeConversation?.title,                     messages = filteredMessages,+                    surfaces = surfaces,                     inputText = inputText,                     attachments = selectedImageUris,                     isRecording = isRecording,
openassistant/src/main/java/com/vayunmathur/openassistant/util/AssistantUiContract.kt
diff --git a/openassistant/src/main/java/com/vayunmathur/openassistant/util/AssistantUiContract.kt b/openassistant/src/main/java/com/vayunmathur/openassistant/util/AssistantUiContract.ktindex edf30d6072..1ad794a1da 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/util/AssistantUiContract.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/util/AssistantUiContract.kt@@ -1,6 +1,7 @@ package com.vayunmathur.openassistant.util  import android.net.Uri+import androidx.a2ui.engine.model.A2uiCoreSurfaceModel import com.vayunmathur.openassistant.data.Memory import com.vayunmathur.openassistant.data.Message @@ -18,6 +19,8 @@ data class ChatUiState(     /** Null until the conversation is persisted; the screen then shows "New conversation". */     val title: String? = null,     val messages: List<Message> = emptyList(),+    /** A2UI surfaces by surface id (`m<messageId>`), drawn under their assistant message. */+    val surfaces: Map<String, A2uiCoreSurfaceModel> = emptyMap(),     val inputText: String = "",     /** Images picked for the next message, not yet sent. */     val attachments: List<Uri> = emptyList(),
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 594ab8aaef..bb25ee1879 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/util/AssistantViewModel.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/util/AssistantViewModel.kt@@ -17,6 +17,7 @@ import com.vayunmathur.openassistant.data.Conversation import com.vayunmathur.openassistant.data.Memory import com.vayunmathur.openassistant.data.Message import com.vayunmathur.openassistant.data.OpenAssistantRepository+import com.vayunmathur.openassistant.platform.A2uiController import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableStateFlow@@ -77,6 +78,14 @@ class AssistantViewModel(     val memories: StateFlow<List<Memory>> = repository.memoriesFlow()         .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptyList()) +    /** Renders the A2UI surfaces on assistant messages; their events come back as user turns. */+    val a2ui = A2uiController(application, viewModelScope) { conversationId, text ->+        viewModelScope.launch {+            upsertMessage(Message(conversationId, text, "user"))+            requestInference(conversationId, text, emptyList(), null)+        }+    }+     init {         cleanupLegacyModelFile()         cleanupStaleSiglipModels()
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 957cdecc23..7f8d895da5 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/util/InferenceService.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/util/InferenceService.kt@@ -17,6 +17,7 @@ import com.vayunmathur.library.util.SecureResultReceiver import com.vayunmathur.library.util.DataStoreUtils import com.vayunmathur.library.downloadservice.ModelUrls import com.vayunmathur.openassistant.platform.AssistantTools+import com.vayunmathur.openassistant.platform.AssistantCatalog import com.vayunmathur.openassistant.platform.ChatRequest import com.vayunmathur.openassistant.platform.ChatResult import com.vayunmathur.openassistant.platform.HistoryTurn@@ -44,6 +45,8 @@ import kotlin.time.Clock import com.vayunmathur.openassistant.data.Message as DbMessage import com.vayunmathur.openassistant.data.OpenAssistantRepository import com.vayunmathur.openassistant.R+import com.vayunmathur.openassistant.domain.splitA2ui+import com.vayunmathur.openassistant.domain.withA2uiBlock import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.selects.select @@ -272,7 +275,7 @@ class InferenceService : Service() {         val cutoff = Clock.System.now().toEpochMilliseconds() - HISTORY_RECENCY_MILLIS         return fetchHistoryFromDb(conversationId)             .filter { it.text != userText || it.timestamp < cutoff }-            .map { HistoryTurn(fromUser = it.role != "assistant", text = it.text) }+            .map { HistoryTurn(fromUser = it.role != "assistant", text = withA2uiBlock(it.text, it.a2ui)) }     }      private suspend fun executeStandardInference(job: InferenceJob.Standard) {@@ -381,9 +384,11 @@ class InferenceService : Service() {         engine = created     } +    /** The user's (or default) prompt plus the A2UI section, which custom prompts must not lose. */     private suspend fun systemPrompt(): String {         val stored = DataStoreUtils.getInstance(applicationContext).getStringAwait(KEY_SYSTEM_PROMPT)-        return if (stored.isNullOrBlank()) DEFAULT_SYSTEM_PROMPT else stored+        val base = if (stored.isNullOrBlank()) DEFAULT_SYSTEM_PROMPT else stored+        return base + "\n\n" + AssistantCatalog.PROMPT_SECTION     }      private suspend fun runInferenceLoop(@@ -429,7 +434,7 @@ class InferenceService : Service() {                 if (halt || job?.isActive == false) {                     false                 } else {-                    latest.set(text)+                    latest.set(splitA2ui(text).visible)                     true                 }             }@@ -447,7 +452,7 @@ class InferenceService : Service() {                 messageDao.deleteById(aiMsgId)                 Log.status("InferenceService", "Standard inference halted successfully.")             } else if (result.text.isNotBlank()) {-                updateMessageInDb(aiMsgId, result.text)+                storeReply(aiMsgId, result.text)             }             ChatResult.TooLong -> updateMessageInDb(                 aiMsgId,@@ -467,10 +472,17 @@ class InferenceService : Service() {     }      private suspend fun fetchHistoryFromDb(id: Long): List<DbMessage> = messageDao.getByConversation(id)++    /** Stores a finished reply: the prose as its text, any A2UI block beside it. */+    private suspend fun storeReply(id: Long, reply: String) {+        val split = splitA2ui(reply, streaming = false)+        val shown = if (split.visible.isBlank() && split.json == null) reply else split.visible+        updateMessageInDb(id, shown, split.json)+    }     private suspend fun upsertMessageToDb(msg: DbMessage): Long = messageDao.upsert(msg)-    private suspend fun updateMessageInDb(id: Long, text: String) {+    private suspend fun updateMessageInDb(id: Long, text: String, a2ui: String? = null) {         val existing = messageDao.getById(id) ?: return-        upsertMessageToDb(existing.copy(text = text))+        upsertMessageToDb(existing.copy(text = text, a2ui = a2ui))     }     private suspend fun updateTitleInDb(id: Long, title: String) {         val oldConversation = conversationDao.getById(id)
openassistant/src/test/java/com/vayunmathur/openassistant/domain/A2uiBlocksTest.kt
diff --git a/openassistant/src/test/java/com/vayunmathur/openassistant/domain/A2uiBlocksTest.kt b/openassistant/src/test/java/com/vayunmathur/openassistant/domain/A2uiBlocksTest.ktnew file mode 100644index 0000000000..6774877b48--- /dev/null+++ b/openassistant/src/test/java/com/vayunmathur/openassistant/domain/A2uiBlocksTest.kt@@ -0,0 +1,52 @@+package com.vayunmathur.openassistant.domain++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNull++class A2uiBlocksTest {++    private val block = "```a2ui\n{\"components\":[]}\n```"++    @Test+    fun splitsProseFromBlock() {+        val split = splitA2ui("Here you go:\n$block", streaming = false)+        assertEquals("Here you go:", split.visible)+        assertEquals("{\"components\":[]}", split.json)+    }++    @Test+    fun plainRepliesAndOtherFencesPassThrough() {+        assertEquals(A2uiSplit("Hello", null), splitA2ui("Hello"))+        val code = "```kotlin\nval x = 1\n```"+        assertEquals(A2uiSplit(code, null), splitA2ui(code, streaming = false))+    }++    @Test+    fun blockOnlyReplyHasNoVisibleText() {+        assertEquals(A2uiSplit("", "{\"components\":[]}"), splitA2ui(block, streaming = false))+    }++    @Test+    fun hidesUnclosedBlockAndPartialFenceWhileStreaming() {+        assertEquals(A2uiSplit("Sure", null), splitA2ui("Sure\n```a2ui\n{\"compo"))+        assertEquals("Sure", splitA2ui("Sure ```a2").visible)+        assertEquals("Sure ``", splitA2ui("Sure ``", streaming = false).visible)+        assertEquals("Run `ls` now", splitA2ui("Run `ls` now").visible)+    }++    @Test+    fun firstBlockWinsAndAllAreHidden() {+        val split = splitA2ui("a ```a2ui\n[1]\n``` b ```a2ui\n[2]\n``` c", streaming = false)+        assertEquals("a  b  c", split.visible)+        assertEquals("[1]", split.json)+    }++    @Test+    fun restoredBlockRoundTrips() {+        val restored = withA2uiBlock("Here you go:", "{\"components\":[]}")+        assertEquals(A2uiSplit("Here you go:", "{\"components\":[]}"), splitA2ui(restored, streaming = false))+        assertEquals("text", withA2uiBlock("text", null))+        assertNull(splitA2ui(withA2uiBlock("", null)).json)+    }+}
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.ktnew file mode 100644index 0000000000..9e5daba9c9--- /dev/null+++ b/openassistant/src/test/java/com/vayunmathur/openassistant/domain/A2uiEnvelopeTest.kt@@ -0,0 +1,75 @@+package com.vayunmathur.openassistant.domain++import androidx.a2ui.model.protocol.A2uiComponentPayload+import androidx.a2ui.model.protocol.A2uiCreateSurfaceMessage+import androidx.a2ui.model.protocol.A2uiUpdateComponentsMessage+import androidx.a2ui.model.protocol.A2uiUpdateDataModelMessage+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNull++class A2uiEnvelopeTest {++    @Test+    fun wrapsComponentsAndDataInAnEnvelope() {+        val json = """+            {"components":[+              {"id":"root","component":"Column","children":["t","f"]},+              {"id":"t","component":"Text","text":"Hi"},+              {"id":"f","component":"TextField","label":"Name","value":{"path":"/name"}}+            ],"data":{"name":"Ada","count":2,"ratio":0.5,"ok":true,"none":null}}+        """.trimIndent()++        val messages = buildA2uiEnvelope("m7", "cat", json)!!++        assertEquals(A2uiCreateSurfaceMessage("m7", "cat"), messages[0])+        assertEquals(+            A2uiUpdateComponentsMessage(+                "m7",+                listOf(+                    A2uiComponentPayload("root", "Column", mapOf("children" to listOf("t", "f"))),+                    A2uiComponentPayload("t", "Text", mapOf("text" to "Hi")),+                    A2uiComponentPayload("f", "TextField", mapOf("label" to "Name", "value" to mapOf("path" to "/name"))),+                ),+            ),+            messages[1],+        )+        assertEquals(+            A2uiUpdateDataModelMessage(+                "m7",+                "/",+                mapOf("name" to "Ada", "count" to 2L, "ratio" to 0.5, "ok" to true, "none" to null),+            ),+            messages[2],+        )+    }++    @Test+    fun acceptsBareComponentArrayAndSkipsBadEntries() {+        val messages = buildA2uiEnvelope("m1", "cat", """[{"id":"root","component":"Text","text":"x"},{"id":"bad"},3]""")!!+        assertEquals(2, messages.size)+        assertEquals(1, (messages[1] as A2uiUpdateComponentsMessage).components.size)+    }++    @Test+    fun rejectsUnusableBlocks() {+        assertNull(buildA2uiEnvelope("m1", "cat", "{not json"))+        assertNull(buildA2uiEnvelope("m1", "cat", """{"components":[]}"""))+        assertNull(buildA2uiEnvelope("m1", "cat", """{"data":{}}"""))+        assertNull(buildA2uiEnvelope("m1", "cat", "\"text\""))+    }++    @Test+    fun formatsActionTurns() {+        assertEquals("[UI action \"cancel\"]", actionTurnText("cancel", emptyMap()))+        assertEquals(+            "[UI action \"rsvp\": {\"name\":\"Ada\",\"veg\":true,\"guests\":[1,2]}]",+            actionTurnText("rsvp", linkedMapOf("name" to "Ada", "veg" to true, "guests" to listOf(1, 2))),+        )+    }++    @Test+    fun surfaceIdIsPerMessage() {+        assertEquals("m42", a2uiSurfaceId(42))+    }+}
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.ktnew file mode 100644index 0000000000..04595180e5--- /dev/null+++ b/openassistant/src/test/java/com/vayunmathur/openassistant/platform/AssistantCatalogTest.kt@@ -0,0 +1,122 @@+package com.vayunmathur.openassistant.platform++import androidx.a2ui.engine.model.A2uiCoreSurfaceModel+import androidx.a2ui.engine.processor.A2uiCoreMessageProcessor+import androidx.a2ui.model.protocol.A2uiClientErrorMessage+import androidx.a2ui.model.protocol.A2uiClientEventMessage+import androidx.a2ui.model.protocol.A2uiDataPath+import com.vayunmathur.openassistant.domain.A2UI_FENCE_OPEN+import com.vayunmathur.openassistant.domain.buildA2uiEnvelope+import com.vayunmathur.openassistant.domain.splitA2ui+import kotlinx.coroutines.CoroutineStart+import kotlinx.coroutines.async+import kotlinx.coroutines.delay+import kotlinx.coroutines.flow.filterIsInstance+import kotlinx.coroutines.flow.first+import kotlinx.coroutines.launch+import kotlinx.coroutines.runBlocking+import kotlinx.coroutines.withTimeout+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++class AssistantCatalogTest {++    private val catalog = AssistantCatalog({}, { pattern, _, _ -> pattern })++    private fun processor() = A2uiCoreMessageProcessor(listOf(catalog), ::ComposeDataModel, ::ComposeComponentRegistry)++    private suspend fun A2uiCoreMessageProcessor.awaitSurface(): A2uiCoreSurfaceModel =+        withTimeout(TIMEOUT) { activeSurfaces.first { it.isNotEmpty() }.single() as A2uiCoreSurfaceModel }++    private suspend fun ComposeComponentRegistry.awaitSettled(count: Int) =+        withTimeout(TIMEOUT) { while (components.size + errors.size < count) delay(5) }++    @Test+    fun promptExampleRendersWithoutErrors() = runBlocking {+        val processor = processor()+        val loop = launch { processor.collectMessages() }+        buildA2uiEnvelope("m1", AssistantCatalog.ID, AssistantCatalog.EXAMPLE)!!.forEach(processor::processMessage)++        val surface = processor.awaitSurface()+        val registry = surface.componentRegistry as ComposeComponentRegistry+        registry.awaitSettled(6)++        assertEquals(setOf("root", "c", "q", "n", "v", "b"), registry.components.keys)+        assertTrue(registry.errors.isEmpty(), "errors: ${registry.errors}")+        assertEquals(false, surface.dataModel[A2uiDataPath("/veg")])+        loop.cancel()+    }++    @Test+    fun invalidComponentsFailAloneAndReportErrors() = runBlocking {+        val processor = processor()+        val loop = launch { processor.collectMessages() }+        val firstError = async(start = CoroutineStart.UNDISPATCHED) {+            processor.outboundEvents.filterIsInstance<A2uiClientErrorMessage>().first()+        }+        val json = """{"components":[+            {"id":"root","component":"Column","children":["ok","bad","nolabel"]},+            {"id":"ok","component":"Text","text":"fine"},+            {"id":"bad","component":"Spinner"},+            {"id":"nolabel","component":"Button","action":{"event":{"name":"go"}}}+        ]}"""+        buildA2uiEnvelope("m2", AssistantCatalog.ID, json)!!.forEach(processor::processMessage)++        val registry = processor.awaitSurface().componentRegistry as ComposeComponentRegistry+        registry.awaitSettled(4)++        assertEquals(setOf("root", "ok"), registry.components.keys)+        assertEquals(setOf("bad", "nolabel"), registry.errors.keys)+        assertEquals("m2", withTimeout(TIMEOUT) { firstError.await() }.surfaceId)+        loop.cancel()+    }++    @Test+    fun buttonEventCarriesResolvedContext() = runBlocking {+        val processor = processor()+        val loop = launch { processor.collectMessages() }+        val event = async(start = CoroutineStart.UNDISPATCHED) {+            processor.outboundEvents.filterIsInstance<A2uiClientEventMessage>().first()+        }+        buildA2uiEnvelope("m3", AssistantCatalog.ID, AssistantCatalog.EXAMPLE)!!.forEach(processor::processMessage)+        val surface = processor.awaitSurface()+        (surface.componentRegistry as ComposeComponentRegistry).awaitSettled(6)++        surface.dataModel.update(A2uiDataPath("/name"), "Ada")+        @Suppress("UNCHECKED_CAST")+        val action = surface.componentRegistry.let { it as ComposeComponentRegistry }+            .components.getValue("b").properties["action"] as Map<String, Any?>+        surface.dispatchAction("b", action)++        val sent = withTimeout(TIMEOUT) { event.await() }+        assertEquals("rsvp", sent.type)+        assertEquals(mapOf("name" to "Ada", "veg" to false), sent.context)+        loop.cancel()+    }++    @Test+    fun promptListsEveryComponentAndItsExampleParses() {+        AssistantCatalog.COMPONENT_NAMES.forEach {+            assertTrue(AssistantCatalog.PROMPT_SECTION.contains("- $it: "), "prompt is missing $it")+        }+        val example = AssistantCatalog.PROMPT_SECTION.substringAfterLast(A2UI_FENCE_OPEN)+        assertEquals(AssistantCatalog.EXAMPLE, splitA2ui(A2UI_FENCE_OPEN + example, streaming = false).json)+    }++    @Test+    fun dataModelWritesCopyPathsAndDeleteOnNull() {+        val data = ComposeDataModel()+        data.update(A2uiDataPath("/a/b"), 1L)+        data.update(A2uiDataPath("/list"), listOf("x"))+        data.update(A2uiDataPath("/list/1"), "y")+        assertEquals(mapOf("a" to mapOf("b" to 1L), "list" to listOf("x", "y")), data[A2uiDataPath("/")])+        data.update(A2uiDataPath("/a/b"), null)+        assertEquals(emptyMap<String, Any?>(), data[A2uiDataPath("/a")])+        assertEquals(null, data[A2uiDataPath("/missing/deep")])+    }++    private companion object {+        const val TIMEOUT = 5_000L+    }+}