# https://github.com/microsoft/magentic-ui 项目说明书

生成时间：2026-05-17 13:28:54 UTC

## 目录

- [项目概述](#overview)
- [快速开始指南](#quick-start)
- [系统架构](#system-architecture)
- [代理系统详解](#agent-system)
- [前端组件结构](#frontend-components)
- [设置与配置管理](#settings-management)
- [后端API架构](#backend-api)
- [WebSocket实时通信](#websocket-communication)
- [数据管理](#data-management)
- [浏览器自动化引擎](#browser-automation)

<a id='overview'></a>

## 项目概述

### 相关页面

相关主题：[系统架构](#system-architecture), [快速开始指南](#quick-start)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [frontend/src/components/layout.tsx](https://github.com/microsoft/magentic-ui/blob/main/frontend/src/components/layout.tsx)
- [frontend/src/components/views/chat/runview.tsx](https://github.com/microsoft/magentic-ui/blob/main/frontend/src/components/views/chat/runview.tsx)
- [frontend/src/components/features/Plans/PlanCard.tsx](https://github.com/microsoft/magentic-ui/blob/main/frontend/src/components/features/Plans/PlanCard.tsx)
- [frontend/src/components/features/Plans/PlanList.tsx](https://github.com/microsoft/magentic-ui/blob/main/frontend/src/components/features/Plans/PlanList.tsx)
- [frontend/src/components/views/chat/progressbar.tsx](https://github.com/microsoft/magentic-ui/blob/main/frontend/src/components/views/chat/progressbar.tsx)
- [frontend/src/components/views/chat/detail_viewer.tsx](https://github.com/microsoft/magentic-ui/blob/main/frontend/src/components/views/chat/detail_viewer.tsx)
- [frontend/src/components/views/chat/chat.tsx](https://github.com/microsoft/magentic-ui/blob/main/frontend/src/components/views/chat/chat.tsx)
- [src/magentic_ui/agents/web_surfer/fara/_prompts.py](https://github.com/microsoft/magentic-ui/blob/main/src/magentic_ui/agents/web_surfer/fara/_prompts.py)
</details>

# 项目概述

## 简介

Magentic-UI 是一个由微软开发的多模态 AI 代理框架，旨在通过自然语言界面实现复杂的自动化任务。该项目将大型语言模型（LLM）的推理能力与浏览器自动化工具相结合，使用户能够通过对话方式控制浏览器、执行搜索、操作网页等任务。系统核心强调**透明性**——用户可以实时监控 AI 的工作过程并在必要时进行干预。资料来源：[frontend/src/components/layout.tsx:1-40]()

Magentic-UI 的主要目标是降低自动化复杂网页操作的门槛，同时确保人类始终保持对 AI 行为的最终控制权。该框架适用于需要执行多步骤网页交互、数据采集、表单填写、跨网站信息整合等场景。

## 核心架构

### 技术栈概览

| 层级 | 技术 | 说明 |
|------|------|------|
| 前端框架 | React + TypeScript | 构建交互式用户界面 |
| UI 组件库 | Ant Design | 提供标准化的 UI 组件 |
| 样式方案 | Tailwind CSS | 原子化 CSS 框架 |
| 后端核心 | Python | 处理 LLM 推理和代理逻辑 |
| 浏览器自动化 | Playwright / noVNC | 浏览器控制和远程显示 |
| 通信协议 | SSE / Stdio / JSON | 与 MCP 服务器通信 |

资料来源：[frontend/src/components/features/McpServersConfig/McpConfigModal.tsx:1-80]()

### 模块划分

Magentic-UI 的代码库按照功能可分为以下主要模块：

```mermaid
graph TD
    A[Magentic-UI 系统] --> B[前端模块 frontend/]
    A --> C[后端模块 src/magentic_ui/]
    
    B --> B1[视图层 views/]
    B --> B2[功能层 features/]
    B --> B3[布局层 layout.tsx]
    
    B1 --> B1a[Chat 聊天视图]
    B1 --> B1b[RunView 运行视图]
    B1 --> B1c[ProgressBar 进度条]
    B1 --> B1d[DetailViewer 详情查看器]
    
    B2 --> B2a[Plans 计划管理]
    B2 --> B2b[McpServersConfig MCP服务器配置]
    
    C --> C1[agents/ 代理模块]
    C --> C2[web_surfer/ 网络冲浪代理]
```

资料来源：[frontend/src/components/views/chat/chat.tsx:1-100]()

## 关键功能模块

### 会话管理与运行状态

系统采用会话（Session）驱动的执行模型。每个会话关联一个运行实例（Run），运行实例具有以下状态：

| 状态 | 描述 | 用户操作 |
|------|------|----------|
| `active` | 运行中 | 可暂停 |
| `paused` | 已暂停 | 可恢复 |
| `pausing` | 正在暂停 | 等待完成当前步骤 |
| `awaiting_input` | 等待用户输入 | 需要用户响应 |
| `completed` | 已完成 | 可查看结果 |

资料来源：[frontend/src/components/views/chat/chat.tsx:30-50]()

```mermaid
stateDiagram-v2
    [*] --> active : 开始运行
    active --> paused : 用户暂停
    active --> awaiting_input : 需要输入
    active --> [*] : 完成
    paused --> active : 恢复运行
    awaiting_input --> active : 用户提供输入
    pausing --> paused : 暂停完成
```

### 计划（Plan）系统

计划系统是 Magentic-UI 的核心功能之一，允许用户创建、保存、复用自动化流程。一个计划由以下要素组成：

| 字段 | 类型 | 说明 |
|------|------|------|
| `id` | string | 计划唯一标识符 |
| `task` | string | 计划标题/任务描述 |
| `steps` | Step[] | 步骤数组 |
| `created_at` | datetime | 创建时间 |

计划步骤包含标题、详细描述、关联的代理等信息。资料来源：[frontend/src/components/features/Plans/PlanCard.tsx:1-100]()

```mermaid
graph LR
    A[创建计划] --> B[编辑步骤]
    B --> C[保存计划]
    C --> D[附加到查询]
    D --> E[执行计划]
    E --> F[监控进度]
    F --> G{完成?}
    G -->|是| H[学习新计划]
    G -->|否| F
```

### 计划学习功能

系统提供从对话历史中学习并生成可复用计划的能力：

- **触发时机**：当用户完成一个复杂任务后，可点击"Learn Plan"按钮
- **生成逻辑**：分析对话历史中的步骤序列，提取为结构化计划
- **保存位置**：保存到用户的计划库（Plan Library）中
- **复用方式**：用户可在新会话中附加已保存的计划

资料来源：[frontend/src/components/features/Plans/LearnPlanButton.tsx:1-60]()

### 进度可视化

系统在执行计划时提供实时进度展示：

```mermaid
graph TD
    A[ProgressBar] --> B[计算当前步骤]
    A --> C[显示步骤标记]
    A --> D[显示状态文本]
    
    B --> E{有最终答案?}
    E -->|是| F[显示Task Completed]
    E -->|否| G[显示Step X of Y]
    
    C --> H[工具提示含详细信息]
    D --> I[包含步骤标题]
```

进度条组件会显示总步骤数、当前步骤、步骤详情提示等信息。资料来源：[frontend/src/components/views/chat/progressbar.tsx:1-100]()

### 详情查看器（DetailViewer）

详情查看器是系统与浏览器交互的核心界面组件：

| 功能 | 说明 |
|------|------|
| 实时预览 | 显示浏览器当前页面 |
| 截图历史 | 查看执行过程中的截图 |
| 控制权交接 | 用户可接管 AI 的控制权 |
| 输入响应 | 用户可直接在查看器中输入信息 |

资料来源：[frontend/src/components/views/chat/detail_viewer.tsx:1-80]()

### MCP 服务器集成

Magentic-UI 支持通过 MCP（Model Context Protocol）协议扩展功能。系统支持三种连接方式：

| 连接类型 | 适用场景 | 配置复杂度 |
|----------|----------|------------|
| SSE | 需要实时推送的服务器 | 中等 |
| Stdio | 本地命令行工具 | 简单 |
| JSON Config | 批量导入复杂配置 | 高 |

资料来源：[frontend/src/components/features/McpServersConfig/McpConfigModal.tsx:1-120]()

## 透明度设计

系统内置多重透明度机制，确保用户始终了解 AI 的行为：

### 实时监控

- 运行状态实时显示在界面上
- 进度条展示当前执行步骤和总步骤
- 详情查看器显示浏览器实时画面

### 人工干预

- **暂停功能**：用户可随时暂停 AI 的执行
- **控制权接管**：用户可直接接管浏览器控制权
- **输入响应**：在 AI 请求时提供人类判断

### 警告机制

界面底部始终显示免责声明：

> Magentic-UI can make mistakes. Please monitor its work and intervene if necessary.

资料来源：[frontend/src/components/layout.tsx:20-25]()

## 网络冲浪代理

后端的核心代理模块负责执行浏览器操作，其功能通过结构化参数定义：

```python
parameters = {
    "action": {
        "web_search": "执行网络搜索",
        "visit_url": "访问指定 URL",
        "scroll": "滚动页面",
        "click_element": "点击元素",
        "fill_input": "填写输入框",
        "pause_and_memorize_fact": "暂停并记忆信息",
        "wait": "等待指定时间",
        "terminate": "终止任务"
    }
}
```

资料来源：[src/magentic_ui/agents/web_surfer/fara/_prompts.py:1-80]()

## 用户界面布局

```
┌─────────────────────────────────────────────────────┐
│                    顶部导航栏                        │
├───────────────────────┬─────────────────────────────┤
│                       │                             │
│     聊天视图          │      详情查看器              │
│     (Chat View)       │      (Detail Viewer)        │
│                       │                             │
│                       │                             │
├───────────────────────┴─────────────────────────────┤
│                    进度条                             │
├─────────────────────────────────────────────────────┤
│                    聊天输入框                         │
└─────────────────────────────────────────────────────┘
```

- 用户可在收起和展开详情查看器之间切换
- 详情查看器支持最小化和全屏模式
- 聊天视图自动调整宽度以适应布局变化

资料来源：[frontend/src/components/views/chat/runview.tsx:1-60]()

## 文件管理

系统提供文件上传和下载功能：

- **上传方式**：通过聊天输入框的附件菜单上传文件
- **文件预览**：支持图片预览和其他文件类型的图标显示
- **下载功能**：每个文件卡片提供独立的下载按钮

资料来源：[frontend/src/components/common/filerenderer.tsx:1-80]()

## 错误处理

### 404 页面

当用户访问不存在的路由时，系统显示友好的 404 页面，包含返回首页的链接。

资料来源：[frontend/src/pages/404.tsx:1-40]()

### 表单验证

各配置模块均实现了输入验证：

- 必填字段检查
- 重复名称检测
- 字符限制（最大长度 50）

资料来源：[frontend/src/components/features/McpServersConfig/McpConfigModal.tsx:60-80]()

## 技术特性总结

| 特性 | 描述 | 状态 |
|------|------|------|
| 多模态交互 | 支持文本、图像、文件等多种输入输出 | ✅ |
| 计划复用 | 可创建、编辑、导入导出计划 | ✅ |
| 实时预览 | noVNC 远程浏览器控制 | ✅ |
| 透明度监控 | 进度条、状态显示、人工干预 | ✅ |
| MCP 扩展 | 支持 SSE/Stdio/JSON 三种连接方式 | ✅ |
| 计划学习 | 从对话历史自动生成可复用计划 | ✅ |

## 相关文档

- **部署指南**：了解如何在不同环境中部署 Magentic-UI
- **API 参考**：深入了解后端代理的参数和返回值
- **插件开发**：学习如何开发自定义 MCP 服务器
- **最佳实践**：掌握高效使用 Magentic-UI 的技巧

---

<a id='quick-start'></a>

## 快速开始指南

### 相关页面

相关主题：[项目概述](#overview)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [CONTRIBUTING.md](https://github.com/microsoft/magentic-ui/blob/main/CONTRIBUTING.md)
- [frontend/README.md](https://github.com/microsoft/magentic-ui/blob/main/frontend/README.md)
</details>

# 快速开始指南

## 概述

Magentic-UI 是一个由 Microsoft 开发的开源项目，旨在提供现代化的用户界面来与 AI Agent 进行交互。本指南将帮助开发者快速搭建开发环境、运行项目，并开始进行开发工作。

## 环境要求

### 系统要求

- **操作系统**: Windows、macOS 或 Linux
- **Node.js**: 用于前端开发
- **Python**: 用于后端开发（建议使用虚拟环境）

### 依赖工具

- **Poetry**: Python 包管理工具，用于管理后端依赖
- **npm/yarn**: Node.js 包管理工具，用于管理前端依赖

## 项目结构

```
magentic-ui/
├── frontend/          # 前端项目（React + TypeScript）
├── src/               # 后端源代码
├── pyproject.toml     # Python 项目配置
└── CONTRIBUTING.md    # 贡献指南
```

## 安装步骤

### 1. Fork 和克隆仓库

首先，访问 [Magentic-UI 仓库](https://github.com/microsoft/magentic-ui)，Fork 到您自己的账户，然后克隆到本地：

```bash
git clone https://github.com/<your-username>/magentic-ui.git
cd magentic-ui
```

资料来源：[CONTRIBUTING.md]()

### 2. 创建开发分支

使用描述性的分支名称来创建新分支：

```bash
git checkout -b fix/session-bug
# 或
git checkout -b feature/file-upload
```

资料来源：[CONTRIBUTING.md]()

### 3. 安装后端依赖

项目使用 Poetry 管理 Python 依赖。在项目根目录执行：

```bash
poetry install
```

### 4. 安装前端依赖

进入前端目录并安装依赖：

```bash
cd frontend
npm install
```

## 前端配置

### 环境变量设置

前端项目需要配置环境变量才能正确连接到后端 API。

1. 复制默认环境变量文件：

```bash
cd frontend
cp .env.default .env.development
```

2. 编辑 `.env.development` 文件，配置以下主要变量：

| 变量名 | 说明 | 默认值 |
|--------|------|--------|
| `GATSBY_API_URL` | 后端 API 地址 | `http://localhost:8081/api` |

前端的所有 API 请求将发送到 `http://localhost:8081/api` 端点。

资料来源：[frontend/README.md]()

### 添加新页面

前端使用文件系统路由。要添加新页面（如 `/about`）：

1. 在 `src/pages` 目录下创建新文件夹
2. 在文件夹中添加 `index.tsx` 文件
3. 参考 `src/pages/index.tsx` 的内容风格

组件的核心逻辑应写在 `src/components` 文件夹中，然后按需在页面中导入使用。

资料来源：[frontend/README.md]()

## 启动开发服务器

### 启动后端服务

```bash
poetry run <后端启动命令>
```

### 启动前端开发服务器

```bash
cd frontend
npm run develop
```

## 代码检查与测试

### 运行本地检查

在提交代码之前，请务必运行检查命令：

```bash
poe check
```

资料来源：[CONTRIBUTING.md]()

### 编写测试

新功能或错误修复必须包含相应的测试用例。测试文件位于 `tests` 目录中，可以参考现有测试的编写风格。

资料来源：[CONTRIBUTING.md]()

## 提交代码

### 提交 Pull Request

1. 将代码推送到您 Fork 的仓库
2. 打开 PR 指向 `main` 分支
3. 在 PR 描述中引用相关 Issue（如 "Closes #123"）
4. 如果需要签署 CLA，CLA 机器人会引导您完成

资料来源：[CONTRIBUTING.md]()

## 常见问题排查

### 前端无法连接后端

确保 `GATSBY_API_URL` 环境变量配置正确，指向运行中的后端服务地址。

### 依赖安装失败

- Python 依赖：确保 Poetry 已正确安装，尝试运行 `poetry install --no-interaction`
- Node.js 依赖：确保 Node.js 版本符合要求，尝试删除 `node_modules` 后重新安装

### 检查命令失败

查看错误输出，根据提示修复代码问题。常见问题包括代码格式不规范、TypeScript 类型错误等。

## 下一步

- 查看 [CONTRIBUTING.md](https://github.com/microsoft/magentic-ui/blob/main/CONTRIBUTING.md) 了解详细贡献指南
- 浏览 [Issues](https://github.com/microsoft/magentic-ui/issues) 寻找待解决的问题
- 特别关注标记为 `help-wanted` 的 Issue，这些特别欢迎社区贡献

---

<a id='system-architecture'></a>

## 系统架构

### 相关页面

相关主题：[代理系统详解](#agent-system), [后端API架构](#backend-api), [前端组件结构](#frontend-components)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [src/magentic_ui/backend/web/app.py](https://github.com/microsoft/magentic-ui/blob/main/src/magentic_ui/backend/web/app.py)
- [src/magentic_ui/backend/teammanager/teammanager.py](https://github.com/microsoft/magentic-ui/blob/main/src/magentic_ui/backend/teammanager/teammanager.py)
- [src/magentic_ui/task_team.py](https://github.com/microsoft/magentic-ui/blob/main/src/magentic_ui/task_team.py)
- [src/magentic_ui/_docker.py](https://github.com/microsoft/magentic-ui/blob/main/src/magentic_ui/_docker.py)
- [frontend/src/components/layout.tsx](https://github.com/microsoft/magentic-ui/blob/main/frontend/src/components/layout.tsx)
- [frontend/src/components/views/chat/runview.tsx](https://github.com/microsoft/magentic-ui/blob/main/frontend/src/components/views/chat/runview.tsx)
- [frontend/src/components/views/chat/chatinput.tsx](https://github.com/microsoft/magentic-ui/blob/main/frontend/src/components/views/chat/chatinput.tsx)
- [frontend/README.md](https://github.com/microsoft/magentic-ui/blob/main/frontend/README.md)

</details>

# 系统架构

## 概述

Magentic-UI 是一个基于 Web 的用户界面系统，用于与 AI Agent 团队进行交互式协作。该项目采用前后端分离架构，前端使用 React 构建，后端基于 Python FastAPI 框架。系统核心围绕任务执行、团队协作和状态管理三大模块展开。资料来源：[frontend/README.md](https://github.com/microsoft/magentic-ui/blob/main/frontend/README.md)

## 整体架构

Magentic-UI 采用典型的分层架构设计，包含以下核心层：

| 层级 | 技术栈 | 职责 |
|------|--------|------|
| 前端展示层 | React + TypeScript + Ant Design | 用户界面渲染、交互处理 |
| 前端状态层 | React Context + Hooks | 会话状态、运行状态管理 |
| 后端 API 层 | FastAPI (Python) | RESTful API 服务 |
| 核心逻辑层 | Python | Agent 团队管理、任务执行 |
| 容器化层 | Docker | 环境隔离、资源管理 |

资料来源：[frontend/src/components/layout.tsx](https://github.com/microsoft/magentic-ui/blob/main/frontend/src/components/layout.tsx)

```mermaid
graph TD
    A[用户浏览器] --> B[React 前端]
    B --> C[FastAPI 后端]
    C --> D[Agent 团队管理]
    D --> E[任务执行引擎]
    E --> F[Docker 容器]
    F --> G[AI 模型服务]
```

## 前端架构

### 技术选型

前端项目位于 `frontend/` 目录，使用以下核心技术：

- **React 18**: 核心 UI 框架
- **TypeScript**: 类型安全
- **Ant Design**: UI 组件库
- **Tailwind CSS**: 样式框架
- **Gatsby**: 静态站点生成器

资料来源：[frontend/README.md](https://github.com/microsoft/magentic-ui/blob/main/frontend/README.md)

### 目录结构

```
frontend/src/
├── components/          # 核心组件
│   ├── common/          # 通用组件
│   ├── features/        # 功能组件
│   │   ├── Plans/       # 计划管理
│   │   └── McpServersConfig/  # MCP 服务器配置
│   ├── layout.tsx       # 布局组件
│   └── views/
│       └── chat/        # 聊天视图
│           ├── chatinput.tsx    # 聊天输入
│           ├── runview.tsx      # 运行视图
│           ├── progressbar.tsx # 进度条
│           └── rendermessage.tsx # 消息渲染
├── pages/               # 页面路由
└── context/             # React Context
```

资料来源：[frontend/src/components/layout.tsx](https://github.com/microsoft/magentic-ui/blob/main/frontend/src/components/layout.tsx)

### 状态管理

系统使用 React Context 进行状态管理，主要包含以下上下文：

| Context | 用途 |
|---------|------|
| `appContext` | 应用级上下文，包含用户信息 |
| `sessionContext` | 会话状态管理 |
| `runContext` | 任务运行状态管理 |

状态流转通过 `SessionManager` 组件统一协调，该组件位于布局的主内容区域。资料来源：[frontend/src/components/layout.tsx:33](https://github.com/microsoft/magentic-ui/blob/main/frontend/src/components/layout.tsx)

### 关键组件

#### ChatInput 组件

`ChatInput` 是用户与系统交互的核心入口，支持以下功能：

- 文本消息输入
- 文件上传
- 计划（Plan）附件
- 任务暂停控制

组件根据 `runStatus` 状态动态调整 UI 行为：当状态为 `active` 时显示暂停按钮，否则显示发送按钮。资料来源：[frontend/src/components/views/chat/chatinput.tsx](https://github.com/microsoft/magentic-ui/blob/main/frontend/src/components/views/chat/chatinput.tsx)

#### RunView 组件

`RunView` 是任务执行的主视图，整合了以下子组件：

- **DetailViewer**: 图像/VNC 详情查看
- **ChatInput**: 消息输入
- **ApprovalButtons**: 审批按钮组
- **ProgressBar**: 执行进度条

组件布局支持展开/收起状态，通过 `detailViewerExpanded` 状态控制。资料来源：[frontend/src/components/views/chat/runview.tsx](https://github.com/microsoft/magentic-ui/blob/main/frontend/src/components/views/chat/runview.tsx)

## 后端架构

### 技术选型

后端项目位于 `src/magentic_ui/backend/`，使用 FastAPI 框架构建 RESTful API 服务。

### API 服务

后端 API 服务通过 `app.py` 定义，提供以下核心端点：

- **会话管理**: 创建、更新、查询会话状态
- **任务执行**: 启动、暂停、取消任务
- **计划管理**: 创建、修改、删除计划
- **文件传输**: 上传下载文件

API 默认运行在 `http://localhost:8081/api`，前端通过环境变量 `GATSBY_API_URL` 配置连接地址。资料来源：[frontend/README.md](https://github.com/microsoft/magentic-ui/blob/main/frontend/README.md)

## Agent 团队架构

### 团队管理

系统核心采用团队（Team）模式进行任务协调，团队管理器负责：

- 创建和初始化 Agent 团队
- 管理团队成员的生命周期
- 协调团队内部通信
- 处理团队执行结果

资料来源：[src/magentic_ui/backend/teammanager/teammanager.py](https://github.com/microsoft/magentic-ui/blob/main/src/magentic_ui/backend/teammanager/teammanager.py)

### 任务团队

`TaskTeam` 是任务执行的核心类，负责：

1. 解析用户输入的任务描述
2. 生成执行计划（Plan）
3. 分配子任务给团队成员
4. 监控执行进度
5. 汇总最终结果

资料来源：[src/magentic_ui/task_team.py](https://github.com/microsoft/magentic-ui/blob/main/src/magentic_ui/task_team.py)

### 计划（Plan）系统

计划系统是系统的核心功能模块，允许用户：

- 创建可复用的任务计划
- 学习并保存执行过的计划
- 将计划附加到新任务中

#### Plan 数据结构

| 字段 | 类型 | 说明 |
|------|------|------|
| task | string | 计划标题 |
| steps | array | 执行步骤列表 |
| created_at | datetime | 创建时间 |
| id | string | 唯一标识 |

资料来源：[frontend/src/components/features/Plans/PlanCard.tsx](https://github.com/microsoft/magentic-ui/blob/main/frontend/src/components/features/Plans/PlanCard.tsx)

#### PlanView 组件

`PlanView` 组件支持两种模式：

- **viewOnly=true**: 只读展示模式，用于消息中渲染计划
- **viewOnly=false**: 编辑模式，用于创建和修改计划

资料来源：[frontend/src/components/views/chat/rendermessage.tsx](https://github.com/microsoft/magentic-ui/blob/main/frontend/src/components/views/chat/rendermessage.tsx)

## 容器化架构

### Docker 集成

系统使用 Docker 进行环境隔离和资源管理，核心功能包括：

- 独立的 Agent 执行环境
- 动态容器创建和销毁
- 资源配额控制

资料来源：[src/magentic_ui/_docker.py](https://github.com/microsoft/magentic-ui/blob/main/src/magentic_ui/_docker.py)

### MCP 服务器配置

系统支持 MCP（Model Context Protocol）服务器集成，提供三种连接方式：

| 连接类型 | 说明 |
|----------|------|
| SSE | Server-Sent Events 推送 |
| Stdio | 标准输入输出流 |
| JSON Config | JSON 配置文件导入 |

资料来源：[frontend/src/components/features/McpServersConfig/McpConfigModal.tsx](https://github.com/microsoft/magentic-ui/blob/main/frontend/src/components/features/McpServersConfig/McpConfigModal.tsx)

## 运行状态机

系统定义了完整的任务运行状态机：

```mermaid
stateDiagram-v2
    [*] --> pending: 创建任务
    pending --> planning: 进入计划阶段
    planning --> awaiting_approval: 等待用户审批
    awaiting_approval --> active: 用户批准
    awaiting_approval --> [*]: 用户拒绝
    active --> paused: 用户暂停
    paused --> active: 恢复执行
    active --> completed: 任务完成
    active --> failed: 执行失败
    completed --> [*]
    failed --> [*]
```

| 状态 | 说明 |
|------|------|
| pending | 任务已创建，等待处理 |
| planning | 正在生成执行计划 |
| awaiting_approval | 等待用户审批计划 |
| awaiting_input | 等待用户输入响应 |
| active | 任务正在执行 |
| paused | 任务已暂停 |
| completed | 任务成功完成 |
| failed | 任务执行失败 |

资料来源：[frontend/src/components/views/chat/chatinput.tsx](https://github.com/microsoft/magentic-ui/blob/main/frontend/src/components/views/chat/chatinput.tsx)

## 进度跟踪

### 进度条组件

`ProgressBar` 组件实时显示任务执行进度，支持以下视觉状态：

- **已完成部分**: 绿色（bg-green-600）
- **当前步骤**: 紫红色（bg-magenta-800）
- **剩余部分**: 灰色（bg-gray-300）

进度计算公式：

```
已完成百分比 = (currentStep / totalSteps) * 100
```

资料来源：[frontend/src/components/views/chat/progressbar.tsx](https://github.com/microsoft/magentic-ui/blob/main/frontend/src/components/views/chat/progressbar.tsx)

### 状态文本显示

进度条下方的状态文本根据执行状态动态变化：

| 条件 | 显示内容 |
|------|----------|
| hasFinalAnswer=true | "Task Completed" |
| 正常执行中 | "Step X of Y: 步骤标题..." |
| 计划模式 | "Planning..." |

资料来源：[frontend/src/components/views/chat/progressbar.tsx](https://github.com/microsoft/magentic-ui/blob/main/frontend/src/components/views/chat/progressbar.tsx)

## 数据流

### 消息渲染流程

```mermaid
graph LR
    A[用户输入] --> B[ChatInput]
    B --> C[API 请求]
    C --> D[后端处理]
    D --> E[Agent 执行]
    E --> F[状态更新]
    F --> G[RenderMessage]
    G --> H[UI 渲染]
```

`RenderMessage` 组件负责将后端返回的消息渲染为可视化内容，支持：

- 纯文本消息
- 多模态内容（文本 + 附件）
- 计划卡片展示
- 文件预览

资料来源：[frontend/src/components/views/chat/rendermessage.tsx](https://github.com/microsoft/magentic-ui/blob/main/frontend/src/components/views/chat/rendermessage.tsx)

### 文件处理流程

文件通过 `RenderFile` 组件处理，支持的文件类型通过 `IconComponent` 动态映射：

1. 提取文件元数据（类型、大小、名称）
2. 选择对应的文件图标组件
3. 渲染文件卡片或缩略图
4. 支持下载功能

资料来源：[frontend/src/components/common/filerenderer.tsx](https://github.com/microsoft/magentic-ui/blob/main/frontend/src/components/common/filerenderer.tsx)

## 安全与限制

### 访问控制

系统通过 `restricted` 标志控制访问权限：

```typescript
if (restricted) {
  return (
    <appContext.Consumer>
      {(context: any) => {
        if (context.user) {
          return layoutContent;
        }
        return null;
      }}
    </appContext.Consumer>
  );
}
```

未认证用户只能看到空白页面。资料来源：[frontend/src/components/layout.tsx](https://github.com/microsoft/magentic-ui/blob/main/frontend/src/components/layout.tsx)

### 错误处理

系统底部显示安全提示：

```
Magentic-UI can make mistakes. Please monitor its work and intervene if necessary.
```

资料来源：[frontend/src/components/layout.tsx](https://github.com/microsoft/magentic-ui/blob/main/frontend/src/components/layout.tsx)

## 环境配置

### 前端环境变量

创建 `.env.development` 文件，配置以下变量：

| 变量名 | 默认值 | 说明 |
|--------|--------|------|
| GATSBY_API_URL | http://localhost:8081/api | 后端 API 地址 |

资料来源：[frontend/README.md](https://github.com/microsoft/magentic-ui/blob/main/frontend/README.md)

### 开发模式

前端开发服务器默认连接到本地后端服务，确保后端在 `localhost:8081` 运行后再启动前端开发服务器。

---

<a id='agent-system'></a>

## 代理系统详解

### 相关页面

相关主题：[系统架构](#system-architecture), [浏览器自动化引擎](#browser-automation)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [src/magentic_ui/agents/web_surfer/_web_surfer.py](https://github.com/microsoft/magentic-ui/blob/main/src/magentic_ui/agents/web_surfer/_web_surfer.py)
- [src/magentic_ui/agents/file_surfer/_file_surfer.py](https://github.com/microsoft/magentic-ui/blob/main/src/magentic_ui/agents/file_surfer/_file_surfer.py)
- [src/magentic_ui/agents/_coder.py](https://github.com/microsoft/magentic-ui/blob/main/src/magentic_ui/agents/_coder.py)
- [src/magentic_ui/teams/orchestrator/_orchestrator.py](https://github.com/microsoft/magentic-ui/blob/main/src/magentic_ui/teams/orchestrator/_orchestrator.py)
- [src/magentic_ui/agents/mcp/_agent.py](https://github.com/microsoft/magentic-ui/blob/main/src/magentic_ui/agents/mcp/_agent.py)
</details>

# 代理系统详解

## 1. 系统概述

Magentic-UI 的代理系统是一个多代理协作框架，旨在通过多个专业化的 AI 代理协同工作来完成复杂任务。该系统基于 Model Context Protocol (MCP) 架构，支持网页浏览、文件操作、代码生成等多种功能。

系统采用**团队协作模式（Group Chat）**，由 Orchestrator（编排器）负责协调多个代理之间的工作分配和消息传递。每个代理都有其特定的专业领域和工具集，通过标准化的消息格式进行通信。

```mermaid
graph TD
    A[用户任务] --> B[Orchestrator 编排器]
    B --> C[WebSurfer 代理]
    B --> D[FileSurfer 代理]
    B --> D[CoderAgent 代理]
    B --> E[MCP Agent 代理]
    C --> F[浏览器控制]
    D --> G[文件系统操作]
    E --> H[MCP 服务器]
```

## 2. 代理类型详解

### 2.1 WebSurfer 代理

WebSurfer 是专门用于网页浏览和交互的代理，能够模拟用户操作浏览器完成任务。

#### 支持的操作类型

| 操作 | 描述 | 必需参数 |
|------|------|----------|
| `visit_url` | 访问指定 URL | `url` |
| `web_search` | 执行网络搜索 | `query` |
| `history_back` | 返回上一页 | 无 |
| `pause_and_memorize_fact` | 暂停并记住信息 | `fact` |
| `wait` | 等待指定秒数 | `time` |
| `terminate` | 终止任务 | `status` |

#### 鼠标和键盘操作

| 操作 | 描述 | 必需参数 |
|------|------|----------|
| `left_click` | 左键点击 | `coordinate` |
| `right_click` | 右键点击 | `coordinate` |
| `mouse_move` | 移动鼠标 | `coordinate` |
| `scroll` | 滚动页面 | `pixels` |
| `key` | 按键操作 | `keys` |
| `type` | 输入文本 | `text`, `coordinate` |

#### 配置参数

```python
web_surfer = WebSurfer(
    name="web_surfer",
    model_client=model_client_websurfer,
    browser=browser,
    animate_actions=False,
    max_actions_per_step=10,
    start_page="about:blank" if task.url_path == "" else task.url_path,
    downloads_folder=os.path.abspath(output_dir),
    debug_dir=os.path.abspath(output_dir),
    model_context_token_limit=model_context_token_limit,
    to_save_screenshots=True,
)
```

**参数说明：**

| 参数 | 类型 | 说明 |
|------|------|------|
| `name` | string | 代理名称标识 |
| `model_client` | ModelClient | 模型客户端实例 |
| `browser` | Browser | 浏览器实例 |
| `animate_actions` | bool | 是否动画显示操作 |
| `max_actions_per_step` | int | 每步最大操作数 |
| `start_page` | string | 起始页面 URL |
| `downloads_folder` | string | 文件下载目录 |
| `debug_dir` | string | 调试信息保存目录 |
| `model_context_token_limit` | int | 上下文 token 限制 |
| `to_save_screenshots` | bool | 是否保存截图 |

### 2.2 FileSurfer 代理

FileSurfer 代理专门用于文件系统操作，支持文件浏览、读取和修改。

#### 核心功能

- 目录浏览和导航
- 文件内容读取
- 文件创建和编辑
- 路径绑定和安全限制

#### 配置参数

```python
file_surfer = FileSurfer(
    name="file_surfer",
    model_client=model_client_file_surfer,
    work_dir=os.path.abspath(output_dir),
    bind_dir=os.path.abspath(output_dir),
    model_context_token_limit=model_context_token_limit,
)
```

**参数说明：**

| 参数 | 类型 | 说明 |
|------|------|------|
| `work_dir` | string | 工作目录路径 |
| `bind_dir` | string | 绑定的安全目录（限制访问范围） |

### 2.3 CoderAgent 代理

CoderAgent 专门用于代码生成和修改任务，支持多种编程语言的代码编写。

#### 核心功能

- 根据需求生成代码
- 代码文件创建和修改
- 工作目录管理

#### 配置参数

```python
coder_agent = CoderAgent(
    name="coder_agent",
    model_client=model_client_coder,
    work_dir=os.path.abspath(output_dir),
    model_context_token_limit=model_context_token_limit,
)
```

### 2.4 MCPAgent 代理

MCP Agent 是基于 Model Context Protocol 的扩展代理，用于连接外部 MCP 服务器。

#### 支持的连接方式

| 连接类型 | 说明 |
|----------|------|
| SSE | Server-Sent Events 方式连接 |
| Stdio | 标准输入输出方式连接 |
| JSON Config | JSON 配置文件方式 |

#### 服务器配置

```typescript
// 前端 MCP 配置界面
interface MCPServerConfig {
  serverName: string;      // 服务器名称（仅字母和数字）
  connectionType: 'sse' | 'stdio' | 'json';
  command?: string;        // Stdio 连接时的命令
  args?: string[];         // Stdio 连接时的参数
  url?: string;           // SSE 连接时的 URL
  env?: Record<string, string>;  // 环境变量
}
```

## 3. Orchestrator 编排器

Orchestrator 是系统的核心组件，负责协调多个代理之间的工作流程。

### 3.1 架构设计

```mermaid
graph LR
    A[用户输入] --> B[Orchestrator]
    B --> C{任务分析}
    C -->|需要浏览网页| D[WebSurfer]
    C -->|需要文件系统| E[FileSurfer]
    C -->|需要编码| F[CoderAgent]
    D --> G[执行结果]
    E --> G
    F --> G
    G --> B
    B --> H[最终响应]
```

### 3.2 团队配置

```python
team = GroupChat(
    participants=agent_list,
    orchestrator_config=orchestrator_config,
    model_client=model_client_orch,
    termination_condition=termination_condition,
)
await team.lazy_init()
```

### 3.3 终止条件

系统支持多种终止条件：

| 条件类型 | 说明 |
|----------|------|
| `max_steps` | 达到最大步数后终止 |
| `llm_judged` | LLM 判断任务完成 |
| `external` | 外部信号终止 |

## 4. 前端集成

### 4.1 运行视图组件

前端通过 `RunView` 组件展示代理运行状态：

```typescript
// 核心组件结构
<RunView
    run={currentRun}
    onSavePlan={handlePlanUpdate}
    onPause={handlePause}
    onRegeneratePlan={handleRegeneratePlan}
    isDetailViewerMinimized={isDetailViewerMinimized}
    setIsDetailViewerMinimized={setIsDetailViewerMinimized}
    showDetailViewer={showDetailViewer}
    setShowDetailViewer={setShowDetailViewer}
    onApprove={handleApprove}
/>
```

### 4.2 状态显示

| 状态 | 说明 |
|------|------|
| `active` | 正在执行任务 |
| `awaiting_input` | 等待用户输入 |
| `paused` | 已暂停 |
| `pausing` | 正在暂停 |
| `completed` | 已完成 |

### 4.3 进度条显示

```typescript
// 进度信息显示逻辑
{hasFinalAnswer ? (
    <span className="text-green-600 font-medium">
        Task Completed
    </span>
) : adjustedProgress.plan?.task ? (
    <span>
        Step {adjustedProgress.currentStep + 1} of {adjustedProgress.totalSteps}
        {`: ${adjustedProgress.plan.steps[adjustedProgress.currentStep]?.title?.substring(0, 30)}...`}
    </span>
) : ...}
```

## 5. 计划系统

### 5.1 计划数据结构

```typescript
interface Plan {
    id: string;
    task: string;           // 计划标题
    steps: PlanStep[];      // 步骤列表
    created_at?: string;    // 创建时间
}

interface PlanStep {
    title: string;          // 步骤标题
    description?: string;  // 步骤描述
    status?: 'pending' | 'active' | 'completed' | 'failed';
}
```

### 5.2 计划视图

- 超过 3 个步骤时显示 "+ X more steps" 提示
- 支持相对时间显示（如 "2 hours ago"）
- 可通过 Modal 编辑计划

## 6. 工具调用格式

### 6.1 函数调用模板

```xml
<tool_call>
{tool_definition}
<code>
{tool_code}
</code>
</tool_call>
```

### 6.2 响应格式

```xml
<tool_response>
{response_content}
</tool_response>
```

### 6.3 特殊模式

系统支持 `SPECIAL_CODE_MODE`，当工具名称包含 `CODE_TOOL_PATTERN` 时自动选择特殊模板：

```python
if SPECIAL_CODE_MODE and any([CODE_TOOL_PATTERN in x for x in tool_names]):
    selected_template = FN_CALL_TEMPLATE_WITH_CI
```

## 7. 环境配置

### 7.1 后端 API 配置

前端请求后端 API 地址：

```
http://localhost:8081/api
```

### 7.2 环境变量设置

在 `frontend/.env.development` 中配置：

```bash
GATSBY_API_URL=http://localhost:8081/api
```

## 8. 数据模型

### 8.1 消息结构

```typescript
interface Message {
    id: string;
    role: 'user' | 'assistant' | 'system' | 'function';
    content: ContentItem[];
    metadata?: {
        type?: 'file' | 'image' | 'plan';
        files?: string;  // JSON string of files
    };
    reasoning_content?: string;
}
```

### 8.2 会话状态

```typescript
interface SessionState {
    messages: Message[];
    session: Session | null;
    sessions: Session[];
    version: string | null;
    connectionId: string;
}
```

## 9. 最佳实践

### 9.1 代理选择建议

| 任务类型 | 推荐代理 |
|----------|----------|
| 网页信息获取 | WebSurfer |
| 文件操作 | FileSurfer |
| 代码生成 | CoderAgent |
| 外部工具集成 | MCPAgent |

### 9.2 性能优化

- 合理设置 `max_actions_per_step` 避免单步过长
- 使用 `model_context_token_limit` 控制上下文长度
- 启用 `to_save_screenshots=True` 便于调试

### 9.3 安全考虑

- FileSurfer 必须设置 `bind_dir` 限制访问范围
- MCPServer 配置需验证服务器名称格式
- 敏感操作需用户确认

## 10. 总结

Magentic-UI 的代理系统通过模块化设计实现了高度的可扩展性和灵活性。Orchestrator 作为核心协调器管理多个专业代理的工作流程，每个代理专注于特定功能领域。前端组件提供了良好的用户体验，实时展示任务进度和执行状态。系统支持 MCP 协议扩展，可轻松集成外部工具和服务。

---

<a id='frontend-components'></a>

## 前端组件结构

### 相关页面

相关主题：[后端API架构](#backend-api), [设置与配置管理](#settings-management)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [frontend/src/components/views/chat/chat.tsx](https://github.com/microsoft/magentic-ui/blob/main/frontend/src/components/views/chat/chat.tsx)
- [frontend/src/components/views/chat/plan.tsx](https://github.com/microsoft/magentic-ui/blob/main/frontend/src/components/views/chat/plan.tsx)
- [frontend/src/components/views/manager.tsx](https://github.com/microsoft/magentic-ui/blob/main/frontend/src/components/views/manager.tsx)
- [frontend/src/components/layout.tsx](https://github.com/microsoft/magentic-ui/blob/main/frontend/src/components/layout.tsx)
- [frontend/src/components/views/chat/runview.tsx](https://github.com/microsoft/magentic-ui/blob/main/frontend/src/components/views/chat/runview.tsx)
- [frontend/src/components/views/chat/rendermessage.tsx](https://github.com/microsoft/magentic-ui/blob/main/frontend/src/components/views/chat/rendermessage.tsx)
- [frontend/src/components/features/Plans/PlanCard.tsx](https://github.com/microsoft/magentic-ui/blob/main/frontend/src/components/features/Plans/PlanCard.tsx)
- [frontend/src/components/features/Plans/PlanList.tsx](https://github.com/microsoft/magentic-ui/blob/main/frontend/src/components/features/Plans/PlanList.tsx)
</details>

# 前端组件结构

## 概述

Magentic-UI 的前端是一个基于 React 和 TypeScript 构建的现代 Web 应用程序，采用组件化架构。该项目位于 `frontend/` 目录下，使用 Ant Design 作为主要的 UI 组件库，并集成了状态管理、路由导航、文件处理等多种功能模块。

前端的核心职责是提供用户交互界面，包括会话管理、聊天视图、计划创建与执行、文件预览、以及与后端 MCP（Model Context Protocol）服务器的集成。

## 目录结构

```
frontend/src/components/
├── common/                 # 通用组件
│   └── filerenderer.tsx   # 文件渲染组件
├── features/              # 功能模块组件
│   ├── McpServersConfig/  # MCP 服务器配置
│   └── Plans/             # 计划相关组件
├── layout.tsx             # 根布局组件
├── store.tsx              # 状态管理
├── views/                 # 视图层组件
│   └── chat/              # 聊天视图模块
│       ├── chat.tsx       # 聊天主视图
│       ├── plan.tsx       # 计划视图
│       ├── rendermessage.tsx  # 消息渲染
│       ├── runview.tsx    # 运行视图
│       ├── progressbar.tsx    # 进度条
│       └── relevant_plans.tsx # 相关计划
└── pages/                 # 页面组件
    └── 404.tsx            # 404错误页面
```

## 核心组件架构

### 布局组件（Layout）

`layout.tsx` 是应用的整体布局容器，负责主题配置和会话管理器的挂载。

```mermaid
graph TD
    A[MagenticUILayout] --> B[ConfigProvider]
    A --> C[SessionManager]
    B --> D[主题配置<br/>暗色/亮色模式]
    C --> E[视图渲染]
    A --> F[底部免责声明]
```

关键特性：
- 使用 Ant Design 的 `ConfigProvider` 实现主题管理，支持 `darkAlgorithm` 和 `defaultAlgorithm`
- 根据 `restricted` 属性控制用户访问权限
- 底部显示 "Magentic-UI can make mistakes" 免责声明 资料来源：[frontend/src/components/layout.tsx]()

### 会话管理器（Manager）

`manager.tsx` 是核心的状态容器组件，负责管理会话列表、活跃会话和子菜单状态。

| 状态/属性 | 类型 | 说明 |
|---------|------|------|
| `sessions` | Session[] | 所有会话列表 |
| `session` | Session \| null | 当前活跃会话 |
| `activeSubMenuItem` | string | 当前子菜单项 |
| `isEditorOpen` | boolean | 会话编辑器是否打开 |

主要功能：
- 加载和管理会话列表
- 处理会话创建、选择和删除
- 支持从计划创建新会话
- 渲染 `PlanList` 和聊天视图

资料来源：[frontend/src/components/views/manager.tsx]()

## 聊天视图模块

### Chat 主组件

`chat.tsx` 是聊天功能的核心入口组件，封装了聊天输入、消息列表和会话控制功能。

```mermaid
graph TD
    A[ChatInput] -->|提交| B{检查运行状态}
    B -->|awaiting_input/paused| C[handleInputResponse]
    B -->|其他状态| D[runTask]
    C --> E[更新会话]
    D --> F[触发后端任务执行]
    A --> G[SampleTasks]
    G -->|选择示例| D
```

核心 Props：

| Prop | 类型 | 说明 |
|------|------|------|
| `onSubmit` | function | 提交消息处理 |
| `error` | string | 错误信息 |
| `onCancel` | function | 取消操作 |
| `runStatus` | string | 当前运行状态 |
| `inputRequest` | object | 输入请求 |
| `isPlanMessage` | boolean | 是否为计划消息 |
| `onPause` | function | 暂停处理 |
| `onExecutePlan` | function | 执行计划回调 |

资料来源：[frontend/src/components/views/chat/chat.tsx]()

### 消息渲染组件

`rendermessage.tsx` 负责将消息内容渲染为可交互的 UI 元素。

```mermaid
graph LR
    A[Message] --> B{消息类型判断}
    B -->|多模态文本| C[逐项渲染]
    B -->|单文本| D[直接渲染]
    B -->|计划内容| E[PlanView组件]
```

关键渲染逻辑：
- 支持多模态内容处理（文本数组）
- 使用 `break-words` 和 `whitespace-pre-wrap` 保证文本格式
- 对于计划内容，调用 `PlanView` 组件进行渲染 资料来源：[frontend/src/components/views/chat/rendermessage.tsx]()

### 进度条组件

`progressbar.tsx` 展示任务执行进度，包括已完成、当前和剩余步骤。

```mermaid
graph TD
    A[adjustedProgress] --> B{hasFinalAnswer?}
    B -->|是| C[显示100%绿色]
    B -->|否| D[分段显示]
    D --> E[绿色: 已完成]
    D --> F[深色: 当前步骤]
    D --> G[灰色: 剩余步骤]
```

进度状态显示：
- **已完成**：绿色进度条，宽度根据 `currentStep / totalSteps` 计算
- **当前步骤**：深色块，显示步骤数和标题
- **完成状态**：显示 "Task Completed" 绿色文本 资料来源：[frontend/src/components/views/chat/progressbar.tsx]()

## 计划组件模块

### PlanView 组件

`plan.tsx` 是计划视图的核心组件，支持只读和编辑两种模式。

| 属性 | 类型 | 说明 |
|------|------|------|
| `viewOnly` | boolean | 是否只读模式 |
| `task` | string | 计划任务描述 |
| `plan` | IPlan[] | 计划步骤数组 |
| `setPlan` | function | 更新计划回调 |

关键功能：
- 哨兵步骤（Sentinel Step）支持循环执行
- 条件配置：按时间间隔（`sleep_duration`）或次数（`condition`）执行
- 支持步骤详情编辑和自动调整文本区域 资料来源：[frontend/src/components/views/chat/plan.tsx]()

### 计划卡片（PlanCard）

`PlanCard.tsx` 展示单个计划的摘要信息，支持快速查看和编辑。

```typescript
interface Plan {
  id: string;
  name: string;
  steps: PlanStep[];
  created_at?: string;
}
```

显示内容：
- 计划名称和前 3 个步骤预览
- 创建时间的相对显示（使用 `getRelativeTimeString`）
- 超过 3 个步骤时显示 "+ X more steps"
- 编辑模式下通过 Modal 展示完整计划编辑器 资料来源：[frontend/src/components/features/Plans/PlanCard.tsx]()

### 计划列表（PlanList）

`PlanList.tsx` 管理用户的保存计划库。

主要功能：
- 创建新计划（空计划）
- 从 JSON 文件导入计划
- 搜索和过滤计划
- 拖拽导入计划文件

| 功能 | 实现方式 |
|------|---------|
| 创建 | PlusOutlined 按钮触发 |
| 导入 | 文件上传 Input + JSON 解析 |
| 搜索 | Input 组件 + 状态过滤 |

资料来源：[frontend/src/components/features/Plans/PlanList.tsx]()

## 运行视图（RunView）

`runview.tsx` 是任务执行详情视图的核心容器。

```mermaid
graph TD
    A[RunView] --> B[DetailViewer]
    A --> C[RenderMessage列表]
    B --> D{展开状态}
    D -->|最小化| E[仅占50%宽度]
    D -->|展开| F[全宽显示]
    C --> G[ApprovalButtons]
    G --> H{状态判断}
    H -->|pending| I[显示批准/拒绝按钮]
```

支持的 props：
- `images` / `imageTitles`: 图片预览数据
- `novncPort`: VNC 连接端口
- `onPause` / `onInputResponse`: 交互回调
- `detailViewerExpanded`: 详情查看器展开状态 资料来源：[frontend/src/components/views/chat/runview.tsx]()

## 文件渲染组件

`filerenderer.tsx` 负责处理和展示各类文件预览。

```mermaid
graph TD
    A[RenderFile] --> B{文件类型判断}
    B -->|图片| C[ImageThumbnail]
    B -->|代码/其他| D[FileCard]
    C --> E[点击打开Modal]
    D --> E
    E --> F[显示文件内容]
    F --> G[支持下载]
```

文件状态管理：
| 状态 | 类型 | 用途 |
|------|------|------|
| `files` | FileInfo[] | 提取的文件列表 |
| `selectedFile` | FileInfo \| null | 当前选中文件 |
| `fileContent` | string \| null | 文件内容 |
| `isModalOpen` | boolean | 预览 Modal 开关 | 资料来源：[frontend/src/components/common/filerenderer.tsx]()

## 组件间数据流

```mermaid
graph LR
    A[layout.tsx] --> B[Manager]
    B --> C[Chat]
    B --> D[PlanList]
    C --> E[ChatInput]
    C --> F[RenderMessage]
    C --> G[RunView]
    F --> H[PlanView]
    F --> I[RenderFile]
    G --> J[DetailViewer]
    G --> K[ProgressBar]
    K --> L[ApprovalButtons]
```

## 技术栈总结

| 层级 | 技术/框架 | 用途 |
|------|---------|------|
| UI 组件库 | Ant Design | 基础 UI 组件 |
| 状态管理 | React hooks + Context | 会话和应用状态 |
| 样式 | Tailwind CSS + CSS Variables | 主题和样式 |
| 图表 | Mermaid (文档用) | 架构图展示 |
| 路由 | React Router (隐式) | 页面导航 |

## 总结

Magentic-UI 前端采用分层组件架构：

1. **布局层**：`layout.tsx` 提供应用外壳和主题配置
2. **管理层**：`manager.tsx` 处理会话生命周期
3. **视图层**：聊天、计划、运行视图等功能模块
4. **展示层**：通用组件如文件渲染、进度条等

组件之间通过 props 传递数据和回调函数，保持良好的解耦性。计划系统是该应用的核心特色，支持创建、保存、导入、执行和从对话中学习计划的全生命周期管理。

---

<a id='settings-management'></a>

## 设置与配置管理

### 相关页面

相关主题：[前端组件结构](#frontend-components)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [frontend/src/hooks/store.tsx](https://github.com/microsoft/magentic-ui/blob/main/frontend/src/hooks/store.tsx)
- [frontend/README.md](https://github.com/microsoft/magentic-ui/blob/main/frontend/README.md)
- [frontend/src/components/features/McpServersConfig/McpConfigModal.tsx](https://github.com/microsoft/magentic-ui/blob/main/frontend/src/components/features/McpServersConfig/McpConfigModal.tsx)
- [frontend/src/components/features/McpServersConfig/McpServerCard.tsx](https://github.com/microsoft/magentic-ui/blob/main/frontend/src/components/features/McpServersConfig/McpServerCard.tsx)
- [frontend/src/components/features/Plans/PlanList.tsx](https://github.com/microsoft/magentic-ui/blob/main/frontend/src/components/features/Plans/PlanList.tsx)
- [frontend/src/components/features/Plans/PlanCard.tsx](https://github.com/microsoft/magentic-ui/blob/main/frontend/src/components/features/Plans/PlanCard.tsx)
</details>

# 设置与配置管理

## 概述

Magentic-UI 的设置与配置管理系统负责管理应用程序的全局状态、用户偏好设置、Agent 流程配置以及外部服务（如 MCP 服务器）的连接配置。该系统采用前后端分离的架构，前端使用 React Hooks 进行状态管理，后端通过 RESTful API 提供持久化支持。

配置管理涵盖了以下核心领域：

- **主题与界面配置**：暗色/亮色模式切换
- **Agent 流程设置**：流向、标签、网格、代币显示等
- **会话管理**：会话列表、当前会话状态
- **MCP 服务器配置**：SSE、Stdio、JSON Config 三种连接方式
- **计划管理**：可复用计划的创建、导入、导出

资料来源：[frontend/src/hooks/store.tsx:1-50]()

## 系统架构

### 整体架构图

```mermaid
graph TD
    A[前端 React 应用] --> B[Zustand Store 状态管理层]
    B --> C[useConfigStore 配置存储]
    B --> D[持久化层 LocalStorage]
    
    E[MCP 服务器] --> F[MCPConfigModal 配置模态框]
    F --> G[后端 API /api/settings]
    G --> H[服务器端存储]
    
    I[Plan 计划管理] --> J[PlanList 计划列表]
    J --> K[PlanCard 计划卡片]
    K --> L[PlanView 计划视图]
    
    M[主题配置] --> N[Ant Design ConfigProvider]
    N --> O[darkAlgorithm 默认算法]
```

### 配置状态管理

前端使用 Zustand 库配合 `persist` 中间件实现全局状态管理，配置数据会自动持久化到浏览器的 LocalStorage 中。

```mermaid
graph LR
    A[用户操作] --> B[setAgentFlowSettings]
    B --> C[Zustand Store]
    C --> D[persist middleware]
    D --> E[LocalStorage]
    E --> F[页面刷新]
    F --> C
```

资料来源：[frontend/src/hooks/store.tsx:30-80]()

## Agent 流程设置

### 配置接口定义

Agent 流程设置通过 `IAgentFlowSettings` 接口管理，包含以下配置项：

| 配置项 | 类型 | 默认值 | 说明 |
|--------|------|--------|------|
| `direction` | `string` | `"TB"` | 流程图方向：TB（从上到下）/ LR（从左到右） |
| `showLabels` | `boolean` | `true` | 是否显示节点标签 |
| `showGrid` | `boolean` | `true` | 是否显示网格背景 |
| `showTokens` | `boolean` | `true` | 是否显示 Token 统计 |
| `showMessages` | `boolean` | `true` | 是否显示消息流 |
| `showMiniMap` | `boolean` | `false` | 是否显示小地图 |

```typescript
// 默认配置定义
const DEFAULT_AGENT_FLOW_SETTINGS: IAgentFlowSettings = {
  direction: "TB",
  showLabels: true,
  showGrid: true,
  showTokens: true,
  showMessages: true,
  showMiniMap: false,
};
```

资料来源：[frontend/src/hooks/store.tsx:20-30]()

### 配置状态接口

完整的配置状态管理包含多个子模块：

```typescript
interface IConfigState {
  // 消息状态
  messages: any[];
  setMessages: (messages: any[]) => void;
  
  // 会话状态
  session: any;
  sessions: any[];
  setSession: (session: any) => void;
  setSessions: (sessions: any[]) => void;
  
  // 版本与连接
  version: string | null;
  connectionId: string;
  
  // Header 状态
  header: IHeaderState;
  setHeader: (header: Partial<IHeaderState>) => void;
  setBreadcrumbs: (breadcrumbs: IBreadcrumb[]) => void;
  
  // 侧边栏状态
  sidebar: ISidebarState;
  setSidebarState: (state: Partial<ISidebarState>) => void;
  collapseSidebar: () => void;
  expandSidebar: () => void;
  toggleSidebar: () => void;
  
  // Agent 流程设置
  agentFlow: IAgentFlowSettings;
  setAgentFlowSettings: (settings: Partial<IAgentFlowSettings>) => void;
}
```

资料来源：[frontend/src/hooks/store.tsx:1-45]()

## MCP 服务器配置

### 连接类型

MCP（Magentic-UI Model Context Protocol）服务器配置支持三种连接方式：

| 连接类型 | 说明 | 使用场景 |
|----------|------|----------|
| `SSE` | Server-Sent Events，基于 HTTP 的服务端推送 | 远程服务连接 |
| `Stdio` | 标准输入输出，通过子进程通信 | 本地命令行工具 |
| `JSON Config` | JSON 格式的配置文件导入 | 批量配置导入 |

### 配置表单结构

```typescript
// 配置表单状态
const [serverName, setServerName] = useState("");
const [activeTab, setActiveTab] = useState<"sse" | "stdio" | "json">("sse");
```

#### 验证规则

| 字段 | 规则 | 错误提示 |
|------|------|----------|
| Server Name | 必填，仅允许字母和数字，最多50字符 | "Server Name is required and can only contain letters and numbers." |
| Server Name | 不可重复 | "Server name already exists." |
| Agent Name | 必填 | Agent 名称错误提示 |

配置模态框支持创建和编辑两种模式：

```typescript
// 根据是否传入 server 对象判断模式
loading={isSaving}
disabled={serverNameError || serverNameDuplicateError || agentNameError}
>
  {server ? "Update Server" : "Add Server"}
</Button>
```

资料来源：[frontend/src/components/features/McpServersConfig/McpConfigModal.tsx:1-100]()

### MCP 服务器卡片

服务器卡片组件展示单个服务器的概要信息：

| 属性 | 说明 |
|------|------|
| `server.name` | 服务器名称 |
| `server.agentDescription` | Agent 描述信息 |
| `DESCRIPTION_CHAR_LIMIT` | 描述文本截断长度（默认2行） |

```typescript
<div className="flex items-center justify-end gap-2 pt-3 border-t">
  <Button type="text" onClick={() => onEdit?.(server)}>Edit</Button>
  <Button type="text" danger onClick={() => onDelete?.(server)}>Remove</Button>
</div>
```

资料来源：[frontend/src/components/features/McpServersConfig/McpServerCard.tsx:1-50]()

## 计划（Plan）管理配置

### 计划列表配置

计划列表页面提供以下功能：

```mermaid
graph TD
    A[计划列表页面] --> B[搜索功能]
    A --> C[创建计划]
    A --> D[导入计划]
    A --> E[计划详情模态框]
    
    B --> F[按标题搜索]
    C --> G[新建空白计划]
    D --> H[JSON 文件导入]
    E --> I[编辑/保存计划]
```

### 功能按钮配置

| 操作 | 按钮图标 | 说明 |
|------|----------|------|
| 创建计划 | `<PlusOutlined />` | 创建新的空白计划 |
| 导入计划 | `<UploadOutlined />` | 从 JSON 文件导入 |
| 搜索 | `<SearchOutlined />` | 按名称过滤计划列表 |

```typescript
<Tooltip title="Create a new empty plan">
  <Button icon={<PlusOutlined />} onClick={handleCreatePlan}>
    Create
  </Button>
</Tooltip>

<Tooltip title="Import a plan from a JSON file">
  <Button icon={<UploadOutlined />} onClick={() => fileInputRef.current?.click()}>
    Import
  </Button>
</Tooltip>
```

资料来源：[frontend/src/components/features/Plans/PlanList.tsx:1-80]()

### 计划卡片配置

计划卡片显示单个计划的详细信息：

```typescript
interface Plan {
  id: string;
  task: string;
  steps: Step[];
  created_at?: string;
}
```

| 显示区域 | 内容 |
|----------|------|
| 标题区 | 计划任务名称 |
| 步骤列表 | 最多显示前3个步骤，超出显示 `+ N more steps` |
| 时间戳 | 相对时间显示（如"2小时前"） |

```typescript
{steps.length > 3 && (
  <div className="text-xs">
    + {steps.length - 3} more steps
  </div>
)}
```

资料来源：[frontend/src/components/features/Plans/PlanCard.tsx:1-60]()

### 计划模态框配置

计划编辑通过模态框进行，支持以下配置：

| 配置项 | 说明 |
|--------|------|
| `open` | 模态框开关状态 |
| `onCancel` | 取消回调 |
| `footer` | 页脚配置（设为 null 隐藏） |
| `width` | 模态框宽度（800px） |
| `destroyOnClose` | 关闭时销毁内部状态 |

```typescript
<Modal
  open={isModalOpen}
  onCancel={handleModalCancel}
  footer={null}
  width={800}
  destroyOnClose
>
  <PlanView
    task={localTask}
    plan={localSteps}
    setPlan={setLocalSteps}
    viewOnly={false}
    onSavePlan={(updatedSteps) => handleSavePlan(updatedSteps, true)}
  />
</Modal>
```

资料来源：[frontend/src/components/features/Plans/PlanCard.tsx:60-90]()

## 环境变量配置

### 前端环境变量

前端配置通过 `.env.development` 文件管理（基于 `.env.default` 模板）：

| 变量名 | 默认值 | 说明 |
|--------|--------|------|
| `GATSBY_API_URL` | `http://localhost:8081/api` | 后端 API 地址 |

### 配置步骤

1. 复制 `.env.default` 为 `.env.development`
2. 设置 `GATSBY_API_URL` 为目标后端地址
3. 前端开发服务器默认连接 `http://localhost:8081/api`

```bash
# 设置环境变量示例
GATSBY_API_URL=http://localhost:8081/api
```

资料来源：[frontend/README.md:1-20]()

## 主题配置

### 暗色模式切换

应用支持暗色/亮色主题切换，通过 Ant Design 的 `ConfigProvider` 实现：

```typescript
<ConfigProvider
  theme={{
    algorithm: darkMode === "dark" 
      ? theme.darkAlgorithm 
      : theme.defaultAlgorithm,
  }}
>
  <main className="flex-1 p-1 text-primary" style={{ height: "100%" }}>
    <SessionManager />
  </main>
</ConfigProvider>
```

### 样式变量

| 变量 | 说明 | 应用组件 |
|------|------|----------|
| `--color-bg-secondary` | 次要背景色 | 输入框、卡片 |
| `--color-text-primary` | 主文本色 | 标题、正文 |
| `--color-border-primary` | 边框色 | 输入框、卡片边框 |

```typescript
// 动态文本颜色示例
const color = darkMode === "dark" 
  ? "var(--color-text-primary)" 
  : "var(--color-text-primary)";
```

资料来源：[frontend/src/components/layout.tsx:1-30]()

## API 集成

### 后端路由

后端提供 `/api/settings` 路由处理配置相关的 HTTP 请求：

```mermaid
sequenceDiagram
    前端组件 >> MCPConfigModal: 保存配置
    MCPConfigModal >> fetch API: POST /api/settings
    fetch API >> 后端路由: settingsroute.py
    后端路由 >> 数据库/存储: 持久化配置
    数据库/存储 -->> 后端路由: 确认保存
    后端路由 -->> MCPConfigModal: 200 OK
```

前端通过标准 Fetch API 与后端通信：

```typescript
const response = await fetch('/api/settings', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
  },
  body: JSON.stringify(settingsData),
});
```

资料来源：[frontend/src/components/features/McpServersConfig/McpConfigModal.tsx:1-50]()

## 状态持久化

### LocalStorage 结构

配置数据通过 Zustand 的 persist 中间件自动保存到浏览器 LocalStorage：

```javascript
// LocalStorage 中的存储键
{
  "configStore": {
    "state": {
      "agentFlow": { ... },
      "sessions": [ ... ],
      "messages": [ ... ]
    },
    "version": 0
  }
}
```

### 初始化流程

```mermaid
graph TD
    A[应用启动] --> B[加载 LocalStorage]
    B --> C{存在配置数据?}
    C -->|是| D[恢复配置状态]
    C -->|否| E[使用默认配置]
    D --> F[渲染应用]
    E --> F
```

```typescript
export const useConfigStore = create<IConfigState>()(
  persist(
    (set) => ({
      // 初始状态定义
      agentFlow: DEFAULT_AGENT_FLOW_SETTINGS,
      sessions: [],
      messages: [],
      // ...
    }),
    {
      name: "configStore", // LocalStorage 键名
    }
  )
);
```

资料来源：[frontend/src/hooks/store.tsx:40-80]()

## 最佳实践

### 配置验证

- MCP 服务器名称仅允许字母和数字
- 必填字段需添加前端验证
- 重复检测需在保存前执行

### 性能优化

- 使用 `destroyOnClose` 释放模态框资源
- 计划列表支持搜索过滤避免全量渲染
- 消息和会话数据按需加载

### 安全考虑

- 环境变量文件不应提交到版本控制
- API 请求应使用 HTTPS
- 敏感配置应加密存储

---

<a id='backend-api'></a>

## 后端API架构

### 相关页面

相关主题：[系统架构](#system-architecture), [WebSocket实时通信](#websocket-communication), [数据管理](#data-management)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [src/magentic_ui/backend/web/app.py](https://github.com/microsoft/magentic-ui/blob/main/src/magentic_ui/backend/web/app.py)
- [src/magentic_ui/backend/web/routes/sessions.py](https://github.com/microsoft/magentic-ui/blob/main/src/magentic_ui/backend/web/routes/sessions.py)
- [src/magentic_ui/backend/web/routes/runs.py](https://github.com/microsoft/magentic-ui/blob/main/src/magentic_ui/backend/web/routes/runs.py)
- [src/magentic_ui/backend/web/routes/teams.py](https://github.com/microsoft/magentic-ui/blob/main/src/magentic_ui/backend/web/routes/teams.py)
- [src/magentic_ui/backend/web/routes/plans.py](https://github.com/microsoft/magentic-ui/blob/main/src/magentic_ui/backend/web/routes/plans.py)
- [src/magentic_ui/backend/datamodel/db.py](https://github.com/microsoft/magentic-ui/blob/main/src/magentic_ui/backend/datamodel/db.py)
</details>

# 后端API架构

## 概述

Magentic-UI 的后端API架构是一套基于 FastAPI 构建的 RESTful API 服务，托管在 `src/magentic_ui/backend/` 目录下。该架构负责处理前端请求、管理会话状态、协调多Agent工作流、执行任务运行以及存储计划数据。API 服务默认运行在 `http://localhost:8081/api` 端点，为前端提供所有核心业务逻辑的数据支撑。

## 架构分层

后端采用分层架构设计，核心模块包括：

| 层级 | 模块路径 | 职责说明 |
|------|----------|----------|
| 应用层 | `backend/web/app.py` | FastAPI 应用入口，路由注册，中间件配置 |
| 路由层 | `backend/web/routes/` | 业务路由处理，分为 sessions、runs、teams、plans 等子模块 |
| 数据层 | `backend/datamodel/` | 数据模型定义，数据库操作封装 |
| 核心层 | `magentic_ui/agents/` | Agent 逻辑，工具调用，任务执行引擎 |

## 核心路由模块

### 会话管理路由 (`sessions`)

会话路由负责管理用户会话的生命周期，涵盖创建、读取、更新、删除等操作。每个会话包含任务上下文、消息历史和关联的运行记录。

| 端点类型 | 功能描述 |
|----------|----------|
| `GET /sessions` | 获取会话列表 |
| `POST /sessions` | 创建新会话 |
| `GET /sessions/{id}` | 获取指定会话详情 |
| `PUT /sessions/{id}` | 更新会话信息 |
| `DELETE /sessions/{id}` | 删除会话 |

### 运行管理路由 (`runs`)

运行路由处理任务执行相关操作，管理和追踪任务的执行状态。运行状态包括 `active`、`paused`、`awaiting_input` 等多种状态。

### 团队协作路由 (`teams`)

团队路由支持多Agent协作场景，管理团队配置、成员交互和任务分配。Web Surfer Agent 等组件通过此模块与其他Agent进行通信。

### 计划管理路由 (`plans`)

计划路由处理可复用计划的创建、存储和检索。计划包含步骤列表和任务描述，支持从对话中学习生成新计划。

## 数据模型

后端数据模型定义在 `backend/datamodel/db.py` 中，采用结构化数据格式存储关键业务实体。

```mermaid
erDiagram
    Session ||--o{ Run : contains
    Session {
        string id
        string task
        datetime created_at
        array messages
    }
    Run ||--o| TeamResult : produces
    Run {
        string id
        string session_id
        string status
        string error_message
        InputRequest input_request
    }
    Plan ||--o{ Step : contains
    Plan {
        string id
        string task
        array steps
        datetime created_at
    }
    TeamResult {
        string task_result
        string stop_reason
    }
```

## API 通信流程

前端与后端通过 JSON 格式进行数据交换，采用 HTTP 请求-响应模式。

```mermaid
sequenceDiagram
    participant FE as 前端组件
    participant API as FastAPI Backend
    participant DB as 数据库
    participant Agent as Agent Engine
    
    FE->>API: HTTP Request (POST /runs)
    API->>DB: 存储会话上下文
    API->>Agent: 分发任务
    Agent-->>API: 运行状态更新
    API-->>FE: SSE/Polling 响应
    Agent->>DB: 持久化结果
```

## 任务执行状态机

任务运行遵循严格的状态转换规则：

```mermaid
stateDiagram-v2
    [*] --> pending: 创建任务
    pending --> active: 开始执行
    active --> paused: 用户暂停
    paused --> active: 恢复执行
    active --> awaiting_input: 请求用户输入
    awaiting_input --> active: 用户响应
    active --> completed: 任务完成
    active --> failed: 执行错误
    completed --> [*]
    failed --> [*]
```

## 前端集成

前端通过环境变量配置后端地址：

```bash
# .env.development
GATSBY_API_URL=http://localhost:8081/api
```

前端状态管理（`hooks/store.tsx`）维护以下核心状态：

| 状态键 | 类型 | 用途 |
|--------|------|------|
| `messages` | array | 当前会话消息列表 |
| `session` | object | 当前会话对象 |
| `sessions` | array | 所有会话列表 |
| `version` | string | API 版本信息 |
| `connectionId` | uuid | 连接唯一标识 |

## Web Surfer Agent 交互

Web Surfer Agent 通过专用工具集与浏览器交互，相关工具定义在 `agents/web_surfer/fara/_prompts.py` 中。支持的浏览器操作包括：

| 操作类型 | 功能说明 |
|----------|----------|
| `visit_url` | 访问指定URL |
| `web_search` | 执行网络搜索 |
| `key` | 模拟键盘按键 |
| `type` | 输入文本内容 |
| `mouse_move` | 移动鼠标指针 |
| `left_click` | 左键点击 |
| `scroll` | 页面滚动 |
| `history_back` | 返回历史页面 |
| `wait` | 等待指定秒数 |

## MCP 服务器配置

后端支持 MCP（Model Context Protocol）服务器集成，允许扩展 Agent 能力。配置通过 `McpConfigModal` 组件进行，支持三种连接方式：

| 连接模式 | 协议类型 | 使用场景 |
|----------|----------|----------|
| SSE | Server-Sent Events | 实时单向数据流 |
| Stdio | 标准输入输出 | 本地进程通信 |
| JSON Config | JSON配置文件 | 批量配置导入 |

## 安全与限制

后端实现了基础的安全检查机制：

- 会话访问权限验证
- 用户代理类型过滤
- 浏览器环境隔离选项
- Docker 容器运行支持

## 技术栈

| 组件 | 技术选型 |
|------|----------|
| Web 框架 | FastAPI |
| 数据验证 | Pydantic |
| 数据库 | SQLite (默认) |
| 异步任务 | Asyncio |
| API 文档 | OpenAPI/Swagger |

## 扩展指南

### 添加新路由

1. 在 `backend/web/routes/` 创建新的路由文件
2. 定义 Pydantic 模型用于请求/响应验证
3. 在 `app.py` 中注册路由
4. 更新前端 API 客户端调用

### 自定义 Agent

Agent 逻辑定义在 `magentic_ui/agents/` 目录，通过注册机制集成到主应用。新的 Agent 需要实现标准的工具接口以保持兼容性。

---

*本页面内容基于 Magentic-UI 仓库源码自动生成，如有问题请提交 Issue。*

---

<a id='websocket-communication'></a>

## WebSocket实时通信

### 相关页面

相关主题：[后端API架构](#backend-api), [代理系统详解](#agent-system)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [src/magentic_ui/backend/web/managers/connection.py](https://github.com/microsoft/magentic-ui/blob/main/src/magentic_ui/backend/web/managers/connection.py)
- [src/magentic_ui/backend/web/app.py](https://github.com/microsoft/magentic-ui/blob/main/src/magentic_ui/backend/web/app.py)
- [frontend/src/components/views/manager.tsx](https://github.com/microsoft/magentic-ui/blob/main/frontend/src/components/views/manager.tsx)
- [frontend/src/components/store.tsx](https://github.com/microsoft/magentic-ui/blob/main/frontend/src/components/store.tsx)
- [frontend/src/components/views/chat/chat.tsx](https://github.com/microsoft/magentic-ui/blob/main/frontend/src/components/views/chat/chat.tsx)
</details>

# WebSocket实时通信

## 概述

WebSocket实时通信是Magentic-UI实现前端与后端双向实时数据交互的核心机制。该系统基于FastAPI的WebSocket框架构建，支持任务执行状态推送、实时消息流转、用户输入响应等关键功能。

WebSocket连接使前端UI能够接收后端Agent任务的实时更新，包括步骤进度、运行状态、输入请求等，同时允许用户中断任务或提供额外输入。资料来源：[src/magentic_ui/backend/web/managers/connection.py:1-50]()

## 架构设计

### 系统组件架构

```mermaid
graph TD
    FE[前端 UI] <--> WS[WebSocket 连接]
    WS <--> CM[连接管理器<br/>ConnectionManager]
    CM <--> TM[任务管理器]
    CM <--> IR[输入响应队列<br/>_input_responses]
    WS <--> MSG[消息处理器]
    
    subgraph 后端服务
        CM
        TM
        IR
        MSG
    end
    
    subgraph 前端组件
        FE
        ChatView
        SessionManager
        store
    end
```

### 核心组件职责

| 组件 | 职责 | 文件位置 |
|------|------|----------|
| ConnectionManager | 管理所有WebSocket连接生命周期 | connection.py |
| 输入响应队列 | 存储用户输入响应 | connection.py |
| ChatView | 前端聊天视图，渲染实时消息 | chat.tsx |
| SessionManager | 会话管理，分配WebSocket | manager.tsx |

资料来源：[src/magentic_ui/backend/web/managers/connection.py:1-30]()

## 连接管理

### ConnectionManager 类

ConnectionManager是后端WebSocket通信的核心管理类，负责维护连接状态、处理消息路由和任务流管理。

```python
class ConnectionManager:
    def __init__(self):
        self._connections: dict[int, WebSocket] = {}
        self._closed_connections: set[int] = set()
        self._input_responses: dict[int, asyncio.Queue] = {}
```

**核心属性说明：**

| 属性 | 类型 | 说明 |
|------|------|------|
| `_connections` | dict[int, WebSocket] | 存储活跃的WebSocket连接，键为run_id |
| `_closed_connections` | set[int] | 已关闭的连接ID集合 |
| `_input_responses` | dict[int, Queue] | 用户输入响应队列 |

资料来源：[src/magentic_ui/backend/web/managers/connection.py:1-20]()

### 连接建立流程

```mermaid
sequenceDiagram
    participant 前端
    participant WebSocket
    participant CM as ConnectionManager
    participant 任务流
    
    前端->>WebSocket: 建立连接
    WebSocket->>CM: connect(websocket, run_id)
    CM->>CM: 接受WebSocket连接
    CM->>CM: 初始化输入队列
    CM-->>前端: 发送系统消息<br/>{type: "system", status: "connected"}
    任务流-->>CM: 推送任务状态
    CM-->>前端: 实时状态更新
```

**connect方法实现：**

```python
async def connect(self, websocket: WebSocket, run_id: int) -> bool:
    try:
        await websocket.accept()
        self._connections[run_id] = websocket
        self._closed_connections.discard(run_id)
        # 初始化输入队列
        self._input_responses[run_id] = asyncio.Queue()
        
        await self._send_message(
            run_id,
            {
                "type": "system",
                "status": "connected",
                "timestamp": datetime.now(timezone.utc).isoformat(),
            },
        )
        return True
    except Exception as e:
        logger.error(f"连接错误 run {run_id}: {e}")
        return False
```

资料来源：[src/magentic_ui/backend/web/managers/connection.py:40-65]()

## 消息协议

### 消息类型定义

系统定义了多种WebSocket消息类型，用于区分不同的通信目的：

| 消息类型 | 方向 | 说明 |
|----------|------|------|
| `system` | 后端→前端 | 系统状态消息，如连接成功 |
| `status` | 后端→前端 | 任务运行状态更新 |
| `stop` | 前端→后端 | 用户请求停止任务 |
| `input_response` | 后端→前端 | 请求用户输入 |
| `text` | 双向 | 文本消息内容 |

### 状态消息结构

```python
{
    "type": "system",
    "status": "connected",
    "timestamp": "2024-01-01T00:00:00+00:00"
}
```

### 任务停止消息格式

前端通过WebSocket发送停止请求：

```python
ws.send(
    JSON.stringify({
        "type": "stop",
        "reason": "Cancelled by user (sidebar)",
    })
);
```

资料来源：[frontend/src/components/views/manager.tsx:1-30]()

## 任务流启动

### start_stream 方法

start_stream是启动任务执行流的核心方法，协调连接管理与任务执行：

```python
async def start_stream(
    self,
    run_id: int,
    task: str | ChatMessage | Sequence[ChatMessage] | None,
    team_config: Dict[str, Any],
    settings_config: Dict[str, Any],
    user_settings: Settings | None = None,
) -> None:
```

**参数说明：**

| 参数 | 类型 | 说明 |
|------|------|------|
| run_id | int | 任务运行ID |
| task | str/ChatMessage/Sequence | 要执行的任务内容 |
| team_config | Dict | Agent团队配置 |
| settings_config | Dict | 设置配置 |
| user_settings | Settings | 用户设置（可选） |

资料来源：[src/magentic_ui/backend/web/managers/connection.py:67-85]()

## 前端集成

### WebSocket初始化

前端在SessionManager中管理WebSocket连接：

```typescript
const getSessionSocket = (
    sessionId: number,
    runId: string,
    fresh_socket: boolean,
    only_retrieve_existing_socket: boolean
): WebSocket | null
```

**获取Socket流程：**

1. 检查是否需要新建Socket
2. 如果需要，返回新WebSocket实例
3. 否则返回现有连接或null

资料来源：[frontend/src/components/views/chat/chat.tsx:1-30]()

### 状态更新处理

前端通过runStatusChange回调接收运行状态变化：

```typescript
onRunStatusChange: (sessionId: number, status: BaseRunStatus) => void
```

**状态流转：**

```mermaid
graph LR
    A[pending] --> B[running]
    B --> C[awaiting_input]
    C --> B
    B --> D[paused]
    D --> B
    B --> E[completed]
    B --> F[stopped]
    B --> G[error]
```

资料来源：[frontend/src/components/views/manager.tsx:30-50]()

### 前端状态存储

使用Zustand管理WebSocket相关状态：

```typescript
const useConfigStore = create<IConfigState>()(
  persist(
    (set) => ({
      connectionId: uuidv4(),
      sessions: [],
      setSessions: (sessions) => set({ sessions }),
      // ...
    })
  )
);
```

资料来源：[frontend/src/components/store.tsx:1-40]()

## API端点

### WebSocket路由配置

在FastAPI应用中注册WebSocket路由：

```python
api.include_router(
    ws.router,
    prefix="/ws",
    tags=["websocket"],
    responses={404: {"description": "Not found"}},
)
```

### 静态文件服务

WebSocket连接基于API前缀`/api/ws`，而后端同时挂载了静态文件目录用于前端资源服务：

```python
app.mount("/api", api)
app.mount(
    "/files",
    StaticFiles(directory=initializer.static_root, html=True),
    name="files",
)
app.mount("/", StaticFiles(directory=initializer.ui_root, html=True), name="ui")
```

资料来源：[src/magentic_ui/backend/web/app.py:50-70]()

## 数据流

### 实时消息流

```mermaid
graph LR
    subgraph 用户交互
        U[用户输入]
        U2[停止请求]
    end
    
    subgraph 前端
        CI[ChatInput]
        SM[SessionManager]
    end
    
    subgraph 后端
        WS[WebSocket]
        CM[ConnectionManager]
        AG[Agent]
    end
    
    U --> CI --> WS --> CM --> AG
    U2 --> SM --> WS --> CM
    AG --> CM --> WS --> SM --> CI
```

### 会话Socket管理

前端为每个会话维护独立的WebSocket连接，通过runId进行标识：

```typescript
const sessionSockets: Record<number, { socket: WebSocket }> = {};

// 停止会话时关闭对应Socket
const ws = sessionSockets[id]?.socket;
if (ws && ws.readyState === WebSocket.OPEN) {
  ws.send(
    JSON.stringify({
      type: "stop",
      reason: "Cancelled by user (sidebar)",
    })
  );
  ws.close();
}
```

资料来源：[frontend/src/components/views/manager.tsx:10-25]()

## 错误处理

### 连接错误处理

```python
try:
    await websocket.accept()
    self._connections[run_id] = websocket
    # ...
except Exception as e:
    logger.error(f"连接错误 for run {run_id}: {e}")
    return False
```

### 内部错误处理器

```python
@app.exception_handler(500)
async def internal_error_handler(request: Request, exc: Exception):
    logger.error(f"内部错误: {str(exc)}")
    return {
        "status": False,
        "message": "服务器内部错误",
        "detail": str(exc) if # ...
    }
```

资料来源：[src/magentic_ui/backend/web/managers/connection.py:60-65]()

## 配置说明

### 环境变量配置

前端WebSocket连接地址通过环境变量配置：

| 变量名 | 说明 | 默认值 |
|--------|------|--------|
| `GATSBY_API_URL` | 后端API地址 | http://localhost:8081/api |
| `GATSBY_WS_URL` | WebSocket地址 | 与API地址相同 |

开发环境配置示例：

```bash
# .env.development
GATSBY_API_URL=http://localhost:8081/api
```

资料来源：[frontend/README.md:1-20]()

## 最佳实践

1. **连接复用**：同一会话的多个任务应尽可能复用现有WebSocket连接
2. **状态同步**：前端应根据WebSocket推送的状态消息更新本地状态
3. **错误恢复**：实现重连机制以处理网络波动导致的连接断开
4. **输入队列**：每个连接维护独立的输入响应队列，避免消息混淆

## 总结

WebSocket实时通信是Magentic-UI实现流畅用户体验的关键基础设施。通过ConnectionManager的统一管理，系统实现了可靠的连接生命周期管理、任务状态推送和用户交互响应。前端组件与后端服务通过标准化的消息协议进行通信，确保了系统的可维护性和扩展性。

---

<a id='data-management'></a>

## 数据管理

### 相关页面

相关主题：[后端API架构](#backend-api)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [frontend/src/components/features/Plans/PlanCard.tsx](https://github.com/microsoft/magentic-ui/blob/main/frontend/src/components/features/Plans/PlanCard.tsx)
- [frontend/src/components/features/Plans/PlanList.tsx](https://github.com/microsoft/magentic-ui/blob/main/frontend/src/components/features/Plans/PlanList.tsx)
- [frontend/src/components/features/Plans/LearnPlanButton.tsx](https://github.com/microsoft/magentic-ui/blob/main/frontend/src/components/features/Plans/LearnPlanButton.tsx)
- [frontend/src/components/common/filerenderer.tsx](https://github.com/microsoft/magentic-ui/blob/main/frontend/src/components/common/filerenderer.tsx)
- [frontend/src/components/views/chat/chat.tsx](https://github.com/microsoft/magentic-ui/blob/main/frontend/src/components/views/chat/chat.tsx)
- [frontend/src/components/views/chat/runview.tsx](https://github.com/microsoft/magentic-ui/blob/main/frontend/src/components/views/chat/runview.tsx)
- [frontend/src/components/features/McpServersConfig/McpConfigModal.tsx](https://github.com/microsoft/magentic-ui/blob/main/frontend/src/components/features/McpServersConfig/McpConfigModal.tsx)
</details>

# 数据管理

Magentic-UI 的数据管理功能涵盖多个模块，包括计划（Plan）管理、文件管理、会话管理和 MCP 服务器配置管理。这些模块共同构成了系统的核心数据层，支持用户创建、存储、检索和执行各种任务计划。

## 概述

Magentic-UI 的数据管理架构采用前端组件与后端 API 分离的设计模式。前端使用 React 组件构建用户界面，通过 API 与后端通信进行数据持久化。主要数据管理对象包括：

| 数据对象 | 功能描述 | 存储位置 |
|---------|---------|---------|
| Plan（计划） | 可复用的任务执行计划 | 后端数据库 |
| File（文件） | 用户上传的文件和生成的输出 | 文件系统/数据库 |
| Session（会话） | 用户与 AI 的交互会话 | 后端数据库 |
| MCP Server Config | MCP 服务器连接配置 | 后端配置 |

## 计划（Plan）管理

计划是 Magentic-UI 的核心数据管理单元，允许用户创建、保存和执行可复用的任务模板。

### 计划数据结构

计划数据包含以下关键字段：

- `id`: 计划唯一标识符
- `task`: 计划标题/任务名称
- `steps`: 执行步骤数组
- `created_at`: 创建时间戳
- `metadata`: 元数据信息

资料来源：[frontend/src/components/features/Plans/PlanCard.tsx:1-80]()

### 创建计划

用户可以通过两种方式创建计划：

1. **手动创建**：在 PlanCard 组件中通过 Modal 对话框手动编辑计划
2. **从对话学习**：使用 LearnPlanButton 从成功执行的对话中提取计划

```tsx
// PlanCard.tsx 中的计划创建流程
<Modal
  open={isModalOpen}
  onCancel={handleModalCancel}
  footer={null}
  width={800}
  destroyOnClose
>
  {isModalOpen && (
    <div>
      <div className="mb-4">
        <label className="block text-sm font-medium mb-1">
          Plan Title
        </label>
        <Input
          type="text"
          value={localTask}
          onChange={(e) => setLocalTask(e.target.value)}
          onPressEnter={() => handleSavePlan(localSteps, false)}
          placeholder="Enter plan title"
        />
      </div>
      <PlanView
        task={localTask}
        plan={localSteps}
        setPlan={setLocalSteps}
        viewOnly={false}
        onSavePlan={(updatedSteps) => {
          handleSavePlan(updatedSteps, true);
        }}
      />
    </div>
  )}
</Modal>
```

资料来源：[frontend/src/components/features/Plans/PlanCard.tsx:54-76]()

### 计划列表展示

PlanList 组件负责展示所有已保存的计划，支持搜索过滤功能。

```tsx
// PlanList.tsx 中的计划列表
<div className="col-span-3 flex flex-col items-center justify-center py-12 text-primary">
  <p>No plans yet. Create one or import an existing plan.</p>
</div>
```

资料来源：[frontend/src/components/features/Plans/PlanList.tsx:1-50]()

### 从对话学习计划

LearnPlanButton 组件提供从当前对话会话学习并保存计划的功能：

```tsx
const handleLearnPlan = useCallback(() => {
  if (!sessionId || !effectiveUserId) return;
  // 调用保存计划 API
};

return (
  <Tooltip title="Learn a reusable plan from this conversation and save it to your library">
    <button
      onClick={handleLearnPlan}
      disabled={!sessionId || !effectiveUserId}
      className={`inline-flex items-center px-3 py-1.5 rounded-md...`}
    >
      <LightBulbIcon className="h-4 w-4 mr-1.5" />
      <span className="text-sm font-medium">Learn Plan</span>
    </button>
  </Tooltip>
);
```

资料来源：[frontend/src/components/features/Plans/LearnPlanButton.tsx:1-60]()

### 附加计划到查询

用户可以将现有计划附加到新的查询中，在 chatinput.tsx 中通过下拉菜单选择：

```tsx
<Menu.SubMenu key="attach-plan" title="Attach Plan">
  {allPlans.length === 0 ? (
    <Menu.Item disabled key="no-plans">
      No plans available
    </Menu.Item>
  ) : (
    allPlans.map((plan: any) => (
      <Menu.Item
        key={plan.id || plan.task}
        onClick={() => handleUsePlan(plan)}
      >
        {plan.task}
      </Menu.Item>
    ))
  )}
</Menu.SubMenu>
```

资料来源：[frontend/src/components/views/chat/chatinput.tsx:1-100]()

### 计划执行流程

```mermaid
graph TD
    A[用户输入任务] --> B{是否附加计划?}
    B -->|是| C[选择已有计划]
    B -->|否| D[创建新计划]
    C --> E[执行计划步骤]
    D --> F[手动创建/学习计划]
    F --> E
    E --> G[显示执行进度]
    G --> H{步骤结果}
    H -->|需要用户输入| I[暂停等待输入]
    H -->|完成| J[任务结束]
    I --> E
```

## 文件管理

Magentic-UI 支持文件上传、存储和展示功能。

### 文件渲染组件

RenderFile 组件负责解析和展示消息中的文件：

```tsx
const RenderFile: React.FC<RenderFileProps> = ({ message }) => {
  const [files, setFiles] = useState<FileInfo[]>([]);
  const [selectedFile, setSelectedFile] = useState<FileInfo | null>(null);
  const [fileContent, setFileContent] = useState<string | null>(null);

  useEffect(() => {
    // 从消息元数据中提取文件信息
    if (message?.metadata?.type === "file" && message?.metadata?.files) {
      const parsedFiles = JSON.parse(message.metadata.files);
      // 处理文件以确保正确的类型检测
    }
  }, []);
};
```

资料来源：[frontend/src/components/common/filerenderer.tsx:1-100]()

### 文件卡片展示

FileCard 组件提供文件的可视化展示：

```tsx
<FileCard
  onFileClick={onFileClick}
  file={file}
  selected={file.id === selectedFile?.id}
>
  <ImageThumbnail file={file} />
  <div className="p-2 bg-white border-t w-full">
    <span className="text-xs truncate w-full block" title={file.name}>
      {file.name}
    </span>
  </div>
  <DownloadButton file={file} />
</FileCard>
```

资料来源：[frontend/src/components/common/filerenderer.tsx:100-150]()

### 文件上传流程

文件上传通过 Upload 组件集成在聊天输入框中：

```tsx
<Menu.Item key="attach-file" className="!py-0 !my-0 !h-8">
  <Upload {...uploadProps} showUploadList={false}>
    <span className="flex items-center gap-2">
      <PaperclipIcon className="w-4 h-4" />
      Attach File
    </span>
  </Upload>
</Menu.Item>
```

资料来源：[frontend/src/components/views/chat/chatinput.tsx:100-150]()

## MCP 服务器配置管理

MCP（Model Context Protocol）服务器配置允许用户管理外部服务连接。

### 配置类型

McpConfigModal 支持三种配置方式：

| 配置类型 | 描述 | 使用场景 |
|---------|------|---------|
| SSE | Server-Sent Events | 实时数据流服务 |
| Stdio | 标准输入输出 | 本地进程通信 |
| JSON Config | JSON 配置文件 | 批量配置导入 |

```tsx
<Tabs
  activeKey={activeTab}
  onChange={handleTabChange}
  items={[
    { key: "sse", label: "SSE" },
    { key: "stdio", label: "Stdio" },
    { key: "json", label: "JSON Config" },
  ]}
/>
```

资料来源：[frontend/src/components/features/McpServersConfig/McpConfigModal.tsx:1-80]()

### 配置验证

服务器名称验证规则：

```tsx
<Form.Item
  label="Server Name"
  required
  validateStatus={serverNameError || serverNameDuplicateError ? 'error' : undefined}
  help={
    serverNameError ? 'Server Name is required and can only contain letters and numbers.' :
    serverNameDuplicateError ? 'Server name already exists.' : undefined
  }
>
  <Input
    value={serverName}
    placeholder="Server Name"
    maxLength={50}
    showCount
  />
</Form.Item>
```

资料来源：[frontend/src/components/features/McpServersConfig/McpConfigModal.tsx:50-70]()

## 会话管理

会话数据记录用户与 AI 的完整交互历史。

### 会话消息处理

RunView 组件负责渲染会话消息：

```tsx
<RenderMessage
  key={`render-${idx}-${msg.config.version || 0}`}
  message={msg.config}
  sessionId={msg.session_id}
  messageIdx={idx}
  isLast={idx === localMessages.length - 1}
  isEditable={isEditable && idx === localMessages.length - 1}
  hidden={hiddenMessageIndices.has(idx)}
  is_step_repeated={repeatedStepIndices.has(idx)}
  is_step_failed={failedStepIndices.has(idx)}
  onSavePlan={onSavePlan}
  runStatus={run.status}
/>
```

资料来源：[frontend/src/components/views/chat/runview.tsx:1-100]()

### 运行状态管理

系统通过 `runStatus` 字段跟踪会话状态：

```tsx
// 状态流转
const getStatusIcon = (
  status: RunStatus,
  errorMessage?: string,
  stopReason?: string,
  inputRequest?: InputRequest,
  isSentinelSleeping?: boolean
) => { /* 状态图标渲染 */ };
```

资料来源：[frontend/src/components/views/chat/runview.tsx:100-150]()

## 数据流架构

```mermaid
graph LR
    A[用户界面] -->|React 组件| B[前端状态]
    B -->|API 请求| C[后端 API]
    C -->|CRUD| D[(数据库)]
    C -->|文件操作| E[文件系统]
    D -->|查询结果| C
    E -->|文件数据| C
```

## 前端环境配置

前端数据管理需要正确配置环境变量：

```bash
# 创建环境配置文件
cp .env.default .env.development

# 关键配置项
GATSBY_API_URL=http://localhost:8081/api
```

资料来源：[frontend/README.md](https://github.com/microsoft/magentic-ui/blob/main/frontend/README.md)

## 总结

Magentic-UI 的数据管理系统通过模块化设计实现了：

1. **计划管理**：支持创建、学习、保存和执行可复用任务计划
2. **文件管理**：提供文件上传、预览和下载功能
3. **配置管理**：MCP 服务器配置的创建和验证
4. **会话管理**：完整的交互历史记录和状态跟踪

所有数据通过 RESTful API 与后端通信，确保前后端分离的架构设计。

---

<a id='browser-automation'></a>

## 浏览器自动化引擎

### 相关页面

相关主题：[代理系统详解](#agent-system)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [src/magentic_ui/agents/web_surfer/fara/_prompts.py](https://github.com/microsoft/magentic-ui/blob/main/src/magentic_ui/agents/web_surfer/fara/_prompts.py)
- [src/magentic_ui/agents/web_surfer/_cua_web_surfer.py](https://github.com/microsoft/magentic-ui/blob/main/src/magentic_ui/agents/web_surfer/_cua_web_surfer.py)
- [src/magentic_ui/tools/playwright/browser/base_playwright_browser.py](https://github.com/microsoft/magentic-ui/blob/main/src/magentic_ui/tools/playwright/browser/base_playwright_browser.py)
- [src/magentic_ui/tools/playwright/browser/vnc_docker_playwright_browser.py](https://github.com/microsoft/magentic-ui/blob/main/src/magentic_ui/tools/playwright/browser/vnc_docker_playwright_browser.py)
- [src/magentic_ui/tools/playwright/playwright_controller.py](https://github.com/microsoft/magentic-ui/blob/main/src/magentic_ui/tools/playwright/playwright_controller.py)
- [docker/magentic-ui-browser-docker/Dockerfile](https://github.com/microsoft/magentic-ui/blob/main/docker/magentic-ui-browser-docker/Dockerfile)
</details>

# 浏览器自动化引擎

## 概述

浏览器自动化引擎是 Magentic-UI 项目中负责控制浏览器执行自动化任务的核心组件。该引擎基于 Playwright 框架构建，提供了一套完整的浏览器交互能力，包括页面导航、元素操作、截图捕获等关键功能。通过 Docker 容器化部署，引擎能够在隔离环境中稳定运行各类浏览器自动化任务。

引擎的核心设计理念是将高级任务指令（如"点击登录按钮"）转换为底层的 Playwright API 调用，同时处理截图反馈、安全检查和任务状态管理。这种架构使得 AI Agent 能够像人类用户一样与网页进行交互，完成复杂的多步骤任务。

## 架构设计

### 整体架构

Magentic-UI 的浏览器自动化引擎采用分层架构设计，从上到下依次为：Web Surfer Agent 层、CUA Web Surfer 执行层、Playwright Controller 控制层、Playwright Browser 浏览器层，以及底层的 Playwright 原生浏览器实例。

```mermaid
graph TD
    A[Web Surfer Agent] --> B[CUA Web Surfer]
    B --> C[Playwright Controller]
    C --> D[Playwright Browser]
    D --> E[Playwright Browser Instance]
    D --> F[VNC Docker Browser]
    C --> G[Screenshot Base64]
    G --> H[AI Agent Feedback]
```

### 核心组件

| 组件名称 | 文件路径 | 职责说明 |
|---------|---------|---------|
| CUA Web Surfer | `_cua_web_surfer.py` | 处理 AI Agent 生成的 action，执行坐标转换和安全检查 |
| Playwright Controller | `playwright_controller.py` | 封装 Playwright API，提供统一的浏览器控制接口 |
| Base Playwright Browser | `base_playwright_browser.py` | 定义浏览器基类，包含通用浏览器操作方法 |
| VNC Docker Browser | `vnc_docker_playwright_browser.py` | 实现 Docker 容器化浏览器，支持远程可视化访问 |
| Browser Dockerfile | `Dockerfile` | 定义容器化浏览器的运行环境配置 |

## 动作系统

### 支持的动作类型

浏览器自动化引擎支持 11 种核心动作类型，每种动作对应不同的浏览器操作需求。

| 动作类型 | 功能描述 | 必需参数 | 可选参数 |
|---------|---------|---------|---------|
| `key` | 执行键盘按键按下操作 | `keys` (数组) | - |
| `type` | 输入文本内容 | `text` (字符串) | `press_enter`, `delete_existing_text` |
| `mouse_move` | 移动鼠标到指定坐标 | `coordinate` (x, y) | - |
| `left_click` | 执行左键单击 | `coordinate` (x, y) | - |
| `scroll` | 执行鼠标滚轮滚动 | `pixels` (数值) | - |
| `visit_url` | 导航到指定 URL | `url` (字符串) | - |
| `web_search` | 执行网络搜索 | `query` (字符串) | - |
| `history_back` | 返回浏览器历史上一页 | - | - |
| `pause_and_memorize_fact` | 暂停并记录信息 | `fact` (字符串) | - |
| `wait` | 等待指定时间 | `time` (秒数) | - |
| `terminate` | 终止任务并报告状态 | `status` | - |

### 参数规范

动作参数采用 JSON Schema 格式定义，确保参数的严格校验和类型安全。

**坐标参数**：`coordinate` 参数为包含两个元素的数组 `[x, y]`，其中 x 表示从左边缘的像素距离，y 表示从上边缘的像素距离。

**滚动参数**：`pixels` 参数使用正数值表示向上滚动，负数值表示向下滚动，与常见滚动方向直觉一致。

**类型操作**：`type` 动作支持 `press_enter` 布尔参数用于在输入完成后自动回车，以及 `delete_existing_text` 布尔参数用于在输入前清空现有文本。

资料来源：[_prompts.py:1-120](https://github.com/microsoft/magentic-ui/blob/main/src/magentic_ui/agents/web_surfer/fara/_prompts.py)

## 执行流程

### 动作处理流程

当 Web Surfer Agent 接收到任务指令后，会经过以下处理流程：

```mermaid
graph TD
    A[接收 Action 指令] --> B[验证 JSON 格式参数]
    B --> C[解析 Action 类型]
    C --> D{判断 Action 类型}
    D -->|coordinate| E[坐标转换处理]
    D -->|keypress| F[Keypress 处理]
    D -->|drag| G[Drag 坐标处理]
    D -->|type| H[Direct Type 处理]
    E --> I[执行 Playwright API]
    F --> I
    G --> I
    H --> I
    I --> J[获取截图]
    J --> K[Base64 编码截图]
    K --> L[生成 Call Output]
    L --> M[返回给 AI Agent]
```

### 动作执行示例

```python
# 坐标移动执行
if action_type == "coordinate":
    await self._playwright_controller.move_mouse(
        self._page,
        x=action_args["x"],
        y=action_args["y"]
    )

# 按键执行
elif action_type == "keypress":
    await self._playwright_controller.keypress(
        self._page,
        keys=action_args["keys"]
    )

# 拖拽执行
elif action_type == "drag":
    await self._playwright_controller.drag_coords(
        self._page,
        path=action_args["path"]
    )

# 文本输入执行
elif action_type == "type":
    await self._playwright_controller.type_direct(
        self._page,
        text=action_args["text"]
    )
```

资料来源：[_cua_web_surfer.py:1-80](https://github.com/microsoft/magentic-ui/blob/main/src/magentic_ui/agents/web_surfer/_cua_web_surfer.py)

## 输出结构

### Call Output 格式

每个动作执行完成后，系统会生成标准化的调用输出，包含执行状态、截图数据和待确认的安全检查项。

```json
{
  "type": "computer_call_output",
  "call_id": "<unique_call_id>",
  "acknowledged_safety_checks": ["<safety_check_message>"],
  "output": {
    "type": "input_image",
    "image_url": "data:image/png;base64,<base64_encoded_screenshot>"
  }
}
```

**输出字段说明**：

| 字段名 | 类型 | 说明 |
|-------|------|-----|
| `type` | 字符串 | 固定值 `computer_call_output` |
| `call_id` | 字符串 | 动作调用的唯一标识符 |
| `acknowledged_safety_checks` | 数组 | 已确认的安全检查项列表 |
| `output.type` | 字符串 | 输出类型，当前固定为 `input_image` |
| `output.image_url` | 字符串 | Base64 编码的 PNG 格式截图数据 URL |

资料来源：[_cua_web_surfer.py:60-75](https://github.com/microsoft/magentic-ui/blob/main/src/magentic_ui/agents/web_surfer/_cua_web_surfer.py)

## 安全机制

### 安全检查处理

引擎实现了安全检查机制，用于在执行可能存在风险的操作前进行确认。系统会遍历所有待处理的安全检查项，并将其包含在输出结果中供上层决策。

```python
pending_checks = item.get("pending_safety_checks", [])
for check in pending_checks:
    message = check["message"]
    # 检查逻辑（当前为占位符实现）
    if False:  # Replace with actual check logic
        raise ValueError(
            f"Safety check failed: {message}. Cannot continue with unacknowledged safety checks."
        )
```

安全检查信息通过 `acknowledged_safety_checks` 字段传递给 AI Agent，由 Agent 决定是否继续执行该操作。这种设计确保了自动化操作在受控环境中进行，避免意外执行危险操作。

## Docker 容器化部署

### 浏览器 Docker 架构

为了提供稳定、一致的浏览器运行环境，Magentic-UI 使用 Docker 容器化部署浏览器实例。这种方式的优势包括：

- **环境一致性**：容器内包含所有必需的依赖和配置
- **隔离性**：浏览器实例与宿主机系统隔离，避免冲突
- **可移植性**：易于在不同环境中部署和迁移
- **资源控制**：可以精细控制 CPU、内存等资源分配

### VNC 访问支持

Docker 容器化的浏览器支持通过 VNC（虚拟网络计算）协议进行远程可视化访问，用户可以实时监控浏览器操作状态。

```mermaid
graph LR
    A[用户界面] -->|WebSocket/VNC| B[VNC Docker Browser]
    B --> C[Playwright Browser]
    C --> D[Screenshot]
    D -->|实时推送| A
```

## 配置参数

### 浏览器显示配置

引擎支持自定义浏览器显示尺寸，以适应不同的任务需求：

| 参数名 | 类型 | 说明 |
|-------|------|-----|
| `display_width_px` | 数值 | 浏览器显示宽度（像素） |
| `display_height_px` | 数值 | 浏览器显示高度（像素） |

### 动作参数控制

通过 `include_input_text_key_args` 配置项，可以控制是否在动作参数中包含 `press_enter` 和 `delete_existing_text` 两个可选参数：

```python
def __init__(self, cfg=None):
    self.display_width_px = cfg["display_width_px"]
    self.display_height_px = cfg["display_height_px"]
    include_input_text_key_args = cfg.pop("include_input_text_key_args", False)
    if not include_input_text_key_args:
        self.parameters["properties"].pop("press_enter", None)
        self.parameters["properties"].pop("delete_existing_text", None)
```

资料来源：[_prompts.py:95-105](https://github.com/microsoft/magentic-ui/blob/main/src/magentic_ui/agents/web_surfer/fara/_prompts.py)

## 与前端的集成

### 实时预览与控制

Magentic-UI 的前端界面通过 DetailViewer 组件与浏览器自动化引擎集成，提供实时预览和控制能力：

- **实时截图**：通过 `DetailViewer` 组件展示浏览器当前状态的截图
- **操作控制**：用户可以通过前端界面介入执行暂停、接管控制等操作
- **状态监控**：显示当前任务的执行状态、步骤进度等信息

### 模态窗口显示

浏览器视图可以通过 BrowserModal 组件在新窗口中打开，支持全屏查看和独立操作：

```typescript
<BrowserModal
    isOpen={isModalOpen}
    onClose={() => setIsModalOpen(false)}
    novncPort={novncPort}
    title="Browser View"
    onPause={onPause}
    runStatus={runStatus}
    onControlHandover={handleModalControlHandover}
    isControlMode={isControlMode}
    onTakeControl={handleTakeControl}
/>
```

资料来源：[detail_viewer.tsx:1-50](https://github.com/microsoft/magentic-ui/blob/main/frontend/src/components/views/chat/detail_viewer.tsx)

## 总结

浏览器自动化引擎是 Magentic-UI 实现 AI Agent 自主浏览器操作的关键基础设施。通过封装 Playwright 提供的强大浏览器自动化能力，该引擎为上层 Agent 提供了统一的、易于使用的浏览器交互接口。Docker 容器化部署方式确保了环境的一致性和任务执行的稳定性，而完善的动作系统和安全检查机制则保障了自动化操作的可靠性和可控性。

---

---

## Doramagic 踩坑日志

项目：microsoft/magentic-ui

摘要：发现 13 个潜在踩坑项，其中 0 个为 high/blocking；最高优先级：安装坑 - 来源证据：Create tutorials and documentation for the codebase。

## 1. 安装坑 · 来源证据：Create tutorials and documentation for the codebase

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：Create tutorials and documentation for the codebase
- 对用户的影响：可能增加新用户试用和生产接入成本。
- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_c0979f7ebb064422a6a8095561f6a9bd | https://github.com/microsoft/magentic-ui/issues/154 | 来源类型 github_issue 暴露的待验证使用条件。

## 2. 安装坑 · 来源证据：Support Podman in place of Docker

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：Support Podman in place of Docker
- 对用户的影响：可能增加新用户试用和生产接入成本。
- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_f88231cc4cad442ca53d92ea3a40a655 | https://github.com/microsoft/magentic-ui/issues/312 | 来源讨论提到 docker 相关条件，需在安装/试用前复核。

## 3. 安装坑 · 来源证据：magentic-ui can't display all the html element

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：magentic-ui can't display all the html element
- 对用户的影响：可能增加新用户试用和生产接入成本。
- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_21f19953edd74379ab2d25cedc37ca1b | https://github.com/microsoft/magentic-ui/issues/362 | 来源讨论提到 docker 相关条件，需在安装/试用前复核。

## 4. 配置坑 · 来源证据：Refreshing or restart the web app will make the current Session unavailable

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个配置相关的待验证问题：Refreshing or restart the web app will make the current Session unavailable
- 对用户的影响：可能增加新用户试用和生产接入成本。
- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_83a9cafd59254028853ef84cd1ccc756 | https://github.com/microsoft/magentic-ui/issues/336 | 来源讨论提到 node 相关条件，需在安装/试用前复核。

## 5. 能力坑 · 能力判断依赖假设

- 严重度：medium
- 证据强度：source_linked
- 发现：README/documentation is current enough for a first validation pass.
- 对用户的影响：假设不成立时，用户拿不到承诺的能力。
- 建议检查：将假设转成下游验证清单。
- 防护动作：假设必须转成验证项；没有验证结果前不能写成事实。
- 证据：capability.assumptions | github_repo:978331188 | https://github.com/microsoft/magentic-ui | README/documentation is current enough for a first validation pass.

## 6. 运行坑 · 来源证据：Why not conduct a requirement analysis before the plan?

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个运行相关的待验证问题：Why not conduct a requirement analysis before the plan?
- 对用户的影响：可能增加新用户试用和生产接入成本。
- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_6003a9c2194f40c0865145385cf98c32 | https://github.com/microsoft/magentic-ui/issues/321 | 来源类型 github_issue 暴露的待验证使用条件。

## 7. 维护坑 · 来源证据：Sticked at click the “Shopping Cart” icon and cannot goto check out page

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个维护/版本相关的待验证问题：Sticked at click the “Shopping Cart” icon and cannot goto check out page
- 对用户的影响：可能增加新用户试用和生产接入成本。
- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_7e754869326e42e1a7c57f3a1962ef9e | https://github.com/microsoft/magentic-ui/issues/360 | 来源类型 github_issue 暴露的待验证使用条件。

## 8. 维护坑 · 维护活跃度未知

- 严重度：medium
- 证据强度：source_linked
- 发现：未记录 last_activity_observed。
- 对用户的影响：新项目、停更项目和活跃项目会被混在一起，推荐信任度下降。
- 建议检查：补 GitHub 最近 commit、release、issue/PR 响应信号。
- 防护动作：维护活跃度未知时，推荐强度不能标为高信任。
- 证据：evidence.maintainer_signals | github_repo:978331188 | https://github.com/microsoft/magentic-ui | last_activity_observed missing

## 9. 安全/权限坑 · 下游验证发现风险项

- 严重度：medium
- 证据强度：source_linked
- 发现：no_demo
- 对用户的影响：下游已经要求复核，不能在页面中弱化。
- 建议检查：进入安全/权限治理复核队列。
- 防护动作：下游风险存在时必须保持 review/recommendation 降级。
- 证据：downstream_validation.risk_items | github_repo:978331188 | https://github.com/microsoft/magentic-ui | no_demo; severity=medium

## 10. 安全/权限坑 · 存在评分风险

- 严重度：medium
- 证据强度：source_linked
- 发现：no_demo
- 对用户的影响：风险会影响是否适合普通用户安装。
- 建议检查：把风险写入边界卡，并确认是否需要人工复核。
- 防护动作：评分风险必须进入边界卡，不能只作为内部分数。
- 证据：risks.scoring_risks | github_repo:978331188 | https://github.com/microsoft/magentic-ui | no_demo; severity=medium

## 11. 安全/权限坑 · 来源证据：Settings redesign

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：Settings redesign
- 对用户的影响：可能影响授权、密钥配置或安全边界。
- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_6a2eeae98b6d4fdab476464d57e64e1d | https://github.com/microsoft/magentic-ui/issues/227 | 来源类型 github_issue 暴露的待验证使用条件。

## 12. 维护坑 · issue/PR 响应质量未知

- 严重度：low
- 证据强度：source_linked
- 发现：issue_or_pr_quality=unknown。
- 对用户的影响：用户无法判断遇到问题后是否有人维护。
- 建议检查：抽样最近 issue/PR，判断是否长期无人处理。
- 防护动作：issue/PR 响应未知时，必须提示维护风险。
- 证据：evidence.maintainer_signals | github_repo:978331188 | https://github.com/microsoft/magentic-ui | issue_or_pr_quality=unknown

## 13. 维护坑 · 发布节奏不明确

- 严重度：low
- 证据强度：source_linked
- 发现：release_recency=unknown。
- 对用户的影响：安装命令和文档可能落后于代码，用户踩坑概率升高。
- 建议检查：确认最近 release/tag 和 README 安装命令是否一致。
- 防护动作：发布节奏未知或过期时，安装说明必须标注可能漂移。
- 证据：evidence.maintainer_signals | github_repo:978331188 | https://github.com/microsoft/magentic-ui | release_recency=unknown

<!-- canonical_name: microsoft/magentic-ui; human_manual_source: deepwiki_human_wiki -->
