wrkm.app
Search
Mobile Development

‘A2UI on Android: From Chat Text to Real Screens with Jetpack Compose

‘A2UI on Android: From Chat Text to Real Screens with Jetpack Compose

Editor
Nov 30, 2026 · 19 min read
‘A2UI on Android: From Chat Text to Real Screens with Jetpack Compose

Vibecoded a sample A2UI project to learn how it works. The article mostly based on the Android Dev Summit video about A2UIGenerated by ChatGPTTry asking a chatbot for new sneakers. Most of the time you get one long paragraph back. It shows a few models with prices, then asks for your size, and you have to type something like “the white ones, size 42, two pairs”. The answer is not wrong, but the format is. A product should be a list of cards that you can swipe. A size should be a chip that you can tap. And at the end of a purchase, I expect a form and a button.A2UI is Google’s try to fix this. The agent does not send text. It sends a description of the UI as JSON, and your app draws it with its own components. For Android, the Jetpack Compose team made a renderer for it, and it is at version 1.0.0-alpha02 right now. Nick Butcher and Anton Beloglazov showed it at Android Dev Summit 2026.I wanted to understand how A2UI works, so I vibe coded a small app called A2UI Shop. It uses an agent that plays replies, and every reply is a file I can read and edit.Two ideas: catalog and surfaceThe agent never sends code. It sends JSON that names components and sets their properties. Here is part of the checkout form from the demo:{ "version": "v0.9", "updateComponents": { "surfaceId": "checkout", "components": [ { "id": "productName", "component": "Text", "variant": "h5", "text": { "path": "/order/name" } }, { "id": "quantity", "component": "QuantityStepper", "min": 1, "max": 5, "value": { "path": "/order/quantity" } } ] }}These two ideas are the core of the protocol.A catalog is the list of components and functions the agent is allowed to use. The app owns it. If the agent asks for something that is not in the catalog, the app will not render it. This works as a safety feature. The agent can only pick from things you already built.A surface is one piece of UI the agent controls, like a list of search results or a checkout form. The agent generates it, fills it with components, and can update or delete it later. One chat reply can contain multiple surfaces.The message set is small. The agent sends createSurface, updateComponents, updateDataModel and deleteSurface. The app sends back an action when the user does something, and an error when the agent sent something invalid. Components are sent as a flat list. They refer to their children by ID, and one of them must have the ID as a root.The demoA2UI Shop is a chat screen. You type a message or tap a suggestion. The agent answers with text and, most of the time, a surface. Each step of a small shopping trip shows one idea:“I need new sneakers for everyday wear” builds a row of product cards piece by piece, from a single template.“Anything under €100?” only changes the data. The list rebuilds its cards, and the UI is not sent again. Here, “rebuild” means the app updates the list that is already on the screen. It finds this list by its surface ID, so it does not generate a new one.Choose size, the button on a card, sends an action. The agent answers with a checkout form.“Actually, I need two pairs” changes one value inside the form.Place order stays disabled until the form is valid. Then the agent removes the form and shows a confirmation.“What size should I get?” makes the agent use a component the app doesn’t have, and then fix it.Sample response after user requests sneakers.[ { "text": "Here are four sneakers I'd look at. Swipe through them and tap one to choose a size." }, { "delayMs": 500 }, { "version": "v0.9", "createSurface": { "surfaceId": "sneaker-results", "catalogId": "https://example.com/a2ui/shop/v1/catalog.json" } }]The agent is a small FastAPI server. It sends each user message to Gemini and streams the reply back over HTTP, one JSON object per line.Wiring it upA2UI Demo ArchitectureStart with one dependency:implementation("androidx.compose.material3:material3-a2ui:1.0.0-alpha02")1. The catalogfun shopCatalog(context: Context): A2uiCatalog { val basicCatalog = materialA2uiBasicCatalogV1( // A2UI doesn't bundle an image loader, so you plug one in. image = MaterialA2uiBasicCatalogV1Defaults.image(CoilImageRenderer), video = MaterialA2uiBasicCatalogV1Defaults.video(NoMediaRenderer), audioPlayer = MaterialA2uiBasicCatalogV1Defaults.audioPlayer(NoMediaRenderer), // Client-side functions: formatString, formatCurrency, required, email, openUrl... functions = A2uiBasicCatalogV1.Functions(context), // Swap in our own button (more on this later). button = CheckoutButtonComponent, ) return A2uiCatalog( catalogId = SHOP_CATALOG_ID, components = basicCatalog.components + ProductCardComponent + QuantityStepperComponent, functions = basicCatalog.functions, )}The Basic Catalog gives the agent the usual building blocks: Text, Image, Row, Column, Card, List, Button, TextField, CheckBox, ChoicePicker and more. They are real Material 3 composables, so they follow your theme, dark mode, font scale and TalkBack with no extra work. The catalog ID is any unique URI. The agent puts it in createSurface to say which catalog it is building against.2. The processorThe processor parses messages, checks them against the catalog, and keeps the state of every surface. It lives in the ViewModel. Here is the short version:class ChatViewModel( catalog: A2uiCatalog, private val agent: Agent,) : ViewModel() { private val processor = A2uiMessageProcessor(catalogs = listOf(catalog)) private val parser = A2uiMessageParser() val surfaces: StateFlow<List> = processor.activeSurfaces init { // Applies queued messages off the main thread. viewModelScope.launch(Dispatchers.Default) { processor.collectMessages() } // Actions and errors from the UI, on their way back to the agent. viewModelScope.launch { processor.outboundEvents.collect { event -> sendToAgent(event.toJson()) } } } // Called for every A2UI line the agent streams. private fun onA2uiLine(line: String) { processor.processInput(parser, line) } companion object { val Factory: ViewModelProvider.Factory = viewModelFactory { initializer { val application = checkNotNull(this[APPLICATION_KEY]) ChatViewModel( catalog = shopCatalog(application), agent = BackendAgent(BuildConfig.AGENT_BASE_URL), ) } } }}Don’t skip the outboundEvents collector. Without it, button taps go nowhere and validation errors disappear without a trace.With every request, the app also sends the agent a list of surface IDs that are still on the screen. The model can’t know if the user closed a form or removed something. Without this list, it will happily update a UI that is not there anymore.// Each reply shows the surfaces it generated, under its chat text.surfaces.forEach { surface -> A2uiSurface( surfaceModel = surface, modifier = Modifier.fillMaxWidth().heightIn(max = 900.dp), )}The height limit matters. The search results inside A2uiSurface are a List, which is lazy, and a lazy list inside a scrolling chat needs a bounded height.What happens on screenProgressive renderingThe first reply is one line of chat text followed by A2UI messages, streamed while the model is still writing. After createSurface, the root Column comes first. It lists three child IDs (title, summary and results) that don't exist yet, so the renderer shows a shimmer effect. When the other messages arrive, the children appear one by one:1) Title2) List3) ProductsProgressive Rendering | Demo ApplicationThe agent doesn’t send four product cards. It sends one card and a list that repeats it. The list’s children is a template instead of an array of IDs:[ { "id": "results", "component": "List", "direction": "horizontal", "align": "start", "children": { "componentId": "product", "path": "/products" } }, { "id": "product", "component": "ProductCard", "productId": { "path": "id" }, "name": { "path": "name" }, "price": { "path": "price" }, "imageUrl": { "path": "imageUrl" }, "actionLabel": "Choose size", "action": { "event": { "name": "selectProduct" } } }]The list renders the product template once for each item in /products. The products come in a separate updateDataModel message. This is what happens when you ask “Anything under €100?”, the agent sends only data which is a new /summary and a new /products array with three items. The list rebuilds its cards from the same template, and no component is sent again.Tapping “Choose size” on a card gets you a checkout form. The agent first puts the order into the surface’s data model, a small JSON document that lives in the app:{ "version": "v0.9", "updateDataModel": { "surfaceId": "checkout", "path": "/order", "value": { "productId": "court-classic", "name": "Court Classic", "price": 69, "imageUrl": "https://images.unsplash.com/...", "size": [], "quantity": 1, "express": false, "email": "" } }}Every input in the form is bound to a path: the size chips to /order/size, the stepper to /order/quantity, the checkbox to /order/express and the text field to /order/email. When the user changes an input, it writes to the data model. The summary line under the form reads the same data:"text": { "call": "formatString", "returnType": "string", "args": { "value": "You're ordering ${/order/quantity} × ${/order/name}" } }Tap the plus button and the text “You’re ordering 2 × Court Classic” changes on the device. Nothing goes to the agent.The agent can also write to this data. When I say “Actually, I need two pairs”, it sends only one message:{ "version": "v0.9", "updateDataModel": { "surfaceId": "checkout", "path": "/order/quantity", "value": 2 } }The stepper and the summary line both change. Everything the user already typed stays, because the agent did not touch the form.Data Update | Demo ApplicationChecksThe Place order button has checks. Each check is a condition from a client-side function, with a message for when it fails:"checks": [ { "condition": { "call": "required", "args": { "value": { "path": "/order/size" } } }, "message": "Choose a size." }, { "condition": { "call": "email", "args": { "value": { "path": "/order/email" } } }, "message": "Enter a valid email address." }]The checks run on the device and update while the user types. The text field has the email check too, so it turns red with its own message. The button stays disabled and shows why, until all checks pass.Check Logic | Demo ApplicationActionsThe action of the button has a context. It is made of paths:"action": { "event": { "name": "placeOrder", "context": { "productId": { "path": "/order/productId" }, "name": { "path": "/order/name" }, "size": { "path": "/order/size" }, "quantity": { "path": "/order/quantity" }, "express": { "path": "/order/express" }, "email": { "path": "/order/email" } } } }The paths are resolved when the user taps. So the agent gets what the user entered, not the values it sent first. I picked size 42, ticked express delivery and typed an email. This is what came out of outboundEvents:{ "version": "v0.9", "action": { "name": "placeOrder", "surfaceId": "checkout", "sourceComponentId": "placeOrder", "timestamp": "2026-11-10T18:11:34.740Z", "context": { "productId": "court-classic", "name": "Court Classic", "size": ["42"], "quantity": 2, "express": true, "email": "sam@example.com" } } }Notice that size is a list. A ChoicePicker always saves an array, even if you can pick only one option.The agent answers with two things. First, a deleteSurface for the checkout form, so the same order can’t be sent twice. Then a new surface with the confirmation.User Action | Demo ApplicationIn the demo, the action goes back to the agent, but it doesn’t have to. An action is just data. You can send it to your own backend or use it to open a screen in the app. For a real order, do this: send it to your server and validate it like any other request. The name of the action and the shape of its context came from the agent, so don’t trust them.When the agent gets it wrongModels make things up, even component names. Suppose the size guide asks for a FootScanner3D. The processor checks it against the catalog and draws the rest of the card as usual. Only the broken component becomes an error placeholder, and this message goes out:{ "version": "v0.9", "error": { "code": "VALIDATION_FAILED", "surfaceId": "size-guide", "message": "Component type 'FootScanner3D' not found in catalog", "path": "/components/table" } }The app sends it to the agent like any other client message. For the model, it is just the next message in the chat. It can answer with an updateComponents that uses the same table ID, but now as a Column of Rows, which exist in the catalog. The renderer replaces it in place and the user sees a size table.Self Correction | Demo ApplicationYou need to add one thing yourself: a retry limit. A confused model can answer an error with another broken UI, again and again. My ViewModel stops sending errors automatically after two in a row and waits for the user.Making the catalog yoursThe Basic Catalog is fine for a demo, but your app will look like every other Material app. There are three ways to change this.Replace a basic componentThe agent still sends a normal Button, but the app draws its own checkout button. You implement the Button interface of the Basic Catalog. It already has the name and the schema, and gives you validated values:object CheckoutButtonComponent : A2uiBasicCatalogV1.Button { @Composable override fun A2uiComponentScope.TypedContent( childId: String, variant: A2uiBasicCatalogV1.Button.Variant, action: Map<String, Any?>, accessibility: A2uiBasicCatalogV1.AccessibilityAttributes?, checks: List<A2uiBasicCatalogV1.CheckRule>, modifier: Modifier, ) { CheckoutButton( onClick = { dispatchAction(action) }, style = when (variant) { A2uiBasicCatalogV1.Button.Variant.Primary -> CheckoutButtonStyle.Primary A2uiBasicCatalogV1.Button.Variant.Borderless -> CheckoutButtonStyle.Text else -> CheckoutButtonStyle.Outlined }, // The first failing check disables the button and explains why. errorMessage = checks.firstOrNull { !it.condition }?.message, modifier = modifier, ) { // The label is another component the agent chose, usually Text. val child = observeA2uiComponentState(childId) if (child is A2uiComponentState.Success) A2uiComponent(child.component) } }}Look at checks. They arrive already evaluated, so condition is a plain boolean. After you replace the button, showing the checks is your job. If you forget, the button can be tapped even when the form is invalid.Add a new componentThe quantity picker is not in the Basic Catalog. It is a small minus/plus stepper.object QuantityStepperComponent : A2uiComponent { override val name = "QuantityStepper" override val description = "A compact minus/plus stepper for choosing a small whole number, such as how many " + "items to order. Bind 'value' to a data model path so the user can change it." private val valueProperty = A2uiProperty.dynamicNumber( key = "value", required = true, description = "The current quantity.", ) private val minProperty = A2uiProperty.number( key = "min", defaultValue = 0, description = "Lowest value.", ) private val maxProperty = A2uiProperty.number( key = "max", defaultValue = 10, description = "Highest value.", ) override val properties = listOf(valueProperty, minProperty, maxProperty) @Composable override fun A2uiComponentScope.Content(properties: A2uiComponentProperties, modifier: Modifier) { val min = properties[minProperty]?.toInt() ?: 0 val max = properties[maxProperty]?.toInt() ?: 10 val value = properties.bind(valueProperty)?.toInt() ?: min // reads and subscribes val onValueChange = properties.bindUpdater(valueProperty) // writes back, or null QuantityStepper( value = value.coerceIn(min, max), range = min..max, onValueChange = onValueChange?.let { update -> { n: Int -> update(n) } }, modifier = modifier, ) }}bind() reads the current value and recomposes when the data model changes. bindUpdater() writes back to it. If the agent sends a plain number instead of a path, bindUpdater() returns null. So you get a read-only stepper without extra code.Add a domain componentProductCard goes one step further. With basic components, one card needs about ten of them: a Card, a Column, an Image, a few Texts, a Row and a Button. As one component, the agent sends only a few properties, and the design rules stay in my code, not in its JSON.object ProductCardComponent : A2uiComponent { override val name = "ProductCard" override val description = "A product tile with a photo, brand, name, price, rating and one button. Use it for " + "search results, usually inside a horizontal List with a template over the products." // Dynamic, so a template can bind them to each item: {"path": "name"}. private val nameProperty = A2uiProperty.dynamicString( key = "name", required = true, description = "Product name.", ) private val priceProperty = A2uiProperty.dynamicNumber( key = "price", required = true, description = "Price as a number.", ) // ...brand, imageUrl, rating, badge, actionLabel // An action, like a Button's. private val actionProperty = A2uiProperty.action( key = "action", required = true, description = "...", )}kThe property definitions do two jobs. At runtime, they take typed values from the JSON. They also create the JSON schema that the model reads, so name and description are really prompt text. This was more important than I expected, because the model knows your components only from what you write there.The model behind the agentThe server asks Gemini for every reply. The Android app doesn’t care what the model writes. It gets a stream of JSON lines and checks each of them against its catalog.The system prompt has four parts:The catalog of the app, as JSON Schema. I exported it once with catalog.toJsonSchemaString(). So the model sees the same contract that the app uses to validate, with ProductCard and QuantityStepper too.The surfaces and their rules. The most important rule: when results are already on the screen, change them with data only.The store inventory and some examples. The examples are full replies for each step of the shopping trip. I wrote them by hand as JSON files, so I got the few-shot examples for free.The model streams NDJSON, and the server sends each JSON object to the app as soon as it is complete. So progressive rendering works without extra code: the app draws the first part of the UI while the model is still writing the rest. The server also fixes some small mistakes of the model. It adds a missing “version”, changes whole-number prices to decimals and skips lines that are not valid JSON. The prompt has no image URLs. The model writes “image:court-classic” and the server replaces it with the real URL. This saves about 6,000 tokens in every request, and the model can’t write a wrong URL.Self-correction works too, and the agent needs no special code for it. When the app rejects a UI, the VALIDATION_FAILED error is just the next message in the conversation. The model fixes its own components in the next turn.The cheapest model was enough. With gemini-3.5-flash-lite and a low thinking level, the first UI appears in about two seconds. In a four-turn test (search, refine, select, compare), every reply passed the validation of the catalog. The system prompt is about 25,000 tokens, mostly the schema and the inventory, and Gemini caches it after the first request.Things that slowed developmentThe docs are behind the library. Some pages on developer.android.com still show the alpha01 setup with urlOpener, messageFormatter and localeProvider. In alpha02 they became one parameter: functions = A2uiBasicCatalogV1.Functions(context). If you are not sure, check the talk or the sources jar.Action context and templates don’t work together yet. A relative path like { “path”: “id” } in the context of an action is not resolved inside a template, and one unresolved value makes the whole context empty. ProductCard has a workaround: it already knows its product from bind, so it adds the ID, name, price and image of the product to the action context by itself.formatCurrency rejects whole numbers. A price of 69 arrives as an integer and fails, but 69.0 works. Models write whole numbers all the time, so the server converts the prices before they reach the app.A horizontal List stretches its items. The default alignment is stretch, so every card was as tall as the surface. “align”: “start” fixes it.weight inside a Column fills the surface. In a Row, weight splits the width as you expect. In a Column, it stretched a table with three rows to the full 900dp height limit. The model liked to add it, so the server removes it there.Surface IDs must be unique. I asked for sneakers twice, and the agent sent createSurface for sneaker-results again. The processor answered with a RUNTIME_ERROR: “Surface ‘sneaker-results’ already exists.” Models repeat IDs like this. Now my app deletes the old surface before it passes the new one on.Spacing needs a stretched parent. A Row with “justify”: “spaceBetween” did nothing until I gave its parent Column “align”: “stretch”. A Column aligns its children to the start by default, so each row was only as wide as its content.Android 17 blocks 10.0.2.2. With targetSdk 37, requests from the emulator to my laptop just timed out. Local network access now needs the ACCESS_LOCAL_NETWORK runtime permission. For a demo, it is easier to run adb reverse tcp:8000 tcp:8000 and call localhost.There is no serializer for outgoing messages. The library parses incoming JSON, but actions and errors come as Kotlin objects. I wrote about 30 lines with org.json to turn them back into protocol JSON.Should you use it?Not for production yet. It is an alpha, the API already changed between alpha01 and alpha02, and for several issues above I needed workarounds in my code.But it’s worth learning now if your app has an assistant feature, or will have one. It fits answers that people act on: finding a product, filtering results, filling a form, comparing a few options. It is not for replacing the screens you design yourself. Keep your navigation and main flows hand-built.What I like most is that the catalog works like a dial. If you give the agent only Text and Button, it can’t surprise you much. If you give it domain components, like a product card, it can do more with less JSON, because your design rules are inside those components.One warning: the demo in the talk calls Gemini directly from the app with an API key. This is fine on stage. In a real app, keep the model behind your own backend, like this demo does. A2UI doesn’t care where the JSON comes from, and the app never needs to know which model wrote it.If you want to try it, start like I did: write the JSON by hand first. When you know how a good reply looks, you know what to ask from the model, and your hand-written replies become its examples.Source code: the Android app and the backend are on GitHub: https://github.com/burkido/A2UIShopFurther readingLet agents generate native Compose UI in your Android apps with A2UI, Android Dev Summit 2026A2UI in Jetpack Compose, Android DevelopersImplement custom components, Android DevelopersA2UI protocol specification v0.9.1A2UI Compose release notes‘A2UI on Android: From Chat Text to Real Screens with Jetpack Compose was originally published in ProAndroidDev on Medium, where people are continuing the conversation by highlighting and responding to this story.

Kaynak: Burak Karaduman

#Android#Kotlin
Share

From other categories