Framework
When a result refers to a business record, a card can give an operator a direct route to it. Stream a typed UI part alongside the text and register the component that knows how to display that kind of result.
A UI part is a typed component the agent can stream into the chat transcript. The chat composer renders cards, diffs, confirmations, and custom widgets the same way it renders text – from the same SSE stream – so the agent never needs to ask the operator to copy/paste an id.
There are two kinds of UI parts:
| Kind | Rendered from | Examples |
|---|---|---|
| Record cards | Fenced code blocks the agent emits as plain text (parsed client-side) | open-mercato:product, open-mercato:deal, open-mercato:person, open-mercato:company, open-mercato:activity |
| Server-emitted parts | AiUiPart objects pushed onto the runtime's UI-part queue and streamed as data-aiui, or enqueued by a read tool on ctx.uiParts and carried in its tool output | mutation-preview-card, field-diff-card, confirmation-card, mutation-result-card, ai_assistant:citations, plus your own |
Record cards are the cheapest way to get a typed widget into the chat. The agent emits a fenced Markdown block whose info string starts with open-mercato:<kind> and whose body is one JSON object. The client-side parser (parseAiContentSegments) replaces the fence with a typed React component.
'When you reference a specific product, embed an interactive PRODUCT CARD instead of plain text. Cards render inline and link back to the backoffice. Emit them as fenced code blocks like:',
'```open-mercato:product',
'{ "id": "<uuid>", "name": "Wireless Headphones", "sku": "WH-001",',
' "price": 199, "currency": "USD",',
' "imageUrl": "/api/attachments/image/<media-id>",',
' "href": "/backend/catalog/catalog/products/<uuid>" }',
'```',
The chat composer turns that fence into a <ProductCard> with photo, price, status badge, and a click-through to the backoffice.
| Kind | Component | Required field | Notable optional fields |
|---|---|---|---|
product | ProductCard | name | imageUrl, sku, price, currency, status, category, description, tags, href |
deal | DealCard | title | status, stage, amount, currency, closeDate, personName, companyName, tags, href |
person | PersonCard | name | title, email, phone, companyName, avatarUrl, tags, href |
company | CompanyCard | name | industry, website, email, city, country, logoUrl, tags, href |
activity | ActivityCard | title | type, dueDate, relatedTo, description, tags, href |
Full payload shapes live in packages/ui/src/ai/records/types.ts. Always:
id so the card can carry a data-record-id attribute (test selectors use it);href so the card is clickable;null – the cards skip undefined/empty values gracefully.There is no registration step for the shipped kinds – <AiChat> always parses them. Two things to do per agent:
responseStyle section with the example fence and a "use cards instead of plain text" rule. Reference: packages/core/src/modules/customers/ai-agents.ts, packages/core/src/modules/catalog/ai-agents.ts.list_products tool exposes both defaultMediaUrl (the canonical column) and an imageUrl alias keyed exactly the way the card payload expects, so the model can pass the field through verbatim.If you ship a new domain entity that deserves a card:
packages/ui/src/ai/records/types.ts and the RecordCardKind union.ProductCard.tsx as a starting point; reuse RecordCardShell for header + leading + meta consistency).packages/ui/src/ai/records/registry.tsx so RecordCard resolves the new kind.__tests__ that asserts <AiMessageContent> renders the new kind from a fenced sample.AiUiPart)Record cards are stateless and inline. Server-emitted parts carry props that the server alone can compute (a pending-action id, an attachment binding, a one-time signed URL) and arrive as discrete chunks on the SSE stream.
import type { AiUiPart } from '@open-mercato/ai-assistant'
const part: AiUiPart = {
componentId: 'mutation-preview-card',
props: {
pendingActionId: pendingAction.id,
expiresAt: pendingAction.expiresAt.toISOString(),
fieldDiff: [
{
field: 'pipelineStageId',
fieldLabel: 'Pipeline stage',
before: 'a195249d-3061-44f7-b997-0b27f608bdee',
after: '5007469d-ba76-4028-be83-d016a50bc0e3',
beforeDisplay: 'Offering',
afterDisplay: 'Lost',
},
],
},
}
The runtime queues parts (AiUiPartQueue) inside resolveAiAgentTools and the chat dispatcher drains them between streamText chunks. Each part lands as a data-aiui SSE chunk; useAiChat deserializes them into AiChatMessageUiPart[] and the chat resolves the componentId against the UI-part registry.
| Component ID | File | Rendered when |
|---|---|---|
mutation-preview-card | parts/MutationPreviewCard.tsx | prepareMutation returns. Shows tool name, agent id, target, diff summary, [Confirm All] / [Cancel] |
field-diff-card | parts/FieldDiffCard.tsx | Nested inside the preview, one per record on bulk mutations |
confirmation-card | parts/ConfirmationCard.tsx | Stand-alone confirm/cancel UI for proposals without a diff |
mutation-result-card | parts/MutationResultCard.tsx | After confirm returns. Renders success rows + failedRecords mixed outcomes |
The canonical map lives in packages/ui/src/ai/parts/approval-cards-map.ts:
import { AI_MUTATION_APPROVAL_CARDS, defaultAiUiPartRegistry } from '@open-mercato/ui/ai'
<AiChat
agent="catalog.merchandising_assistant"
registry={{ ...defaultAiUiPartRegistry, ...AI_MUTATION_APPROVAL_CARDS }}
/>
The defaultAiUiPartRegistry is a singleton that already includes the approval cards and the ai_assistant:citations sources list. You only need to extend it when you ship custom parts.
ai_assistant:citations)Read tools that ground an answer in records, documents or pages call emitCitations(ctx, [...]) from @open-mercato/ai-assistant. It validates the entries, drops unsafe links and enqueues one ai_assistant:citations part on ctx.uiParts; the chat renders it as a numbered Sources list and the run trace keeps it. See Citations for the payload schema, href rules, resolvers and persistence.
<AiChat> also renders a compact live task plan above the technical tool-call rows. This is not a UI part and it is not persisted with chat messages. The server injects data-agent-task-plan and data-agent-task-update chunks into the same SSE stream so operators see what the agent intends to do before the domain tools finish.
Agents that opt in with taskPlan: { enabled: true } can set better labels by calling the read-only meta.update_task_plan tool before domain tools:
await meta.update_task_plan({
tasks: [
{
id: 'search-products',
label: 'Search matching products',
detail: 'Catalog search',
toolName: 'catalog.search_products',
},
{ id: 'summarize', label: 'Summarize useful matches' },
],
})
The runtime sanitizes labels and rejects hidden-reasoning-like text such as chain-of-thought, scratchpads, or XML thinking tags. Treat task labels as visible progress copy. Use toolName when a step maps to a tool so the runtime can advance that row from pending to running and done as the matching tool lifecycle streams.
Use a custom part for things the model cannot author from a fenced JSON block – anything that needs server-only state, an action handler, or rich interaction (a chart, an inline document signer, a "send a Slack reply" button).
// packages/<pkg>/src/modules/<module>/widgets/ai-parts/SalesSnapshotCard.tsx
'use client'
import * as React from 'react'
export interface SalesSnapshotCardProps {
totalRevenue: number
currency: string
topProducts: Array<{ id: string; name: string; revenue: number }>
}
export function SalesSnapshotCard(props: SalesSnapshotCardProps) {
return (
<div data-ai-part="sales:snapshot-card" className="rounded-lg border bg-card p-3 text-sm">
<div className="text-muted-foreground text-xs uppercase tracking-wide">Snapshot</div>
<div className="text-base font-semibold">
{new Intl.NumberFormat(undefined, { style: 'currency', currency: props.currency })
.format(props.totalRevenue)}
</div>
<ul className="mt-2 space-y-1">
{props.topProducts.map((p) => (
<li key={p.id} className="flex justify-between">
<span className="truncate">{p.name}</span>
<span className="font-mono">{p.revenue}</span>
</li>
))}
</ul>
</div>
)
}
Pick a stable, namespaced id (<module>:<kind>). Reserved ids live in RESERVED_AI_UI_PART_IDS and are owned by the framework – never reuse them.
// packages/<pkg>/src/modules/<module>/widgets/ai-parts/index.ts
import { registerAiUiPart } from '@open-mercato/ui/ai'
import { SalesSnapshotCard } from './SalesSnapshotCard'
registerAiUiPart('sales:snapshot-card', SalesSnapshotCard)
The default registry is global. If you embed multiple <AiChat> instances that should not share registrations (playground, tests), build a scoped registry:
import { createAiUiPartRegistry } from '@open-mercato/ui/ai'
const registry = createAiUiPartRegistry()
registry.register('sales:snapshot-card', SalesSnapshotCard)
<AiChat agent="..." registry={registry} />
In a read tool, enqueue the part on the per-call ctx.uiParts collector. When the handler returns, the runtime merges the collected parts into the tool output's uiParts envelope; the chat picks them up from the tool-output-available chunk and persists them with the assistant message, so they survive a reload:
import { defineAiTool } from '@open-mercato/ai-assistant'
export const showSalesSnapshot = defineAiTool({
name: 'sales.show_snapshot',
description: 'Render an inline sales snapshot card for the current tenant.',
isMutation: false,
requiredFeatures: ['sales.view'],
inputSchema: z.object({ from: z.string(), to: z.string() }),
async handler(args, ctx) {
const totals = await loadSalesSnapshot(ctx, args)
// `ctx.uiParts` is a per-call collector, set only for in-process agent
// tool calls (undefined on MCP and /tools/execute). Enqueued parts travel
// in the tool output's `uiParts` envelope as `{ componentId, payload }`
// (`props` is accepted as an alias for `payload`).
ctx.uiParts?.enqueue({
componentId: 'sales:snapshot-card',
props: {
totalRevenue: totals.revenue,
currency: totals.currency,
topProducts: totals.topProducts,
},
})
return { ok: true, summary: 'Snapshot rendered' }
},
})
How the collector merges into the output:
uiParts array (appended to when the tool already returns one; a non-array uiParts field is left untouched and the emitted parts are dropped with a warning);{ result, uiParts }, but only when at least one part was emitted;The collector is not set for mutation tools gated by the approval flow, for MCP calls or for POST /api/ai_assistant/tools/execute, so always use optional chaining (ctx.uiParts?.enqueue). For mutation tools, push the part from inside prepareMutation({ uiPart: ... }) so it travels with the pending action – see Mutation Approvals.
Include a responseStyle rule like:
When the operator asks for a sales overview / "how are we doing", call
sales.show_snapshot– it returns an inline snapshot card the operator can read at a glance. Always call the tool; never paraphrase the data in prose.
Without a prompt rule the model will route around the tool and quote numbers in plain text.
For reference when debugging the network panel:
data: {"type":"text-delta","delta":"Sure, here is..."}
data: {"type":"reasoning-delta","delta":"Considering catalog..."}
data: {"type":"tool-input-start","toolCallId":"...","toolName":"catalog.list_products"}
data: {"type":"tool-input-available","toolCallId":"...","input":{...}}
data: {"type":"tool-output-available","toolCallId":"...","output":"..."}
data: {"type":"data-agent-task-plan","planId":"turn_...","tasks":[{"id":"search-products","label":"Search matching products","state":"pending","source":"agent"}]}
data: {"type":"data-agent-task-update","planId":"turn_...","task":{"id":"search-products","label":"Search matching products","state":"done","source":"agent","toolCallId":"call_..."}}}
data: {"type":"tool-output-available","toolCallId":"...","output":{"items":[...],"uiParts":[{"componentId":"ai_assistant:citations","payload":{"citations":[...]}}]}}
data: {"type":"data-aiui","payload":{"componentId":"mutation-preview-card","props":{...}}}
data: [DONE]
useAiChat consumes the stream and routes each chunk to the right slot on the assistant message:
| Chunk | Lands on |
|---|---|
text-delta | message.content |
reasoning-delta | message.reasoning (rendered in the collapsible Reasoning panel) |
tool-input-* / tool-output-* | message.toolCalls[]; a uiPart / uiParts envelope in the output also lands on message.uiParts[] |
data-agent-task-plan / data-agent-task-update | message.taskPlan[] (client-local live plan) |
data-aiui | message.uiParts[] resolved by the registry |
Use the playground (/backend/config/ai-assistant/playground) for manual smoke tests. Tools that emit UI parts should also have a unit test that:
McpToolContext whose uiParts is { enqueue: jest.fn() }.enqueue received the expected componentId + payload shape.Reference: packages/ui/src/ai/__tests__/AiChat.registry.test.tsx covers the registry resolution path.
componentId. Renaming or removing a registered id is a breaking change.defineAiToolemitCitations, the sources part and run citations