AI
Mateu lets you embed an AI chat assistant directly into your application shell.
Once enabled, a floating IA button appears in the navigation bar. Clicking it opens a side panel with a streaming chat interface backed by a Server-Sent Events (SSE) endpoint of your choice.
Enabling the AI chat
Section titled “Enabling the AI chat”Add @AI to your root UI class and provide the SSE endpoint URL:
@UI("")@Title("My App")@AI(sse = "/api/ai/chat")public class MyApp {
@Menu Users users;
@Menu Reports reports;}That is all that is required on the Java side.
MCP tools and file uploads
Section titled “MCP tools and file uploads”@AI has these optional attributes beyond sse:
-
mcp— path (or absolute URL) of the app’s MCP endpoint. The chat forwards it with every message so the agent can operate this app through its tools. -
upload— path (or absolute URL) where the chat POSTs attached files (multipart). When set, the chat panel shows an attach button; each upload is saved server-side (its URL travels to the frontend asChatDto.uploadUrl) and the assistant reads it — your endpoint decides where it is stored and how the agent reaches it (e.g. through a filesystem MCP server). Empty (the default) = no file attachments. -
followingLabel/followLabel— the text of the chat’s Follow mode button while it is on / off. Empty (the default) = «Following» / «Follow» («Siguiendo» / «Seguir»), in the user’s language.
@UI("")@AI(sse = "/api/ai/chat", mcp = "/api/ai/mcp", upload = "/api/ai/upload")public class MyApp { ... }In YAML
Section titled “In YAML”A data-authored app shell (type: AppShell) declares the same settings in an ai: block — the data
twin of @AI, and it wins over an @AI on the shell’s class:
type: AppShelltitle: Bookingsai: sse: /api/ai/chat mcp: /api/ai/mcp upload: /api/ai/upload followingLabel: Siguiendo al copiloto # optional, Follow mode on followLabel: Seguir al copiloto # optional, Follow mode offmenu: - type: RouteLink label: Bookings route: bookingsHow it works
Section titled “How it works”- Mateu reads the
ssevalue from@AIat startup. - It propagates the URL through
AppDto.sseUrlto the frontend. - The app shell renders a
mateu-chatpanel in its content row, on the content’s start side: on a wide viewport it pushes the page aside (resizable, with a ⤢ wide mode), on a narrow one it covers the content area — never the header. - A chat toggle (the conversation icon) is added to the shell’s header widgets (or the sidebar, depending on the app variant — see below).
- Clicking it shows or hides the chat panel.
- The chat panel connects to the SSE endpoint and streams responses back to the user.
SSE endpoint contract
Section titled “SSE endpoint contract”mateu-chat sends a POST request to the SSE URL with a JSON body and streams back the response as Server-Sent Events.
Request
Section titled “Request”Headers
| Header | Description |
|---|---|
Authorization | Bearer <jwt> — present when the user is logged in |
X-Session-Id | Mateu session identifier |
Content-Type | application/json |
Accept | text/event-stream |
Authorization and X-Session-Id go only to an endpoint on an origin trusted with the user’s
credentials — the app’s own backend and the remotes its menu names. A chat endpoint (or upload
endpoint) on any other origin is called without them, on every renderer.
Body
{ "message": "Show me order ORD-42", "sessionId": "chat-session-nanoid", "menuContext": [ { "path": ["Orders", "List"], "navigation": { "route": "/orders", "consumedRoute": "", "actionId": "", "baseUrl": "/_orders", "serverSideType": "com.example.OrderHome", "uriPrefix": "" } }, { "path": ["Customers"], "navigation": { "route": "/customers", "consumedRoute": "", "actionId": "", "baseUrl": "/_customers", "serverSideType": "com.example.CustomerHome", "uriPrefix": "" } } ]}Every message also carries what the user is LOOKING AT, so the agent grounds its answers and actions on it — if the user is already on the relevant screen, it acts there instead of navigating away.
| Field | When | What |
|---|---|---|
message | always | The user’s text input. |
sessionId | always | A stable, unguessable per-panel id, useful for conversational memory, uploads or logging. |
currentRoute | always | The route of the screen the question is asked from (an agent gateway can route by it). |
context | always | A snapshot supplied by the shell: current url and screen title, appState, appData, and the active component’s state and data. |
screen | when there is one | A self-describing projection of the current screen — title, fields (id, label, dataType, value) and actions (id, label) — the same shape an MCP agent gets, so the assistant fills and runs precisely instead of guessing from raw state. |
mcpUrl | when @AI(mcp=…) is set | The app’s MCP endpoint, as an absolute url, so the agent can operate THIS app. |
attachments | when files were attached | [{"name", "path"}] as returned by the @AI(upload=…) endpoint. |
menuContext | first message only | The application menu flattened into navigable screens: breadcrumb path (e.g. ["Bookings", "List"]), optional description, and the exact navigation payload that opens it. Cache it against sessionId if you need it later in the conversation. |
A relative sse, mcp or upload url is resolved against the app’s own backend by every
renderer (the browser against the page’s origin; the native renderers against the backend they
are connected to).
Response
Section titled “Response”The response is a stream of Server-Sent Events, read as SSE: an event ends at a blank line, its data: lines are joined with a newline, only the single optional space after data: is dropped (indentation survives), and comment lines (: keep-alive) are ignored. Plain-text events are line-oriented: each one is one line of the reply, and the lines are joined with newlines, so markdown structure (headings, lists, code fences, tables) survives. To stream token by token, use agent-delta events instead (below).
Each event’s data is interpreted, in order of precedence, as:
-
Token usage — a JSON object with any of
inputTokens,outputTokens,totalTokens. It is not shown as text; the values are merged into the token bar under the message list:data: {"inputTokens": 1200, "outputTokens": 340, "totalTokens": 1540} -
UI event — a JSON object with a string
eventfield (detailis optional and defaults to{}). It is consumed silently and dispatched as a DOMCustomEvent— except the reservedagent-errorevent, whosedetail.messageis rendered as a warning in the reply bubble instead:data: {"event": "navigation-requested", "detail": { ... }}data: {"event": "agent-error", "detail": {"message": "The agent timed out."}} -
Text — anything else is one line of the agent’s markdown reply, appended to the current bubble. After
agent-deltaevents, the next text event is instead the whole, final reply and replaces what was streamed (so the server can send the answer cleaned up — without markers, after a guardrail — once it is complete).
Streaming and progress (optional)
Section titled “Streaming and progress (optional)”An agent that wants the user to see the answer as it is written, and what it is doing until then, sends these reserved events. All are optional, and a client that predates them just dispatches them as DOM events and ignores them.
| Event | detail | What the chat does |
|---|---|---|
agent-delta | {"text": "…"} | Appends a piece of the reply (any size, newlines included — it is JSON, so a piece is never cut at a line). |
agent-status | {"phase": "resolving | guardrails | connecting | thinking", "text": "…"} | Shows text in the progress line under the conversation, with the seconds spent in that phase. |
agent-tool | {"name", "server", "kind", "phase": "start | end", "ms", "error"} | While a tool runs, the progress line reads «Llamando a name… N s»; the turn’s tool calls are listed under the reply, with their duration or error. |
data: {"event":"agent-status","detail":{"phase":"thinking","text":"Pensando…"}}
data: {"event":"agent-tool","detail":{"name":"booking_findBookings","server":"booking","kind":"mcp","phase":"start"}}
data: {"event":"agent-tool","detail":{"name":"booking_findBookings","server":"booking","kind":"mcp","phase":"end","ms":1510}}
data: {"event":"agent-delta","detail":{"text":"Tienes 3 "}}
data: {"event":"agent-delta","detail":{"text":"reservas."}}
data: {"inputTokens":250,"outputTokens":30,"totalTokens":280}
data: Tienes 3 reservas.Usage objects whose counters are all zero are ignored (older agents sent them as placeholders while working). The token bar shows the last usage received; it is not summed across replies.
There is no end-of-stream sentinel (no [DONE]): the reply is finished when the server closes the stream. If the stream closes without any text, the chat shows a warning suggesting the LLM is not configured.
Follow mode
Section titled “Follow mode”The robot button in the chat header is Follow mode. It is on by default: it reads Following (Siguiendo in Spanish), filled with the primary colour, while the view follows the assistant; turned off it reads Follow (Seguir), outlined:
- On (the default): a
navigation-requestedorrender-screenthe agent streams is applied as it arrives — the content moves to the screen the agent opened. - Off: the user stays where they are. Those two events are held back on the reply as buttons
(«Open /bookings», «Show the generated screen») and applied only when the user clicks them, with the
same checks as if they had arrived live. Events that do not move the view (a page’s own
@SubscribeToevents,close-requested) keep applying.
The choice is remembered per browser (localStorage key mateu-chat-follow). Your endpoint does not
need to know about it: it streams the same events either way. It applies to the chat’s stream; the
live UI push channel (MCP “drive a live UI”) is not affected.
The button’s texts are the app’s to choose, one per state:
| On | Off | |
|---|---|---|
| Java | @AI(followingLabel = "…") | @AI(followLabel = "…") |
YAML (type: AppShell) | ai.followingLabel | ai.followLabel |
| C# | [AI("…", FollowingLabel = "…")] | [AI("…", FollowLabel = "…")] |
| Python | @ai("…", following_label="…") | @ai("…", follow_label="…") |
They travel as AppDto.followingLabel / AppDto.followLabel; a blank one keeps the renderer’s own,
in the user’s language.
Mateu also forwards the current JWT and session-id as request headers so your endpoint can authenticate and personalise responses.
Message rendering: markdown, images, and inline SVG
Section titled “Message rendering: markdown, images, and inline SVG”Agent replies render as markdown (via mateu-markdown: marked + DOMPurify). Sanitization uses the html + svg profiles, so replies may safely embed:
- Images, including
data:URIs — e.g. a chart generated server-side and inlined as. - Inline
<svg>— e.g. a diagram of the user’s model rendered by a tool and pasted straight into the reply.
The chat bubble sizes both to its width (max-width: 100%, height auto), so diagrams and images fit the panel without horizontal scrolling. Custom elements also pass sanitization, so a reply can even instantiate web components available in the host page.
Supported app variants
Section titled “Supported app variants”The chat panel is drawn by every navigating shell variant of the web renderer; where its toggle sits depends on the variant:
| Variant | Chat toggle |
|---|---|
MENU_ON_TOP, HAMBURGER_MENU, HAMBURGER_SECTIONS, TILES, TABS | In the header’s widget zone (end side), before the app’s own widgets |
MENU_ON_LEFT | At the bottom of the left sidebar |
RAIL, and a chromeless app | No toggle: open it from the command center’s “Ask AI” row |
The embedded MEDIATOR shell (a CRUD nested in a page) draws no chat of its own.
Example: Spring AI SSE endpoint
Section titled “Example: Spring AI SSE endpoint”record ChatRequest( String message, String sessionId, String currentRoute, Map<String, Object> context, Map<String, Object> screen, // may be null String mcpUrl, // may be null List<Attachment> attachments, // may be null List<MenuContextEntry> menuContext // first message only) {}
record Attachment(String name, String path) {}
record MenuContextEntry(List<String> path, Map<String, Object> navigation) {}
@RestController@RequestMapping("/api/ai")public class AiChatController {
private final ChatClient chatClient;
public AiChatController(ChatClient chatClient) { this.chatClient = chatClient; }
@PostMapping(value = "/chat", produces = MediaType.TEXT_EVENT_STREAM_VALUE) public Flux<String> chat(@RequestBody ChatRequest req) { // Build a system prompt that describes the available screens // menuContext only travels with the first message of a session String menuDescription = Optional.ofNullable(req.menuContext()).orElse(List.of()).stream() .map(e -> "- " + String.join(" > ", e.path()) + " → " + e.navigation()) .collect(Collectors.joining("\n"));
String systemPrompt = """ You are an assistant for this application. The following screens are available (path → navigation payload): %s
When the user asks to open a screen, emit a navigation event at the END of your response: data: {"event": "navigation-requested", "detail": <navigation payload>} Only emit one event. Never show the raw JSON to the user. """.formatted(menuDescription);
// The contract is line-oriented: each SSE data event must be ONE line // of the reply, so buffer the token stream and emit complete lines. return chatClient.prompt() .system(systemPrompt) .user(req.message()) .stream() .content() .bufferUntil(token -> token.contains("\n")) .map(tokens -> String.join("", tokens).stripTrailing()); }}LLM-driven UI interactions
Section titled “LLM-driven UI interactions”The AI assistant is not limited to returning text.
It can also trigger UI actions — navigation, form updates, or any custom behaviour — by emitting a special JSON event inside the SSE stream.
Event format
Section titled “Event format”Any data: line whose payload is a JSON object with an event field is treated as a UI event instead of chat text:
data: {"event": "<event-name>", "detail": { ... }}mateu-chat will:
- Parse the JSON.
- Dispatch
new CustomEvent(event, { detail, bubbles: true, composed: true }). - Not display the JSON in the chat message — it is consumed silently.
Text tokens and UI events can be freely mixed in the same stream.
Built-in event: navigation-requested
Section titled “Built-in event: navigation-requested”Mateu’s app shell listens for navigation-requested and routes the user to the specified view.
Payload fields:
| Field | Type | Description |
|---|---|---|
route | string | Target route (e.g. /orders/123) |
consumedRoute | string | Route consumed by the app shell (usually "") |
actionId | string | Action to trigger on arrival (e.g. "view") |
baseUrl | string | Base URL of the target micro-frontend |
serverSideType | string | Fully-qualified Java class of the target UI |
uriPrefix | string | URI prefix (usually "") |
Example — navigate to a specific order:
data: {"event": "navigation-requested", "detail": {"route": "/orders/ORD-42", "consumedRoute": "", "actionId": "view", "baseUrl": "/_orders", "serverSideType": "com.example.OrderHome", "uriPrefix": ""}}Built-in event: close-requested
Section titled “Built-in event: close-requested”Closes the chat panel (no detail). A Chat component placed on a page has nothing to close into,
so it shows no close button and ignores the event.
Built-in event: render-screen
Section titled “Built-in event: render-screen”The agent can author a screen and have it shown. detail:
| Field | Type | Description |
|---|---|---|
yaml | string | The screen, as a YAML definition (the same component catalogue as specs/ui/**; uidl-schema.json describes it). |
uidl | object or string | The same, as a JSON component tree — an alternative to yaml (yaml wins when both are sent). |
target | string | content (default), drawer or dialog. |
title | string | The drawer’s or dialog’s header. |
data: {"event": "render-screen", "detail": {"yaml": "type: VerticalLayout\ncontent:\n - type: Text\n text: Check-in for Nora Duarte\n", "target": "drawer", "title": "Check-in"}}It is handled the moment it arrives — the reply can go on streaming under it — in one of two ways:
- A page subscribes to it. A view on screen annotated
@SubscribeTo(event = "render-screen", action = "…")takes it: its action runs with thedetailas parameters (readyamlfromhttpRequest.runActionRq().parameters()), and it renders the screen however it likes — inside its own layout, next to other content. - Nobody subscribes: the shell renders it. The built-in render target posts the definition to
the backend’s reserved
__preview__action (the one the visual editor uses), which turns it into a normal UI increment through the real mapper, and shows it in the content area, or in a drawer or a dialog over the current page. In the content area it is transient: any navigation — the same menu entry included — brings the route’s own screen back; and, like a navigation, it first asks before discarding unsaved changes of the screen it replaces (a drawer or dialog replaces nothing). An invalid definition shows the preview’s own “Invalid or empty YAML” notice. A static bundle has no backend: there, auidl(JSON) screen is expanded in the browser and a YAML one shows why it cannot be.
__preview__ renders only what it is given: no view model is created or bound, so it shows the user
nothing of the application they could not already see. It still goes through the route guard (a
route whose access: refuses the caller answers 403) and the wire-type policy, and the wire-only
component types (a ServerSideComponent naming a class) are not authorable, so a definition cannot
smuggle in an island bound to a view model. Whatever the rendered screen does afterwards — its
buttons, its REST sources — goes through the same checks as any other request.
An agent’s screen is untrusted, and runs no code. An LLM can be steered by the data it reads
(prompt injection), so pairing an agent grants “drive my UI” — navigate, fill, click, which the user
could do anyway — never “run code in my signed-in tab”. Every shell renders an agent’s screen
(render-screen from the chat or from a live push) through __preview__ with _untrusted: true,
and the backend — Java, .NET and Python alike — takes out of it everything that could run script:
- an
Elementkeeps no event-handler attribute (on…), nosrcdoc, noimportmodule and no unsafe URL attribute (only relative,http(s):,mailto:andtel:links); its content is shown as text (html: false); an element that loads or runs code (script,iframe,object,embed,style,base,link,meta,template, …) or a framework element (mateu-*) becomes an emptydiv. Itson:events still run the screen’s own actions, like a button; RunJSrules, an action’sjsandAddContentToHead/AddContentToBodycommands are dropped;- a
javascript:/vbscript:URL anywhere is blanked; - a
MicroFrontenddoes not load from another server (an absolutebaseUrlis dropped).
Everything else renders as authored. The web renderers (Vaadin and Redwood) apply the same rules
again in the browser — a static bundle expands a JSON screen locally, and an older backend ignores
the flag. The rules are pinned by one set of cases, conformance/untrusted/cases.json, run by every
implementation. The visual editor’s preview — your own YAML — does not send the flag and renders as
written.
The event catalogue
Section titled “The event catalogue”Every renderer reads the stream the same way and handles the same events:
| Event | Vaadin (web) | Redwood (VB) | React Native | IntelliJ |
|---|---|---|---|---|
text / agent-delta | Markdown answer, streamed | Markdown answer, streamed | Markdown answer, streamed | Markdown answer, streamed |
agent-status / agent-tool | Progress line + the turn’s tool steps | Progress line + tool steps | Progress line | Progress line |
| usage | Token bar (last usage) | Token bar | Token line | Token line |
agent-error | Warning in the reply | Warning in the reply | Warning in the reply | Warning in the reply |
navigation-requested | Like a menu click with all the fields; outside an app shell, route resolution | Like a menu click with all the fields (baseUrl/uriPrefix register a remote) | Like a menu click (route, consumedRoute, serverSideType, baseUrl — another backend gets its own session, which carries the user’s credentials only when the app’s menu names that backend; an actionId with no route runs as an app action) | Like a menu click (one backend per session, so baseUrl/uriPrefix are not used) |
close-requested | Closes the panel (ignored by a Chat on a page) | Closes the panel | Closes the panel | Closes the dialog / hides the inline panel |
render-screen | Subscriber first, else content / drawer / dialog | Subscriber first, else content / drawer / dialog | Subscriber first, else content / sheet | Subscriber first, else a transient Preview tab / side window / dialog |
| anything else — only an event a view on screen subscribes to | A DOM CustomEvent (bubbling, composed) for the @SubscribeTo views — page scripts hear it too | A DOM CustomEvent + the @SubscribeTo views on screen | The session event bus (@SubscribeTo views) | The session event bus (@SubscribeTo views) |
An agent cannot fire just any event at the app. Besides the three built-in ones, an event goes out
only while a view on screen declares it (@SubscribeTo(event = …)), and never when it is one of
the framework’s own event names (server-side-action-requested, route-changed,
page-banners-received, dirty, mateu-…, DOM events…) — whatever a view declares. Anything else
is dropped. The lists are pinned by conformance/client/agent-events.json.
Links in an answer to a screen of the app ([Nora Duarte](/booking/bookings/4MBZS7)) open it in the
app through the menu entry that serves it, on every renderer. Attachments are offered wherever an
upload endpoint is declared (React Native: images, through the photo picker).
The same events can also come from outside the chat: an MCP agent paired with the tab sends
them through the app’s live UI push channel (mateu_push_ui, mateu_navigate,
mateu_dispatch_event), and every renderer applies them with the code above. See
Agent operability → Drive a live UI.
Custom events
Section titled “Custom events”You can define your own events and handle them anywhere in your component tree.
Backend — emit the event mid-stream:
// Inside your SSE Flux, emit this frame after the answer tokens:String frame = "data: " + objectMapper.writeValueAsString(Map.of( "event", "highlight-row", "detail", Map.of("id", orderId))) + "\n\n";Frontend — listen for it in a custom web component or page:
document.addEventListener('highlight-row', (e) => { highlightRow(e.detail.id);});System prompt guidance
Section titled “System prompt guidance”To make the LLM emit these events reliably, describe the contract in the system prompt:
You are an assistant for the Orders application.
When the user asks to open or view a specific record, emit a navigation eventat the END of your response, after any explanatory text:
data: {"event": "navigation-requested", "detail": {"route": "/orders/<id>", "consumedRoute": "", "actionId": "view", "baseUrl": "/_orders", "serverSideType": "com.example.OrderHome", "uriPrefix": ""}}
Only emit one event per response. Never show the raw JSON to the user.Summary
Section titled “Summary”- Annotate your root UI class with
@AI(sse = "<url>"). - Implement an SSE endpoint at that URL (Mateu ships the chat panel and its contract, not the agent).
- Mateu handles the rest: button, panel, streaming UI.
- Stream the reply line by line, or token by token with
agent-deltaevents (andagent-status/agent-toolto show progress); replies render as markdown and may embed images (data:URIs included) and inline SVG. - Emit
{"event": "...", "detail": {...}}in the stream to trigger UI actions from the LLM; emit token-usage JSON to feed the token bar.
Related: the command center (@App(commandCenter=true)) adds an always-present palette that unifies navigation, global search and an AI hand-off — an AI-adjacent entry point alongside the IA button.