AI助手与对话
AssistantMessageList
@mox-hub/patterns · AI · 助手与对话 · canonical
assistant-message-list@mox-hub/patternsAI Executioncanonicalsrc/components/assistant-message-list.tsx变体演示assistant-message-list
Props API
| Prop | 类型 | 默认值 | 说明 |
|---|---|---|---|
| messages* | AssistantMessageView[] | — | — |
| status* | string | — | — |
| error* | { message: string; } | — | — |
| onDismissError* | () => void | — | — |
| renderText* | (text: string) => ReactNode | (value) => <span className="whitespace-pre-wrap">{value}</span> | — |
| renderTool* | (part: AssistantToolPart, index: number) => ReactNode | (part) => <AssistantToolCard part={part} /> | — |
| renderToolGroup* | (children: ReactNode[], key: string) => ReactNode | — | — |
| renderToolGroupParts* | (parts: AssistantToolPart[], renderTool: (part: AssistantToolPart, index: number) => ReactNode, key: string) => ReactNode | — | — |
| isDecisionPart* | (part: AssistantToolPart) => boolean | isDecisionToolPart | — |
| stickToBottom* | boolean | false | — |
| stickThreshold* | number | 48 | — |
| maxHeight* | string | number | '60vh' | — |
| renderActions* | (message: AssistantMessageView) => ReactNode | — | — |
| renderReasoning* | (part: AssistantMessagePart) => ReactNode | — | — |
| renderPending* | () => ReactNode | — | — |
| labels* | Partial<AssistantMessageListLabels> | — | — |
源码
/**
* 消息流 —— assistant 左侧(Bot 头像 + 气泡)、user 右侧气泡。
* text 段经 renderText 注入(默认纯文本),tool 段默认走 AssistantToolCard,
* 连续工具卡 ≥2 张折叠为 AssistantToolGroup。
*
* 库内不依赖 ai 包 / chat hook / MarkdownView:消息、错误与渲染器全部由 props 注入。
*/
import {
Children,
Fragment,
useCallback,
useEffect,
useRef,
useState,
type ReactNode,
} from 'react'
import { ArrowDown, Bot } from 'lucide-react'
import { Button } from '@mox-hub/ui/components/button'
import { usePatternLabels } from '../lib/i18n'
import {
AssistantToolCard,
AssistantToolGroup,
isDecisionToolPart,
type AssistantToolPart,
} from './assistant-tool-card'
import { ThinkingLoader } from './thinking-loader'
/**
* UIMessage part 的防御性形状(库内不直接依赖 ai 包,避免类型强耦合)。
*
* 已知类型:
* - `text`:正文段,内容在 `text`;
* - `reasoning`:思考段,内容在 `text`;
* - `tool-<toolName>`:工具调用段,典型字段见 AssistantToolPart
* (toolName / state / input / output / errorText)。
*
* 其余字段经索引签名透传,作为上游类型演进的逃生口;消费方读取时自行收窄。
*/
export interface AssistantMessagePart {
type: string
text?: string
[key: string]: unknown
}
export interface AssistantMessageView {
id: string
role: string
parts: AssistantMessagePart[]
metadata?: { runStatus?: string }
}
/** 组件内文案缺省(中文常量;消费方经 labels 覆写接入 i18n)。 */
export interface AssistantMessageListLabels {
working: string
thinking: string
dismissError: string
scrollToBottom: string
}
export const ASSISTANT_MESSAGE_LIST_DEFAULT_LABELS: AssistantMessageListLabels = {
working: '执行中…',
thinking: '正在思考…',
dismissError: '忽略',
scrollToBottom: '回到底部',
}
export interface AssistantMessageListProps {
messages: AssistantMessageView[]
/** submitted = 等待首包;其他值不渲染思考行 */
status?: string
error?: { message: string } | null
onDismissError?: () => void
/** text 段渲染器(主仓注入 MarkdownView);缺省纯文本 */
renderText?: (text: string) => ReactNode
/** 工具卡渲染器;缺省 AssistantToolCard(无决策卡注入) */
renderTool?: (part: AssistantToolPart, index: number) => ReactNode
/**
* 连续工具卡组渲染器(旧契约):接收已渲染的子节点数组与组 key。
* 缺省使用 AssistantToolGroup 的新契约(parts + renderTool),不再向子元素注入 part。
*/
renderToolGroup?: (children: ReactNode[], key: string) => ReactNode
/**
* 连续工具卡组渲染器(新契约):接收 part 列表与 renderTool,自行渲染组。
* 优先于 renderToolGroup;缺省 AssistantToolGroup 从 parts 现算汇总。
*/
renderToolGroupParts?: (
parts: AssistantToolPart[],
renderTool: (part: AssistantToolPart, index: number) => ReactNode,
key: string,
) => ReactNode
/** 决策建议工具判定;缺省 isDecisionToolPart */
isDecisionPart?: (part: AssistantToolPart) => boolean
/** 开启吸底滚动容器(默认关闭,保持旧布局零变化) */
stickToBottom?: boolean
/** 距底部多少 px 内视为贴底(默认 48) */
stickThreshold?: number
/** 吸底容器最大高度;数字按 px,默认 60vh */
maxHeight?: number | string
/** 每行消息的操作插槽(复制/重试/编辑/反馈) */
renderActions?: (message: AssistantMessageView) => ReactNode
/** reasoning 段渲染器;缺省纯文本 */
renderReasoning?: (part: AssistantMessagePart) => ReactNode
/** 等待首包行渲染器;缺省 ThinkingLoader */
renderPending?: () => ReactNode
labels?: Partial<AssistantMessageListLabels>
}
function AssistantBubble({
message,
renderText,
renderTool,
renderToolGroup,
renderToolGroupParts,
isDecisionPart,
renderReasoning,
text,
}: {
message: AssistantMessageView
renderText: (text: string) => ReactNode
renderTool: (part: AssistantToolPart, index: number) => ReactNode
renderToolGroup?: (children: ReactNode[], key: string) => ReactNode
renderToolGroupParts?: (
parts: AssistantToolPart[],
renderTool: (part: AssistantToolPart, index: number) => ReactNode,
key: string,
) => ReactNode
isDecisionPart: (part: AssistantToolPart) => boolean
renderReasoning?: (part: AssistantMessagePart) => ReactNode
text: AssistantMessageListLabels
}) {
const runStatus = message.metadata?.runStatus
if (message.parts.length === 0) {
const working = runStatus === 'running'
return (
<div data-ai-component="assistant.message-pending">
<ThinkingLoader
state={working ? 'working' : 'thinking'}
labels={{ working: text.working, thinking: text.thinking }}
/>
</div>
)
}
// 连续工具卡折叠为组汇总(≥2 张才成组);决策建议卡始终独立渲染
const nodes: ReactNode[] = []
let toolRun: { part: AssistantToolPart; index: number }[] = []
const flushToolRun = () => {
if (toolRun.length === 0) return
const run = toolRun
toolRun = []
// 单张卡:keyed Fragment 包裹,renderTool 的返回值无需自带 key。
if (run.length < 2) {
for (const { part, index } of run) {
nodes.push(<Fragment key={index}>{renderTool(part, index)}</Fragment>)
}
return
}
const groupKey = `tool-group-${run[0].index}`
const parts = run.map(({ part }) => part)
// 组内索引映射回消息 parts 原始索引,保持 renderTool(part, index) 契约稳定。
const renderRunTool = (part: AssistantToolPart, index: number) =>
renderTool(part, run[index]?.index ?? index)
if (renderToolGroupParts) {
nodes.push(
<Fragment key={groupKey}>
{renderToolGroupParts(parts, renderRunTool, groupKey)}
</Fragment>,
)
return
}
if (renderToolGroup) {
// 旧契约兼容:先渲染子节点;Children.toArray 统一补 key,不对元素注入 part。
const children = Children.toArray(
run.map(({ part, index }) => renderTool(part, index)),
)
nodes.push(<Fragment key={groupKey}>{renderToolGroup(children, groupKey)}</Fragment>)
return
}
// 缺省:AssistantToolGroup 直接从 parts 现算汇总。
nodes.push(
<Fragment key={groupKey}>
<AssistantToolGroup parts={parts} renderTool={renderRunTool} />
</Fragment>,
)
}
message.parts.forEach((part, index) => {
if (part.type.startsWith('tool-')) {
const toolPart = part as unknown as AssistantToolPart
if (isDecisionPart(toolPart)) {
flushToolRun()
nodes.push(<Fragment key={index}>{renderTool(toolPart, index)}</Fragment>)
return
}
toolRun.push({ part: toolPart, index })
return
}
flushToolRun()
if (part.type === 'reasoning') {
const content = typeof part.text === 'string' ? part.text : ''
if (!content) return
nodes.push(
<div className="w-full" key={index}>
{renderReasoning ? (
renderReasoning(part)
) : (
<p className="break-words text-xs whitespace-pre-wrap text-content-text-muted">
{content}
</p>
)}
</div>,
)
return
}
if (part.type === 'text') {
if (!part.text) return
nodes.push(
<div
className="w-full break-words rounded-lg bg-content-bg-secondary px-3 py-2 text-sm text-content-text"
key={index}
>
{renderText(part.text)}
</div>,
)
}
})
flushToolRun()
return (
<div
className="flex min-w-0 max-w-4/5 flex-col items-start gap-1.5"
data-ai-component="assistant.message-assistant"
>
{nodes}
</div>
)
}
function MessageRow({
message,
renderText,
renderTool,
renderToolGroup,
renderToolGroupParts,
isDecisionPart,
renderReasoning,
renderActions,
text,
}: {
message: AssistantMessageView
renderText: (text: string) => ReactNode
renderTool: (part: AssistantToolPart, index: number) => ReactNode
renderToolGroup?: (children: ReactNode[], key: string) => ReactNode
renderToolGroupParts?: (
parts: AssistantToolPart[],
renderTool: (part: AssistantToolPart, index: number) => ReactNode,
key: string,
) => ReactNode
isDecisionPart: (part: AssistantToolPart) => boolean
renderReasoning?: (part: AssistantMessagePart) => ReactNode
renderActions?: (message: AssistantMessageView) => ReactNode
text: AssistantMessageListLabels
}) {
const isUser = message.role === 'user'
const actions = renderActions ? renderActions(message) : null
if (isUser) {
const content = message.parts
.filter((part) => part.type === 'text')
.map((part) => part.text ?? '')
.join('')
return (
<div
className="group/message flex flex-col items-end gap-1"
data-ai-component="assistant.message-user"
>
<div className="max-w-4/5 rounded-lg bg-accent-blue-light px-3 py-2 text-sm whitespace-pre-wrap break-words text-content-text">
{content}
</div>
{actions}
</div>
)
}
return (
<div
className="group/message flex flex-col gap-1"
data-ai-component="assistant.message-assistant-row"
>
<div className="flex items-start gap-2">
<span className="flex size-6 shrink-0 items-center justify-center rounded-lg bg-accent-purple-light text-accent-purple">
<Bot className="size-3.5" />
</span>
<AssistantBubble
message={message}
renderText={renderText}
renderTool={renderTool}
renderToolGroup={renderToolGroup}
renderToolGroupParts={renderToolGroupParts}
isDecisionPart={isDecisionPart}
renderReasoning={renderReasoning}
text={text}
/>
</div>
{actions ? <div className="ps-8">{actions}</div> : null}
</div>
)
}
export function AssistantMessageList({
messages,
status,
error,
onDismissError,
renderText = (value) => <span className="whitespace-pre-wrap">{value}</span>,
renderTool = (part) => <AssistantToolCard part={part} />,
renderToolGroup,
renderToolGroupParts,
isDecisionPart = isDecisionToolPart,
stickToBottom = false,
stickThreshold = 48,
maxHeight = '60vh',
renderActions,
renderReasoning,
renderPending,
labels,
}: AssistantMessageListProps) {
const D = usePatternLabels(
'assistantMessageList',
ASSISTANT_MESSAGE_LIST_DEFAULT_LABELS,
)
const text = {
working: labels?.working ?? D.working,
thinking: labels?.thinking ?? D.thinking,
dismissError: labels?.dismissError ?? D.dismissError,
scrollToBottom: labels?.scrollToBottom ?? D.scrollToBottom,
}
const scrollRef = useRef<HTMLDivElement>(null)
const [atBottom, setAtBottom] = useState(true)
const scrollToBottom = useCallback((behavior: ScrollBehavior = 'smooth') => {
const node = scrollRef.current
if (!node) return
if (behavior === 'auto') {
node.scrollTop = node.scrollHeight
return
}
node.scrollTo?.({ top: node.scrollHeight, behavior })
}, [])
const handleScroll = useCallback(() => {
const node = scrollRef.current
if (!node) return
setAtBottom(
node.scrollHeight - node.scrollTop - node.clientHeight <= stickThreshold,
)
}, [stickThreshold])
// 内容增长 + 原本贴底 → 继续贴底(用户上翻后不抢滚动位置)
useEffect(() => {
if (!stickToBottom || !atBottom) return
scrollToBottom('auto')
}, [messages, status, error, atBottom, stickToBottom, scrollToBottom])
useEffect(() => {
if (!stickToBottom) return
const node = scrollRef.current
if (!node || typeof ResizeObserver === 'undefined') return
const observer = new ResizeObserver(() => {
if (atBottom) scrollToBottom('auto')
})
observer.observe(node)
if (node.firstElementChild) observer.observe(node.firstElementChild)
return () => observer.disconnect()
}, [stickToBottom, atBottom, scrollToBottom])
const body = (
<>
{messages.map((message) => (
<MessageRow
key={message.id}
message={message}
renderText={renderText}
renderTool={renderTool}
renderToolGroup={renderToolGroup}
renderToolGroupParts={renderToolGroupParts}
isDecisionPart={isDecisionPart}
renderReasoning={renderReasoning}
renderActions={renderActions}
text={text}
/>
))}
{status === 'submitted' ? (
<div className="flex items-start gap-2" data-ai-component="assistant.message-thinking">
<span className="flex size-6 shrink-0 items-center justify-center rounded-lg bg-accent-purple-light text-accent-purple">
<Bot className="size-3.5" />
</span>
{renderPending ? (
renderPending()
) : (
<ThinkingLoader
labels={{ thinking: text.thinking, working: text.working }}
/>
)}
</div>
) : null}
{error ? (
<div className="flex flex-col items-end gap-1" data-ai-component="assistant.message-error">
<div className="max-w-4/5 rounded-lg border border-accent-red/30 bg-accent-red-light/60 px-3 py-2 text-xs text-accent-red">
<p className="break-words">{error.message}</p>
{onDismissError ? (
// 次要操作贴右下;按钮语义不叠加文字下划线
<button
type="button"
onClick={onDismissError}
className="mt-1 block cursor-pointer text-2xs transition-opacity hover:opacity-80 ms-auto"
>
{text.dismissError}
</button>
) : null}
</div>
</div>
) : null}
</>
)
if (!stickToBottom) {
return (
<div className="space-y-3" data-ai-component="assistant.message-list">
{body}
</div>
)
}
return (
<div className="relative" data-ai-component="assistant.message-list">
<div
ref={scrollRef}
role="log"
aria-live="polite"
tabIndex={0}
onScroll={handleScroll}
style={{ maxHeight }}
className="space-y-3 overflow-y-auto overscroll-contain pe-1 outline-none focus-visible:ring-2 focus-visible:ring-ring/50"
data-ai-component="assistant.message-scroll"
>
{body}
</div>
{!atBottom ? (
<Button
type="button"
variant="outline"
size="xs"
className="absolute end-2 bottom-2 bg-background shadow-xs"
onClick={() => scrollToBottom()}
>
<ArrowDown aria-hidden />
{text.scrollToBottom}
</Button>
) : null}
</div>
)
}
可访问性与 RTL
- 键盘:交互件保留
:focus-visible焦点环;浮层支持 Escape 关闭与焦点归还,菜单 / 页签按 Base UI 约定支持方向键。 筛选菜单、拖拽排序、执行树与模型 listbox 等关键键盘流由 Playwright 断言覆盖,见规范示例 · 交互与可访问性。 - RTL:间距、对齐与方向性图标使用逻辑属性 (
ms-*/text-start/rtl:-scale-x-100);通过ThemeProvider或I18nProvider的direction="rtl"驱动,`lint:rtl` 会拦截新增物理类。 - 文案:优先用组件
labels/translate/translatorprops,其次用I18nProvider目录;内置 zh-CN 默认值,en-US 为参考翻译。见Theming · i18n 与 RTL。 - 对比度:高对比度 token、2px 控件边框与 3px 焦点环由主题层统一提供,见Foundations · Contrast。
用法说明
消息流:user 右侧/assistant 左侧气泡,text 经 renderText、tool 经 renderTool 注入;连续工具卡自动折叠成组;reasoning 段经 renderReasoning、每行操作经 renderActions 注入。stickToBottom 开启吸底滚动容器(role=log,回到底部按钮),默认关闭保持旧布局。