This is the abridged developer documentation for aparté # Articles > Dated pieces on what changes around agents and their chat interfaces, each with its sources and the code that checks it. Dated pieces on what changes around agents and the chats in front of them, and what it means for a page that hosts one. Each article names its sources, and the code it shows is tested, in this repository or in the package’s own. * **[aparté 1.0: what the number promises, and where the library goes next](/articles/aparte-1-0/)**, November 8, 2026. What the version commits to, what the beta taught, and what comes next, from sub-agents and a canvas to a chat that does not need our design system. * **[n8n’s chat widget: what people run into, and a replacement that takes the same call](/articles/n8n-chat-widget/)**, October 27, 2026. The problems n8n users report most with `@n8n/chat`, with their sources, what n8n 3.0 changes for a chat widget, and `@aparte/n8n-chat`, a `createChat` that takes the same options, tested against a live n8n. * **[Agent Builder shuts down on November 30: stop tying your chat UI to a vendor](/articles/agent-builder-shutdown/)**, October 26, 2026. What stops when OpenAI closes Agent Builder, the migration path, and how an open protocol between the agent and the chat makes the next shutdown cheaper. With a demo that runs without a key. # Agent Builder shuts down on November 30: stop tying your chat UI to a vendor > OpenAI's Agent Builder closes on November 30, 2026. What stops, what the migration path is, and how to put an open protocol between your agent and its chat so the next shutdown costs less — with a tested demo. *Published October 26, 2026.* On November 30, 2026, OpenAI shuts down Agent Builder, the visual editor that ran agent workflows on OpenAI’s servers. It was released in late 2025 and deprecated on June 3, 2026. If your chat talks to an Agent Builder workflow, it stops working that day. This page covers what stops, the way out OpenAI documents, and one choice that would have made this shutdown cheaper: an open protocol between the chat and the agent. ## What stops, and what stays [Section titled “What stops, and what stays”](#what-stops-and-what-stays) | Date | What happens | | ----------------- | ------------------------------------------------------------------- | | June 3, 2026 | OpenAI notifies Agent Builder users that the product is deprecated. | | November 30, 2026 | Agent Builder is scheduled to shut down. | Source: OpenAI’s [deprecations page](https://developers.openai.com/api/docs/deprecations). **ChatKit stays.** ChatKit is OpenAI’s chat component, and its recommended setup pointed it at an Agent Builder workflow. What goes is that backend: a ChatKit embed connected to an Agent Builder workflow works only “during the Agent Builder transition window”, in the words of the [ChatKit guide](https://developers.openai.com/api/docs/guides/chatkit). After that, ChatKit needs a server you run, through its “custom server integration” and the ChatKit Python SDK. **The migration path is an export to code.** In Agent Builder, **Code → Agents SDK** exports the workflow as TypeScript or Python for the [OpenAI Agents SDK](https://openai.github.io/openai-agents-js/). You run that code yourself, or paste it into a ChatGPT Workspace Agent, which needs a Business, Enterprise or Edu plan. OpenAI’s [migration guide](https://developers.openai.com/api/docs/guides/agent-builder/migrate-from-agent-builder) is candid about the limits: the export “does not convert your workflow graph or guarantee that every behavior transfers unchanged”. ## What it cost the people who built on it [Section titled “What it cost the people who built on it”](#what-it-cost-the-people-who-built-on-it) The [deprecation thread](https://community.openai.com/t/1382650) on OpenAI’s forum, from June 2026, shows what the export leaves you to do: * One developer who built ChatKit apps for several clients on Agent Builder wrote that managing the backend themselves “makes the use of this tool economically unviable”. * Several rebuilt the backend on servers of their own, such as a FastAPI server deployed on IBM or a container on AWS Lambda. The thread then turns to cold starts: one developer had cut theirs “from 30 seconds to just under 20. Still way too long.”, and moved to Lambda, where another had measured about three seconds. * “Agent Builder was much easier. I am already missing it.” None of this is about the chat. The chat was fine. It stopped working because it was wired to a product’s backend: a workflow ID, exchanged by your server for a client secret, opening a session on OpenAI’s hosted workflow. The interface and the backend were one product, so when the backend went, the integration went with it. ## Put a protocol between the chat and the agent [Section titled “Put a protocol between the chat and the agent”](#put-a-protocol-between-the-chat-and-the-agent) The lesson is not “avoid OpenAI”. The Agents SDK code you export is a good place to be. The lesson is about the line between the chat and the agent: make it a **protocol that both sides can implement independently**, not a product’s session API. Then you can change either side without touching the other: move the agent to another host, another framework or another model, or move the chat to another library. [AG-UI](https://docs.ag-ui.com) is such a protocol. It is an open, MIT-licensed event stream for agent UIs: text as it is written, tool calls with their arguments and results, state, and interrupts for human approval. Agno, LangGraph, Mastra, CrewAI, Pydantic AI and Google’s ADK serve their agents over it, and TanStack AI is [compliant in both directions](https://tanstack.com/blog/ag-ui-compliance). AG-UI lists the OpenAI Agents SDK integration as “in progress” ([AG-UI README](https://github.com/ag-ui-protocol/ag-ui)), so today it takes about eighty lines of glue. Here they are. ### 1. The agent, as Agent Builder exports it [Section titled “1. The agent, as Agent Builder exports it”](#1-the-agent-as-agent-builder-exports-it) ```ts import { Agent, tool } from '@openai/agents'; export const getOrderStatus = tool({ name: 'get_order_status', description: 'Look up where an order is, by its number.', parameters: { type: 'object', properties: { orderNumber: { type: 'string' } }, required: ['orderNumber'], additionalProperties: false, }, strict: true, async execute(input) { const { orderNumber } = input as { orderNumber: string }; return { orderNumber, status: 'shipped', carrier: 'La Poste', arrives: 'in 2 days' }; }, }); export const supportAgent = new Agent({ name: 'Support', instructions: 'You answer questions about orders. Look an order up before saying where it is.', tools: [getOrderStatus], }); ``` This file never mentions the chat. That is the point. ### 2. The bridge: the agent’s run, as AG-UI events [Section titled “2. The bridge: the agent’s run, as AG-UI events”](#2-the-bridge-the-agents-run-as-ag-ui-events) The Agents SDK streams its run as events: the model’s text deltas, then each tool call and its output. The bridge reads them and writes AG-UI events as server-sent events. It is a Web `Request` in and a Web `Response` out, so it drops into a Next.js route, Hono, Deno, Bun or a Worker as it is. This is the core of it: ```ts send({ type: EventType.RUN_STARTED, threadId, runId }); const result = await runner.run(agent, toAgentInput(messages), { stream: true, signal: request.signal }); for await (const event of result) { if (event.type === 'raw_model_stream_event' && event.data.type === 'output_text_delta') { // first word: TEXT_MESSAGE_START, then one TEXT_MESSAGE_CONTENT per delta send({ type: EventType.TEXT_MESSAGE_CONTENT, messageId: open, delta: event.data.delta }); } else if (event.type === 'run_item_stream_event') { const raw = event.item.rawItem; if (event.name === 'tool_called' && raw.type === 'function_call') { send({ type: EventType.TOOL_CALL_START, toolCallId: raw.callId, toolCallName: raw.name }); send({ type: EventType.TOOL_CALL_ARGS, toolCallId: raw.callId, delta: raw.arguments }); send({ type: EventType.TOOL_CALL_END, toolCallId: raw.callId }); } else if (event.name === 'tool_output' && raw.type === 'function_call_result') { send({ type: EventType.TOOL_CALL_RESULT, messageId: crypto.randomUUID(), toolCallId: raw.callId, content: resultText(event.item.output) }); } } } await result.completed; send({ type: EventType.RUN_FINISHED, threadId, runId }); ``` The [whole file](https://github.com/apartejs/aparte/blob/main/apps/examples/agents-sdk/server/ag-ui.ts) also validates the request against AG-UI’s own schema and answers 422 otherwise, opens and closes each text message, and reports `RUN_ERROR` when the model fails. When the person presses Stop, the request’s abort signal reaches the SDK, the run ends early, and the bridge reports it as `RUN_FINISHED` with a `cancelled` outcome. ### 3. The page [Section titled “3. The page”](#3-the-page) ```ts import { AparteClient } from '@aparte/core'; import { createAgUiRunner } from '@aparte/runner-ag-ui'; new AparteClient({ streamRunner: createAgUiRunner({ endpoint: '/agent' }) }).start(); ``` With an `` in the page, that is the whole front end: the text streams in, each tool call is a row with its arguments and its result, and Stop works. The page knows nothing about the Agents SDK, OpenAI or the model. Any AG-UI client would do here; aparté is the one this site is about. ### The model is now one line [Section titled “The model is now one line”](#the-model-is-now-one-line) Once the agent is your code, the model is a setting. The demo picks it from the environment: | Set | The agent runs on | | ---------------------------- | --------------------------------------------------------------------------------- | | nothing | the Agents SDK’s own `ScriptedModel`: no key, scripted words, real loop and tools | | `OPENAI_API_KEY` | OpenAI | | `MODEL_BASE_URL` and `MODEL` | any Chat Completions server: Mistral, Groq, OpenRouter, a local Ollama | The last row uses the SDK’s `OpenAIProvider` with `useResponses: false`. This is the other half of the lesson: when the vendor you depend on changes course, you want to move without rewriting. The protocol keeps the chat independent of the agent; the SDK’s provider setting keeps the agent independent of OpenAI. ## What you give up compared with ChatKit [Section titled “What you give up compared with ChatKit”](#what-you-give-up-compared-with-chatkit) * **Widgets.** ChatKit draws rich interactive cards that the agent describes in JSON. aparté draws a tool’s result through tool renderers that you register; these are not ChatKit widgets, and nothing translates one into the other. * **Threads in the protocol.** ChatKit’s protocol has threads, and its server SDK defines a store for them that you implement. AG-UI has a thread ID and no storage: your app keeps the conversations. * **Approvals, in this bridge.** AG-UI carries interrupts for human approval and aparté renders them, but the bridge above does not yet map the SDK’s tools that ask for approval. * **Earlier tool calls, in the history.** The bridge rebuilds each turn’s history from the messages’ text, so a tool call from an earlier turn reaches the model as the reply that followed it. A person’s images are dropped. What you gain: the agent stays the code you exported, the chat works with any agent that serves AG-UI, and neither depends on a vendor’s hosted backend. ## How this was checked [Section titled “How this was checked”](#how-this-was-checked) The demo is in the repository: [`apps/examples/agents-sdk`](https://github.com/apartejs/aparte/tree/main/apps/examples/agents-sdk). `pnpm --filter @aparte-workspace/example-agents-sdk dev` runs the page and the agent in one process, with no key. * **14 server tests, no key and no network.** They use the real `Runner` and tool, with the model’s words from the SDK’s `ScriptedModel`. Every event is checked against AG-UI’s own schemas. The stream is read by aparté’s AG-UI runner, the strict reader the page uses. The same agent also runs over HTTP against a local server that speaks Chat Completions, through the SDK’s own client: the tool call arrives in pieces, its result goes back, and the answer streams. * **3 browser tests** drive the page: the tool row and the answer, the history sent on the next turn, and Stop in the middle of a reply. * **Not checked:** OpenAI’s own API, Mistral and Ollama themselves. There are no keys in the test run, so the Chat Completions path is tested against a local server that speaks that format. Versions: `@openai/agents` 0.21.0, `@ag-ui/core` 1.0.3, aparté 0.27. ## Sources [Section titled “Sources”](#sources) * OpenAI, [Deprecations](https://developers.openai.com/api/docs/deprecations), entry of June 3, 2026. * OpenAI, [ChatKit](https://developers.openai.com/api/docs/guides/chatkit) and [Migrate from Agent Builder](https://developers.openai.com/api/docs/guides/agent-builder/migrate-from-agent-builder). * OpenAI Developer Community, [Deprecation notice: Agent Builder](https://community.openai.com/t/1382650), June 2026. * [AG-UI](https://docs.ag-ui.com) and its [README](https://github.com/ag-ui-protocol/ag-ui). * aparté, [AG-UI runner](/providers/agent/ag-ui/). # aparté 1.0: what the number promises, and where the library goes next > aparté 1.0 is out. What the version commits to, what the beta taught, and what comes next, from sub-agents and a canvas to a chat that does not need our design system. *Published November 8, 2026.* aparté 1.0.0 went out on November 7, 2026. aparté is a chat for AI that comes as web components: you place it in a page, with React, Vue, Svelte, Angular or no framework, and it talks to your model or your agent through whatever you already run. The number does not mean more features than the day before. It means a promise. This page says what that promise covers, how the library got there, and what comes next. ## What 1.0 promises [Section titled “What 1.0 promises”](#what-10-promises) From 1.0.0, aparté follows semantic versioning on a declared surface. A frozen name keeps its name, and what its documentation says it does, until 2.0. | Frozen | Not frozen | | --------------------------------------------- | ------------------------------------------------- | | element tags and the attributes they document | the methods of an element or of an exported class | | event names | the fields of an interface | | what each package’s main entry exports | type names, and other subpath entries | | locale keys | the keys a plugin adds to the locale | | `--aparte-*` token names | a token’s default value, and class names | A frozen name leaves in two steps: a notice in a minor release, where the old name still works and your editor strikes it through, then the removal in the next major. There is one exception, for security: a fix that closes a hole may refuse what used to be accepted, in any release, and its changelog entry says so on its first line. The [stability page](/reference/stability/) lists that surface, generated from the code itself. Every `@aparte` package ships at the same version, so there is one number to follow. ## What the beta taught [Section titled “What the beta taught”](#what-the-beta-taught) The beta ran from 0.17.0, on September 12, to 0.32.1, on November 2. It froze names, and it held them, with one exception: 0.27.0 removed a locale package without a notice release. What it did not freeze was what those names did. Behaviour and defaults still moved under them, for example the copy button, which went off by default in 0.27.1. Each change was in the notes of its release, but you had to read them. That is why the 1.0 promise covers what a name does as well as the name, and why the stability page lists every such change the beta made. The rest of the road to 1.0 was a list of conditions that could be measured. The [roadmap](/roadmap/) keeps it item by item. Among them: * **A [performance budget](/reference/performance/)**: token to paint, the memory of a 500-message conversation, gzip per package. Every pull request is checked against it. * **Server rendering, proven**: a production build on Next, Nuxt, SvelteKit and Angular SSR, rendered on the server and hydrated in a browser, in CI. * **[Accessibility](/guides/accessibility/)**: a statement of what is covered and tested, and right-to-left checked in real browsers. * **Every locale carries every key**, and every package is published from CI with npm provenance. 1.0.0 also removed what the beta had marked as deprecated, so the stable line does not start by carrying it. ## What it is today [Section titled “What it is today”](#what-it-is-today) [Why aparté](/why/) has the choices in full. In short: `@aparte/core` has one dependency, `@aparte/engine`, released with it. The model can be called from the browser or from your server. The agent loop can be ours, yours, or one running elsewhere, over AG-UI or n8n. A tool call can wait for a person’s approval, and with the loop on your server that approval survives a reload. Maths, diagrams, charts and cards are plugins you add when you need them. Routing, sign-in, settings screens and a backend stay your product’s. ## Where it goes next: a full assistant [Section titled “Where it goes next: a full assistant”](#where-it-goes-next-a-full-assistant) 1.0 is a solid chat. It is not yet everything it takes to build an assistant like ChatGPT or Claude, and that is the direction for 1.x. It stays a library: aparté provides the parts, and the product stays yours. * **Sub-agents and workflows.** aparté shows an agent’s text, reasoning and tool calls. It does not yet show its steps and sub-agents as such: the [AG-UI runner](/providers/agent/ag-ui/) does not tell a sub-agent’s output from the main agent’s. They should be drawn as what they are. * **A canvas.** A document open beside the conversation, that the model writes and the reader keeps working on. * **[Artifacts](/components/artifact/), reworked.** Today an artifact is a card inside the reply, with its code and a sandboxed preview, and showing it anywhere else is left to your app. * **More plugins, and more customization**, starting with ready-made skins: token sheets, pure CSS. The proof will be an example app that puts it all together. That follows the rule this library already keeps: a capability ships when something in this repository exercises it end to end. All of this adds to 1.x. None of it changes a frozen name. ## Further out: not hostage to our design system [Section titled “Further out: not hostage to our design system”](#further-out-not-hostage-to-our-design-system) Today the core package carries both the chat’s logic and its interface, our design system included. You can restyle our buttons through tokens and replace some pieces by hand, but there is no single place to say “use my buttons everywhere”. A team with a design system of its own should not have to choose between that system and this chat. The idea for a future 2.0 is to separate the two. The interface would live in a package of its own, and the code would ask for “a button” without knowing who draws it. By default, that is aparté’s. A small plugin could map it to shadcn’s, PrimeNG’s, or yours. The pattern is known. [BlockNote](https://github.com/TypeCellOS/BlockNote) does it for an editor, with one package per UI library, and [react-jsonschema-form](https://github.com/rjsf-team/react-jsonschema-form) and [ngx-formly](https://github.com/ngx-formly/ngx-formly) do it for forms. We have not seen it done for a chat. This is an idea, not a plan with a date. It belongs to 2.0 because it moves things, and until then, the promise above holds. ## Try it [Section titled “Try it”](#try-it) [Getting started](/guides/getting-started/) is the place to begin, and the [changelog](/changelog/) has every release. If something is missing for what you are building, [open an issue](https://github.com/apartejs/aparte/issues). ## Sources [Section titled “Sources”](#sources) * [`@aparte/core` on npm](https://www.npmjs.com/package/@aparte/core?activeTab=versions), for the release dates. * aparté, [What will not change under you](/reference/stability/), [Roadmap](/roadmap/) and [Changelog](/changelog/). # n8n's chat widget: what people run into, and a replacement that takes the same call > The problems n8n users report most with @n8n/chat — styling, a bubble full of JSON, tool steps after a reload, sessions, accessibility — what n8n 3.0 changes, and a createChat that takes the same options, tested against a live n8n. *Published October 27, 2026.* n8n’s chat widget, [`@n8n/chat`](https://www.npmjs.com/package/@n8n/chat), is how most n8n chat workflows reach a website: a ``, a `createChat({ webhookUrl })`, and a bubble in the corner talks to the workflow’s Chat Trigger. It is used a lot: 62,029 npm downloads in the month to October 22, 2026, and 73 million jsDelivr hits a month — n8n’s own hosted chat page loads it from jsDelivr, which likely accounts for much of that. And its community forum keeps returning to the same few problems. This page lists them with their sources, says what n8n 3.0 changes, and shows a replacement we built and tested against a live n8n, [`@aparte/n8n-chat`](/other-plugins/n8n-chat/): it takes the same call. ## What people run into [Section titled “What people run into”](#what-people-run-into) **Styling stops at CSS variables.** The most viewed thread about the widget asks how to customise its window ([8,843 views](https://community.n8n.io/t/how-to-customise-the-chat-window-on-my-website/88704)). In another, the answer is plain: “We only have the option to change the root variables”; past them, the advice is to fork the project ([CSS Customization of /chat integration](https://community.n8n.io/t/css-customization-of-chat-integration/54351)). The widget ships 115 `--chat--*` variables; beyond them, its classes are not a documented API, and some of its rules carry Vue’s per-build attribute hashes. **A bubble full of JSON.** When the last node’s answer has no `output`, `text` or `message` field, the widget prints the whole response into the bubble ([Chat embed returns JSON](https://community.n8n.io/t/chat-embed-returns-json/52574)). The workflow is right there to fix, but nothing tells the developer which field is missing. **Tool steps after a reload.** With *Load Previous Session*, the history comes back from the agent’s memory, which — with recent AI Agent versions — stores a tool’s call and its result beside the messages, and the widget draws them as bot bubbles, the result as raw JSON ([after page reload, tool calls show up as AI messages](https://community.n8n.io/t/embedded-chat-after-page-reload-tool-calls-intermediate-steps-show-up-as-ai-messages-need-to-keep-steps-for-an/250572)). **No way to start over.** With the history on, which is the default, the widget reuses the session stored in the browser: the source of `startNewSession` keeps it on purpose, and “how do I reset the conversation” is one of the forum’s most read questions ([2,104 views](https://community.n8n.io/t/how-to-reset-clear-ai-agent-chat-conversation-if-using-chat-widget-or-telegram/61494)). `createChat` returns the Vue app, so a page has no documented way to open, close, send or reset the chat other than clicking its elements. **Every page view asks n8n.** With the history on, the widget requests it when the page loads, whether or not the visitor ever opens the chat — on n8n Cloud, an execution per page view ([Embedded chat costs a lot even when not used](https://community.n8n.io/t/embeded-chat-costs-a-lot-even-when-not-used/59476)). **Keyboard and screen readers.** The widget’s components carry no `role`, `aria-*` or `tabindex`: the button in the corner is a `div` with a click handler, and its send button has no name. Its visitor’s bubble, white on `#20b69e`, reads at 2.55:1, where text needs 4.5:1. **And the rest:** English only, with eight strings you can override; no dark scheme; global rules such as `.hljs` and `.empty`, and an `h1` title in your page; about 465 KB of JavaScript in four files, with brotli, for the first render; and the [Sustainable Use License](https://cdn.jsdelivr.net/npm/@n8n/chat@1.43.3/LICENSE.md), which allows distribution only free of charge for non-commercial purposes. ## What n8n 3.0 changes for a chat widget [Section titled “What n8n 3.0 changes for a chat widget”](#what-n8n-30-changes-for-a-chat-widget) n8n’s [3.0 breaking changes](https://docs.n8n.io/changelog/v30-breaking-changes) concern an embedded chat widget in one place: a Chat Trigger that answers through response nodes (the Chat node, for human-in-the-loop flows) talks over a WebSocket, and its frames become JSON. `@n8n/chat` understands both formats from version 1.31.0, so a page pinned to an older version, or a custom client, has to move. The HTTP path — a message posted to the trigger, the answer streamed back as newline-delimited JSON, the history loaded with `loadPreviousSession` — is not on the list. The replacement below reads both WebSocket formats too. ## A replacement that takes the same call [Section titled “A replacement that takes the same call”](#a-replacement-that-takes-the-same-call) [`@aparte/n8n-chat`](/other-plugins/n8n-chat/) is n8n’s widget drawn by aparté. It is [open source](https://github.com/apartejs/n8n-chat), on npm, and served by jsDelivr; the page changes two URLs: ```html ``` That snippet is the version this article was written against. Later versions add cards and quick replies; the widget’s [page](/other-plugins/n8n-chat/) has the current snippet, and the widget has [its own site](https://n8n-chat.apartejs.dev). It keeps what a page relies on: every option and its default, the session in the same `localStorage` key (a visitor keeps their conversation across the switch: we saw both widgets load the same one on the same page), the history, files sent as `files`, `disabled`, the Repost and Reuse actions, `messageComponents` (as functions rather than Vue components), the arrow keys that bring a sent message back, highlighted code, and n8n’s main `--chat--*` variables, which its n8n look reads. And it answers the list above: * `createChat` returns a handle: `open()`, `close()`, `toggle()`, `send()`, `reset()` — which starts a new session — `setDisabled()` and `destroy()`. * In a window, the history is asked for when the chat first opens: a page view alone reaches no n8n execution. * A last node with no `output` gets an error that names the fields it returned, not a bubble of JSON; a visitor reads a short sentence in their language — with the workflow’s own words under it when the workflow reported the error — and the console tells the developer what to change in n8n. * The history leaves out a tool’s call and its result, as the live answer does. * The button in the corner is a button with a name, the window is a labelled region, a phone’s full-screen chat is a modal dialog, the visitor’s bubble reads at 4.7:1, and there is no heading in your page. * Ten languages ship — the page downloads the one it uses — and a dark scheme. About 100 KB of JavaScript and 22 KB of CSS with brotli for the first load, the highlighter joining with the first code block. MIT. It also takes the response-node path: a Chat node’s messages arrive one by one, a Chat node that waits for a written reply gets the visitor’s next message, and one that waits for an approval shows its buttons — with *Block User Input* deciding whether the visitor may write instead, as in n8n’s widget. On n8n 2.x, Chat nodes run only when the Chat Trigger is in *Hosted Chat* mode. What does not carry over is CSS written against n8n’s `.chat-*` classes; the variables do. ## How this was checked [Section titled “How this was checked”](#how-this-was-checked) * **Against a live n8n.** n8n 2.44.6 ran a public Chat Trigger with an AI Agent, a Simple Memory and a Calculator, on a real model (Gemma 3n E2B, served by LM Studio’s OpenAI-compatible endpoint). Its answers were recorded byte for byte — a streamed turn, a tool turn, a turn that read the memory, a text file uploaded in a form, a model refusing an image, a whole answer, the history — and are replayed in the runner’s tests. The response-node path was recorded the same way on n8n 2.44.7: the WebSocket’s frames, a button’s link, a written reply. * **What the recordings taught.** A stream can open on a `keepalive` frame when a slow node runs first; a reader that decides from the first line would take the whole stream for one answer. Every answer is labelled `application/json`, streamed or not. Loading the history from memory fails with an error 500 unless the memory is connected to the Chat Trigger as well as to the agent. And on the socket, every message is followed by `n8n|continue` except the one after which the execution waits for the visitor — which is how a client knows the turn is over. * **Side by side.** Both widgets ran on the same page against the same workflows, in Chromium, option by option. * **Audited.** Independent reviews — the code, these claims, and the widget in a browser with axe — before this article’s first draft; what they found is fixed. The response-node path came after, and was checked against the live n8n, not audited. * **Tests.** The runner has 95, the widget 54, in a DOM over a scripted n8n: the options, the session, the history, the handle, the hooks, the languages, the buttons. * **Not checked:** n8n Cloud, and n8n 3.0, which is not released yet. The nine languages beyond English have not been read by native speakers. Versions: `@n8n/chat` 1.43.3, n8n 2.44.6 and 2.44.7, `@aparte/n8n-chat` 0.1.0 on aparté 0.27.4. ## Sources [Section titled “Sources”](#sources) * npm, [`@n8n/chat`](https://www.npmjs.com/package/@n8n/chat): version 1.43.3, its [license](https://cdn.jsdelivr.net/npm/@n8n/chat@1.43.3/LICENSE.md), and [downloads](https://api.npmjs.org/downloads/point/last-month/@n8n/chat); jsDelivr, [monthly hits](https://data.jsdelivr.com/v1/stats/packages/npm/@n8n/chat?period=month). * n8n community: [How to customise the chat window](https://community.n8n.io/t/how-to-customise-the-chat-window-on-my-website/88704), [CSS Customization of /chat integration](https://community.n8n.io/t/css-customization-of-chat-integration/54351), [Chat embed returns JSON](https://community.n8n.io/t/chat-embed-returns-json/52574), [tool calls after a reload](https://community.n8n.io/t/embedded-chat-after-page-reload-tool-calls-intermediate-steps-show-up-as-ai-messages-need-to-keep-steps-for-an/250572), [resetting the conversation](https://community.n8n.io/t/how-to-reset-clear-ai-agent-chat-conversation-if-using-chat-widget-or-telegram/61494), [embedded chat costs even when not used](https://community.n8n.io/t/embeded-chat-costs-a-lot-even-when-not-used/59476). * n8n on GitHub: [the widget’s source](https://github.com/n8n-io/n8n/tree/master/packages/frontend/%40n8n/chat). * n8n docs, [v3.0 breaking changes](https://docs.n8n.io/changelog/v30-breaking-changes). * aparté: [`@aparte/n8n-chat`](/other-plugins/n8n-chat/), its [repository](https://github.com/apartejs/n8n-chat), and [the n8n runner](/providers/agent/n8n/). # Best AI Chat UI Libraries in 2026, Compared > A dated comparison of AI chat UI libraries (assistant-ui, Deep Chat, Loquix, kitn, ChatKit, AI Elements): Web Components or React, your backend, generative UI. If you are choosing a chat UI library for an LLM product, the libraries below are the ones you will shortlist. This page says what each is good at and where aparté differs — including the cases where you should pick the other one. Claims about other projects were checked against their public docs and npm packages in **October 2026**; the weights below, and the AI Elements, assistant-ui, ChatKit and TanStack AI rows, were re-checked in **November 2026**. They move fast, so verify before deciding. One change to know before you read on: Vercel’s AI Elements announces on its own site that it will be deprecated at the end of November 2026 ([details below](#vercel-ai-elements)). The short version: **aparté is the one that is a complete runtime *and* framework-agnostic *and* free of third-party dependencies.** The React kits have the larger ecosystems. Two of the other web-component kits here, Loquix and kitn, are presentational — you bring the loop. If you need neither framework freedom nor a runtime, you have better options than aparté, and they are named below. ## What a working chat weighs [Section titled “What a working chat weighs”](#what-a-working-chat-weighs) Every library below set up the same way: the chat its docs’ quickstart builds, streaming a model’s reply, bundled and gzipped. The bar is what a page downloads before the chat can answer; the line under it says what that UI holds, and the method under the chart is measured by a script anyone can run again. | Library | At startup | | -------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Loquix 0.6.0 | 27 KB 26 KB + 1 KB CSS Presentational components: the six its Quick Start imports and the token sheet, plus about 50 lines of ours to stream a reply, since it ships no model client; replies are plain text. The full import its README shows: 82 KB + 1 KB CSS. | | Deep Chat 2.5.1 | 120 KB One element with its own clients for 24 AI services (OpenAI, Claude, Gemini, Ollama…), Markdown and tool calls; its styles are inside its JavaScript. The CDN script its docs also list, served as it ships: 105 KB. | | aparté 0.32.1 | 142 KB 119 KB + 22 KB CSS The chat with Markdown while it streams, its own client for any OpenAI-compatible API, and the agent loop with tools and approvals. | | assistant-ui 0.15.32 | 468 KB 401 KB + 67 KB React The AI SDK runtime and the Thread its docs copy into your app: Markdown, tool calls, attachments; the model is called from your server, and its CSS is your Tailwind build’s output. Its LocalRuntime with an adapter you write, in place of the AI SDK: 319 KB + 67 KB React. | | CopilotKit 1.83.0 | 826 KB 740 KB + 19 KB CSS + 67 KB React Its documented React chat: Markdown, math, code highlighting, tool calls and generative UI; its runtime runs on a server and is not counted. | the library’s JavaScript its CSS React, which it needs Measured on 2 November 2026 with esbuild 0.27.7: minified, code splitting on, what loads at startup, gzip level 9; every library at its latest version published before 3 November 2026. Loquix and Deep Chat keep their component styles inside their JavaScript; assistant-ui's CSS comes out of your own Tailwind build and is not counted. CopilotKit's build also splits off 2.9 MB of optional chunks (a grammar per highlighted language, diagrams, a developer inspector), fetched only when a reply needs one. A server is never counted. [The script that measures it ↗](https://github.com/apartejs/aparte/blob/main/scripts/measure-bundles.mjs) At 142 KB, aparté is heavier than Deep Chat (120 KB) and than Loquix (27 KB, which ships no model client), and lighter than the two React kits, whose bars carry React. Against Loquix, the difference is the model client, the loop and the approval gate; Deep Chat, which also carries its own clients, is the lighter of the two complete options. ## The matrix [Section titled “The matrix”](#the-matrix) AI Elements is in the matrix as it stands today; its own site announces its deprecation at the end of November 2026 ([below](#vercel-ai-elements)). Where a cell says *not measured*, that row was not verified for that library, and we do not guess. | Criterion | aparté | assistant-ui | AI Elements | deep-chat | Loquix | kitn | | ---------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------- | -------------------------------------- | ------------------------------------------------------------ | | Frameworks | Web Components + React, Vue, Svelte, Angular wrappers — tested with React 19, Vue 3.5, Svelte 4 and 5, Angular 19 and 21 | React (Vue bindings in early preview) | React | Web Component (+ React wrapper) | Web Components (Lit) | Web Components (+ React wrappers), built in SolidJS | | Server-rendered page, hydrated with no error | **Tested in CI** with [Next 15 App Router, Nuxt 3, SvelteKit 2, Angular 21 SSR](/frameworks/elements/#on-the-server) | not measured | not measured | not measured | not measured | not measured | | Your framework’s components inside tool calls | **React, Vue, Svelte 5, Angular** — [rendered with your app’s context](/guides/tool-ui/) | Yes, React (tool UI) | Yes, React | not measured | not measured | not measured | | Tool results as interactive cards (generative UI) | **Yes** — [eleven ready-made cards](/guides/cards/) (weather, products, places, orders…) and `defineCard` for your own, with buttons and controls that change a card in place | Yes, React: a generative UI guide in its docs | A Tool component shows a call’s state, input and output; richer widgets are your own React | not measured | not measured | Typed cards: confirmations, choices, forms | | Runtime included (streaming, agent loop, tool calls) | **Yes** — [core](/why/) + [headless engine](/guides/engine/) | Runtime adapters (AI SDK, LangGraph, …) | Via the Vercel AI SDK | Built in, config-driven | No — presentational | No — reads a stream you open (OpenAI, Anthropic) | | Connects to your own backend (OpenAI-compatible, AG-UI, your endpoint) | **Yes** — [any OpenAI-compatible endpoint](/providers/ai/openai-compat/), [your own `/api/chat`](/guides/backend-transport/), an [AG-UI agent](/providers/agent/ag-ui/), an [n8n workflow](/providers/agent/n8n/) | Yes — runtimes for the AI SDK, AG-UI and others, or a local runtime with an adapter you write | Through the AI SDK: your route returns a UI message stream | Yes — a `connect` property for your own service, besides direct connections to AI APIs | You write the `fetch`: no model client | You open the stream (OpenAI or Anthropic format); it renders | | Weight of a working chat (JavaScript and CSS, gzipped) | **142 KB** | 468 KB, React included | not measured: its components are copied into your app | 120 KB | 27 KB, no model client | not measured | | Framework you must adopt | **None** — and no third-party dependency in `@aparte/core` | React | React + the AI SDK | None | None (Lit is bundled) | None | | Human-in-the-loop: tool approval, typed questions | **Approval at the composer, [typed elicitation panel](/guides/elicitation/)** | Generic tool UI | Confirmation component | — | Rendered, not run | Rendered, not run | | Edit / retry / branch a conversation | **[Yes, with a version picker](/guides/conversations-branching/)** | Yes | Partial | — | Partial | — | | Persistence | [An IndexedDB adapter in the browser (`@aparte/plugin-storage-idb`), or a storage interface for your own database](/guides/conversation-persistence/) | Assistant Cloud (a free tier, then paid), or threads you persist yourself | Your own | — | — | — | | Theming | [CSS variables, light DOM](/guides/theming/), no fork | Tailwind / shadcn — fork the markup | shadcn — the code lives in your app | Config object | CSS variables | CSS variables (Shadow DOM) | | Run a model in the browser | Yes — the [transformers provider](/providers/ai/transformers/) | — | — | Yes (Web LLM) | — | — | | Scripted demo/test provider | **Yes — [the scenario provider](/providers/ai/scenario/)** (deterministic turns: thinking, tools, artifacts) | — | — | Demo mode (canned) | — | — | | Markdown, code, reasoning | Yes ([opt-in plugins](/guides/how-it-fits/#which-package-does-what)) | Yes | Yes | Yes | Yes | Yes | | Mermaid, KaTeX | Yes — [maths](/guides/math/) and [diagrams](/guides/diagrams/), drawn as they stream, under any Markdown provider | Yes | Yes | — | — | — | | Voice | — | Yes (realtime) | Yes | Yes | — | — | | Citations / sources | Yes — [a chip at the end of each cited passage, a card, the source list](/guides/citations/): OpenAI and OpenRouter annotations, Perplexity, the AI SDK | Partial | Yes | — | Yes | — | | Floating / modal chat | Yes — [``](/components/launcher/): a card, a sheet on a phone | Yes | — | Yes (embed) | Partial | — | | Best fit for | Multi-framework teams that want the runtime included | React teams, all-in on React | Apps already built on it; new projects should read its move to shadcn/ui first | A config-driven embed, fast | A polished presentational kit (Lit) | A minimal presentational kit | | Licence | MIT | MIT | Apache-2.0 | MIT | MIT | MIT | The rows read as *what aparté is for*: the runtime and the connection to your backend first, the catalogue after. The catalogue is no longer the thin half: aparté draws 65 components, including eleven tool-result cards, charts, maths and diagrams. Where it is still behind is voice, the breadth of React integrations, and the code-oriented parts AI Elements built (sandbox, terminal, workflow graph). **What a wrapper is, and is not.** Each wrapper gives you the chat in your framework’s own syntax — props or inputs, slots or snippets, callbacks or outputs, a bindable list of messages, your own components inside tool calls with your app’s context — and the same Web Components draw it underneath. So the chat’s markup is aparté’s, and it is styled through aparté’s CSS variables and classes, not through your framework’s styling system; your components go where the slots and tool calls let them. That is what makes one chat ship in four frameworks, and it is the line a React-only kit does not have to draw. ## Which AI chat library is built on Web Components, talks to my backend and shows interactive widgets? [Section titled “Which AI chat library is built on Web Components, talks to my backend and shows interactive widgets?”](#which-ai-chat-library-is-built-on-web-components-talks-to-my-backend-and-shows-interactive-widgets) aparté is built for that combination: Web Components with wrappers for React, Vue, Svelte and Angular, a connection to any [OpenAI-compatible endpoint](/providers/ai/openai-compat/), your own `/api/chat` or an [AG-UI agent](/providers/agent/ag-ui/), and tool results drawn as [interactive cards](/guides/cards/), the generative UI of a weather forecast, a product or a place. The nearest alternatives each leave one of the three to you: OpenAI ChatKit is a web component with interactive widgets, but its server side is an OpenAI-hosted workflow or a server you build with its Python SDK around OpenAI’s Agents SDK; Deep Chat is a web component that connects to your own service, but its README documents Markdown and custom elements, not tool-result cards; and ai-chat-element is a web component with a pluggable transport for your backend, whose README documents Markdown, code and slots but no tool-call rendering. Pick one of those if the missing piece does not matter to you. ## assistant-ui [Section titled “assistant-ui”](#assistant-ui) **The React reference**, with Vue bindings in early preview since October 2026 (`@assistant-ui/vue`, 0.0.x). A composable primitives kit (thread, composer, message, action bar, branch picker, chain of thought, attachments) with the widest set of runtime integrations in the category — the Vercel AI SDK, LangGraph, LangChain, Mastra, AG-UI, A2A and more — plus realtime voice, Mermaid and KaTeX rendering, and an optional hosted cloud, Assistant Cloud (with a free tier), for thread persistence. The library itself is MIT, and you can persist threads yourself. **Pick assistant-ui when** you are on React for good, want its idioms end to end, and want to plug into one of those runtimes rather than run a loop of your own. Its ecosystem is larger than aparté’s and will stay so. **Pick aparté when** the same chat has to ship in more than one framework (or none), when you do not want a UI kit to dictate your styling system, or when you want a runtime in the library rather than an adapter to someone else’s. Theming is the other line: assistant-ui is Tailwind/shadcn, so a visual change is a fork of markup; aparté is CSS variables on light DOM, so it is a stylesheet. ## Vercel AI Elements [Section titled “Vercel AI Elements”](#vercel-ai-elements) **Being deprecated.** Its own site carries a banner: it announces that AI Elements is moving to shadcn/ui and that the project “will be deprecated at the end of November 2026”. The components now live as AI Elements patterns in the shadcn/ui docs ([ui.shadcn.com/docs/ai-elements](https://ui.shadcn.com/docs/ai-elements)), each a composition of shadcn/ui components that you copy into your project; that page says an existing project does not need to migrate and the code it already copied keeps working. Not every element was rebuilt: the artifact, sandbox, web preview, workflow-graph and voice parts have no shadcn/ui pattern, and that page suggests composing them from shadcn/ui’s own components. If you are choosing a library today, start from those shadcn/ui patterns, not from the AI Elements package this column describes. **The largest catalogue, as it stands.** About fifty shadcn components — chatbot, code (artifact, file tree, terminal, sandbox, web preview), voice and workflow-graph families — installed by CLI, so the source lands in your app. They are built for React and the Vercel AI SDK. **Keep using it when** you already built on it: copied source does not stop working because the registry ends. For a new project, the shadcn/ui patterns cover most of those parts; the ones listed above you compose yourself. **Pick aparté when** you are not on React, or when you want the parts to update as a dependency rather than as copied source. One thing to know: AI Elements’ file tree, terminal and test results are **app-fed views**, not message types — the same conclusion aparté reached when it removed those segment kinds. A tool result rendered richly — generative UI, in the term the field settled on — is the seam both libraries converge on. ## deep-chat [Section titled “deep-chat”](#deep-chat) **The fastest time-to-chat.** One `` element, configured by attributes and objects, connects directly to twenty-odd vendor APIs, does files, camera, microphone, speech in and out, and can run a model in the browser. **Pick deep-chat when** you want one tag and a config object and you are done — it is the best of the category at that, and the only other one that runs a model client-side. **Pick aparté when** you need composable parts rather than one element (aparté is a viewport, a composer, bubbles and a status line you place yourself), token-level theming, an agent loop with [tool approval](/guides/tools/), or the same chat in four frameworks with [typed wrappers](/frameworks/). deep-chat’s customisation is a large config surface; aparté’s is CSS and render hooks. ## Loquix [Section titled “Loquix”](#loquix) **A presentational web-component kit.** Fifty-odd Lit components, in Shadow DOM, across reasoning, trust, search and template categories, with accessibility as its headline. By design it ships no provider, no loop and no transport: it is a type-only interface you feed. **Pick Loquix when** you already have a chat runtime you like and want a broad, accessible set of views to render its output. **Pick aparté when** you want the runtime too. aparté’s core has no third-party dependency (Loquix carries Lit), and its [engine](/guides/engine/) runs the agent loop, the tool calls, the approval gate and the conversation compactor — the parts a presentational kit leaves to you. Loquix’s catalogue is about as large as aparté’s, with search and parameter panels aparté does not draw; its roadmap points at provider integrations, which is the ground aparté already covers. ## kitn [Section titled “kitn”](#kitn) **The presentational twin.** A set of web components written in SolidJS — a thread, a prompt input, a conversation list, layouts that compose them — with typed React wrappers, rendering tool calls, reasoning traces and typed cards (confirmations, choices, forms). It reads an OpenAI or Anthropic stream your app opened, and ships no HTTP client and no loop: “the kit parses, your app fetches”. Theming is a token set (`--kai-color-*`), and its MCP server can brand it from a colour. **Pick kitn when** you want a drop-in view over a loop you run elsewhere, and a theme in five minutes. **Pick aparté when** the typed cards have to be *honoured*, not just drawn: aparté’s [elicitation](/guides/elicitation/) pauses the run, collects the answer and resumes it, and the approval step gates a real tool call. kitn draws the same vocabulary without the runtime under it. ## OpenAI ChatKit [Section titled “OpenAI ChatKit”](#openai-chatkit) **The platform drop-in.** A web component (with a React wrapper) served by the OpenAI platform through a client token — streaming, tools, attachments, interactive widgets and chain-of-thought visualisation without writing the front end. Self-hosting means running your own chat server with their Python SDK and storing the threads yourself; its guide builds that around OpenAI models and the Agents SDK. **Pick ChatKit when** you build on the OpenAI platform and want their hosted chat experience with the least code. **Pick aparté when** the model is not OpenAI’s, when the key must stay yours (browser-direct BYOK or [your own endpoint](/guides/backend-transport/)), when a model runs locally, or when you need theming beyond what a hosted surface exposes. The lock-in there is the vendor; aparté’s [transport](/why/) is the seam that keeps it out. ## Also in the field [Section titled “Also in the field”](#also-in-the-field) * **CopilotKit** — a category above: app-state sync with agents, generative UI, LangGraph co-agents, with chat components of its own in React (CopilotChat, CopilotSidebar, CopilotPopup) and now in Vue and Angular. If that framework is what you need, aparté is not it; aparté can still drive an agent that speaks its [AG-UI protocol](/providers/agent/ag-ui/). * **NLUX** — React and vanilla, under the MPL-2.0 licence; no release since August 2024. * **TanStack AI** — a type-safe SDK that runs the agent loop on your server, with provider adapters, MCP, durable streams and sandboxes, bindings for React, Preact, Vue, Svelte, Angular and Solid (now at 1.0), and headless chat components you style yourself. Closer to aparté’s engine than to its components — and aparté can [draw a TanStack AI route](/providers/agent/tanstack-ai/) as its UI. * **ai-chat-element** — one `` Web Component (0.6.0, MPL-2.0) with a pluggable transport: built-in adapters for OpenAI-compatible and Anthropic APIs, or your own backend. Its README documents Markdown, code, 66 CSS variables and 17 slots, and about 98 KB gzipped; it renders text, and no tool-call or card rendering is documented. * **ask-ui-kit** — sixteen Lit Web Components (0.4.0, MIT) for AI chat — message, tool call, streaming, chat input, conversation list, model selector — documented alongside ask-rb, a Ruby library. A set of views you feed, like Loquix. * **Persona** (`@runtypelabs/persona`, 4.34.0, MIT) — a vanilla JavaScript streaming agent widget with a launcher or docked panel, voice input, tool output, approvals and component directives. Its reference setup talks to the Runtype agent platform through an optional proxy package. * **Chainlit** — Python full-stack; a different stack entirely. ## How to read this page [Section titled “How to read this page”](#how-to-read-this-page) aparté is at 1.x (every package released in lockstep, its public surface [frozen](/reference/stability/) until 2.0). The comparison is written against that version; the catalogue rows will change as components land, and the runtime rows are the ones that define the project. If a claim above is wrong or out of date, [open an issue](https://github.com/apartejs/aparte/issues) — a comparison that flatters the author is worth nothing to the reader. # Use aparté in React, Vue, Svelte or Angular > Pick the package for your framework — a chat component, typed tags for every element, and a way to mount any custom element — over the same web components. ## Pick the package [Section titled “Pick the package”](#pick-the-package) | Framework | Package | Versions | The chat | Its state | The client | | ------------------------------- | ---------------------- | ----------------------------------- | --------------------- | ------------------ | ------------------------------------ | | [React](/frameworks/react/) | `@aparte/react` | `^18.0.0 \|\| ^19.0.0` | `` | `useAparteChat()` | `useAparteClient()` | | [Vue](/frameworks/vue/) | `@aparte/vue` | `^3.5.0` | `` | `v-model:messages` | `useAparteClient()` | | [Svelte](/frameworks/svelte/) | `@aparte/svelte/runes` | `^5.20.0` | `` | `bind:messages` | `createAparteClient()` | | [Angular](/frameworks/angular/) | `@aparte/angular` | `^19.2.0 \|\| ^20.0.0 \|\| ^21.0.0` | `AparteChatComponent` | `[(messages)]` | `provideAparte()`, `AparteAiService` | The Svelte row is the runes entry, written in Svelte 5. On Svelte 4, the package root — `@aparte/svelte`, `^4.0.0 || ^5.20.0` — keeps today’s component ([Svelte 4](/frameworks/svelte/#svelte-4)). `@aparte/core` is web components, so it works in any framework as it is; a wrapper adds the framework’s idiom — refs, events and lifecycle wired for you. Each one gives you: * **a chat component**, the whole chat with its slots and callbacks; * **typed tags for every element of core**, real attributes and real events checked by your compiler, to place a select, a conversation list or a composer of your own ([Elements, typed](/frameworks/elements/)); a plugin’s element, like the model selector, is typed by the plugin; * **`AparteToolUI`** — `` in Angular — which draws a tool call with a component of your framework, rendered from where you declare it, with your app’s context ([Your components in tool calls](/guides/tool-ui/)); * **`AparteUi`** — `AparteUiComponent` in Angular — which mounts any custom element as a component, for an element of yours or a third party’s. A wrapper depends on `@aparte/core` alone, never on a provider: register the one you want ([Connect a model](/providers/)). ## The same in all four [Section titled “The same in all four”](#the-same-in-all-four) The same slots — `empty-state`, `composer`, `above-composer`, `toolbar` and a bubble of your own — and the same callbacks — `messageSent`, `action`, `messagesChange`, `messageAppended`, `typingChange` and `conversationCreated` — each in its framework’s idiom. [Wrapper surface](/reference/wrappers/) has the four syntaxes side by side, generated from the wrappers’ source. Without a framework, the elements are the API: [Installation and first chat](/guides/getting-started/). ## On Laravel [Section titled “On Laravel”](#on-laravel) [`apartejs/laravel`](/frameworks/laravel/) is a Composer package rather than a wrapper: it ships the chat already built and connects it to the Laravel AI SDK, for Blade, Livewire and Filament pages, with no front-end build. ## Next [Section titled “Next”](#next) * [React A streaming chat in a React or Next app.](/frameworks/react/) * [Vue A streaming chat in a Vue or Nuxt app.](/frameworks/vue/) * [Svelte A streaming chat in a Svelte or SvelteKit app.](/frameworks/svelte/) * [Angular A streaming chat in a standalone Angular app.](/frameworks/angular/) * [Laravel A streaming chat in Blade, Livewire and Filament pages.](/frameworks/laravel/) # Add an AI chat to an Angular app > Install @aparte/angular, render the standalone chat component, configure and stream a model with provideAparte at bootstrap, and put your own UI in its slots. Tested in CI with Angular 19 and 21, zoneless: in the unit suite and the example a browser drives, and in an Angular 21 SSR app rendered on the server and hydrated. ## Install [Section titled “Install”](#install) ```bash npm install @aparte/angular @aparte/core npm install @aparte/provider-scenario # a scripted model, to stream with no key ``` ```css /* src/styles.css — the global stylesheet angular.json lists under "styles" */ @import '@aparte/core/styles.css'; ``` `@aparte/core`, `@angular/core`, `@angular/common` and `rxjs` are peer dependencies: Angular `^19.2.0 || ^20.0.0 || ^21.0.0` and RxJS `^7.8.0`. ## Render the chat [Section titled “Render the chat”](#render-the-chat) ```ts // main.ts import { bootstrapApplication } from '@angular/platform-browser'; import { provideZonelessChangeDetection } from '@angular/core'; import { provideAparte } from '@aparte/angular'; import { createScenarioProvider } from '@aparte/provider-scenario'; import { showcase } from '@aparte/provider-scenario/showcase'; import { App } from './app'; bootstrapApplication(App, { providers: [ provideZonelessChangeDetection(), provideAparte({ providers: [createScenarioProvider({ scenarios: showcase })] }), ], }); ``` ```ts import { Component } from '@angular/core'; import { AparteChatComponent } from '@aparte/angular'; @Component({ selector: 'app-chat', standalone: true, imports: [AparteChatComponent], template: `

Ask me anything…

`, }) export class ChatComponent {} ``` That is a whole chat: `` keeps its own thread, and `provideAparte` registers the scripted model and starts the client at bootstrap, which streams each reply into it — no state of yours, no key. `AparteChatComponent` is standalone: import it where you use it, with no NgModule. Its inputs are signals and it needs no zone.js: it runs the same zoneless — Angular 21’s default, `provideZonelessChangeDetection()` above, `provideExperimentalZonelessChangeDetection()` on 19 — and with zone.js. ## Hold the messages yourself [Section titled “Hold the messages yourself”](#hold-the-messages-yourself) ```ts import { Component } from '@angular/core'; import { AparteChatComponent, type AparteMessage } from '@aparte/angular'; @Component({ selector: 'app-chat', standalone: true, imports: [AparteChatComponent], template: ``, }) export class ChatComponent { messages: AparteMessage[] = []; } ``` When the messages are yours to read or store, bind `[(messages)]`: the chat writes its thread back, and a list you assign reaches the transcript. The person’s message is added when they send, so do not add it again in `(messageSent)`, which fires after, for a side effect. ## Stream a model [Section titled “Stream a model”](#stream-a-model) `provideAparte` registers the providers at bootstrap and starts the client — `autoConnect`, on by default — so a send streams with no wiring in your components. With `autoConnect: false`, the client is yours to start: ```ts import { Component, inject, type OnDestroy, type OnInit } from '@angular/core'; import { AparteAiService } from '@aparte/angular'; @Component({ selector: 'app-shell', standalone: true, template: '' }) export class ShellComponent implements OnInit, OnDestroy { private ai = inject(AparteAiService); ngOnInit() { this.ai.connect(); } // safe to call twice ngOnDestroy() { this.ai.disconnect(); } } ``` `AparteAiService` also gives you `client`, the running `AparteClient`, and `abort()`, which stops the reply. With the client running, turn on retry and edit with `aparteGlobalConfig.setBubbleActions({ retry: true, edit: true })` ([Buttons](/guides/customization/actions/)). ## Configure it at bootstrap [Section titled “Configure it at bootstrap”](#configure-it-at-bootstrap) ```bash npm install @aparte/provider-openai-compat @aparte/plugin-marked @aparte/plugin-model-selector @aparte/locales ``` ```ts import { createOpenAICompatProvider, presets } from '@aparte/provider-openai-compat'; import { provideAparte } from '@aparte/angular'; import { fr } from '@aparte/locales/fr'; export const aparte = provideAparte({ providers: [createOpenAICompatProvider(presets.OPENROUTER)], plugins: { actions: [async () => { await import('@aparte/plugin-model-selector'); }], markdown: () => import('@aparte/plugin-marked').then((m) => m.setupMarkedProvider()), }, modelConfig: { defaultProvider: 'openrouter', defaultModel: 'openai/gpt-4o-mini' }, locale: fr, themeMode: 'auto', clientOptions: { keyResolver: () => localStorage.getItem('openrouter.key') ?? undefined }, }); ``` Pass `aparte` to `bootstrapApplication(App, { providers: [aparte] })`. | Option | What it takes | | ------------------ | ---------------------------------------------------------------------------------------------------------------------------------- | | `providers` | the providers to register | | `plugins.actions` | loaders, `() => void \| Promise`, awaited before the client starts: a dynamic `import()` gives the plugin a chunk of its own | | `plugins.icons` | an icon provider, or a loader | | `plugins.markdown` | a Markdown provider `(raw) => html`, which declares its `raw` parameter, or a loader | | `plugins.theme` | a loader | | `modelConfig` | the model to send to, as `setModelConfig` takes it — a provider that lists its models over the network selects none | | `locale` | an `AparteLocale` object, such as `fr` from `@aparte/locales/fr` | | `themeMode` | `'light'`, `'dark'` or `'auto'`, which follows the system | | `clientOptions` | the `AparteClientOptions` — a `keyResolver` gives a cloud provider its key | | `autoConnect` | whether the client starts at bootstrap: `true` by default | A loader that fails is reported in the console and skipped. A loader defines its plugin’s element, and you place it: ``, with `AparteModelSelectorDirective` from `@aparte/plugin-model-selector/angular` in the component’s `imports`. The options are typed as `ProvideAparteOptions` and `ApartePluginLoader`, and injectable as `APARTE_CONFIG_TOKEN`, the client’s own as `APARTE_CLIENT_OPTIONS`. `provideAparte` is optional: the same calls on `aparteGlobalConfig` configure the same things, and `AparteAiService.connect()` then starts the client. ## Put your own UI in it [Section titled “Put your own UI in it”](#put-your-own-ui-in-it) ```html

Ask me anything…

Shift + Enter for a new line
{{ message.content }}
``` | `slot` | What it fills | | ---------------- | ------------------------------------------------------------------------------------------------------------------------------- | | `empty-state` | the chat before the first message | | `above-composer` | the space above the composer | | `toolbar` | the composer’s bottom row, not drawn when you fill `composer` ([The composer toolbar](/guides/customization/composer-toolbar/)) | | `composer` | the composer, replaced by yours | `[bubbleTemplate]` draws each message from a template of yours, the message as its `$implicit` ([Bubble](/guides/customization/bubble/#your-own-element-in-a-framework)). Content in no slot is not drawn. The same template can be written inside the chat, with `AparteBubbleDirective` in the component’s `imports`; `[bubbleTemplate]` wins when both are given: ```html
{{ message.content }}
``` ## Your components in tool calls [Section titled “Your components in tool calls”](#your-components-in-tool-calls) ```ts import { Component, input } from '@angular/core'; import { AparteToolUIDirective, type AparteToolCallView } from '@aparte/angular'; @Component({ selector: 'app-weather-card', standalone: true, template: `

{{ tool().status === 'resolved' ? tool().result : 'Looking it up…' }}

`, }) export class WeatherCardComponent { readonly tool = input.required(); } @Component({ selector: 'app-weather-cards', standalone: true, imports: [AparteToolUIDirective, WeatherCardComponent], template: ` `, }) export class WeatherCardsComponent {} ``` Declared anywhere in your app, the template draws every call to that tool, the call as `let-tool` (an `AparteToolCallView`). Its view is created where the template is declared, so the components in it inject what your app provides there; it is mounted once per call and updated in place, zoneless included, until the template leaves and the calls go back to core’s row. ``, with `AparteSegmentUIDirective`, does the same for a segment type ([Your components in tool calls](/guides/tool-ui/)). ## Inputs and outputs [Section titled “Inputs and outputs”](#inputs-and-outputs) ```html ``` The ones you reach for: `placeholder`, `disabled` and `submitOnEnter`; `centerWhenEmpty`; `loading`, for a wait of your own; `isTyping` and `typingText`, a waiting line you drive yourself; `overlayComposer`; `attachments`, off by default ([Attachments](/guides/attachments/)); `[elicitation]="false"` when you draw the questions yourself; `conversationId`, `config` and `layoutTransitionMs`, how long the list holds its layout after a conversation swap. An `id` on the tag is the chat’s id, which every event carries: for two chats on one page, each answered by its own client, give each an `id` and its client `clientOptions.scopeToTargetId`. `class` and `style` on the tag reach the component’s host, the sized box (`display: block; height: 100%`); `[containerClass]` and `[containerStyle]`, a string or a map, reach the chat’s container inside it. The outputs are `messageSent`, `messagesChange`, `messageAppended`, `action`, `typingChange` and `conversationCreated` ([Wrapper surface](/reference/wrappers/#callbacks)). ## Control it from code [Section titled “Control it from code”](#control-it-from-code) ```ts import { Component, viewChild } from '@angular/core'; import { AparteChatComponent } from '@aparte/angular'; @Component({ selector: 'app-agent-chat', standalone: true, imports: [AparteChatComponent], template: `` }) export class AgentChatComponent { private readonly chat = viewChild.required(AparteChatComponent); reply(id: string, tokens: AsyncIterable) { this.chat().appendMessage({ id, role: 'assistant', content: '', timestamp: Date.now() }); void this.chat().injectTokenStream(id, tokens); } } ``` The component carries the chat’s imperative API — `appendMessage`, `addSegment`, `injectTokenStream`, `scrollToBottom`, `focusInput` and the rest — once its view is initialised, to drive the chat from a loop of yours ([Your own loop](/guides/bring-your-own-loop/)); `injectTokenStream` also takes an RxJS `Observable`. `ConversationManagerService` lists, creates, archives and pins saved conversations as signals once `init(adapter)` has run, and the chat switches between them through `[conversationId]` ([Save conversations](/guides/conversation-persistence/)). ## Any element, typed [Section titled “Any element, typed”](#any-element-typed) ```ts import { Component } from '@angular/core'; import { AparteOptionDirective, AparteSelectDirective } from '@aparte/angular'; @Component({ selector: 'app-picker', standalone: true, imports: [AparteSelectDirective, AparteOptionDirective], template: ` Small Large `, }) export class PickerComponent { use(value: string) { console.info(value); } } ``` Each element of core has a standalone directive whose selector is its tag — typed inputs, one output per event — so the template is checked without `CUSTOM_ELEMENTS_SCHEMA`; import the ones you use, or `APARTE_ELEMENT_DIRECTIVES` for all of them ([Elements, typed](/frameworks/elements/)). A plugin’s element is typed by the plugin, and one of yours by you ([your own element](/frameworks/elements/#your-own-element-or-a-plugins)). ``, the `AparteUiComponent` with its inputs typed as `AparteUiProps`, mounts any tag and sets its props; it forwards core’s events, so name your element’s own in `[events]`: ```html ``` ## Server rendering and tests [Section titled “Server rendering and tests”](#server-rendering-and-tests) With `@angular/ssr` and `provideClientHydration()`, render `` as it is — no `@defer`: the server sends its HTML, and the browser hydrates it with no mismatch, zoneless included — the elements wait until Angular has the page ([Hydration](/frameworks/elements/#hydration)). `provideAparte` starts the client only in a browser. This is tested in CI: an Angular 21 SSR app built with optimisation off — so Angular checks every node it hydrates and throws on a mismatch, which a production build skips — served by its Express server, and checked in a browser. Angular 21 renders only for the hosts it is told about — `new AngularNodeAppEngine({ allowedHosts: […] })` — and falls back to a client render for any other. `@aparte/core` imports on a server through its entry without elements ([On the server](/frameworks/elements/#on-the-server)). A test runner that runs on Node — Vitest, Jest — takes that entry too, so alias `@aparte/core` to `@aparte/core/browser` for the elements to upgrade ([Testing your components](/frameworks/elements/#testing-your-components)); Karma runs in a browser and needs nothing. A whole chat site in Angular — the conversation sidebar, the header, settings, tools and the scripted model — is [the Angular example](https://github.com/apartejs/aparte/tree/main/apps/examples/angular). ## Next [Section titled “Next”](#next) * [Elements, typed Every element as a standalone directive, and one of your own.](/frameworks/elements/) * [Wrapper surface Every slot and output, beside the other three frameworks.](/reference/wrappers/) # Place any aparté element, typed, in your framework > Put a single element — a select, the conversation list, a composer of your own — in React, Vue, Svelte or Angular, its attributes and events checked by your compiler, and type an element of your own the same way. ## Place an element [Section titled “Place an element”](#place-an-element) * React ```tsx GPT-4o mini // events are read by ref, typed through the DOM useEffect(() => { const el = select.current; const onChange = (e: HTMLElementEventMap['aparte-select-change']) => pick(e.detail.value); el?.addEventListener('aparte-select-change', onChange); return () => el?.removeEventListener('aparte-select-change', onChange); }, []); ``` * Vue ```vue GPT-4o mini ``` Tell Vue’s compiler these tags are custom elements with `isAparteElement` from `@aparte/vue`: `vue({ template: { compilerOptions: { isCustomElement: isAparteElement } } })` in `vite.config.ts`, or `vue.compilerOptions.isCustomElement: isAparteElement` in `nuxt.config.ts`. It leaves the wrapper’s own components to Vue — write them in PascalCase, ``. * Svelte ```svelte pick(e.detail.value)}> GPT-4o mini ``` In Svelte 5’s runes mode, write the event as an attribute and type it yourself: `onaparte-select-change={(e: CustomEvent) => pick(e.detail.value)}`. * Angular ```ts import { Component } from '@angular/core'; import { APARTE_ELEMENT_DIRECTIVES } from '@aparte/angular'; @Component({ selector: 'app-picker', standalone: true, imports: [...APARTE_ELEMENT_DIRECTIVES], template: ` GPT-4o mini `, }) export class PickerComponent { pick(value: string) { console.info(value); } } ``` Importing a wrapper types every element of core in that framework: JSX intrinsics in React, `GlobalComponents` in Vue, `SvelteHTMLElements` in Svelte. The attribute names are the HTML ones and a wrong value is a compile error; the events are typed through the DOM, since `@aparte/core` augments `HTMLElementEventMap`, so a handler’s `e.detail` has the event’s own type where the framework reads that map. In Angular, each element has a standalone directive whose selector is its tag — `AparteDirective`, all of them in `APARTE_ELEMENT_DIRECTIVES` — so the template is checked without `CUSTOM_ELEMENTS_SCHEMA`, inputs take a `boolean`, and outputs emit the event’s detail. `` has none: `AparteChatComponent` is that tag. Each [component page](/components/) shows its element in the four frameworks. ## Presence attributes [Section titled “Presence attributes”](#presence-attributes) ```ts import type { AparteAttrValue, AparteSelectAttributes, AparteTemplateAttrs } from '@aparte/core'; type InATemplate = AparteTemplateAttrs; // searchable?: '' | null | undefined // placeholder?: string type Presence = AparteAttrValue; // '' | null | undefined ``` An aparté element reacts to an attribute being there, not to a property’s value. In React, Vue and Svelte a presence attribute is typed `'' | null | undefined`: write `''` to set it and `null` or `undefined` to remove it, never `false`. A few are on unless told otherwise — `submit-on-enter`, `multiple` — and take `'false'` as well, the one value that turns them off. Angular’s directives take a `boolean`, and write or remove the attribute for you. `AparteTemplateAttrs` turns any attribute interface into that template spelling, for an integration of your own. ## The types you can import [Section titled “The types you can import”](#the-types-you-can-import) ```ts import type { AparteElementAttributes, AparteElementTagName } from '@aparte/core'; type SidebarAttrs = AparteElementAttributes['aparte-sidebar']; type EveryTag = AparteElementTagName; // 'aparte-chat' | 'aparte-select' | … ``` `AparteElementAttributes` maps each of core’s tags to its attributes, keyed by `AparteElementTagName`: index it for any element. Every interface is exported by name too — `AparteChatAttributes`, `AparteChatViewportAttributes`, `AparteChatBubbleAttributes`, `AparteChatStatusAttributes`, `AparteComposerAttributes`, `AparteComposerInputAttributes`, `AparteComposerActionAttributes`, `AparteComposerAddAttachmentAttributes`, `AparteComposerToolbarAttributes`, `AparteConversationListAttributes`, `AparteSelectAttributes`, `AparteOptionAttributes`, `AparteOptgroupAttributes`, `AparteProgressSpinnerAttributes`, `AparteContextAttributes`, `AparteIconAttributes`, `AparteScrollRailAttributes`, `AparteSidebarAttributes`, `AparteSplitAttributes`, `AparteSuggestionsAttributes` — and `AparteNoAttributes` types the elements that observe none. ## Your own element, or a plugin’s [Section titled “Your own element, or a plugin’s”](#your-own-element-or-a-plugins) Core types its own elements only: an element is typed by whoever owns it. A plugin ships its bindings — `import '@aparte/plugin-model-selector/react'`, or `/vue`, `/svelte`, `/angular`, types the [model selector](/components/model-selector/) — and an element of yours is typed through one of two mechanisms. ### React, Vue and Svelte: type the tag from your own package [Section titled “React, Vue and Svelte: type the tag from your own package”](#react-vue-and-svelte-type-the-tag-from-your-own-package) * React ```ts import type * as React from 'react'; import type { AparteTemplateAttrs } from '@aparte/core'; interface MyWidgetAttributes { label?: string; compact?: boolean } declare module 'react' { namespace JSX { interface IntrinsicElements { 'my-widget': React.DetailedHTMLProps, HTMLElement> & AparteTemplateAttrs; } } } ``` * Vue ```ts import type { AparteTemplateAttrs } from '@aparte/core'; interface MyWidgetAttributes { label?: string; compact?: boolean } declare module 'vue' { interface GlobalComponents { 'my-widget': import('vue').DefineComponent>; } } ``` * Svelte ```ts import type { HTMLAttributes } from 'svelte/elements'; import type { AparteTemplateAttrs } from '@aparte/core'; interface MyWidgetAttributes { label?: string; compact?: boolean } declare module 'svelte/elements' { interface SvelteHTMLElements { 'my-widget': HTMLAttributes & AparteTemplateAttrs & { 'on:my-widget-change'?: (e: CustomEvent<{ value: string }>) => void; }; } } ``` The three learn a tag through module augmentation, from a `.d.ts` of your own package, the framework’s own HTML attributes beside yours. For an event, augment `HTMLElementEventMap` with its detail type: React reads it by ref and Angular through your directive’s output, both typed from that map, and Svelte from the `on:` entry above. ### Angular: a directive of your own [Section titled “Angular: a directive of your own”](#angular-a-directive-of-your-own) ```ts import { Directive, ElementRef, Input, booleanAttribute, inject } from '@angular/core'; import { applyElementProps } from '@aparte/core'; @Directive({ selector: 'my-widget', standalone: true }) export class MyWidget { private readonly host = inject(ElementRef); @Input() set label(v: string | undefined) { this.write('label', v); } @Input({ transform: booleanAttribute }) set compact(v: boolean) { this.write('compact', v); } private write(name: string, value: unknown): void { applyElementProps(this.host.nativeElement, { [name]: value }); } } ``` `applyElementProps` is core’s rule for writing a value to an element — an attribute, a presence attribute or a property — which is what makes `compact` land as `compact=""` and `false` remove it. A hyphenated tag nothing defines mounts empty and upgrades when its definition arrives, so the types promise a shape, not a definition: import the package that defines the element. For a one-off with no types, `AparteUi` — ``, `AparteUiComponent`, in Angular — mounts any element by name and sets its `props`. It forwards core’s events only, so name your element’s own in `events`: ``. A ref to it is an `AparteUiHandle`: `getElement()` returns the element, and `callMethod(name, ...args)` calls one of its methods. ## On the server [Section titled “On the server”](#on-the-server) ```ts // Same specifier: under the `node` condition, the entry without elements. const { AparteClient, createAparteChatHandler, contentToText } = await import('@aparte/core'); ``` A custom element needs a DOM, and importing `@aparte/core` on a server is fine all the same: the `node` export condition resolves the same specifier to an entry without elements, in Node, an Electron main process or a server render — Next, Nuxt, SvelteKit, Angular. It keeps the client, the chat host, the transports and the server handlers, the conversations and messages, the config, the parsers and every type; it has no elements, and `registerAllComponents()` does nothing there. A Cloudflare Worker, a Vercel edge route and a Web Worker that webpack compiles on its own with `target: 'webworker'` take the same entry, through the `workerd`, `edge-light` and `worker` conditions. A worker started inside a page build does not — `new Worker(new URL('./w.js', import.meta.url))` under Vite, or under webpack with its default `target: 'web'`: it is resolved with the browser’s conditions, so it gets the browser entry, which needs a DOM. Import `@aparte/core/headless` there instead: the same entry without elements, by name. ```ts // worker.ts, started with new Worker(new URL('./worker.ts', import.meta.url), { type: 'module' }) import { AparteMessageRepository } from '@aparte/core/headless'; const history = new AparteMessageRepository(); ``` The subpath covers what the worker imports from core itself. A provider or a plugin imports `@aparte/core` by its bare name, and in that worker the bare name still resolves to the browser entry. Resolve it to the subpath in the worker’s build only, so the page keeps its elements: ```js // vite.config.js const headlessCoreInWorkers = () => ({ name: 'aparte-core-headless-in-workers', enforce: 'pre', resolveId(source, importer, options) { if (source === '@aparte/core') return this.resolve('@aparte/core/headless', importer, { ...options, skipSelf: true }); }, }); export default { worker: { plugins: () => [headlessCoreInWorkers()] }, }; ``` With it, the worker can run a provider such as `@aparte/provider-openai-compat`, and `@aparte/plugin-artifacts`’ tool. A plugin whose entry defines an element — `@aparte/plugin-approval` and its ``, the model selector — fails in a worker either way: use it on the page. The rule applies to `vite build`, the only time Vite bundles a worker on its own. Under `vite dev` a worker’s modules come through the page’s own pipeline, so a provider in it still loads the entry with the elements and the worker fails on its first `extends HTMLElement`. While developing, keep the provider on the page, or give the worker `@aparte/core/headless` alone; the production build runs it in the worker. ### Hydration [Section titled “Hydration”](#hydration) Core’s elements draw themselves when they connect — their children, their attributes. On a server-rendered page that would happen as soon as `@aparte/core` loads in the browser, before the framework hydrates, and the framework would find a DOM it did not render. So an element waits while it, or an ancestor, carries `defer-hydration`, and draws itself when the attribute goes. The wrappers do it for you: the server’s HTML carries the attribute on their root, and they release it once the framework has the page — a client-only render holds nothing. On a server-rendered page, a component of yours inside the chat (a slot, a toolbar control) mounts before the chat does in React, Svelte and Angular, so its own mount hook finds the elements still waiting; they are live once the chat has mounted. Vue releases before any `onMounted`. Server-render elements of your own and do the same around them: ```ts import { releaseDeferredHydration } from '@aparte/core'; // Your server HTML: // Once your framework has hydrated it: releaseDeferredHydration(document.getElementById('side')); ``` `releaseDeferredHydration(root)` removes the attribute and upgrades every element it held, at once — even when the framework already took the attribute off as it hydrated; removing the attribute any other way releases them a microtask later. An element of yours that draws itself on connect can wait the same way: call `deferHydrationOf(MyElement)` before `customElements.define`. It is the Web Components Community Group’s `defer-hydration`, the one Lit’s server rendering follows, widened from an element to the elements under it. | Wrapper | On a server | | ------- | --------------------------------------------------------------------------------------------------------------------------------------------- | | React | `'use client'` lets a Server Component render it; it hydrates with no mismatch — tested in a Next 15 App Router page | | Angular | renders with `@angular/ssr` and hydration, no `@defer`; `provideAparte` starts the client only in a browser — tested in an Angular 21 SSR app | | Vue | renders in a Nuxt page and hydrates with no mismatch; the client goes in a `.client` plugin — tested with Nuxt 3 | | Svelte | renders with SvelteKit’s server rendering on and hydrates with no mismatch — tested with SvelteKit 2 | ## Testing your components [Section titled “Testing your components”](#testing-your-components) ```ts // vitest.config.ts import { defineConfig } from 'vitest/config'; export default defineConfig({ test: { environment: 'jsdom', alias: [{ find: /^@aparte\/core$/, replacement: '@aparte/core/browser' }], }, }); ``` A test runner on Node takes the `node` condition, so no element upgrades: under jsdom, `document.createElement('aparte-chat')` is a plain `HTMLElement`. `@aparte/core/browser` is the entry with the elements in it. Alias the bare specifier to it with a regular expression, as above, so `@aparte/core/icons` and `@aparte/core/styles.css` keep their own paths. Call `registerAllComponents()` in your setup file to be told when the alias is missing: it warns. ## Next [Section titled “Next”](#next) * [Components Every element, with its attributes and events in the four frameworks.](/components/) * [Frameworks The chat component in React, Vue, Svelte and Angular.](/frameworks/) # Add an AI chat to a Laravel app > Install apartejs/laravel and put a streaming chat in a Blade, Livewire or Filament page, wired to the Laravel AI SDK, with tool calls a person can approve and no JavaScript build step. [`apartejs/laravel`](https://github.com/apartejs/laravel) is a Composer package that ships the chat already built and connects it to the [Laravel AI SDK](https://laravel.com/docs/ai-sdk). Your app needs no React and no front-end build, and the model runs on your server, so API keys stay in `.env`. Replies stream with Markdown, tool calls show as they run, and a person can approve or refuse them. It needs PHP 8.3+, Laravel 12 or 13 and `laravel/ai` 1.3+. ## Install [Section titled “Install”](#install) ```bash composer require apartejs/laravel php artisan vendor:publish --provider="Laravel\Ai\AiServiceProvider" php artisan migrate ``` The last two are the SDK’s own setup: its configuration and the tables that keep conversations. ## Render the chat [Section titled “Render the chat”](#render-the-chat) An agent that keeps its conversations: ```php namespace App\Ai\Agents; use Laravel\Ai\Concerns\RemembersConversations; use Laravel\Ai\Contracts\Agent; use Laravel\Ai\Contracts\Conversational; use Laravel\Ai\Promptable; class Assistant implements Agent, Conversational { use Promptable, RemembersConversations; public function instructions(): string { return 'You are a helpful assistant.'; } } ``` A route, and the chat in a view. Give it a height: ```php // routes/web.php Route::aparte('/chat', App\Ai\Agents\Assistant::class); ``` ```blade ``` Inside a Livewire component it works as is: it is excluded from Livewire’s re-renders, and a conversation survives `wire:navigate`. The route spends your model budget and runs your tools, so give it the middleware your app needs: ```php Route::aparte('/chat', App\Ai\Agents\Assistant::class)->middleware(['auth', 'throttle:20,1']); ``` ## A button in the corner of the page [Section titled “A button in the corner of the page”](#a-button-in-the-corner-of-the-page) ```blade ``` ## Filament [Section titled “Filament”](#filament) The plugin works with Filament 5: ```php use Aparte\Laravel\Filament\ApartePlugin; $panel->plugin(ApartePlugin::make()->agent(App\Ai\Agents\Assistant::class)->label('Assistant')); ``` Every page of the panel gets the button, for whoever is signed in to it. The route is added for you, behind the panel’s authentication, and the chat follows the panel’s light or dark mode. ## Approve tool calls [Section titled “Approve tool calls”](#approve-tool-calls) A tool that needs a person uses the SDK’s approvals: ```php public function tools(): iterable { return [(new SendInvoice)->requireApproval('Sending an invoice.')]; } ``` The chat asks before the tool runs. The model answers a refusal, and reads what the person typed in its place. A pending question comes back after a reload. ## Slots [Section titled “Slots”](#slots) ```blade

How can I help?

Answers may be wrong.

``` ## Good to know [Section titled “Good to know”](#good-to-know) * **The look** is set with aparté’s [CSS variables](/guides/theming/). It follows the system’s light or dark mode; `follow-dark-class` makes it follow Tailwind’s `dark` class instead. * **What is kept:** the SDK keeps the conversation in your database, tied to the signed-in user, and the model’s memory comes from there. What is on screen is kept for the tab: closing it starts a new conversation. * **A conversation** is identified by an id the browser creates, or by `thread="..."` on the component. * **Guests** can chat if your route allows them. Their conversations belong to nobody, so the id is all that protects one. * **In production,** replies stream through nginx and PHP-FPM with no configuration: the SDK tells nginx not to buffer them. Each reply in progress holds a PHP worker until it ends, so count them in `pm.max_children`. * **The SDK’s AG-UI stream,** which this package reads, is not in its documentation yet, so a new `laravel/ai` version could change it. # Add an AI chat to a React app > Install @aparte/react, render and stream a model with useAparteClient, then hold the messages yourself, fill its slots and draw tool calls with your own components — in a React app, Next.js included. Tested in CI with React 19: in the example a browser drives, and in a Next 15 App Router page rendered on the server and hydrated. ## Install [Section titled “Install”](#install) ```bash npm install @aparte/react @aparte/core npm install @aparte/provider-scenario # a scripted model, to stream with no key ``` `@aparte/core`, `react` and `react-dom` are peer dependencies: React `^18.0.0 || ^19.0.0`. ## Render the chat [Section titled “Render the chat”](#render-the-chat) ```tsx import { aparteGlobalConfig } from '@aparte/core'; import { createScenarioProvider } from '@aparte/provider-scenario'; import { showcase } from '@aparte/provider-scenario/showcase'; import { AparteChat, useAparteClient } from '@aparte/react'; import '@aparte/core/styles.css'; aparteGlobalConfig.registerAIProvider(createScenarioProvider({ scenarios: showcase })); export function Chat() { useAparteClient(); return Ask me anything…

} />; } ``` That is a whole chat: `` keeps its own thread, and the client `useAparteClient` starts streams each reply into it from the scripted model — no state of yours, no key. In the Next App Router, put `'use client'` at the top of this file: hooks run in a client component — a server component can render `` itself, the package is a client boundary. Next renders it to HTML on the server, and the browser hydrates it with no mismatch: the elements wait until React has the page ([Hydration](/frameworks/elements/#hydration)). This is tested in CI: a Next 15 App Router page built for production, served, and checked in a browser. ## Hold the messages yourself [Section titled “Hold the messages yourself”](#hold-the-messages-yourself) ```tsx import { AparteChat, useAparteChat, useAparteClient } from '@aparte/react'; export function Chat() { const chat = useAparteChat(); useAparteClient(); return ; } ``` When the messages are yours to read or store, `useAparteChat` holds them and the component’s ref: hand both to ``. The person’s message is added when they send, so do not add it yourself; `onMessageSent` fires after, for a side effect. ## Stream a model [Section titled “Stream a model”](#stream-a-model) `useAparteClient` starts a client when the component mounts, stops it when it unmounts, and returns `{ client, abort }`. It takes the `AparteClientOptions` and reads them once, on the first render: a function option keeps the values it closed over then, so read live state from a ref inside it, and remount the component with a new `key` to change the options. For a real model, register its provider, name the model and give the key — `aparteGlobalConfig.setModelConfig({ defaultProvider: 'openrouter', defaultModel: 'openai/gpt-4o-mini' })` and `useAparteClient({ keyResolver })` ([Connect a model](/providers/)). A `config` prop gives one `` providers and a transport of its own; give its client the same one, `useAparteClient({ config })`. With the client running, turn on retry and edit with `aparteGlobalConfig.setBubbleActions({ retry: true, edit: true })` ([Buttons](/guides/customization/actions/)). ## Put your own UI in it [Section titled “Put your own UI in it”](#put-your-own-ui-in-it) ```tsx Ask me anything…

} toolbar={Shift + Enter for a new line} /> ``` | Prop | What it fills | | ----------------------- | ------------------------------------------------------------------------------------------------------------------------------- | | `emptyState` | the chat before the first message | | `aboveComposer` | the space above the composer | | `toolbar` | the composer’s bottom row, not drawn when you pass `composer` ([The composer toolbar](/guides/customization/composer-toolbar/)) | | `composer` | the composer, replaced by yours | | `renderBubble(message)` | each message, drawn by you ([Bubble](/guides/customization/bubble/#your-own-element-in-a-framework)) | The component takes these and no children. ## Your components in tool calls [Section titled “Your components in tool calls”](#your-components-in-tool-calls) ```tsx import { AparteToolUI } from '@aparte/react'; export function WeatherCards() { return ( name="get_weather"> {(tool) =>

{tool.input.city}: {tool.status === 'resolved' ? tool.result : 'looking it up…'}

}
); } ``` Mounted anywhere under your providers, `` draws every call to that tool with your component, through a portal — so the card reads your contexts — mounted once per call and updated in place, until it unmounts and the calls go back to core’s row. `` does the same for a segment type ([Your components in tool calls](/guides/tool-ui/)). ## Props and callbacks [Section titled “Props and callbacks”](#props-and-callbacks) ```tsx ``` The ones you reach for: `placeholder`, `disabled` and `submitOnEnter`; `centerWhenEmpty`; `loading`, for a wait of your own; `isTyping` and `typingText`, a waiting line you drive yourself; `overlayComposer`; `attachments`, off by default ([Attachments](/guides/attachments/)); `elicitation={false}` when you draw the questions yourself; `conversationId`, `config` and `layoutTransitionMs`, how long the list holds its layout after a conversation swap. The root takes `className` and `style`. `id` is the chat’s id, which every event carries: for two chats on one page, each answered by its own client, give each an `id` and its client `scopeToTargetId` with it. The callbacks — `onMessageSent`, `onAction`, `onMessagesChange`, `onMessageAppended`, `onTypingChange` and `onConversationCreated` — are beside the other frameworks’ in [Wrapper surface](/reference/wrappers/#callbacks). ## Control it from code [Section titled “Control it from code”](#control-it-from-code) `chat.ref`, and the helpers `useAparteChat` returns beside it, are the chat’s imperative API: `appendMessage`, `addSegment`, `injectTokenStream`, `scrollToBottom`, `focusInput` and the rest, to drive the chat from a loop of yours ([Your own loop](/guides/bring-your-own-loop/)). `useConversationManager()` lists, creates, archives and pins saved conversations once you call `init(adapter)` with your storage adapter — and the chat’s `config` as second argument, if it has one — and the chat switches between them through `conversationId` ([Save conversations](/guides/conversation-persistence/)). ## Any element, typed [Section titled “Any element, typed”](#any-element-typed) ```tsx GPT-4o mini ``` Importing from `@aparte/react` types every element of core as JSX: the attribute names are the HTML ones, a presence attribute takes `''` to be on and `null` or `undefined` to be off, and events are read by ref, typed through the DOM ([Elements, typed](/frameworks/elements/)). A plugin’s element is typed by the plugin, and one of yours by you ([your own element](/frameworks/elements/#your-own-element-or-a-plugins)). `` mounts any tag and sets its props; it forwards core’s events, so name your element’s own in `events`. A ref to it gives `getElement()` and `callMethod(name, ...args)`: ```tsx setCount(e.detail)} /> ``` ## Tests [Section titled “Tests”](#tests) Vitest runs on Node, where `@aparte/core` resolves to its entry without elements, so a tag never upgrades under jsdom: alias it to `@aparte/core/browser` ([Testing your components](/frameworks/elements/#testing-your-components)). A whole chat site in React — the conversation sidebar, the header, settings, tools and the scripted model — is [the React example](https://github.com/apartejs/aparte/tree/main/apps/examples/react). ## Next [Section titled “Next”](#next) * [Elements, typed Any element in React, with its attributes and events checked.](/frameworks/elements/) * [Wrapper surface Every slot and callback, beside the other three frameworks.](/reference/wrappers/) # Add an AI chat to a Svelte app > Install @aparte/svelte, render from @aparte/svelte/runes and stream a model with createAparteClient, then bind its messages, fill its snippets and draw tool calls with your own components — on Svelte 5, SvelteKit included, with the Svelte 4 component beside it. Tested in CI with Svelte 4 and 5: in the two examples a browser drives, and in a SvelteKit 2 page rendered on the server and hydrated. ## Install [Section titled “Install”](#install) ```bash npm install @aparte/svelte @aparte/core npm install @aparte/provider-scenario # a scripted model, to stream with no key ``` `@aparte/core` and `svelte` are peer dependencies: Svelte `^4.0.0 || ^5.20.0`. The package ships its `.svelte` sources, which your build compiles. On Svelte 5, import from `@aparte/svelte/runes` — props, snippets, `bind:messages` and callback props, written in runes (Svelte `^5.20.0`). The package root keeps the component written in Svelte 4’s syntax, which runs on both majors ([Svelte 4](#svelte-4)). ## Render the chat [Section titled “Render the chat”](#render-the-chat) ```svelte {#snippet emptyState()}

Ask me anything…

{/snippet}
``` That is a whole chat: `` keeps its own thread, and the client `createAparteClient` starts streams each reply into it from the scripted model — no state of yours, no key. The module script runs once, however many times the component mounts. ## Hold the messages yourself [Section titled “Hold the messages yourself”](#hold-the-messages-yourself) ```svelte ``` When the messages are yours to read or store, `bind:messages` keeps your state in step with what the chat does, and a write of yours — a new array, or a `push` — reaches the transcript. The person’s message is added when they send, so do not add it yourself; `onmessageSent` fires after, for a side effect. ## Stream a model [Section titled “Stream a model”](#stream-a-model) `createAparteClient` starts a client when the component mounts, stops it when it is destroyed, and returns `{ client, abort }`; it takes the `AparteClientOptions`. For a real model, register its provider, name the model and give the key — `aparteGlobalConfig.setModelConfig({ defaultProvider: 'openrouter', defaultModel: 'openai/gpt-4o-mini' })` and `createAparteClient({ keyResolver })` ([Connect a model](/providers/)). A `config` prop gives one `` providers and a transport of its own; give its client the same one, `createAparteClient({ config })`. With the client running, turn on retry and edit with `aparteGlobalConfig.setBubbleActions({ retry: true, edit: true })` ([Buttons](/guides/customization/actions/)). ## Callbacks [Section titled “Callbacks”](#callbacks) Each callback — `onmessageSent`, `onaction`, `onmessagesChange`, `onmessageAppended`, `ontypingChange`, `onconversationCreated` — is a prop that gets the payload itself: `onconversationCreated={(id) => goto('/chat/' + id)}`. The names are the ones Svelte’s own migration gives a `dispatch('messageSent')`: `on`, then the event. ## Put your own UI in it [Section titled “Put your own UI in it”](#put-your-own-ui-in-it) ```svelte {#snippet emptyState()}

Ask me anything…

{/snippet} {#snippet toolbar()}Shift + Enter for a new line{/snippet} {#snippet bubble(message)}{/snippet}
``` | Snippet | What it fills | | ----------------- | ------------------------------------------------------------------------------------------------------------------------------- | | `emptyState` | the chat before the first message | | `aboveComposer` | the space above the composer | | `toolbar` | the composer’s bottom row, not drawn when you fill `composer` ([The composer toolbar](/guides/customization/composer-toolbar/)) | | `composer` | the composer, replaced by yours | | `bubble(message)` | each message, drawn by you ([Bubble](/guides/customization/bubble/#your-own-element-in-a-framework)) | ## Your components in tool calls [Section titled “Your components in tool calls”](#your-components-in-tool-calls) ```svelte {#snippet children(tool)}{/snippet} ``` Mounted anywhere in your app, `` draws every call to that tool with your snippet, mounted with the contexts of where you declare it — so `getContext` finds what your app set there — once per call and updated in place, until it unmounts and the calls go back to core’s row. `` does the same for a segment type ([Your components in tool calls](/guides/tool-ui/)). ## Props [Section titled “Props”](#props) ```svelte ``` The ones you reach for: `placeholder`, `disabled` and `submitOnEnter`; `centerWhenEmpty`; `loading`, for a wait of your own; `isTyping` and `typingText`, a waiting line you drive yourself; `overlayComposer`; `attachments`, off by default ([Attachments](/guides/attachments/)); `elicitation={false}` when you draw the questions yourself; `conversationId`, `config` and `layoutTransitionMs`, how long the list holds its layout after a conversation swap. The root takes `class` and a `style` string. `id` is the chat’s id, which every event carries: for two chats on one page, each answered by its own client, give each an `id` and its client `scopeToTargetId` with it ([Wrapper surface](/reference/wrappers/)). ## Control it from code [Section titled “Control it from code”](#control-it-from-code) ```svelte ``` Bound, the component is the chat’s imperative API — `appendMessage`, `addSegment`, `injectTokenStream`, `scrollToBottom`, `focusInput`, `setConversationId` and the rest — to drive the chat from a loop of yours ([Your own loop](/guides/bring-your-own-loop/)). `createConversations()` lists, creates, archives and pins saved conversations as reactive state once you call `init(adapter)` with your storage adapter, and the chat switches between them through `conversationId` ([Save conversations](/guides/conversation-persistence/)). ## Any element, typed [Section titled “Any element, typed”](#any-element-typed) ```svelte (model = e.detail.value)}> GPT-4o mini ``` Importing from `@aparte/svelte` declares every element of core in `SvelteHTMLElements`, so `svelte-check` covers its attributes and its event attributes: a presence attribute takes `''` to be on and `null` to be off ([Elements, typed](/frameworks/elements/)). A plugin’s element is typed by the plugin, and one of yours by you ([your own element](/frameworks/elements/#your-own-element-or-a-plugins)). `` mounts any tag and sets its props; it forwards core’s events, so name your element’s own in `events`: ```svelte (count = e.detail)} /> ``` `onelementEvent` gets the element’s own event. Bound, it gives `ui.getElement()` and `ui.callMethod(name, ...args)`. ## SvelteKit and tests [Section titled “SvelteKit and tests”](#sveltekit-and-tests) Under SvelteKit, render the chat with server rendering on: the server sends its HTML, and the browser hydrates it with no mismatch — the elements wait until Svelte has the page ([Hydration](/frameworks/elements/#hydration)). Register your provider in the page’s `

Ask me anything…

``` The package root stays this component, with `createAparteChat()` and `createConversationManager()` for it. The runes version of everything here lives in `@aparte/svelte/runes`: on Svelte 5, start there. ## Next [Section titled “Next”](#next) * [Elements, typed Any element in Svelte, with its attributes and events checked.](/frameworks/elements/) * [Wrapper surface Every slot and callback, beside the other three frameworks.](/reference/wrappers/) # Add an AI chat to a Vue app > Install @aparte/vue, render and stream a model with useAparteClient, then bind v-model:messages, fill its slots and draw tool calls with your own components — in a Vue app, Nuxt included. Tested in CI with Vue 3.5: in the example a browser drives, and in a Nuxt 3 page rendered on the server and hydrated. ## Install [Section titled “Install”](#install) ```bash npm install @aparte/vue @aparte/core npm install @aparte/provider-scenario # a scripted model, to stream with no key ``` ```ts // vite.config.ts — the aparte-* tags are custom elements, not Vue components import vue from '@vitejs/plugin-vue'; import { defineConfig } from 'vite'; import { isAparteElement } from '@aparte/vue'; export default defineConfig({ plugins: [vue({ template: { compilerOptions: { isCustomElement: isAparteElement } } })], }); ``` `@aparte/core` and `vue` are peer dependencies: Vue `^3.5.0`. `isAparteElement` keeps Vue from resolving an `aparte-*` tag as a component of yours; under Nuxt it goes in `nuxt.config.ts`, as `vue.compilerOptions.isCustomElement`. Write the wrapper’s own components in PascalCase — ``: Vue reads `` as `AparteToolUi`, which does not exist, and you get its warning rather than an inert element. ## Render the chat [Section titled “Render the chat”](#render-the-chat) ```ts // main.ts — registered once, before the app mounts import { createApp } from 'vue'; import { aparteGlobalConfig } from '@aparte/core'; import { createScenarioProvider } from '@aparte/provider-scenario'; import { showcase } from '@aparte/provider-scenario/showcase'; import '@aparte/core/styles.css'; import App from './App.vue'; aparteGlobalConfig.registerAIProvider(createScenarioProvider({ scenarios: showcase })); createApp(App).mount('#app'); ``` ```vue ``` That is a whole chat: `` keeps its own thread, and the client `useAparteClient` starts streams each reply into it from the scripted model — no state of yours, no key. ## Hold the messages yourself [Section titled “Hold the messages yourself”](#hold-the-messages-yourself) ```vue ``` When the messages are yours to read or store, bind `v-model:messages` to a ref of yours — or use `useAparteChat()`, which holds them with the component’s ref (`:ref="chat.chatRef"`, `:messages="chat.messages.value"`, `@messages-change="chat.onMessagesChange"`). The person’s message is added when they send, so do not add it yourself; `@message-sent` fires after, for a side effect. ## Stream a model [Section titled “Stream a model”](#stream-a-model) `useAparteClient` starts a client when the component mounts, stops it before it unmounts, and returns `{ client, abort }`; it takes the `AparteClientOptions`. For a real model, register its provider, name the model and give the key — `aparteGlobalConfig.setModelConfig({ defaultProvider: 'openrouter', defaultModel: 'openai/gpt-4o-mini' })` and `useAparteClient({ keyResolver })` ([Connect a model](/providers/)). A `config` prop gives one `` providers and a transport of its own; give its client the same one, `useAparteClient({ config })`. With the client running, turn on retry and edit with `aparteGlobalConfig.setBubbleActions({ retry: true, edit: true })` ([Buttons](/guides/customization/actions/)). ## Put your own UI in it [Section titled “Put your own UI in it”](#put-your-own-ui-in-it) ```vue ``` | Slot | What it fills | | ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------- | | `empty-state` | the chat before the first message | | `above-composer` | the space above the composer | | `toolbar` | the composer’s bottom row, not drawn when you fill `composer` ([The composer toolbar](/guides/customization/composer-toolbar/)) | | `composer` | the composer, replaced by yours | | `bubble`, with `{ message }` | each message, drawn by you ([Bubble](/guides/customization/bubble/#your-own-element-in-a-framework)) | Content outside these slots is not drawn. ## Your components in tool calls [Section titled “Your components in tool calls”](#your-components-in-tool-calls) ```vue ``` Mounted anywhere in your app, `` draws every call to that tool with your component, teleported into the call — so `inject` reads what your app provides around it — mounted once per call and updated in place, until it unmounts and the calls go back to core’s row. `` does the same for a segment type ([Your components in tool calls](/guides/tool-ui/)). ## Props and events [Section titled “Props and events”](#props-and-events) ```vue ``` The ones you reach for: `placeholder`, `disabled` and `submit-on-enter`; `center-when-empty`; `loading`, for a wait of your own; `is-typing` and `typing-text`, a waiting line you drive yourself; `overlay-composer`; `attachments`, off by default ([Attachments](/guides/attachments/)); `:elicitation="false"` when you draw the questions yourself; `conversation-id`, `config` and `layout-transition-ms`, how long the list holds its layout after a conversation swap. `class` and `style` fall through to the root. `id` is the chat’s id, which every event carries: for two chats on one page, each answered by its own client, give each an `id` and its client `scopeToTargetId` with it. The events — `@message-sent`, `@action`, `@messages-change` (and `update:messages`, for `v-model`), `@message-appended`, `@typing-change` and `@conversation-created` — hand you the payload itself ([Wrapper surface](/reference/wrappers/#callbacks)). ## Control it from code [Section titled “Control it from code”](#control-it-from-code) `chat.chatRef`, and the methods `useAparteChat` returns beside it, are the chat’s imperative API: `appendMessage`, `addSegment`, `injectTokenStream`, `scrollToBottom`, `focusInput` and the rest, to drive the chat from a loop of yours ([Your own loop](/guides/bring-your-own-loop/)). `useConversationManager()` lists, creates, archives and pins saved conversations once you call `init(adapter)` with your storage adapter — and the chat’s `config` as second argument, if it has one — and the chat switches between them through `conversation-id` ([Save conversations](/guides/conversation-persistence/)). ## Any element, typed [Section titled “Any element, typed”](#any-element-typed) ```vue ``` Importing from `@aparte/vue` declares every element of core in `GlobalComponents`, so `vue-tsc` checks its attributes in any template: a presence attribute takes `''` to be on and `null` to be off ([Elements, typed](/frameworks/elements/)). A plugin’s element is typed by the plugin, and one of yours by you ([your own element](/frameworks/elements/#your-own-element-or-a-plugins)). `` mounts any tag and sets its props; it forwards core’s events, so name your element’s own in `events`: ```vue ``` ## Nuxt and tests [Section titled “Nuxt and tests”](#nuxt-and-tests) Under Nuxt, render the chat in a page as it is: the server sends its HTML, and the browser hydrates it with no mismatch — the elements wait until Vue has the page ([Hydration](/frameworks/elements/#hydration)). Start the client in a plugin that runs in the browser only (`plugins/aparte.client.ts`, `new AparteClient().start()` after registering your provider), and give `nuxt.config.ts` `vue.compilerOptions.isCustomElement: isAparteElement`. This is tested in CI: a Nuxt 3 page built for production, served by its server, and checked in a browser. `@aparte/core` imports on a server through its entry without elements ([On the server](/frameworks/elements/#on-the-server)). Vitest runs on Node, so alias `@aparte/core` to `@aparte/core/browser` for the elements to upgrade ([Testing your components](/frameworks/elements/#testing-your-components)). A whole chat site in Vue — the conversation sidebar, the header, settings, tools and the scripted model — is [the Vue example](https://github.com/apartejs/aparte/tree/main/apps/examples/vue). ## Next [Section titled “Next”](#next) * [Elements, typed Any element in Vue, with its attributes checked.](/frameworks/elements/) * [Wrapper surface Every slot and event, beside the other three frameworks.](/reference/wrappers/) # Accessibility > What the chat does for keyboard and screen-reader users, what it leaves to your page, and what is tested. ## What a screen reader hears [Section titled “What a screen reader hears”](#what-a-screen-reader-hears) | Part | Role | Name | | ----------------------------------------- | ------------------------------------------- | ------------------------------------------------------------------------------------------------------- | | The message list | `log`, `aria-live="polite"`, and a tab stop | ”Transcript” | | A message | `article` | ”Message from Camille” when the bubble’s `name` is Camille, else “Your message” or “Assistant response” | | A message’s buttons | `toolbar` | ”Message actions” | | A reply still waiting for its first words | hidden text in its waiting dots | ”Typing” | | Your status line, `` | `status`, `aria-live="polite"` | its `text`, else “Typing” | | The composer’s input | `textbox`, `aria-multiline="true"` | its placeholder | While a reply streams, its message is marked busy, so a screen reader reads it once it is complete, and a reply still waiting says a turn is in progress rather than leaving a silence. Moving to another version of a reply is announced without taking the focus. Every name the chat writes itself comes from the locale, so it follows the language ([Translation](/guides/localization/)), and a key the locale leaves out reads in English; the status line’s name is the text you give it. ## Keyboard [Section titled “Keyboard”](#keyboard) | Where | Keys | | --------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | The composer | `Enter` sends, `Shift`+`Enter` starts a new line; `submit-on-enter="false"` (`submitOnEnter={false}` on the framework components) swaps them; while a reply streams, `Enter` keeps the draft | | A one-line field in a question or an approval | `Enter` sends what is written, and `submit-on-enter="false"` makes it `Shift`+`Enter`; in an approval’s instruction the other key starts a new line, and a multi-line answer keeps `Enter` for its next line | | A message’s buttons | one tab stop: `←` `→` move between them, mirrored right-to-left, `Home` `End` jump to the ends | | A select | `Enter`, `Space` or `↓` opens, `↓` `↑` move, `Home` `End` jump to the ends — in a searchable select, they move in its filter field — `Enter` chooses, `Escape` closes | | A conversation’s menu | `↓` `↑` move and wrap, `Home` `End`, `Escape` closes, `Tab` leaves for the button that opened it | | A split’s seam | arrows move it a step (up and down on a vertical split), `Shift` with an arrow a larger one, `Home` `End` to the ends, `Enter` folds the primary pane and a second `Enter` restores it | | The sidebar as a drawer | its toggle opens it with the focus inside, and `Tab` stays inside while it is open; `Escape` closes it and gives the focus back | A [select](/components/select/) is a combobox: `aria-expanded`, `aria-controls` and `aria-activedescendant` sit on the element that has the focus, which is its filter field when it is `searchable`. A [conversation](/components/conversation-list/)’s row is a button that opens it, beside a ⋯ button that opens its menu; asking before a delete turns that menu into a dialog named by the question. The [split](/components/split/)’s arrows follow the reading direction. ## Focus, motion, contrast and touch [Section titled “Focus, motion, contrast and touch”](#focus-motion-contrast-and-touch) * **Focus.** Every control shows a ring on keyboard focus (`:focus-visible`): 2px wide, 2px outside the control (`--aparte-focus-outline-width`, `--aparte-focus-outline-offset`), the thickness WCAG 2.2 asks of a focus indicator, drawn in `--aparte-border-focus`, which follows `--aparte-neutral`. A design that wants it quieter narrows it everywhere at once: ```css :root { --aparte-focus-outline-width: 1px; --aparte-focus-outline-offset: 0px; } ``` * **Motion.** Under `prefers-reduced-motion`, the duration tokens drop to near zero, so the chat’s transitions and animations stop, and so do yours where they read those tokens. What is happening is still announced. * **Contrast.** Under forced colours, as in Windows High Contrast mode, a part drawn only by its fill gets a border. * **Touch.** On a coarse pointer, the composer’s controls, the message buttons, the scroll button, a conversation’s ⋯ and a split’s grab zone grow to `--aparte-touch-target-size`; the message buttons, a pending file’s ✕ and every attachment’s file name stay shown instead of waiting for a hover, and the scroll rail is hidden. ## What you add [Section titled “What you add”](#what-you-add) * **A name for each chat**, when a page has more than one, so a reader knows which transcript they are in: wrap each in a landmark, `
`. The chat element has no role of its own, so a name set on it alone is not read. * **A translated label for each action you register.** `registerAction({ id, icon, label, zones })` writes `label` as the button’s name as given, without the locale: register the action again with the new label when the language changes. * **Roles for the kit’s neutral classes.** `.aparte-menu`, `.aparte-accordion`, `.aparte-popover` and `.aparte-tooltip` draw a surface; `role="menu"`, `menuitem`, `tooltip` and the keys those patterns need are yours. The conversation list’s row menu is a complete one to copy. * **Arrow keys across a long conversation list**, if you want them: every row is in the tab order, with no roving `tabindex`. * **A name in what a render hook returns.** An element with `textContent` carries it; a string of markup must carry it too ([Render hooks](/guides/customization/render-hooks/)). * **Your page around the chat**: headings, landmarks, a skip link. ## What is tested [Section titled “What is tested”](#what-is-tested) An axe suite runs in a real browser, in Chromium, WebKit, Firefox, and fails on any serious or critical violation, in each of these states: an idle chat, a streamed exchange, an open model menu, a turn in flight, and a failed turn. One more test reaches the composer, fills it and sends with the keyboard alone. axe sees what a machine can. Whether your labels say something useful, and whether your page reads in a sensible order, takes a person using your app. ## Next [Section titled “Next”](#next) * [Translation The locale every name on this page comes from.](/guides/localization/) * [Customization Your own parts of the chat, and the names they carry.](/guides/customization/) # Let people attach files and send them to the model > Show the paperclip, read the files when the message is sent, choose what reaches the model, and open an image full size. [A composer with files attached](/preview/demo/composer-attachments/) ```html
``` Files waiting in the composer, before the message is sent. ## Show the paperclip [Section titled “Show the paperclip”](#show-the-paperclip) * Vanilla ```html ``` * React ```tsx ``` * Vue ```vue ``` * Svelte ```svelte ``` * Angular ```html ``` The chat has no paperclip until you set `attachments`: set it when something reads the files — `AparteClient` does, and so does a loop of yours that reads them on send. It adds the button and the row of files waiting to go. In a composer you write yourself, place the two elements where you want them, and choose what the file dialog offers: ```html
``` `accept` and `multiple="false"` shape the file dialog only: a drop or a paste can still add other types and more files, and each pick adds to the files already waiting. To hold a limit, watch `aparte-composer-change` and call `removeAttachment`, below. ## Read the files on send [Section titled “Read the files on send”](#read-the-files-on-send) * Vanilla ```ts document.querySelector('aparte-chat')?.addEventListener('aparte-send', (event) => { const { content, files } = event.detail; // files: File[] | undefined }); ``` * React ```tsx { if (detail.files) upload(detail.files); }} /> ``` * Vue ```vue ``` * Svelte ```svelte { if (e.detail.files) upload(e.detail.files); }} /> ``` * Angular ```html ``` The files leave with the message, on `aparte-send`. React, Vue and Angular hand you its detail; Svelte’s `on:messageSent` hands you an event, as the DOM does, hence `e.detail`. To follow the files while they wait — to enable a button, say — listen for `aparte-composer-change`, whose `detail.state.attachments` is the current list. The composer element also takes them from code: `addAttachments(files)`, `removeAttachment(file)`, `clearAttachments()`, and `attachments` to read them. ## What the model receives [Section titled “What the model receives”](#what-the-model-receives) ```ts import { AparteClient } from '@aparte/core'; new AparteClient({ rawFileInject: 'all', // or 'images-only', or 'none' fileInjectFilter: (file) => !/(^|\.)env$|\.(pem|key)$/i.test(file.name), }).start(); ``` `AparteClient` puts the files into the request itself: * **an image** goes as an image part, for a model that reads images; * **a text file** — Markdown, JSON, CSV, source code, a log, an `.env` — is read in the browser and goes **in full**, under a `// File: name` line; * **anything else**, a PDF or a spreadsheet, does not go: the file stays on screen and on the send event for an upload of yours, and the console says so once per file name. `'images-only'` sends the images alone, and `'none'` sends no file, for an app that uploads them or retrieves what it needs from them itself. `fileInjectFilter` is called for each file the mode lets through — every file, in `'all'` — and `false` keeps that one out: the example keeps out `.env`, `.pem` and `.key` files, and yours can test whatever your users might attach by mistake. The files go with that one request: on the next turns, a retry included, the history carries the message’s text, not its files, so keep what the model needs in your app — an upload, a retrieval step. Whether the model reads an image depends on the [provider](/providers/) and the model. ## With your own loop [Section titled “With your own loop”](#with-your-own-loop) ```ts import { filesToAttachments } from '@aparte/core'; const chat = document.querySelector('aparte-chat'); chat?.addEventListener('aparte-send', (event) => { const { content, files } = event.detail; chat.viewport?.appendMessage({ id: crypto.randomUUID(), role: 'user', content, timestamp: Date.now(), ...(files?.length ? { attachments: filesToAttachments(files) } : {}), }); }); ``` This is for plain HTML without `AparteClient`: the client and the framework packages already add the person’s message with its files, so do not append it again there. `filesToAttachments` turns the sent files into the `attachments` a message shows. Call `appendMessage` on the message list, `chat.viewport`, not on the chat itself. ## Open an image full size [Section titled “Open an image full size”](#open-an-image-full-size) ```ts import { aparteGlobalConfig } from '@aparte/core'; declare function openLightbox(url: string, name: string): void; aparteGlobalConfig.setHostHandlers({ attachmentPreview: true }); document.addEventListener('aparte-attachment-preview', (event) => { openLightbox(event.detail.url, event.detail.name); }); ``` [A chat that accepts files](/preview/demo/attachments-chat/) ```html ``` Files on a sent message: an image tile and a file chip. Once you say you open them, an image becomes a button, by click, `Enter` or `Space`, that sends `aparte-attachment-preview` with its `url` and `name`; until then it is a picture, with no pointer and no tab stop. Core draws no lightbox: the view is yours. A chat with its own configuration takes `setHostHandlers` on that configuration. ## Open a file [Section titled “Open a file”](#open-a-file) A file in a sent message — a PDF, a spreadsheet — opens the same way, under its own declaration, so a lightbox written for images is never handed a PDF. The event carries the file’s `type`: ```ts import { aparteGlobalConfig } from '@aparte/core'; aparteGlobalConfig.setHostHandlers({ filePreview: true }); document.addEventListener('aparte-attachment-preview', (event) => { if (!event.detail.type.startsWith('image/')) window.open(event.detail.url, '_blank', 'noopener'); }); ``` Only a file whose URL a tab can open becomes a button: the object URL the composer made for it, or a remote URL. A `data:` URL stays a plain tile, since a browser refuses to open one in a tab. ## Drag, drop and paste [Section titled “Drag, drop and paste”](#drag-drop-and-paste) A file dropped anywhere on the composer attaches. While a file is dragged over it, the composer carries `aparte-is-dragover`, and its outline follows your theme. Drag and drop comes with the paperclip button, so a composer without the button takes no drop. A `disabled` composer takes no drop and greys the button; a composer streaming a reply still takes files. An image pasted into the input attaches too, on the same condition: a composer with the button takes it, one without takes nothing. ## Release memory and save the files [Section titled “Release memory and save the files”](#release-memory-and-save-the-files) ```ts import { revokeAttachmentUrls, type AparteMessage } from '@aparte/core'; function forget(messages: AparteMessage[]): void { for (const message of messages) revokeAttachmentUrls(message.attachments); } ``` Each attachment’s `url` keeps its file in memory for as long as the page lives. When attachments leave the screen for good, `revokeAttachmentUrls` lets the memory go; calling it twice is harmless, and the message list’s `clearAll()` does it for the messages it drops. The file itself stays on the attachment as `blob`: your storage adapter saves it as an `AparteAttachmentRow`, with its conversation and message ids, and builds a new `url` when it loads the message ([Save conversations](/guides/conversation-persistence/#what-comes-back-after-a-reload)). ## Next [Section titled “Next”](#next) * [Attachments The tiles and chips, in the composer and on a message.](/components/attachments/) * [Composer Every part of the composer, the paperclip among them.](/components/composer/) * [Your own loop Send the files to a model yourself.](/guides/bring-your-own-loop/) # Keep the key on your server > Send each request through your own /api/chat — the page names a provider, your server holds the key, calls the model and streams the reply back — with the chat unchanged. ## Write the route [Section titled “Write the route”](#write-the-route) ```bash npm install @aparte/core @aparte/provider-openai-compat ``` ```ts // app/api/chat/route.ts (Next.js) import { createAparteChatHandler } from '@aparte/core'; import { createOpenAICompatProvider, presets } from '@aparte/provider-openai-compat'; declare function getSession(req: Request): Promise<{ userId: string } | null>; // your session lookup export const POST = createAparteChatHandler({ providers: { openai: createOpenAICompatProvider(presets.OPENAI) }, resolveKey: (providerId) => process.env[`${providerId.toUpperCase()}_KEY`], authorize: async (req) => Boolean(await getSession(req)), // required: this route spends your key }); ``` `createAparteChatHandler` returns a Fetch handler, `Request` to `Response`, for a Next.js route in the Node runtime, Node, Deno or Bun. It reads `{ providerId, request }`, runs that provider on the server — the request, the key, the vendor call, the stream — and streams the reply back as NDJSON, one event per line; a request with `stream: false` gets a `{ text }` body. On those runtimes `@aparte/core` resolves to its `node` entry, which has no DOM ([On the server](/frameworks/elements/#on-the-server)), and so does it in a Cloudflare Worker or on a Vercel edge route. | Option | What it does | | ------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `providers` | the providers, keyed by the `providerId` the page sends: an unknown id is a 400, a provider that is not a [format adapter](/providers/#write-your-own-provider) a 500 | | `authorize(req)` | required, run before anything else: `false` answers 401, a `Response` answers itself, `true` goes on | | `resolveKey(providerId)` | the vendor key, from your environment or a secret store; `undefined` for a keyless server | | `allowedOrigins` | the origins of your pages, such as `['https://app.example.com']`: a request from any other `Origin` is refused with a 403, before `authorize` | | `fetchImpl` | the `fetch` that calls the vendor | These are the `AparteChatHandlerOptions`. authorize has to authenticate `Boolean(req.headers.get('cookie'))` passes any request that carries any cookie, a cross-site one included, and the route then spends your key for anyone who can load it. Call the session lookup that guards your other routes. A page on another site can post to this route It does so with your visitor’s cookie, in a form that needs no preflight. The handler refuses any body not declared `application/json` with a 415, which such a form cannot send, before it calls `authorize`. For a cookie session also set `SameSite=Lax` or `Strict`, and list your pages in `allowedOrigins`. ## What the route accepts [Section titled “What the route accepts”](#what-the-route-accepts) The page sends a `providerId`, never a URL: the vendor’s address comes from the provider in your map, so no request can point your server at another host. A vendor’s error keeps its status, and its body reaches the page as `{ error: { message, code?, type? } }`, without the vendor’s own text. The rest of the request is the page’s: `modelId`, the messages, the system prompt, the tools and `maxTokens` reach the provider as sent, so `authorize` decides who calls the route, not what they send. To limit the models or the size, check the body in a wrapper of yours, or in `authorize` through `req.clone().json()`: clone it, because the handler reads the body itself. ## Point the page at it [Section titled “Point the page at it”](#point-the-page-at-it) ```ts import { aparteGlobalConfig, AparteClient, AparteBackendTransport } from '@aparte/core'; import { createOpenAICompatProvider, presets } from '@aparte/provider-openai-compat'; aparteGlobalConfig.registerAIProvider(createOpenAICompatProvider(presets.OPENAI)); // the id the route knows, no key aparteGlobalConfig.setTransport(new AparteBackendTransport({ endpoint: '/api/chat' })); aparteGlobalConfig.setModelConfig({ defaultProvider: 'openai', defaultModel: 'gpt-4.1-mini' }); new AparteClient().start(); ``` The page posts `{ providerId, request }` to your route and streams the reply into the chat; no key is in it. Register a provider under each id the route knows: the page reads what a model can do from it, and refuses to send to an id it does not have. `BackendTransportOptions` takes the `endpoint`, `headers` sent with every request, and `buildBody(request, providerId)` for a route that expects another body. A cookie goes along only to a route on the page’s own origin, so a route on another origin is authenticated through `headers`. Nothing of that provider runs in the page: no request is built from it and its `chat()` is never called. For an id no client package exists for, a stub that lists the models is enough: ```ts import { aparteGlobalConfig } from '@aparte/core'; aparteGlobalConfig.registerAIProvider({ id: 'internal', getMetadata: () => ({ id: 'internal', name: 'Internal' }), getModels: () => [{ id: 'house-model', name: 'House model', capabilities: ['streaming', 'function_calling'] }], chat: () => { throw new Error('runs on the server'); }, }); ``` The tools and the loop stay in the page: the route makes one model call at a time. When the tools live on your server, move the loop there too, with [the server loop](/guides/server-loop/). ## If your server already uses the AI SDK [Section titled “If your server already uses the AI SDK”](#if-your-server-already-uses-the-ai-sdk) ```bash npm install @aparte/core @aparte/provider-ai-sdk ai @ai-sdk/anthropic ``` ```ts // app/api/chat/route.ts (Next.js) — the AI SDK on your server, aparté in the page import { createAnthropic } from '@ai-sdk/anthropic'; import { streamText } from 'ai'; import type { AparteChatRequest, AparteStreamEvent } from '@aparte/core'; import { fullStreamToAparteEvents, toModelMessages, toToolChoice, toToolSet } from '@aparte/provider-ai-sdk'; declare function getSession(req: Request): Promise<{ userId: string } | null>; // your session lookup const MODELS = ['claude-sonnet-4-5', 'claude-haiku-4-5']; export async function POST(req: Request): Promise { if (!(await getSession(req))) return new Response('Unauthorized', { status: 401 }); const { request } = (await req.json()) as { request: AparteChatRequest }; if (!MODELS.includes(request.modelId)) return new Response('Unknown model', { status: 400 }); const result = streamText({ model: createAnthropic({ apiKey: process.env['ANTHROPIC_API_KEY'] })(request.modelId), messages: toModelMessages(request.messages), temperature: request.temperature, maxOutputTokens: request.maxTokens, seed: request.seed, abortSignal: req.signal, ...(request.tools?.length ? { tools: toToolSet(request.tools), toolChoice: toToolChoice(request.toolChoice) ?? 'auto' } : {}), }); if (request.stream === false) { try { return Response.json({ text: await result.text }); } catch (err) { console.error('[api/chat] vendor request failed', err); return Response.json({ error: { message: 'Vendor request failed.' } }, { status: 502 }); } } const ndjson = fullStreamToAparteEvents(result.fullStream) .pipeThrough(new TransformStream({ transform: (event, controller) => { if (event.type === 'error') { console.error('[api/chat] vendor stream error', event.message); // the vendor's words stay in your log controller.enqueue({ type: 'error', message: 'Vendor request failed.' }); return; } controller.enqueue(event); }, })) .pipeThrough(new TransformStream({ transform: (event, controller) => controller.enqueue(`${JSON.stringify(event)}\n`), })) .pipeThrough(new TextEncoderStream()); return new Response(ndjson, { headers: { 'content-type': 'application/x-ndjson' } }); } ``` ```ts import { aparteGlobalConfig, AparteClient, AparteBackendTransport } from '@aparte/core'; import { createAiSdkProvider } from '@aparte/provider-ai-sdk'; // The id the page sends, and what the model can do; the call itself is the route's. aparteGlobalConfig.registerAIProvider(createAiSdkProvider({ id: 'anthropic', name: 'Anthropic', languageModel: () => { throw new Error('This provider runs on the server.'); }, })); aparteGlobalConfig.setTransport(new AparteBackendTransport({ endpoint: '/api/chat' })); aparteGlobalConfig.setModelConfig({ defaultProvider: 'anthropic', defaultModel: 'claude-sonnet-4-5' }); new AparteClient().start(); ``` The handler above runs format adapters, and the [AI SDK bridge](/providers/ai/ai-sdk/) is not one: it makes its own call through `streamText`. Its four helpers make the same route by hand — `toModelMessages` and `toToolChoice` translate the request, `toToolSet` gives the SDK the tools as declarations, which the page’s loop runs, and `fullStreamToAparteEvents` turns the SDK’s stream into the events the page reads. The page registers a provider under the id it sends and names one of the route’s models; its `languageModel` is never called, since the route makes the call. Two things in this route are what the handler does for you: the vendor’s error replaced before it leaves the server, and the `{ text }` answer to a request with `stream: false`. The check on the model is one the handler does not make; add it to either route. ## Write the stream yourself [Section titled “Write the stream yourself”](#write-the-stream-yourself) ```text {"type":"text","delta":"Hel"} {"type":"text","delta":"lo."} {"type":"done","usage":{"inputTokens":12,"outputTokens":3,"totalTokens":15}} ``` A route of your own answers `AparteBackendTransport` with NDJSON, one `AparteStreamEvent` per line — aparté’s events, not the AI SDK’s data stream protocol. `parseAparteEventStream(body)` reads that stream back into events. A transport of your own is set with `aparteGlobalConfig.setTransport`, like the two built in ([`AparteTransport`](/reference/core/transports/#apartetransport)). ## Next [Section titled “Next”](#next) * [Connect a model The providers your route's map takes.](/providers/) * [Run the loop on your server The tools on your server too, next to the loop.](/guides/server-loop/) # Blocks in a text answer > A backend that only sends text can still send a card or quick replies — a code block whose language names it. Cards, suggestions, and your own. Some backends send only text: a workflow engine that runs its tools itself (n8n), a server that streams its answer and nothing else, a model with no tools. Their answer can still put something richer than prose on screen, with one rule: > **A code block whose language aparté knows becomes part of the interface. Any other is shown as code.** ````md Which day suits you? ```suggestions ["Tuesday 3", "Wednesday 4", "Thursday 5"] ``` ```` The block’s body is JSON, written by your backend — build it from your tool’s real result (in n8n, a **Code** node) rather than asking a model to type JSON: it is exact every time. A chat that does not know the language, an email, or a model reading the history back sees the sentence and the block, which still reads as what it is. ## The languages aparté knows [Section titled “The languages aparté knows”](#the-languages-aparté-knows) | Language | What it becomes | Turn it on | | ------------- | --------------------------------------------------------------- | -------------------------------------------------------------------------- | | `card-` | that card: `card-order`, `card-place`, `card-weather`, your own | `setupCardFences()` — [cards](/guides/cards/#a-card-written-in-the-answer) | | `suggestions` | quick replies above the composer, for the person to click | `setupSuggestionBlocks()` | Each is off until you turn it on: once on, the block is no longer shown as code, so it is the app’s choice. ## Quick replies — `suggestions` [Section titled “Quick replies — suggestions”](#quick-replies--suggestions) The replies the **last** answer offers, as buttons above the composer: the free times of a booking bot, “Return an item” after an order status, “Yes” / “No”. A click sends the reply as if it were typed. Nothing of the block shows in the message, and the replies go the moment a message is sent. ```ts import { setupSuggestionBlocks } from '@aparte/core'; setupSuggestionBlocks(); ``` ```html ``` The block holds an array of strings, each both the label and what is sent. A `{ "label", "prompt" }` object is read for its label alone: the block arrives in the reply’s text, where a model can write it too, and a button must send what it shows. A page that wants a button to show one thing and send another writes it in the `suggestions` attribute of the element, which is the page’s own. A reply is shown only if it is 1 to 100 characters long and holds nothing invisible: no zero-width, bidi or tag characters, no stray joiners or variation selectors (an emoji sequence such as 🏳️‍🌈 is fine). A reply that fails is left out, and the console says which one, once. A click on a reply sends its text alone, leaves what the person was typing and any files they attached where they were, and does nothing while a question holds the composer or a reply is streaming. ````md ```suggestions ["Tuesday 3", "Another week"] ``` ```` `` shows nothing until an answer offers replies, and nothing when the last message is the person’s. A block that is not a list of replies is shown as its source; a block still being written offers nothing until it closes. The fixed prompt starters of an empty chat are the same element without `answers` ([`empty-only`](/components/suggestions/)); a page can have both. ## A language of your own [Section titled “A language of your own”](#a-language-of-your-own) The rule is one seam, public: `registerCodeLanguageRenderer`. Cards and suggestions are two users of it, and a language of yours is a third. A fenced block in a drawn language loses its code card, so what you draw stands for it (`card: true` keeps it, with its copy button, for a source worth taking); `bare: true` also drops the scroller around the drawing, for one that handles its own overflow, as a card’s carousel does: ```ts import { aparteGlobalConfig, escapeHtml } from '@aparte/core'; aparteGlobalConfig.registerCodeLanguageRenderer({ languages: ['ticket'], bare: true, render: ({ source, open }) => { if (open) return ''; // still being written const t = JSON.parse(source); return `
Ticket ${escapeHtml(t.id)}: ${escapeHtml(t.subject)}
`; }, }); ``` What `render` returns is inserted as it is (it is your code, like a segment renderer), so escape what comes from the block. For a block it cannot draw, answer with the source in an element of class `aparte-code-error`, which core shows as quiet code. A card with a layout, variants and buttons is easier with [`defineCard`](/guides/cards/#a-card-of-your-own), whose block comes for free. # Show a loop of your own in the chat > Drive the chat from a loop that runs elsewhere — your backend, a worker, an Electron process — without AparteClient, streaming text, reasoning and tool calls into it. When the loop lives somewhere else, the chat only shows it: your code puts messages and tokens in, and the chat draws, streams and scrolls them as it does for `AparteClient`. No client, no provider, no transport. ## Stream tokens in [Section titled “Stream tokens in”](#stream-tokens-in) * Vanilla ```ts import { uuid } from '@aparte/core'; const chat = document.querySelector('aparte-chat')!; chat.addEventListener('aparte-send', async (event) => { const viewport = chat.viewport!; viewport.appendMessage({ id: uuid(), role: 'user', content: event.detail.content, timestamp: Date.now() }); const id = uuid(); viewport.appendMessage({ id, role: 'assistant', content: '', timestamp: Date.now() }); for await (const token of myAgentLoop(event.detail.content)) viewport.appendToken(id, token); viewport.completeMessage(id); }); ``` * React ```tsx import { useCallback } from 'react'; import { AparteChat, useAparteChat } from '@aparte/react'; import { uuid } from '@aparte/core'; import '@aparte/core/styles.css'; export function Chat() { const chat = useAparteChat(); const onMessageSent = useCallback(async (event: { content: string }) => { const id = uuid(); chat.ref.current?.appendMessage({ id, role: 'assistant', content: '', timestamp: Date.now() }); await chat.ref.current?.injectTokenStream(id, myAgentLoop(event.content)); }, [chat.ref]); return ( ); } ``` * Vue ```vue ``` * Svelte ```svelte ``` On Svelte 4, the component from `@aparte/svelte` binds the same way: `let chat: AparteChatImperativeApi | null = null;` and ``. * Angular ```ts import { Component, viewChild } from '@angular/core'; import { AparteChatComponent } from '@aparte/angular'; import { uuid } from '@aparte/core'; import type { AparteMessage, AparteSendEventDetail } from '@aparte/core'; @Component({ selector: 'app-chat', standalone: true, imports: [AparteChatComponent], template: ``, }) export class ChatComponent { readonly chat = viewChild.required(AparteChatComponent); messages: AparteMessage[] = []; async onMessageSent(event: AparteSendEventDetail) { const id = uuid(); this.chat().appendMessage({ id, role: 'assistant', content: '', timestamp: Date.now() }); await this.chat().injectTokenStream(id, myAgentLoop(event.content)); } } ``` `myAgentLoop` is any `AsyncIterable`: an async generator over a fetch stream, a model’s SDK, whatever produces tokens. The framework packages add the person’s message when it is sent; in plain HTML, add it yourself, as above. Then add an empty assistant message, which shows the waiting dots until the first token, and stream into it: `injectTokenStream` in a framework, which also accepts an RxJS `Observable` in Angular, `appendToken` and `completeMessage` on the message list in plain HTML. Add the message before streaming into it: an id the framework does not know is kept by the message list alone, out of your `messages`. A new `injectTokenStream` cancels the one before, and `stopTokenStream()` cancels it; the source is closed, so a generator’s `finally` runs. `injectTokenStream` also sends the turn’s events: the send button is Stop while it streams, Stop cancels it, and the [conversation manager](/guides/conversation-persistence/) saves the reply when it ends. In plain HTML, [Make Stop work](#make-stop-work) shows the events to send yourself. ## From a source that pushes [Section titled “From a source that pushes”](#from-a-source-that-pushes) ```ts function createTokenQueue() { const buffer: string[] = []; let notify: (() => void) | null = null; let done = false; return { push(token: string) { buffer.push(token); notify?.(); }, end() { done = true; notify?.(); }, async *stream(): AsyncGenerator { for (;;) { while (buffer.length) yield buffer.shift()!; if (done) return; await new Promise((resolve) => { notify = resolve; }); notify = null; } }, }; } ``` A WebSocket, an Electron bridge or `postMessage` pushes its tokens rather than being pulled: push them into the queue, call `end()` when the reply is done, and stream `queue.stream()` into the message. ## Show reasoning and tool calls [Section titled “Show reasoning and tool calls”](#show-reasoning-and-tool-calls) ```ts const id = uuid(); chat.appendMessage({ id, role: 'assistant', content: '', timestamp: Date.now() }); // the reply the parts go into chat.addSegment({ id: 'think-1', type: 'thinking', content: '' }); for await (const chunk of reasoning) chat.appendToSegment('think-1', chunk); chat.updateSegment('think-1', { isStreaming: false }); chat.addSegment({ id: 'call-1', type: 'tool_call', status: 'pending', toolCall: { id: 'tc-1', name: 'search', input: { q: 'pricing' } } }); chat.updateSegment('call-1', { status: 'resolved', result: '3 pages found.' }); chat.updateMessage(id, { status: 'completed' }); // or 'error': the turn is over ``` A reply made of parts — reasoning, a tool call, an answer — is made of segments, each drawn by its renderer. On a framework chat, `addSegment`, `appendToSegment`, `updateSegment` and `removeSegment` act on the last message, so add the assistant message first: after a send, the last message is the person’s. On the message list, the message is named first: `addSegment(messageId, segment)`, `appendToSegment(messageId, segmentId, chunk)`, `updateSegment(messageId, segmentId, patch)`. Once a message has segments, its plain `content` is no longer drawn: give the answer a `text` segment of its own. A turn of segments does not end by itself: give it a final status with `updateMessage`, which also closes the segments still open. In plain HTML the transcript stays read-only until you do; on a framework chat it is read-only between `aparte-message-start` and the event that ends the turn. ## Make Stop work [Section titled “Make Stop work”](#make-stop-work) On a framework chat, `injectTokenStream` does it: nothing to add. A loop that writes segments rather than tokens, or a stream written with `appendToken` in plain HTML, is not a turn the composer can see: send the turn’s events yourself, on the chat’s element (the ``, or the framework component’s root, given an `id`), bubbling: `aparte-message-start` turns the send button to Stop, and `aparte-message-done`, `-error` or `-aborted` turns it back. Stop sends `aparte-abort` on `window`, with the chat’s `id` as `targetId`, for your loop to cancel, and the [conversation manager](/guides/conversation-persistence/) saves a reply when it ends. The [events reference](/reference/events/) types each detail. ```ts import { uuid } from '@aparte/core'; const chat = document.querySelector('aparte-chat')!; const lifecycle = (name: string, detail: object) => chat.dispatchEvent(new CustomEvent(name, { bubbles: true, composed: true, detail: { targetId: chat.id, ...detail } })); let controller = new AbortController(); chat.addEventListener('aparte-send', async (event) => { const viewport = chat.viewport!; // …the person's message, added as in the first example const id = uuid(); controller = new AbortController(); viewport.appendMessage({ id, role: 'assistant', content: '', timestamp: Date.now() }); lifecycle('aparte-message-start', { messageId: id, role: 'assistant' }); try { for await (const token of myAgentLoop(event.detail.content, controller.signal)) viewport.appendToken(id, token); } finally { viewport.completeMessage(id); lifecycle(controller.signal.aborted ? 'aparte-message-aborted' : 'aparte-message-done', { messageId: id, role: 'assistant' }); } }); window.addEventListener('aparte-abort', (event) => { if (!event.detail?.targetId || event.detail.targetId === chat.id) controller.abort(); }); ``` ## Replay a stored conversation [Section titled “Replay a stored conversation”](#replay-a-stored-conversation) ```ts import type { AparteChatImperativeApi, AparteMessage } from '@aparte/core'; declare const chat: AparteChatImperativeApi; declare const stored: AparteMessage[]; // from your backend chat.clearMessages(); for (const message of stored) chat.appendMessage(message, { historical: true }); ``` A historical message is a record, not a turn: its segments are taken as they are and nothing on it streams, so a tool call saved while it ran does not come back spinning. In plain HTML, `viewport.setMessages(stored)` replaces the whole conversation the same way. ## What you give up [Section titled “What you give up”](#what-you-give-up) The parts `AparteClient` drives do not run: no tool calls or approvals of its own, no retry or edit sending again, no request to build. The retry and edit buttons are off, and when you turn them on with `aparteGlobalConfig.setBubbleActions({ retry: true, edit: true })` they only send `aparte-retry` and `aparte-edit`, which your loop answers as in [Conversations and branches](/guides/conversations-branching/#with-your-own-loop). Files the person attaches arrive on the send event, for your loop to read, as in [Attachments](/guides/attachments/#with-your-own-loop). `requestUserInput` still asks the person anything, from your code ([Ask the user a question](/guides/elicitation/)). ## The pieces core exports for this [Section titled “The pieces core exports for this”](#the-pieces-core-exports-for-this) ````ts import { aparteGlobalConfig, AparteStreamParser } from '@aparte/core'; const parser = new AparteStreamParser({ blocks: aparteGlobalConfig.getStreamBlocks(), thinkingDelimiters: [ { start: '', end: '' }, { start: '<|begin_of_thought|>', end: '<|end_of_thought|>' }, ], }); for (const delta of ['Here: ', '```', 'ts\n', 'const x = 1;\n', '```']) { const { segments } = parser.parse(delta); // the segments each delta completes } parser.finalize(); // and whatever is still buffered ```` `AparteStreamParser` turns a model’s text into segments as it streams — text, code fences, reasoning, and the tags registered with `aparteGlobalConfig.registerStreamBlock` when you pass them as its `blocks`, as above. Its reasoning delimiters replace the default `` and ``: list every pair you want. They are this parser’s own: `AparteClient` reads the defaults, so a model that marks its reasoning another way needs this parser in a loop of yours, or a provider that sends the reasoning as its own events. The rest, each one line: * `parseMarkdownToSegments(text, options)` — the same, for a whole reply at once, to store or inspect it. * `readableToAsyncIterable(events, signal)` — the event stream `parseAparteEventStream` returns, as something you can `for await`, stopped by a signal. * `parseAparteEventStream(body)` — the stream a [backend transport](/guides/backend-transport/) endpoint answers, read back into events. * `contentToText(content)` — the text of a message whose content has several parts. * `uuid()` and `copyText(text)` — an id and a copy that work on a plain `http://` address too, where `crypto.randomUUID` does not. * `registerAllComponents()` — keeps every element in a bundle whose bundler drops side-effect imports, and warns naming any tag that is not registered. * `populateBubbleFromMessage(bubble, message)` — a message element filled from a message. * `AparteChatHost` — what the framework packages bind to, for a framework of your own; the [client reference](/reference/core/client/) has its binding. ## aparté’s loop, elsewhere [Section titled “aparté’s loop, elsewhere”](#apartés-loop-elsewhere) If the loop is yours to write, `runStreamAgent` from [`@aparte/engine`](/guides/engine/) is the loop `AparteClient` runs — headless, with no DOM — in Node, a worker or an Electron process. On a server, [the server loop](/guides/server-loop/) runs it next to your tools and keeps the page’s tool rows, Stop and approvals. ## Next [Section titled “Next”](#next) * [The agent engine The loop on its own, in any JavaScript runtime.](/guides/engine/) * [Run the loop on your server The same loop, with the page drawing it.](/guides/server-loop/) * [Frameworks The chat in React, Vue, Svelte and Angular, and its ref.](/frameworks/) # Generative UI cards: a tool result as a chat widget > Generative UI for AI chat: draw what a tool returns as an interactive card, the weather first, in variants, from your tool's own fields. [A weather tool drawn as a card, in three variants](/preview/demo/cards-weather/) ```html ``` One tool, one card, three variants chosen from the data. A tool’s call is drawn as a row: its name, its input, its output. For a tool whose result a person reads — the weather, a product, a place — a card says it better. This is what is often called generative UI: an interactive card in the chat where a block of JSON would have been. `@aparte/plugin-cards` draws that card where the row would be, while the call runs and once it has returned, and your tool keeps its own fields. ## Install and plug a card in [Section titled “Install and plug a card in”](#install-and-plug-a-card-in) ```bash npm install @aparte/plugin-cards ``` ```ts import { setupWeatherCard } from '@aparte/plugin-cards/weather'; setupWeatherCard({ tool: 'get_weather', map: (result) => ({ location: result.city, condition: result.sky, temperature: result.temp_c, high: result.max, low: result.min, }), }); ``` Each card has its own entry, so an app ships only the cards it imports. `tool` names the tool (a string or a `RegExp`, or several in an array); `map` turns the tool’s result into the card’s fields. The result `map` receives is the tool’s `structuredContent` when it returned one, else its text read as JSON, else the text. Return `null` when there is nothing to draw: the card then says it is not available, and the console says why once. ## Variants [Section titled “Variants”](#variants) A variant is the same card laid out another way. Pass one name, or a function that picks one from the data: ```ts setupWeatherCard({ tool: 'get_weather', map: (result) => result, variant: (data) => (data.daily.length > 2 ? 'forecast' : data.hourly.length ? 'hero' : 'compact'), }); ``` | variant | what it shows | | ---------------- | ----------------------------------------------------------------------------------------------------------------------------------- | | `hero` (default) | The sky behind the temperature, the range and the feel, wind, humidity and rain, then the next hours under the temperature’s curve. | | `compact` | One line: the glyph, the temperature, the place and the sky, the range. | | `forecast` | The current weather on its sky, then the days ahead, each with its range on a scale shared by all of them. | The variant is written on the card as `data-variant`, so your stylesheet can address one variant without registering a second card. ## The weather card’s fields [Section titled “The weather card’s fields”](#the-weather-cards-fields) Only `temperature` (or `daily`) is needed; every other field adds a line when it is there. | field | | | ----------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `location` | The place’s name. | | `condition` | One of `clear`, `partly-cloudy`, `cloudy`, `fog`, `drizzle`, `rain`, `heavy-rain`, `sleet`, `snow`, `thunder`, `wind` — or a description, read in English or French. | | `summary` | Your tool’s own words for the sky; otherwise the condition’s name, in the chat’s language. | | `temperature`, `feelsLike`, `high`, `low` | Numbers, in `unit` (`C` by default, or `F`). | | `humidity`, `precipitation` | Percentages (`40` or `0.4`). | | `wind` | A speed in km/h, or `{ speed, unit, direction }` — `unit` is `km/h`, `mph`, `m/s` or `kn`, `direction` in degrees. | | `night` | Draw the night sky and the moon. | | `time` | When it was measured. | | `hourly` | `[{ time, temperature, condition?, precipitation? }]`, eight shown. | | `daily` | `[{ date, high, low, condition?, precipitation? }]`, seven shown. | Three readers turn the codes of the usual APIs into a condition: `conditionFromWmo` (Open-Meteo’s `weather_code`), `conditionFromOpenWeather` (OpenWeather’s condition id) and `conditionFromText`. `fromOpenMeteo` reads a whole Open-Meteo forecast response, so a tool that calls it can hand its answer over as it is: ```ts import { setupWeatherCard, fromOpenMeteo } from '@aparte/plugin-cards/weather'; setupWeatherCard({ tool: 'get_weather', map: (result) => fromOpenMeteo(result.forecast, { location: result.city }), }); ``` `readWeather` is the card’s own reading of its fields, for a test of your `map`. ## The other cards [Section titled “The other cards”](#the-other-cards) Every card is plugged in the same way: its own entry, `tool`, `map`, `variant`, `actions`. ### Articles and results — `items` [Section titled “Articles and results — items”](#articles-and-results--items) Anything with a title, and often a picture: search results, articles, recommendations. One item or a list of them (ten at most), as a `carousel` (default), a `list` or a `grid`: ```ts import { setupItemsCard } from '@aparte/plugin-cards/items'; interface Hit { title: string; site: string; snippet: string; thumbnail: string; url: string } setupItemsCard({ tool: 'search_docs', map: (result: { query: string; hits: Hit[] }) => ({ title: `Results for "${result.query}"`, items: result.hits.map((hit) => ({ title: hit.title, subtitle: hit.site, description: hit.snippet, image: hit.thumbnail, url: hit.url, actions: [{ label: 'Summarise', id: 'summarise' }], })), }), }); // A button read from a tool's result never sends text as the person: it carries an `id`, // and your app decides what it does. A card the model wrote itself (`origin` is 'fence') // is not your app's: act only on the origins you trust. document.addEventListener('aparte-card-action', (event) => { const { action, data, origin } = event.detail; if (origin === 'fence') return; if (action.id === 'summarise') sendToChat(`Summarise ${(data as { url: string }).url}`); }); declare function sendToChat(text: string): void; ``` An item reads `title`, `subtitle`, `description`, `image` (a string, or `{ src, alt }`), `badge`, `meta` (up to three short lines), `url` (the whole tile opens it) and `actions` (two at most, each a web link or an `id`: what a button sends as the person is never read from a tool’s result, since a page the tool read could choose it). A card the model wrote as a `card-items` block draws only the links among its actions: an `id` there would let the model press a button of your app, with its own label and data, so `actions` is where your own buttons for such a card come from. ### Products — `product` [Section titled “Products — product”](#products--product) A price and the one it replaces (the discount is worked out, never read from text), a rating, the stock, the merchant, the options. One product or several, as `card` tiles (default), `compact` rows or a `detail` sheet: ```ts import { setupProductCard } from '@aparte/plugin-cards/product'; setupProductCard({ tool: 'search_products', variant: (data) => (data.products.length === 1 ? 'detail' : 'card'), }); ``` Its reader takes the shapes shops already return — schema.org `Product`/`Offer`, Shopify, Google Shopping results — and prices written as text (`"1.299,00 €"`), so `map` is often not needed. `discountOf(product)` gives the discount it shows. ### Places — `place` [Section titled “Places — place”](#places--place) A restaurant, a shop, a museum: rating, price level, distance, and whether it is open now — worked out from its hours at the moment it is drawn, across midnight, in the place’s own time zone when it gives one. Directions, Call and Website buttons appear on each place when the data allows them, beside your own `actions` (`builtIns: false` leaves them out): ```ts import { setupPlaceCard } from '@aparte/plugin-cards/place'; setupPlaceCard({ tool: 'find_places', currencySymbol: '€' }); ``` `card` tiles (default), `compact` rows, and a `detail` sheet with the week’s hours, today first. Its reader takes both generations of Google Places and Yelp. The hours logic is exported too: `readHours`, `readTime`, `placeStatus`, `isOpenAt`, `directionsUrl` and `phoneUrl`. Without a photo it draws a map of its own and fetches nothing; `mapTiles` puts a place with coordinates on your real map tiles instead, which are your own choice and not subject to the image policy ([A real map](/components/place-card/#a-real-map)). ### Key figures — `stats` [Section titled “Key figures — stats”](#key-figures--stats) A few numbers that answer a question: revenue, orders, conversion. `tiles` (default) is a grid of figures, each with its change and a sparkline; `list` is a fact sheet, one row per figure; `hero` draws the first figure large over a wide chart and the others beneath it: ```ts import { setupStatsCard } from '@aparte/plugin-cards/stats'; setupStatsCard({ tool: 'get_sales_summary', map: (result) => ({ title: 'Sales this week', items: [ { label: 'Revenue', value: result.revenue, currency: 'EUR', change: 0.12, good: 'up', trend: result.daily }, { label: 'Returns', value: result.returns, change: '+3%', good: 'down' }, ], }), }); ``` A figure (`StatInput`) needs `label` and `value`. `format` is `number`, `percent`, `currency`, `compact`, `duration` or `text` (`StatFormat`); `change` is a percentage — a number up to 1 is a ratio, `0.12` reads +12 %, so write `"1%"` for one per cent — or, with `changeFormat: 'absolute'`, in the figure’s unit. `good` says which way is good and colours the change; without it the change stays neutral. `icon` names one of the card’s glyphs (`StatIcon`). A plain record — `{ Revenue: 12000, Orders: 340 }` — is read as label → value pairs, its keys made readable by `humanizeKey`. `readStats` turns a `StatsInput` into the `StatsData` it draws (`Stat` per figure), and `statValue` and `statChange` write a figure the way the card does. The variant names are `StatsVariant`. ### Orders and bookings — `order` [Section titled “Orders and bookings — order”](#orders-and-bookings--order) What was bought or booked, what it cost, where it stands. `receipt` (default) is the whole record, lines, totals, payment and delivery; `compact` is one row, for a list of past orders; `confirmation` is the moment it is placed: ```ts import { setupOrderCard } from '@aparte/plugin-cards/order'; setupOrderCard({ tool: 'get_order', variant: 'receipt' }); setupOrderCard({ tool: 'book_room', map: (r) => ({ ...r, kind: 'booking' }), variant: 'confirmation' }); ``` `readOrder` already takes a Shopify or WooCommerce order and a Stripe Checkout session — Stripe counts in cents, so say `minorUnits: true`; the card does not guess. An `OrderInput` has a `kind` (`OrderKind`: `order` or `booking`), a `status` (`OrderStatus`, or your own word), `items` (`OrderLineInput`: `title`, `quantity`, `price`, `total`…), the totals — the subtotal and the total are worked out when missing, and a tool’s own total always wins — `payment`, `delivery` (an estimate, a carrier, a tracking link), `facts` of your own, a `headline` for the confirmation when the status’s sentence is not what happened (“Return started”), and, for a booking, `booking` with its `start`, `end`, `location` and `guests`. A date (`OrderDateInput`) is an ISO string, an epoch or a `Date`; `readWhen` reads one into an `OrderWhen`, which knows that a hotel’s `"2026-11-07"` is a day, not midnight, and `nightsOf` counts the nights between two of them. The card draws an `OrderData` of `OrderLine`s and `OrderFact`s; its variants are `OrderVariant`. ### Market quotes — `stock` [Section titled “Market quotes — stock”](#market-quotes--stock) A stock, an index, a crypto-currency, a currency pair. `chart` (default) is the quote at length, its chart against the previous close; `compact` is one row per quote with its sparkline; `ticker` is a strip of quotes that scrolls sideways; `candles` is the `chart` card with candlesticks in place of the line: ```ts import { setupStockCard } from '@aparte/plugin-cards/stock'; setupStockCard({ tool: 'get_quote', variant: 'candles' }); ``` A quote (`QuoteInput`) needs a `symbol`; the price, the change, the day’s figures, `series` for the line (`ChartPoint`s or plain numbers) and `candles` for the candlesticks (`Candle`s) each add their part, and `marketState` (`MarketState`) says whether the market is open. Several quotes (`QuotesInput`) are drawn as rows, whichever variant was asked: a watchlist is read by comparing lines. `readQuotes` takes Yahoo Finance, Alpha Vantage, Finnhub, CoinGecko and Binance as they come, into the `StockData` it draws. `directionOf` says which way a quote moved, `baselineOf` what its chart is measured against — the previous close for a day, where the series starts for anything longer — and `digitsOf` how many decimals its price wears. Its variants are `StockVariant`; a range is a `StockRange` — the next section shows the buttons that change it. ### An agent’s plan — `plan` [Section titled “An agent’s plan — plan”](#an-agents-plan--plan) The card an agent updates while it works: the same call sent again with new statuses, drawn into the same card. A status change moves no row: the title, its bold form, the `activeForm` wording a todo list gives a running step (“Running the tests”) and the duration slot are all reserved. Say `timed: true` when your steps will gain times later, so their slot is there from the first draw; a `detail` an update brings adds its line. `checklist` (default) has “3 of 7 done” and a bar over one row per step; `timeline` puts each step on a rail with its time; `compact` is one line, for a plan that runs in a small space: ```ts import { setupPlanCard } from '@aparte/plugin-cards/plan'; setupPlanCard({ tool: 'update_plan' }); // A tool whose input is the list and whose result is only "ok" reads its input instead: setupPlanCard({ tool: 'TodoWrite', map: (_result, input) => input }); ``` `readPlan` reads a list of steps, a list of strings, a Markdown checklist (`- [x] Write the tests`) and the todo lists agents already write — Claude Code’s and OpenAI’s, Codex’s plan, LangGraph’s plan-and-execute state (its `past_steps` results are not shown: map them to `detail` to show them). A `PlanInput` is a list of steps or `{ title, goal, steps, timed }`; a step (`PlanStepInput`) has a `title`, a `status` (`PlanStatus`: `pending`, `in-progress`, `done`, `failed`, `skipped`, `blocked`, or the usual words for them, which `readStatus` reads), a `detail`, its times and one level of `substeps`. `planProgress` counts how far a `PlanData` has got (a `PlanProgress`), `durationText` writes a step’s duration, and the card shows `PLAN_STEPS_SHOWN` steps at most (`PlanStep`s, its variants `PlanVariant`). ### Matches — `score` [Section titled “Matches — score”](#matches--score) A match, or a scoreboard of them, in any sport. `card` (default) puts the two teams face to face with the score between them; `compact` is one row per match; `detail` adds the score by period and the match’s events, each on its team’s side: ```ts import { setupScoreCard } from '@aparte/plugin-cards/score'; setupScoreCard({ tool: 'get_match', map: (result) => result.response, variant: 'detail' }); ``` `readMatches` takes API-Football, football-data.org, ESPN and TheSportsDB as they come. A `MatchInput` needs its `home` and `away` teams (`TeamInput`: a `name`, and a `shortName`, a `logo`, a `color`, a `record`…); its `status` (`MatchStatus`, or a feed’s own code), `clock`, `startTime`, `competition`, `venue`, `sport` (`Sport`), `periods` (`MatchPeriodInput`) and `events` (`MatchEventInput`: a `minute`, a `team` — a `MatchSide` — a `type` from `MatchEventType`, a `player`) each add their part. Several matches (`ScoreInput`) are always rows. `ScoreCardOptions` adds `now`, the time “Today” is worked out from. The card draws a `ScoreData` of `Match`es, `Team`s, `MatchPeriod`s and `MatchEvent`s; a team without a logo gets its `monogram` on its colour (`teamColor` reads one, `inkOn` picks the text that reads on it). Its variants are `ScoreVariant`. ### Pictures, videos, sounds — `media` [Section titled “Pictures, videos, sounds — media”](#pictures-videos-sounds--media) One medium large (`single`, the default), a gallery as a mosaic (`gallery`), or a row of thumbnails (`strip`). Every picture opens in a lightbox: ```ts import { setupMediaCard } from '@aparte/plugin-cards/media'; setupMediaCard({ tool: 'generate_image' }); // an image model's { data: [{ url }] } as it is setupMediaCard({ tool: 'search_photos', map: (result) => result.results, variant: 'gallery' }); ``` A video plays in the browser’s own `