Ordo UI
AI助手与对话

Tool

@mox-hub/patterns · AI · 助手与对话 · canonical

tool@mox-hub/patternsAI Executioncanonicalsrc/components/tool.tsx
变体演示tool
完成
输入
{"status":"进行中"}
输出
{"count":3,"items":["A","B","C"]}
失败
错误
upstream timeout after 30s

Props API

Prop类型默认值说明
state*string——
defaultOpen*booleanfalse—
open*boolean——
onOpenChange*(open: boolean) => void——
autoOpenOnError*booleantrue—
children*ReactNode——
labels*Partial<ToolLabels>——
className*string——

源码

packages/patterns/src/components/tool.tsx
/**
 * Tool - 工具调用卡原子族(治理方案 W4 P0 · B4)
 *
 * 分层定位:本件是**低层结构与状态原子**,只负责折叠骨架、八态映射与开合语义;
 * `assistant-tool-card` 是**预设组合**——在同一套七态归一之上叠加动词×实体词表、
 * JSON 高亮/高度封顶、实体行卡、决策内联、live 计时与业务注入点(resolveEntity /
 * toolPresentation / renderDecision)。后续可把 assistant-tool-card 的通用骨架迁到
 * 本族之上;迁移完成前两者并存,本件刻意不引入 JSON 解析、实体推断或计时。
 *
 * 组成:
 * - `Tool`:状态与开合上下文(受控/非受控双模);
 * - `ToolHeader`:折叠头(button 语义 + aria-expanded / aria-controls + live 播报);
 * - `ToolContent`:内容区(关闭即条件卸载,比 inert 更彻底——不背隐藏 DOM);
 * - `ToolSection` / `ToolInput` / `ToolOutput` / `ToolError`:可选的展示分区。
 *
 * 状态归一:未知字符串一律落到 `input-available`(与 assistant-tool-card 的
 * `toolPartPhase` 一致),保证旧消费方传任意 part.state 都有稳定渲染。
 *
 * 自动开合:`output-error` / `output-denied` 默认自动展开、恢复后自动收起;
 * 受控 `open` 传入时完全不干预,用户手动切换后也不再自动干预。
 */

import {
  createContext,
  useContext,
  useId,
  useState,
  type ComponentProps,
  type ReactNode,
} from 'react';
import { Ban, CheckCircle2, ChevronDown, PauseCircle, XCircle } from 'lucide-react';
import { cn } from '@mox-hub/ui';
import { RawButton } from '@mox-hub/ui/components/raw/raw-button';
import { Spinner } from '@mox-hub/ui/components/spinner';
import { usePatternLabels } from '../lib/i18n';

/** UIMessage tool part 的八态(与 assistant-tool-card 的 ToolPartPhase 同构)。 */
export type ToolState =
  | 'input-streaming'
  | 'input-available'
  | 'approval-requested'
  | 'approval-responded'
  | 'approval-denied'
  | 'output-available'
  | 'output-error'
  | 'output-denied';

/** 文案覆写(缺省 zh-CN;消费方经 labels 覆写接入 i18n)。 */
export interface ToolLabels {
  /** input-available */
  running: string;
  /** input-streaming */
  preparing: string;
  approvalRequested: string;
  approvalResponded: string;
  approvalDenied: string;
  /** output-available */
  completed: string;
  /** output-error */
  failed: string;
  /** output-denied */
  outputDenied: string;
  /** 输入分区标签 */
  input: string;
  /** 输出分区标签 */
  output: string;
  /** 错误分区标签 */
  error: string;
  /** 折叠头展开动作(title 提示) */
  show: string;
  /** 折叠头收起动作(title 提示) */
  hide: string;
}

export const TOOL_DEFAULT_LABELS: ToolLabels = {
  running: '运行中',
  preparing: '准备参数中',
  approvalRequested: '等待批准',
  approvalResponded: '已批准',
  approvalDenied: '已拒绝',
  completed: '完成',
  failed: '失败',
  outputDenied: '调用被拒绝',
  input: '输入',
  output: '输出',
  error: '错误',
  show: '展开',
  hide: '收起',
};

/** 状态 → 文案键(未知状态已在 normalizeToolState 归一,不会到达此表)。 */
const STATUS_LABEL_KEYS: Record<ToolState, keyof ToolLabels> = {
  'input-streaming': 'preparing',
  'input-available': 'running',
  'approval-requested': 'approvalRequested',
  'approval-responded': 'approvalResponded',
  'approval-denied': 'approvalDenied',
  'output-available': 'completed',
  'output-error': 'failed',
  'output-denied': 'outputDenied',
};

/** 八态归一:未知值回退 input-available(最保守的「参数已就绪」态)。 */
function normalizeToolState(state: string): ToolState {
  switch (state) {
    case 'input-streaming':
    case 'input-available':
    case 'approval-requested':
    case 'approval-responded':
    case 'approval-denied':
    case 'output-available':
    case 'output-error':
    case 'output-denied':
      return state;
    default:
      return 'input-available';
  }
}

const ERROR_STATES = new Set<ToolState>(['output-error', 'output-denied']);

interface ToolContextValue {
  /** 归一侧的八态 */
  state: ToolState;
  open: boolean;
  /** 用户显式切换(受控时只发 onOpenChange;非受控时同步内部状态) */
  setOpen: (open: boolean) => void;
  labels: ToolLabels;
  /** 折叠头 id(内容区 aria-labelledby 指向它) */
  headerId: string;
  /** 内容区 id(折叠头 aria-controls 指向它) */
  contentId: string;
}

const ToolContext = createContext<ToolContextValue | null>(null);

function useToolContext(component: string): ToolContextValue {
  const context = useContext(ToolContext);
  if (!context) {
    throw new Error(`<${component}> must be used within <Tool>.`);
  }
  return context;
}

export interface ToolProps extends Omit<ComponentProps<'div'>, 'children'> {
  state: ToolState | string;
  defaultOpen?: boolean;
  open?: boolean;
  onOpenChange?: (open: boolean) => void;
  /** 失败自动展开 / 恢复自动收起,默认 true */
  autoOpenOnError?: boolean;
  children: ReactNode;
  labels?: Partial<ToolLabels>;
  className?: string;
}

export function Tool({
  state,
  defaultOpen = false,
  open: openProp,
  onOpenChange,
  autoOpenOnError = true,
  children,
  labels,
  className,
  ...rootProps
}: ToolProps) {
  const providerLabels = usePatternLabels('tool', TOOL_DEFAULT_LABELS);
  const mergedLabels: ToolLabels = { ...providerLabels, ...labels };
  const normalizedState = normalizeToolState(state);
  const uid = useId();
  const headerId = `${uid}-header`;
  const contentId = `${uid}-content`;
  const failed = ERROR_STATES.has(normalizedState);
  const controlled = openProp !== undefined;

  // 初始即失败也自动展开(defaultOpen 显式 true 时视为用户自己的展开,恢复后不代收)。
  const initialAutoOpen = !controlled && autoOpenOnError && failed;
  const [openState, setOpenState] = useState(defaultOpen || initialAutoOpen);
  const [autoOpened, setAutoOpened] = useState(initialAutoOpen && !defaultOpen);

  // 渲染期比对失败态迁移:失败 → 自动展开;恢复 → 仅收起「自动展开」的那次。
  const [prevFailed, setPrevFailed] = useState(failed);
  const [userToggled, setUserToggled] = useState(false);
  if (failed !== prevFailed) {
    setPrevFailed(failed);
    if (!controlled && autoOpenOnError) {
      if (failed && !userToggled && !openState) {
        setOpenState(true);
        setAutoOpened(true);
      } else if (!failed && autoOpened && !userToggled) {
        setOpenState(false);
        setAutoOpened(false);
      }
    }
  }

  const open = openProp ?? openState;
  const setOpen = (next: boolean) => {
    // 用户接管后不再自动开合
    setUserToggled(true);
    setAutoOpened(false);
    if (!controlled) setOpenState(next);
    onOpenChange?.(next);
  };

  return (
    <ToolContext.Provider
      value={{ state: normalizedState, open, setOpen, labels: mergedLabels, headerId, contentId }}
    >
      <div
        {...rootProps}
        data-slot="tool"
        data-ai-component="tool"
        data-tool-state={normalizedState}
        data-open={open || undefined}
        className={cn(
          'w-full overflow-hidden rounded-lg border border-border bg-background/40',
          className,
        )}
      >
        {children}
      </div>
    </ToolContext.Provider>
  );
}

export interface ToolHeaderProps {
  icon?: ReactNode;
  title: string;
  /** 右侧元信息(耗时、模型、状态文本等) */
  meta?: ReactNode;
  /** 状态图标/文本槽;不传则根据 Tool 的 state 自动渲染 */
  status?: ReactNode;
  className?: string;
}

/** 状态图标 + 文案(自动槽;status prop 传入时整体替换) */
function ToolStatus({ state, label }: { state: ToolState; label: string }) {
  const iconClass = 'size-3.5 shrink-0';
  let icon: ReactNode = null;
  let textClass = 'text-content-text-muted';
  switch (state) {
    case 'input-streaming':
    case 'input-available':
      icon = (
        <Spinner
          size="sm"
          aria-hidden="true"
          label={label}
          className={cn(iconClass, 'text-accent-blue')}
        />
      );
      break;
    case 'approval-requested':
      icon = (
        <PauseCircle aria-hidden="true" className={cn(iconClass, 'text-accent-yellow')} />
      );
      break;
    case 'approval-responded':
      icon = (
        <CheckCircle2 aria-hidden="true" className={cn(iconClass, 'text-accent-green')} />
      );
      break;
    case 'approval-denied':
    case 'output-error':
      icon = <XCircle aria-hidden="true" className={cn(iconClass, 'text-accent-red')} />;
      textClass = state === 'output-error' ? 'text-destructive' : textClass;
      break;
    case 'output-available':
      icon = (
        <CheckCircle2 aria-hidden="true" className={cn(iconClass, 'text-accent-green')} />
      );
      break;
    case 'output-denied':
      icon = <Ban aria-hidden="true" className={cn(iconClass, 'text-accent-red')} />;
      textClass = 'text-destructive';
      break;
  }
  return (
    <span
      data-slot="tool-status"
      data-state={state}
      className={cn('inline-flex min-w-0 shrink-0 items-center gap-1 text-xs', textClass)}
    >
      {icon}
      <span className="truncate">{label}</span>
    </span>
  );
}

export function ToolHeader({ icon, title, meta, status, className }: ToolHeaderProps) {
  const { state, open, setOpen, labels, headerId, contentId } = useToolContext('ToolHeader');
  const statusLabel = labels[STATUS_LABEL_KEYS[state]];

  return (
    <>
      {/* 状态迁移播报:放在 button 之外(button 后代在可访问树中会被呈现化) */}
      <span role="status" aria-live="polite" className="sr-only">
        {statusLabel}
      </span>
      <RawButton
        id={headerId}
        type="button"
        data-slot="tool-header"
        data-state={state}
        aria-expanded={open}
        aria-controls={contentId}
        title={open ? labels.hide : labels.show}
        onClick={() => setOpen(!open)}
        className={cn(
          'flex w-full items-center gap-1.5 rounded-lg px-2.5 py-1.5 text-start text-xs',
          'transition-colors duration-fast hover:bg-muted focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring/50',
          className,
        )}
      >
        {icon != null ? (
          <span
            data-slot="tool-header-icon"
            aria-hidden="true"
            className="shrink-0 text-content-text-muted"
          >
            {icon}
          </span>
        ) : null}
        <span data-slot="tool-header-title" className="shrink-0 font-medium text-content-text">
          {title}
        </span>
        {status !== undefined ? status : <ToolStatus state={state} label={statusLabel} />}
        <span className="min-w-0 flex-1" />
        {meta != null ? (
          <span
            data-slot="tool-header-meta"
            className="shrink-0 text-xs text-content-text-muted"
          >
            {meta}
          </span>
        ) : null}
        <ChevronDown
          aria-hidden="true"
          className={cn(
            'size-3 shrink-0 text-content-text-muted transition-transform duration-fast',
            open && 'rotate-180',
          )}
        />
      </RawButton>
    </>
  );
}

export interface ToolContentProps {
  children: ReactNode;
  className?: string;
}

export function ToolContent({ children, className }: ToolContentProps) {
  const { open, headerId, contentId } = useToolContext('ToolContent');
  // 关闭即卸载:不保留隐藏 DOM,也不存在焦点落入不可见区的路径(比 inert 更彻底)
  if (!open) return null;
  return (
    <div
      id={contentId}
      role="region"
      aria-labelledby={headerId}
      data-slot="tool-content"
      className={cn('space-y-1.5 border-t border-border/60 px-2.5 py-1.5 text-xs', className)}
    >
      {children}
    </div>
  );
}

interface ToolSectionBoxProps {
  slot: string;
  label?: string;
  tone?: 'default' | 'destructive';
  children: ReactNode;
  className?: string;
}

/** 分区底壳:muted 背景 + 等宽正文;错误档走 destructive 色。 */
function ToolSectionBox({
  slot,
  label,
  tone = 'default',
  children,
  className,
}: ToolSectionBoxProps) {
  const destructive = tone === 'destructive';
  return (
    <section
      data-slot={slot}
      className={cn('rounded-md px-2 py-1.5', destructive ? 'bg-destructive/10' : 'bg-muted/40', className)}
    >
      {label ? (
        <div
          className={cn(
            'mb-0.5 text-xs font-medium',
            destructive ? 'text-destructive' : 'text-content-text-muted',
          )}
        >
          {label}
        </div>
      ) : null}
      <div
        className={cn(
          'font-mono text-xs break-all whitespace-pre-wrap',
          destructive ? 'text-destructive' : 'text-content-text-secondary',
        )}
      >
        {children}
      </div>
    </section>
  );
}

export interface ToolSectionProps {
  label?: string;
  children: ReactNode;
  className?: string;
}

export function ToolSection({ label, children, className }: ToolSectionProps) {
  return (
    <ToolSectionBox slot="tool-section" label={label} className={className}>
      {children}
    </ToolSectionBox>
  );
}

export interface ToolInputProps {
  label?: string;
  children: ReactNode;
  className?: string;
}

export function ToolInput({ label, children, className }: ToolInputProps) {
  const { labels } = useToolContext('ToolInput');
  return (
    <ToolSectionBox slot="tool-input" label={label ?? labels.input} className={className}>
      {children}
    </ToolSectionBox>
  );
}

export interface ToolOutputProps {
  label?: string;
  children: ReactNode;
  className?: string;
}

export function ToolOutput({ label, children, className }: ToolOutputProps) {
  const { labels } = useToolContext('ToolOutput');
  return (
    <ToolSectionBox slot="tool-output" label={label ?? labels.output} className={className}>
      {children}
    </ToolSectionBox>
  );
}

export interface ToolErrorProps {
  message: string;
  label?: string;
  className?: string;
}

export function ToolError({ message, label, className }: ToolErrorProps) {
  const { labels } = useToolContext('ToolError');
  return (
    <ToolSectionBox
      slot="tool-error"
      label={label ?? labels.error}
      tone="destructive"
      className={className}
    >
      {message}
    </ToolSectionBox>
  );
}

可访问性与 RTL

  • 键盘:交互件保留:focus-visible焦点环;浮层支持 Escape 关闭与焦点归还,菜单 / 页签按 Base UI 约定支持方向键。 筛选菜单、拖拽排序、执行树与模型 listbox 等关键键盘流由 Playwright 断言覆盖,见规范示例 · 交互与可访问性。
  • RTL:间距、对齐与方向性图标使用逻辑属性 (ms-* /text-start /rtl:-scale-x-100);通过 ThemeProvider 或I18nProvider 的direction="rtl"驱动,`lint:rtl` 会拦截新增物理类。
  • 文案:优先用组件labels /translate /translator props,其次用I18nProvider目录;内置 zh-CN 默认值,en-US 为参考翻译。见Theming · i18n 与 RTL。
  • 对比度:高对比度 token、2px 控件边框与 3px 焦点环由主题层统一提供,见Foundations · Contrast。

用法说明

工具卡原子族:Tool/ToolHeader/ToolContent/ToolInput/ToolOutput/ToolError;状态七态归一,折叠区 inert,assistant-tool-card 是它的预设组合。