🧩 组件架构与布局系统详解

理解 AppLayout 主布局、Header/Sider/Footer 组件、Agent 对话组件、MCP 和 Prompt 管理组件

本课程聚焦 src/components/ 目录,它是 Kuai 前端的 UI 层。项目使用 Ant Design 6 + Ant Design X 作为 UI 库,采用 CSS Modules 进行样式隔离,所有组件均为 React 客户端组件。

📚 前置知识

📁 组件目录结构

src/components/ ├── AppLayout.jsx # 主布局组件(整个应用的壳) ├── layout/ # 布局组件 │ ├── header/ # 顶部导航栏 │ │ ├── index.jsx # BasicHeader 组件 │ │ └── index.module.css # 样式 │ ├── footer/ # 底部信息栏 │ │ └── index.jsx │ └── sider/ # 左侧导航 │ └── SideNav.jsx # 侧边栏菜单 │ ├── features/ # 功能组件(按业务模块组织) │ ├── agent/ # Agent 相关组件 │ │ ├── agent-common/ # 通用 Agent 组件(技能管理、使用统计) │ │ ├── diagram-editor/ # Draw.io 图表编辑器 │ │ ├── test-case-editor/ # 测试用例脑图编辑器 │ │ ├── rating/ # Agent 评分系统 │ │ ├── AgentHeaderActions/# Agent 页面头部操作 │ │ └── AgentScheduleManager/ # 定时任务管理 │ ├── mcp/ # MCP 管理组件 │ │ └── ToolDebugModal.jsx # 工具调试弹窗 │ ├── prompt/ # 提示词管理组件 │ └── share/ # 分享功能 │ └── EmbedCodeGenerator.jsx │ ├── common/ # 通用组件 │ ├── AgentChat/ # ⭐ Agent 对话组件(核心) │ │ ├── index.jsx # 主组件(1845 行) │ │ ├── AgentChat.module.css │ │ └── submitKeyMode.js # 发送快捷键配置 │ ├── ChatMessage/ # 消息渲染 │ ├── ChatContentWrapper/ # 内容包装 │ ├── ClaudeCodeTracker/ # Claude Code 执行追踪 │ ├── TodoTracker/ # Todo 追踪器 │ ├── ThinkingProcess/ # 思考过程展示 │ ├── StatusBanner/ # 状态横幅 │ └── XmindProgressBanner/ # XMind 进度横幅 │ ├── ai-elements/ # AI 对话 UI 元素 │ ├── message.jsx # 消息组件 │ └── tool.jsx # 工具调用组件 │ └── ui/ # 基础 UI 组件 ├── button.jsx ├── input.jsx ├── spinner.jsx ├── tooltip.jsx └── ...

🏠 AppLayout 主布局

入口组件 src/components/AppLayout.jsx 是整个应用的布局壳,它决定了页面的整体结构。

布局结构

// src/components/AppLayout.jsx (简化)
'use client';

function AppLayoutContent({ children }) {
  const [menuCollapsed, setMenuCollapsed] = useState(false);
  const pathname = usePathname();
  const fullScreen = useSelector((state) => state.config.fullScreen);

  // 判断是否是特殊页面(不需要导航栏)
  const isSharePage = pathname?.startsWith('/share');
  const isEmbedPage = pathname?.startsWith('/metrics/embed');
  const isAgentPage = pathname?.startsWith('/agents');
  const useMobileAppShell = isMobile && isAgentPage;

  // 分享页面/嵌入页面:简洁布局
  if (isSharePage || isEmbedPage || useMobileAppShell) {
    return <div style={{ minHeight: '100dvh' }}>{children}</div>;
  }

  // 标准布局:Header + Sider + Content + Footer
  return (
    <Layout style={{ height: '100vh' }}>
      {!fullScreen && <Header />}           {/* 顶部导航栏 */}
      <Layout style={{ flex: 1 }}>
        {!fullScreen && (                     {/* 左侧菜单 */}
          <Layout.Sider collapsible collapsed={menuCollapsed}>
            <SideNav />
          </Layout.Sider>
        )}
        <Layout>
          <Footer />                          {/* 底部(绝对定位) */}
          <Layout.Content>                    {/* 主内容区 */}
            {children}
          </Layout.Content>
        </Layout>
      </Layout>
    </Layout>
  );
}

布局模式对比

页面类型 Header Sider Footer 判断条件
标准页面 显示 显示(可折叠) 显示 默认
全屏模式 隐藏 隐藏 显示 fullScreen=true(ESC 退出)
分享页面 隐藏 隐藏 隐藏 /share 路径
嵌入页面 隐藏 隐藏 隐藏 /metrics/embed 路径
移动端 Agent 隐藏 隐藏 隐藏 isMobile + /agents

性能优化:并行请求

AppLayout 在挂载时使用 Promise.all() 并行获取所有初始化数据:

await Promise.all([
  dispatch(fetchUserDataAction()),  // 用户信息
  dispatch(getMoonApps()),          // Moon 应用
  dispatch(getAgileGroup()),        // 敏捷组
  dispatch(getBusinessLine()),      // 业务线
  dispatch(getGroup()),             // 组织架构
]);

这比串行请求减少 30-50% 的首屏加载时间。

🔝 Header / Sider / Footer 组件

Header(顶部导航栏)

src/components/layout/header/index.jsx 包含:

// 路径到中文标签的映射(部分)
const PATH_LABEL_MAP = {
  application: 'Agent管理',
  knowledge: '知识库',
  'prompt-system': '提示词管理',
  metrics: '度量指标管理',
  rating: '评分',
  history: '历史记录',
  // ...
};

Sider(侧边栏)

src/components/layout/sider/SideNav.jsx 是导航菜单组件:

Footer(底部栏)

Footer 使用绝对定位覆盖在内容区下方,可被内容滚动覆盖。包含版本信息和版权信息。

💬 Agent 对话组件

核心组件 src/components/common/AgentChat/index.jsx 是最重要的功能组件,有 1845 行代码,负责 Agent 对话的全部 UI 交互。

组件结构

AgentChat (index.jsx) ├── Conversation # 对话容器(自动滚动) │ ├── ConversationEmptyState # 空状态(欢迎页 + 示例问题) │ └── ConversationContent # 消息列表 │ └── Message × N # 每条消息 │ ├── MessageContent # 消息内容 │ │ ├── ThinkingProcess # AI 思考过程 │ │ ├── Streamdown # 流式 Markdown 渲染 │ │ ├── TodoTracker # Todo 追踪 │ │ ├── ClaudeCodeTracker # 代码执行追踪 │ │ ├── UIRenderer # 自定义 UI 渲染 │ │ └── Tool × N # 工具调用展示 │ │ ├── ToolHeader # 工具名称 + 状态 │ │ ├── ToolInput # 输入参数 │ │ └── ToolOutput # 输出结果 │ ├── MessageActions # 操作按钮(复制、重新生成等) │ └── StatusBanner # 状态横幅(思考中、初始化等) ├── InputArea # 输入区域 │ ├── 图片上传 # COS 图片上传 │ ├── TextArea # 文本输入 │ └── 发送按钮 # 发送/停止 └── ConversationScrollButton # 回到底部按钮

流式渲染

AgentChat 使用 Streamdown 库进行流式 Markdown 渲染,支持:

Streamdown 能在流式接收过程中实时渲染不完整的 Markdown,比如正在接收的代码块会显示为"正在编写代码..."。

消息发送流程

// 简化的发送流程
const sendMessage = async (text) => {
  // 1. 添加用户消息到本地状态
  addMessage({ role: 'user', content: text });

  // 2. 添加 assistant 占位消息(显示"思考中...")
  addMessage({
    role: 'assistant',
    content: '',
    isInitializing: true,
  });

  // 3. 调用 API,获取 SSE 流
  const response = await fetch(`/api/agents/${agentId}/chat`, {
    method: 'POST',
    body: JSON.stringify({ message: text, sessionId }),
  });

  // 4. 消费流式响应,逐步更新 assistant 消息
  const reader = response.body.getReader();
  while (true) {
    const { done, value } = await reader.read();
    if (done) break;
    // 解析 SSE 数据,更新消息的 parts 数组
    updateMessage(sseData);
  }
};

🔧 MCP 管理组件

功能模块 MCP(Model Context Protocol)管理组件在 src/components/features/mcp/ 目录下。

ToolDebugModal

ToolDebugModal.jsx 是 MCP 工具调试弹窗,允许开发者:

MCP 工具的 CRUD 操作通过 src/services/modules/mcp.js 调用 Java 后端 API,前端组件主要负责展示和交互。MCP Proxy API 通过 src/app/api/proxy/mcphub/[...path]/route.js 代理到 MCPHub 服务。

📝 Prompt 管理组件

Prompt 管理组件分布在 src/components/features/prompt/ 和相关页面中,核心功能包括:

Prompt 服务层

Prompt 的 API 调用通过 src/services/modules/prompt.js 封装,调用 Java 后端的 Prompt API。前端的 src/lib/agents/prompt.js 则负责在 Agent 运行时管理 Prompt 的加载和缓存。

🧰 通用组件详解

ClaudeCodeTracker

src/components/common/ClaudeCodeTracker/ 追踪 Claude Code 代理的执行过程,展示代码分析、文件读写等操作的实时进度。

TodoTracker

src/components/common/TodoTracker/ 展示 Agent 的 Todo 列表,Agent 可以通过 write_todos 工具管理任务清单,前端实时渲染进度。

ThinkingProcess

展示 AI 的"思考过程"(thinking/reasoning),以可折叠的方式呈现,用户可以展开查看 AI 的推理步骤。

ai-elements 组件库

src/components/ai-elements/ 提供对话 UI 的基础构建块:

// message.jsx — 消息组件
<Message>
  <MessageContent>...</MessageContent>
  <MessageResponse>...</MessageResponse>
  <MessageActions>
    <MessageAction onClick={copy}>复制</MessageAction>
    <MessageAction onClick={regenerate}>重新生成</MessageAction>
  </MessageActions>
</Message>

// tool.jsx — 工具调用组件
<Tool>
  <ToolHeader>文件读取</ToolHeader>
  <ToolContent>
    <ToolInput>{ path: '/src/index.js' }</ToolInput>
    <ToolOutput>文件内容...</ToolOutput>
  </ToolContent>
</Tool>

🎨 样式方案

CSS Modules

项目使用 CSS Modules 进行样式隔离,每个组件的样式文件命名为 xxx.module.css:

// 导入
import styles from './AgentChat.module.css';

// 使用(自动生成唯一类名)
<div className={styles.chatContainer}>
  <div className={styles.messageList}>...</div>
</div>

CSS Modules 的好处是样式完全隔离,不会影响其他组件。类名在编译时会被自动转换为唯一的哈希值。

🧪 知识检验

题目 1:布局模式

当用户访问 /share/abc123 分享页面时,AppLayout 会渲染哪些布局组件?

A. Header + Sider + Content + Footer(完整布局)
B. 只有 Content + Footer
C. 只有一个简单的 div 包裹 children
D. Header + Content(无 Sider)
答案 C。AppLayout 中有判断:if (isSharePage || isEmbedPage || useMobileAppShell),满足条件时直接返回一个 <div style={{ minHeight: '100dvh' }}>{children}</div>,不渲染 Header、Sider、Footer。这是因为分享页面需要全屏展示对话内容,不需要导航栏。

题目 2:AgentChat 组件

AgentChat 组件中,AI 回复的 Markdown 内容使用什么库进行流式渲染?

A. react-markdown(标准 Markdown 渲染)
B. marked.js
C. Streamdown(支持流式不完整 Markdown 渲染)
D. highlight.js
答案 C。AgentChat 使用 Streamdown 库(从 streamdown 包导入),它支持在流式接收过程中实时渲染不完整的 Markdown。配合 @streamdown/code、@streamdown/mermaid、@streamdown/math、@streamdown/cjk 插件,支持代码高亮、图表、数学公式和中日韩字符。虽然 react-markdown 也被导入用于某些场景,但主要的流式渲染依赖 Streamdown。

题目 3:组件组织

项目中 features/ 和 common/ 目录的区别是什么?

A. features 放第三方库组件,common 放自定义组件
B. features 放页面级组件,common 放布局组件
C. features 放业务功能组件(按模块分),common 放跨模块复用的通用组件
D. 没有区别,只是历史遗留
答案 C。features/ 按业务模块组织(agent/、mcp/、prompt/、share/),每个模块下的组件只属于该业务。common/ 放跨多个页面/模块复用的通用组件,如 AgentChat、ChatMessage、ClaudeCodeTracker 等。这种组织方式让代码更容易定位和维护。