Skip to content

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.

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.

@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 as ChatDto.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 { ... }

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:

specs/ui/app.yaml
type: AppShell
title: Bookings
ai:
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 off
menu:
- type: RouteLink
label: Bookings
route: bookings
  1. Mateu reads the sse value from @AI at startup.
  2. It propagates the URL through AppDto.sseUrl to the frontend.
  3. The app shell renders a mateu-chat panel 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.
  4. A chat toggle (the conversation icon) is added to the shell’s header widgets (or the sidebar, depending on the app variant — see below).
  5. Clicking it shows or hides the chat panel.
  6. The chat panel connects to the SSE endpoint and streams responses back to the user.

mateu-chat sends a POST request to the SSE URL with a JSON body and streams back the response as Server-Sent Events.

Headers

HeaderDescription
AuthorizationBearer <jwt> — present when the user is logged in
X-Session-IdMateu session identifier
Content-Typeapplication/json
Accepttext/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.

FieldWhenWhat
messagealwaysThe user’s text input.
sessionIdalwaysA stable, unguessable per-panel id, useful for conversational memory, uploads or logging.
currentRoutealwaysThe route of the screen the question is asked from (an agent gateway can route by it).
contextalwaysA snapshot supplied by the shell: current url and screen title, appState, appData, and the active component’s state and data.
screenwhen there is oneA 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.
mcpUrlwhen @AI(mcp=…) is setThe app’s MCP endpoint, as an absolute url, so the agent can operate THIS app.
attachmentswhen files were attached[{"name", "path"}] as returned by the @AI(upload=…) endpoint.
menuContextfirst message onlyThe 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).

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:

  1. 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}
  2. UI event — a JSON object with a string event field (detail is optional and defaults to {}). It is consumed silently and dispatched as a DOM CustomEvent — except the reserved agent-error event, whose detail.message is rendered as a warning in the reply bubble instead:

    data: {"event": "navigation-requested", "detail": { ... }}
    data: {"event": "agent-error", "detail": {"message": "The agent timed out."}}
  3. Text — anything else is one line of the agent’s markdown reply, appended to the current bubble. After agent-delta events, 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).

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.

EventdetailWhat 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.

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-requested or render-screen the 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 @SubscribeTo events, 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:

OnOff
Java@AI(followingLabel = "…")@AI(followLabel = "…")
YAML (type: AppShell)ai.followingLabelai.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 ![sales](data:image/png;base64,...).
  • 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.

The chat panel is drawn by every navigating shell variant of the web renderer; where its toggle sits depends on the variant:

VariantChat toggle
MENU_ON_TOP, HAMBURGER_MENU, HAMBURGER_SECTIONS, TILES, TABSIn the header’s widget zone (end side), before the app’s own widgets
MENU_ON_LEFTAt the bottom of the left sidebar
RAIL, and a chromeless appNo 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.

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());
}
}

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.

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:

  1. Parse the JSON.
  2. Dispatch new CustomEvent(event, { detail, bubbles: true, composed: true }).
  3. 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.

Mateu’s app shell listens for navigation-requested and routes the user to the specified view.

Payload fields:

FieldTypeDescription
routestringTarget route (e.g. /orders/123)
consumedRoutestringRoute consumed by the app shell (usually "")
actionIdstringAction to trigger on arrival (e.g. "view")
baseUrlstringBase URL of the target micro-frontend
serverSideTypestringFully-qualified Java class of the target UI
uriPrefixstringURI 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": ""}}

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.

The agent can author a screen and have it shown. detail:

FieldTypeDescription
yamlstringThe screen, as a YAML definition (the same component catalogue as specs/ui/**; uidl-schema.json describes it).
uidlobject or stringThe same, as a JSON component tree — an alternative to yaml (yaml wins when both are sent).
targetstringcontent (default), drawer or dialog.
titlestringThe 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:

  1. A page subscribes to it. A view on screen annotated @SubscribeTo(event = "render-screen", action = "…") takes it: its action runs with the detail as parameters (read yaml from httpRequest.runActionRq().parameters()), and it renders the screen however it likes — inside its own layout, next to other content.
  2. 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, a uidl (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 Element keeps no event-handler attribute (on…), no srcdoc, no import module and no unsafe URL attribute (only relative, http(s):, mailto: and tel: 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 empty div. Its on: events still run the screen’s own actions, like a button;
  • RunJS rules, an action’s js and AddContentToHead / AddContentToBody commands are dropped;
  • a javascript: / vbscript: URL anywhere is blanked;
  • a MicroFrontend does not load from another server (an absolute baseUrl is 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.

Every renderer reads the stream the same way and handles the same events:

EventVaadin (web)Redwood (VB)React NativeIntelliJ
text / agent-deltaMarkdown answer, streamedMarkdown answer, streamedMarkdown answer, streamedMarkdown answer, streamed
agent-status / agent-toolProgress line + the turn’s tool stepsProgress line + tool stepsProgress lineProgress line
usageToken bar (last usage)Token barToken lineToken line
agent-errorWarning in the replyWarning in the replyWarning in the replyWarning in the reply
navigation-requestedLike a menu click with all the fields; outside an app shell, route resolutionLike 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-requestedCloses the panel (ignored by a Chat on a page)Closes the panelCloses the panelCloses the dialog / hides the inline panel
render-screenSubscriber first, else content / drawer / dialogSubscriber first, else content / drawer / dialogSubscriber first, else content / sheetSubscriber first, else a transient Preview tab / side window / dialog
anything else — only an event a view on screen subscribes toA DOM CustomEvent (bubbling, composed) for the @SubscribeTo views — page scripts hear it tooA DOM CustomEvent + the @SubscribeTo views on screenThe 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.

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);
});

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 event
at 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.
  • 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-delta events (and agent-status / agent-tool to 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.