Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,9 @@ The `context` is read from the data model at the moment of the press, so it carr
When the agent created the surface with `sendDataModel: true`, the whole data model rides along as `metadata.a2uiClientDataModel`.

How the message reaches the agent is your decision (most applications send it as the next turn of the conversation).
When you send it as a user message, `Chat` and `MessageList` show the button's label, such as "Search flights", in place of the serialized message.
An action from a control without literal text shows its name in plain words, so `bookingSubmit` reads "Booking submit".
Pass `a2uiActionLabels={false}` to show the message as it was sent.
Without `onAction`, buttons that would send an action are disabled, so a read-only surface cannot look pressable.

## What happens when a check fails?
Expand Down
11 changes: 11 additions & 0 deletions libs/react/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2151,6 +2151,17 @@ retries and what the conversation shows are your application's decisions.
`createA2uiActionMessage(surface, componentId)` from
`@threadplane/content/a2ui` builds the same message outside React.

When an application sends the message as the next user turn, `Chat` and
`MessageList` do not show its JSON. A user message that is a serialized action
shows the `label` instead ("Search flights"), or the action name in plain
words when there is none (`bookingSubmit` reads "Booking submit"). The stored
message is unchanged, and every other message renders as before. Pass
`a2uiActionLabels={false}` to show the message as sent.

```tsx
<Chat session={session} a2uiActionLabels={false} />
```

A Button with an event action is disabled when there is no `onAction`. A
Button with no action, or whose `disabled` prop is true, is disabled too. A
Button used as a `Modal` trigger opens the modal and needs no action.
Expand Down
4 changes: 4 additions & 0 deletions libs/react/src/chat/chat.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,8 @@ export interface ChatProps
readonly renderMessageActivity?: MessageListProps['renderMessageActivity'];
/** One reasoning disclosure per multi-step turn; see `MessageListProps.mergeReasoning`. Defaults to true. */
readonly mergeReasoning?: MessageListProps['mergeReasoning'];
/** Shows an A2UI action sent as a user message by its label; see `MessageListProps.a2uiActionLabels`. Defaults to true. */
readonly a2uiActionLabels?: MessageListProps['a2uiActionLabels'];
/**
* The waiting indicator in the transcript; see `MessageListProps.typingIndicator`. Pass
* `{ announce: false }` when the app already announces progress, such as a status in
Expand Down Expand Up @@ -223,6 +225,7 @@ export function Chat({
generativeUi,
markdownComponents,
mergeReasoning,
a2uiActionLabels,
renderMessageActivity,
typingIndicator,
welcome,
Expand Down Expand Up @@ -404,6 +407,7 @@ export function Chat({
generativeUi={generativeUi}
markdownComponents={markdownComponents}
mergeReasoning={mergeReasoning}
a2uiActionLabels={a2uiActionLabels}
renderMessageActivity={renderMessageActivity}
typingIndicator={typingIndicator}
renderScrollControl={(controls) =>
Expand Down
3 changes: 3 additions & 0 deletions libs/react/src/chat/chat.type-test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,9 @@ ok.className = 'x';
<Chat session={session} modelPicker={{ options: [], value: 'a' }} />;
// @ts-expect-error Options are value and label records, not strings.
<Chat session={session} modelPicker={{ options: ['a'], value: 'a', onValueChange: () => undefined }} />;
<Chat session={session} a2uiActionLabels={false} />;
// @ts-expect-error Action labels are a switch, not a renderer.
<Chat session={session} a2uiActionLabels={() => 'Go'} />;
void missing;

import type { ReactNode } from 'react';
Expand Down
30 changes: 30 additions & 0 deletions libs/react/src/chat/internal/a2ui-action-label.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
const record = (value: unknown): value is Record<string, unknown> =>
value != null && typeof value === 'object' && !Array.isArray(value);

/**
* The words to show for a message whose content is a serialized A2UI action
* (`{"version":"v0.9","action":{…}}`): the pressed control's own label, or the
* action name in plain words ("bookingSubmit" reads "Booking submit"). Null
* for any other content.
*/
export function a2uiActionLabel(content: string): string | null {
const trimmed = content.trimStart();
if (!trimmed.startsWith('{')) return null;
let parsed: unknown;
try {
parsed = JSON.parse(trimmed);
} catch {
return null;
}
if (!record(parsed)) return null;
const version = parsed['version'];
if (typeof version !== 'string' || !version.startsWith('v')) return null;
const action = parsed['action'];
if (!record(action)) return null;
const name = action['name'];
if (typeof name !== 'string' || name === '') return null;
const label = action['label'];
if (typeof label === 'string' && label !== '') return label;
const words = name.replace(/([a-z])([A-Z])/g, '$1 $2').toLowerCase();
return words.charAt(0).toUpperCase() + words.slice(1);
}
151 changes: 151 additions & 0 deletions libs/react/src/chat/message-list-a2ui-action-label.spec.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,151 @@
import { cleanup, render } from '@testing-library/react';
import { afterEach, describe, expect, it } from 'vitest';
import {
completeDelivery,
type AgentSession,
type AgentSnapshot,
type Message,
} from '@threadplane/core';
import { createA2uiActionMessage } from '@threadplane/content/a2ui';
import { createMessageContent } from '@threadplane/content/messages';
import { Chat, MessageList } from './index';

afterEach(cleanup);

const msg = (id: string, role: Message['role'], content: string): Message =>
Object.freeze({ id, role, content, delivery: completeDelivery(id, 'success') }) as Message;
const snapshot = (messages: Message[]) =>
Object.freeze({ status: 'idle', messages, toolCalls: [] }) as AgentSnapshot;
const project = (messages: Message[]) => createMessageContent().project(snapshot(messages));
const action = (fields: Record<string, unknown>) =>
JSON.stringify({ version: 'v0.9', action: { surfaceId: 's', sourceComponentId: 'b', context: {}, ...fields } });
const bubble = (view: ReturnType<typeof render>) =>
view.container.querySelector('.tp-chat-message--user');
// The message text alone, without the row's screen-reader role prefix.
const text = (view: ReturnType<typeof render>) =>
view.container.querySelector('.tp-chat-message--user .tp-markdown')?.textContent;

describe('MessageList A2UI action labels', () => {
it('leaves the serialized action in place when turned off', () => {
const view = render(
<MessageList
a2uiActionLabels={false}
rows={project([msg('u', 'user', action({ name: 'bookingSubmit', label: 'Search flights' }))])}
/>
);
expect(bubble(view)?.textContent).toContain('"bookingSubmit"');
expect(view.container.querySelector('[data-a2ui-action]')).toBeNull();
});

it('shows the pressed control label in place of the JSON by default', () => {
const view = render(
<MessageList
rows={project([msg('u', 'user', action({ name: 'bookingSubmit', label: 'Search flights' }))])}
/>
);
expect(text(view)).toBe('Search flights');
expect(bubble(view)?.querySelector('.tp-markdown[data-a2ui-action] > p')).not.toBeNull();
});

it('labels the message the shared builder produces for a Button', () => {
const message = createA2uiActionMessage(
{
surfaceId: 's',
components: [
{ id: 'go', component: 'Button', child: 'go-text', action: { event: { name: 'bookingSubmit' } } },
{ id: 'go-text', component: 'Text', text: 'Search flights' },
],
dataModel: {},
} as never,
'go',
'2026-11-17T00:00:00.000Z'
);
const view = render(
<MessageList rows={project([msg('u', 'user', JSON.stringify(message))])} />
);
expect(text(view)).toBe('Search flights');
});

it('puts the action name in plain words when no label was sent', () => {
for (const [name, words] of [
['bookingSubmit', 'Booking submit'],
['addToCart', 'Add to cart'],
['refresh', 'Refresh'],
]) {
const view = render(
<MessageList rows={project([msg('u', 'user', action({ name, label: '' }))])} />
);
expect(text(view)).toBe(words);
cleanup();
}
});

it('leaves every other user message as written', () => {
for (const content of [
'Find me a flight',
'{"city":"Paris"}',
'{not json',
'{"version":"v0.9"}',
'{"version":"v0.9","action":{"label":"No name"}}',
'{"version":1,"action":{"name":"go"}}',
'[{"version":"v0.9","action":{"name":"go"}}]',
]) {
const plain = render(<MessageList a2uiActionLabels={false} rows={project([msg('u', 'user', content)])} />);
const expected = bubble(plain)?.innerHTML;
cleanup();
const view = render(<MessageList rows={project([msg('u', 'user', content)])} />);
expect(bubble(view)?.innerHTML).toBe(expected);
cleanup();
}
});

it('never relabels an assistant message that quotes an action', () => {
const content = action({ name: 'bookingSubmit', label: 'Search flights' });
const view = render(<MessageList rows={project([msg('a', 'assistant', content)])} />);
const row = view.container.querySelector('.tp-chat-message--assistant');
expect(row?.textContent).toContain('"bookingSubmit"');
expect(row?.querySelector('[data-a2ui-action]')).toBeNull();
});

it('renders the label as text, not markup', () => {
const view = render(
<MessageList
rows={project([msg('u', 'user', action({ name: 'go', label: '**Bold** <img src=x onerror=alert(1)>' }))])}
/>
);
expect(text(view)).toBe('**Bold** <img src=x onerror=alert(1)>');
expect(bubble(view)?.querySelector('img, strong')).toBeNull();
});

it('leaves a custom renderMessage in charge of the row', () => {
const view = render(
<MessageList
renderMessage={(row) => <i data-custom>{row.message.content.length}</i>}
rows={project([msg('u', 'user', action({ name: 'go', label: 'Go' }))])}
/>
);
expect(view.container.querySelector('[data-custom]')).not.toBeNull();
expect(view.container.querySelector('[data-a2ui-action]')).toBeNull();
});
});

describe('Chat A2UI action labels', () => {
const session = (messages: Message[]): AgentSession => {
const value = snapshot(messages);
return {
getSnapshot: () => value,
subscribe: () => () => undefined,
submit: async () => undefined,
stop: async () => undefined,
} as unknown as AgentSession;
};
const messages = [msg('u', 'user', action({ name: 'bookingSubmit', label: 'Search flights' }))];

it('passes the choice through to its transcript', () => {
const off = render(<Chat session={session(messages)} a2uiActionLabels={false} />);
expect(bubble(off)?.textContent).toContain('"bookingSubmit"');
cleanup();
const on = render(<Chat session={session(messages)} />);
expect(text(on)).toBe('Search flights');
});
});
38 changes: 30 additions & 8 deletions libs/react/src/chat/message-list.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ import {
withoutStaleRetry,
} from './tool-outcome.js';
import { Reasoning } from './reasoning.js';
import { a2uiActionLabel } from './internal/a2ui-action-label.js';
import { isTyping, TypingIndicator } from './typing-indicator.js';
import {
BuiltInActions,
Expand Down Expand Up @@ -190,6 +191,14 @@ export interface MessageListProps<TRow extends MessageRow = MessageRow> {
* reasoning on its own message. Custom renderMessage retains full row ownership.
*/
readonly mergeReasoning?: boolean;
/**
* Shows a user message that is a serialized A2UI action as the pressed
* control's label ("Search flights") in place of its JSON. Without a label
* the action name is put in plain words. Defaults to true; false shows the
* JSON as sent. Other messages are unchanged, and custom renderMessage
* retains full row ownership.
*/
readonly a2uiActionLabels?: boolean;
/** Typesets math in message text; see `MarkdownProps.math`. Keep stable; custom renderMessage retains full ownership. */
readonly math?: MarkdownProps['math'];
/**
Expand Down Expand Up @@ -393,8 +402,10 @@ function RowView<TRow extends MessageRow>({
generativeUi,
markdownComponents,
mergeReasoning,
a2uiActionLabels,
renderMessageActivity,
}: {
readonly a2uiActionLabels?: boolean;
readonly renderMessageActivity?: (
context: MessageActivityContext<TRow>
) => ReactNode;
Expand Down Expand Up @@ -525,14 +536,23 @@ function RowView<TRow extends MessageRow>({
});
// The plan and Stop belong to the row's last built-in group, the one the turn is still running.
const planGroup = [...runs].reverse().find((run) => 'activities' in run);
const text = (
<Markdown
snapshot={row.markdown}
citations={row.role === 'assistant' ? row.message.citations : undefined}
math={math}
components={markdownComponents}
/>
);
const actionLabel =
a2uiActionLabels !== false && row.role === 'user'
? a2uiActionLabel(row.message.content)
: null;
const text =
actionLabel !== null ? (
<div className="tp-markdown" data-a2ui-action="">
<p>{actionLabel}</p>
</div>
) : (
<Markdown
snapshot={row.markdown}
citations={row.role === 'assistant' ? row.message.citations : undefined}
math={math}
components={markdownComponents}
/>
);
return (
<ChatMessage
role={row.role}
Expand Down Expand Up @@ -684,6 +704,7 @@ export function MessageList<TRow extends MessageRow = MessageRow>({
generativeUi,
markdownComponents,
mergeReasoning,
a2uiActionLabels,
renderMessageActivity,
children,
renderScrollControl,
Expand Down Expand Up @@ -851,6 +872,7 @@ export function MessageList<TRow extends MessageRow = MessageRow>({
generativeUi={generativeUi}
markdownComponents={markdownComponents}
mergeReasoning={mergeReasoning !== false}
a2uiActionLabels={a2uiActionLabels}
renderMessageActivity={renderMessageActivity}
/>
{renderApprovalRecords(recordsAfter, row.id)}
Expand Down
11 changes: 11 additions & 0 deletions scripts/react-parity/dispositions.json
Original file line number Diff line number Diff line change
Expand Up @@ -15017,6 +15017,17 @@
"reason": "Internal hook projecting snapshots through app-passed message content, or owning one projection per session for Chat; not exported.",
"note": "Verified through the Chat DOM tests: owned disposal on unmount and session change, StrictMode recreation, and app-passed content never disposed. Not part of the public surface."
},
{
"id": "source:libs/react/src/chat/internal/a2ui-action-label.ts",
"taskIds": [
"T22",
"T27"
],
"treatment": "react",
"status": "in-progress",
"reason": "Internal reader giving the words for a user message that is a serialized A2UI action: its stamped label, or the action name in plain words; not exported.",
"note": "Verified through the MessageList and Chat DOM tests: default label, opt-out, name fallback, untouched non-action and assistant messages, and text-only rendering. Not part of the public surface."
},
{
"id": "source:libs/react/src/chat/message-list.tsx",
"taskIds": [
Expand Down
Loading