Ordo UI
AI执行与编排

TraceWaterfall

@mox-hub/patterns · AI · 执行与编排 · canonical

trace-waterfall@mox-hub/patternsAI Executioncanonicalsrc/components/trace-waterfall.tsx
变体演示trace-waterfall
4 个 span总耗时 1.0sToken 1980成本 US$0.01
发布编排1.0s
检索变更70ms
300
生成发布说明300ms
1680
运行冒烟测试450ms

Props API

Prop类型默认值说明
spans*TraceSpan[]——
window*{ start: number; end: number; }——
now*number——
collapsed*string[]——
onCollapsedChange*(ids: string[]) => void——
selectedId*string——
onSelect*(span: TraceSpan) => void——
showUsage*booleantrue—
maxRows*number500—
labels*Partial<TraceWaterfallLabels>——
className*string——

源码

packages/patterns/src/components/trace-waterfall.tsx
import {
  useEffect,
  useMemo,
  useState,
  type ComponentProps,
} from 'react';
import {
  Bot,
  Boxes,
  ChevronRight,
  Circle,
  MessageSquare,
  Search,
  Wrench,
} from 'lucide-react';

import { cn } from '@mox-hub/ui';
import { TONE_CLASS, type Tone } from '@mox-hub/ui/components/tone';
import {
  formatCompact,
  formatCurrency,
  formatLiveDuration,
} from '@mox-hub/ui/format';

import { usePatternLabels } from '../lib/i18n';

/**
 * TraceWaterfall —— 执行轨迹瀑布图(执行平面)。
 *
 * 数据契约对齐 **OpenTelemetry GenAI 语义约定**:
 * - `kind` 对应 `gen_ai.operation.name`(chat / execute_tool / invoke_agent /
 *   embeddings / retrieval / other);
 * - `model` ← `gen_ai.request.model`,`agentName` ← `gen_ai.agent.name`,
 *   `toolName` ← `gen_ai.tool.name`;
 * - `inputTokens` / `outputTokens` ← `gen_ai.usage.input_tokens` / `output_tokens`;
 * - `status` ← `Status.code`(unset / ok / error)。
 *
 * 输入是**扁平 span 列表**(OTel 导出就是扁平结构),组件按 `parentId` 建树。
 * 父 span 不在窗口内时该 span 提升为根——不丢孤儿,也不伪造层级。
 *
 * 视觉:横向时间条 + 左侧缩进树;时间轴固定 LTR(时间方向不随 RTL 反转),
 * 文本列走逻辑属性。折叠只隐藏子行,汇总统计始终按全量 span 计算(折叠不隐账)。
 */
export type TraceSpanKind =
  | 'chat'
  | 'execute_tool'
  | 'invoke_agent'
  | 'embeddings'
  | 'retrieval'
  | 'other';

export type TraceSpanStatus = 'unset' | 'ok' | 'error';

export interface TraceSpan {
  /** span id(OTel spanId) */
  id: string;
  /** 父 span id;缺省 / 找不到父级 → 根 */
  parentId?: string;
  /** span name(人类可读) */
  name: string;
  /** gen_ai.operation.name 归一值 */
  kind?: TraceSpanKind;
  /** Status.code */
  status?: TraceSpanStatus;
  /** 开始时间(毫秒时间戳,与挂钟同基准) */
  startTime: number;
  /** 结束时间;运行中不传 */
  endTime?: number;
  agentName?: string;
  model?: string;
  toolName?: string;
  inputTokens?: number;
  outputTokens?: number;
  /** 成本(USD) */
  cost?: number;
  /** 错误信息 */
  error?: string;
}

export interface TraceNode extends TraceSpan {
  depth: number;
  children: TraceNode[];
}

/** 扁平 span → 树。孤儿 span 提升为根;同级按 startTime 升序。 */
export function buildTraceTree(spans: TraceSpan[]): TraceNode[] {
  const byId = new Map<string, TraceNode>();
  for (const span of spans) {
    byId.set(span.id, { ...span, depth: 0, children: [] });
  }

  const roots: TraceNode[] = [];
  for (const node of byId.values()) {
    const parent = node.parentId ? byId.get(node.parentId) : undefined;
    if (parent) {
      parent.children.push(node);
    } else {
      roots.push(node);
    }
  }

  const sort = (nodes: TraceNode[], depth: number) => {
    nodes.sort((a, b) => a.startTime - b.startTime);
    for (const node of nodes) {
      node.depth = depth;
      sort(node.children, depth + 1);
    }
  };
  sort(roots, 0);

  return roots;
}

/** 树 → 按可见性拍平(折叠的子树不展开) */
export function flattenTraceTree(
  roots: TraceNode[],
  collapsed: ReadonlySet<string> = new Set(),
): TraceNode[] {
  const out: TraceNode[] = [];
  const walk = (nodes: TraceNode[]) => {
    for (const node of nodes) {
      out.push(node);
      if (!collapsed.has(node.id)) walk(node.children);
    }
  };
  walk(roots);
  return out;
}

const KIND_ICON = {
  chat: MessageSquare,
  execute_tool: Wrench,
  invoke_agent: Bot,
  embeddings: Boxes,
  retrieval: Search,
  other: Circle,
} as const;

const KIND_TONE: Record<TraceSpanKind, Tone> = {
  chat: 'info',
  execute_tool: 'info',
  invoke_agent: 'success',
  embeddings: 'warning',
  retrieval: 'warning',
  other: 'default',
};

const KIND_BAR: Record<TraceSpanKind, string> = {
  chat: 'bg-accent-purple/60',
  execute_tool: 'bg-accent-blue/60',
  invoke_agent: 'bg-accent-green/60',
  embeddings: 'bg-accent-orange/60',
  retrieval: 'bg-accent-yellow/60',
  other: 'bg-muted-foreground/40',
};

export interface TraceWaterfallLabels {
  /** 无障碍名 */
  region: string;
  empty: string;
  spans: (count: number) => string;
  running: string;
  duration: string;
  tokens: string;
  cost: string;
  expand: string;
  collapse: string;
  error: string;
}

export const TRACE_WATERFALL_DEFAULT_LABELS: TraceWaterfallLabels = {
  region: '执行轨迹',
  empty: '暂无执行轨迹',
  spans: (count) => `${count} 个 span`,
  running: '运行中',
  duration: '总耗时',
  tokens: 'Token',
  cost: '成本',
  expand: '展开子调用',
  collapse: '收起子调用',
  error: '出错',
};

export interface TraceWaterfallProps
  extends Omit<ComponentProps<'div'>, 'children' | 'onSelect'> {
  spans: TraceSpan[];
  /** 时间窗口;缺省取全量 span 的最早开始与最晚结束(运行中取 now) */
  window?: { start: number; end: number };
  /** 运行中时钟注入;缺省自跑 1s tick(仅存在运行中 span 时) */
  now?: number;
  /** 受控折叠集合;缺省内部维护 */
  collapsed?: string[];
  onCollapsedChange?: (ids: string[]) => void;
  /** 选中 span 高亮 */
  selectedId?: string;
  onSelect?: (span: TraceSpan) => void;
  /** 是否显示 token / 成本汇总;默认 true */
  showUsage?: boolean;
  /** 最大渲染行数;超出显示提示(默认 500,防长轨迹拖垮页面) */
  maxRows?: number;
  labels?: Partial<TraceWaterfallLabels>;
}

export function TraceWaterfall({
  spans,
  window: timeWindow,
  now,
  collapsed: collapsedProp,
  onCollapsedChange,
  selectedId,
  onSelect,
  showUsage = true,
  maxRows = 500,
  labels,
  className,
  ...props
}: TraceWaterfallProps) {
  const D = usePatternLabels('traceWaterfall', TRACE_WATERFALL_DEFAULT_LABELS);
  const text: TraceWaterfallLabels = {
    region: labels?.region ?? D.region,
    empty: labels?.empty ?? D.empty,
    spans: labels?.spans ?? D.spans,
    running: labels?.running ?? D.running,
    duration: labels?.duration ?? D.duration,
    tokens: labels?.tokens ?? D.tokens,
    cost: labels?.cost ?? D.cost,
    expand: labels?.expand ?? D.expand,
    collapse: labels?.collapse ?? D.collapse,
    error: labels?.error ?? D.error,
  };

  const controlled = collapsedProp !== undefined;
  const [innerCollapsed, setInnerCollapsed] = useState<Set<string>>(
    () => new Set(),
  );
  const collapsed = useMemo(
    () => (controlled ? new Set(collapsedProp) : innerCollapsed),
    [controlled, collapsedProp, innerCollapsed],
  );

  const toggle = (id: string) => {
    const next = new Set(collapsed);
    if (next.has(id)) next.delete(id);
    else next.add(id);
    if (!controlled) setInnerCollapsed(next);
    onCollapsedChange?.([...next]);
  };

  const roots = useMemo(() => buildTraceTree(spans), [spans]);
  // collapsed 是 Set:重建引用会重算,但内容变化必然来自 spans/受控值,成本可接受
  const rows = useMemo(
    () => flattenTraceTree(roots, collapsed),
    [roots, collapsed],
  );

  const hasRunning = spans.some((span) => span.endTime === undefined);
  const [clock, setClock] = useState(() => Date.now());
  useEffect(() => {
    if (!hasRunning || now !== undefined) return;
    const timer = setInterval(() => setClock(Date.now()), 1000);
    return () => clearInterval(timer);
  }, [hasRunning, now]);
  const current = now ?? clock;

  const bounds = useMemo(() => {
    if (spans.length === 0) return { start: 0, end: 1 };
    const start =
      timeWindow?.start ?? Math.min(...spans.map((span) => span.startTime));
    const end =
      timeWindow?.end ??
      Math.max(
        current,
        ...spans.map((span) => span.endTime ?? span.startTime),
      );
    return { start, end: end > start ? end : start + 1 };
  }, [spans, timeWindow, current]);

  const totalTokens = spans.reduce(
    (sum, span) => sum + (span.inputTokens ?? 0) + (span.outputTokens ?? 0),
    0,
  );
  const totalCost = spans.reduce((sum, span) => sum + (span.cost ?? 0), 0);
  const totalDuration = bounds.end - bounds.start;
  const visibleRows = rows.slice(0, maxRows);
  const hiddenRows = rows.length - visibleRows.length;

  if (spans.length === 0) {
    return (
      <div
        data-ai-component="trace.waterfall"
        className={cn(
          'rounded-lg border border-content-border bg-content-bg-secondary p-4 text-center text-xs text-content-text-muted',
          className,
        )}
        {...props}
      >
        {text.empty}
      </div>
    );
  }

  return (
    <div
      role="region"
      aria-label={text.region}
      data-ai-component="trace.waterfall"
      className={cn(
        'overflow-hidden rounded-lg border border-content-border bg-content-bg',
        className,
      )}
      {...props}
    >
      <header className="flex flex-wrap items-center gap-x-4 gap-y-1 border-b border-content-border bg-content-bg-secondary px-3 py-2 text-2xs text-content-text-secondary">
        <span className="font-semibold text-content-text">
          {text.spans(spans.length)}
        </span>
        <span>
          {text.duration}{' '}
          <span className="tabular-nums text-content-text">
            {formatLiveDuration(totalDuration)}
          </span>
        </span>
        {showUsage ? (
          <>
            <span>
              {text.tokens}{' '}
              <span className="tabular-nums text-content-text">
                {formatCompact(totalTokens)}
              </span>
            </span>
            <span>
              {text.cost}{' '}
              <span className="tabular-nums text-content-text">
                {formatCurrency(totalCost)}
              </span>
            </span>
          </>
        ) : null}
      </header>

      <div className="divide-y divide-content-border-light">
        {visibleRows.map((node) => {
          const kind = node.kind ?? 'other';
          const Icon = KIND_ICON[kind];
          const tone = node.status === 'error' ? 'danger' : KIND_TONE[kind];
          const running = node.endTime === undefined;
          const end = node.endTime ?? current;
          const left = ((node.startTime - bounds.start) / totalDuration) * 100;
          const width = Math.max(
            ((end - node.startTime) / totalDuration) * 100,
            0.75,
          );
          const hasChildren = node.children.length > 0;
          const isCollapsed = collapsed.has(node.id);

          return (
            <div
              key={node.id}
              data-ai-component="trace.row"
              data-status={node.status ?? 'unset'}
              data-selected={selectedId === node.id ? 'true' : undefined}
              className={cn(
                'flex items-stretch gap-2 px-2 py-1 transition-colors duration-fast',
                selectedId === node.id
                  ? 'bg-accent-blue-light/50'
                  : 'hover:bg-muted',
              )}
            >
              <div
                className="flex w-56 shrink-0 items-center gap-1 text-xs"
                style={{ paddingInlineStart: node.depth * 12 }}
              >
                {hasChildren ? (
                  <button
                    type="button"
                    aria-label={isCollapsed ? text.expand : text.collapse}
                    aria-expanded={!isCollapsed}
                    className="rounded-sm p-0.5 text-content-text-muted outline-none transition-colors duration-fast hover:text-content-text focus-visible:ring-2 focus-visible:ring-ring/50"
                    onClick={() => toggle(node.id)}
                  >
                    <ChevronRight
                      aria-hidden
                      className={cn(
                        'size-3 transition-transform duration-fast',
                        !isCollapsed && 'rotate-90',
                      )}
                    />
                  </button>
                ) : (
                  <span className="size-4 shrink-0" aria-hidden />
                )}

                <Icon
                  aria-hidden
                  className={cn('size-3.5 shrink-0', TONE_CLASS[tone].text)}
                />
                {onSelect ? (
                  <button
                    type="button"
                    className="min-w-0 flex-1 cursor-pointer truncate rounded-sm text-start outline-none focus-visible:ring-2 focus-visible:ring-ring/50"
                    title={node.error ?? node.name}
                    onClick={() => onSelect(node)}
                  >
                    {node.name}
                  </button>
                ) : (
                  <span
                    className="min-w-0 flex-1 truncate"
                    title={node.error ?? node.name}
                  >
                    {node.name}
                  </span>
                )}
                <span className="shrink-0 tabular-nums text-2xs text-content-text-muted">
                  {running
                    ? text.running
                    : formatLiveDuration(end - node.startTime)}
                </span>
              </div>

              <div className="relative min-w-0 flex-1" dir="ltr">
                <div className="relative h-5">
                  <span
                    className={cn(
                      'absolute inset-y-0.5 rounded-sm',
                      node.status === 'error'
                        ? 'bg-destructive/60'
                        : KIND_BAR[kind],
                      selectedId === node.id && 'ring-1 ring-ring',
                    )}
                    style={{ left: `${left}%`, width: `${width}%` }}
                    aria-hidden
                  />
                  {showUsage &&
                  (node.inputTokens ?? 0) + (node.outputTokens ?? 0) > 0 ? (
                    <span
                      className="absolute top-1/2 -translate-y-1/2 ps-1 text-2xs tabular-nums text-content-text-muted"
                      style={{ left: `${Math.min(left + width, 96)}%` }}
                    >
                      {formatCompact(
                        (node.inputTokens ?? 0) + (node.outputTokens ?? 0),
                      )}
                    </span>
                  ) : null}
                </div>
              </div>
            </div>
          );
        })}
      </div>

      {hiddenRows > 0 ? (
        <div className="border-t border-content-border bg-content-bg-secondary px-3 py-1.5 text-2xs text-content-text-muted">
          +{hiddenRows}
        </div>
      ) : 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 /translator props,其次用I18nProvider目录;内置 zh-CN 默认值,en-US 为参考翻译。见Theming · i18n 与 RTL。
  • 对比度:高对比度 token、2px 控件边框与 3px 焦点环由主题层统一提供,见Foundations · Contrast。

用法说明

执行轨迹瀑布图:输入扁平 span(OTel GenAI 语义:kind/model/agentName/toolName/inputTokens/outputTokens/status),按 parentId 建树、孤儿提升为根;时间轴固定 LTR,折叠不隐账,maxRows 截断如实报。