从 App.tsx 入口出发,追踪 URL 路由、状态管理、MCP 工具桥接、AI 对话通信的完整链路
ai-home 没有使用 React Router,而是通过 URL 参数 ?page= 实现页面级路由。入口文件 src/app/App.tsx 只有 37 行,逻辑极其简洁:
class App extends React.Component { componentDidMount() { // 埋点:记录用户进入了哪个页面 const queryParams = new URLSearchParams(window.location.search); const page = queryParams.get('page') || 'home'; KIO.log(LogType.AIHomePageLoad, { page }); } render() { const page = new URLSearchParams(window.location.search).get('page'); const isMain = page === 'mainPage'; const isFeedback = page === 'feedback'; return ( <> <GlobalShortcuts /> {isMain ? <MainPage /> : isFeedback ? <ProductFeedbackPage /> : <HomePage />} <Toaster position="top-center" expand /> </> ); } }
| URL 参数 | 组件 | 职责 |
|---|---|---|
?page=mainPage | MainPage | 编辑器主界面 — 2D 画布 + 3D 视图 + AI 对话 |
?page=feedback | ProductFeedbackPage | 反馈页 |
| 无参数 / 其他 | HomePage | 项目列表首页 |
ai-home 嵌入在 Coohom 主站的 iframe 中,URL 参数路由更轻量,且与主站的路由机制天然兼容。页面切换不需要 history 管理。
ai-home 没有用 Redux 或 Zustand,而是基于内部的 @qunhe/reactive-framework(简称 KAF)构建了一套 响应式状态管理 体系。
src/app/state.ts 定义了全局状态管理器 RootStateManager,它使用 combine 组合了多个子状态管理器:
export class RootStateManager extends combine<State, { scene2D: AIHomeScene2DStateManager; viewerState: ViewerStateManager; userInfo: UserInfoStateManager; }>({ scene2D: AIHomeScene2DStateManager, viewerState: ViewerStateManager, userInfo: UserInfoStateManager, }) { @observable declare designDoc: DesignDocument; // 状态字段通过 @observable 装饰器声明 // 子管理器自动合并到 this.scene2D / this.viewerState / this.userInfo }
ConversationManager(对话管理器)同样使用 @observable 装饰器:
class ConversationManager { @observable messages: Message[] = []; @observable streamMessage: Message | undefined = undefined; @observable status: ConversationStatus = ConversationStatus.done; @observable connectionStatus: ConnectionStatus = ConnectionStatus.disconnected; @observable isInitialized = false; }
@observable 不同于 MobX 的 observable。KAF 的响应式系统是自研的,与 KAF 的文档模型(Document)、撤销/重做(TransactionDocument)、选择管理(Selection)深度集成。
项目 AGENTS.md 明确规定:
StateManager 管理src/app/hooks/,以 use 开头useEffect 中清理StateManager 状态结构前必须先输出方案说明,等待确认MCP(Model Context Protocol)工具是 ai-home 最有特色的设计之一。后端 Agent 在推理过程中,可以通过 MCP 协议让前端执行特定操作(如 3D 截图、模型搜索),再把结果回传给后端继续推理。
src/app/agent/MCP/index.ts 定义了所有前端 MCP 工具:
export const FRONT_TOOLS: MCPTool[] = [ { name: 'search_decoration_model', callback: searchDecorationModel }, { name: 'replace_decoration_model', callback: replaceDecorationModel }, { name: 'capture_3d_screenshot', callback: capture3DScreenshot }, { name: 'capture_3d_render', callback: capture3DRender }, ];
这些工具通过 AgentSDKService 注册到 SDK 中:
class AgentSDKService { async init(config) { this.sdk = new AgentConversationSDK(initSDKConfig); this.sdk.registerAgentHooks({ websocketHooks: { ... } }); this.sdk.registerTools(FRONT_TOOLS); // ← 注册前端工具 return this.sdk; } }
以 capture_3d_screenshot 为例,它的职责是截取当前 3D 场景的截图并返回图片 URL:
export const capture3DScreenshot = async (args: { designId: string; levelId: string; }): Promise<MCPToolResult> => { // 1. 参数校验 if (!designId) return createErrorResult(...); // 2. 调用前端 3D 引擎截图 API const imageUrls = await capture3DScreenshotApi({ designId, levelId }); // 3. 构建 MCP 标准返回格式 return { content: imageUrls.map(url => ({ type: 'image_url', image_url: { url, detail: 'auto' }, })), }; };
每个前端 MCP 工具都需要在 MCP 中台注册,类型选择 postMessage。工具的 name 必须与中台注册的 toolName 保持一致,否则后端 Agent 无法找到对应的前端工具。
AI 对话是 ai-home 的核心功能。整个通信链路由三层组成:
| 层级 | 类 | 职责 |
|---|---|---|
| SDK 层 | AgentConversationSDK | WebSocket 连接管理、消息收发、MCP 工具分发 |
| 服务层 | AgentSDKService | SDK 初始化、连接状态管理、单例封装 |
| 管理层 | ConversationManager | 对话状态、消息列表、流式消息、错误处理 |
async sendMessage(userMsg: UserMessage, conversationId?: string) { // 1. 检查连接状态 if (this.connectionStatus !== ConnectionStatus.connected) return; // 2. 确保对话已打开 if (!this.isInitialized) { await this.openConversation(conversationId); } // 3. 乐观更新 — 先在 UI 上显示用户消息 const tempMessage = createTempMessage(userMsg, conversationUuid, tempMessageUuid); this.messages = [...this.messages, tempMessage]; // 4. 通过 SDK 发送 this.conversationRef.send(userMsg); }
打开对话时,ConversationManager 注册了一系列回调:
| 回调 | 触发时机 | 处理逻辑 |
|---|---|---|
onMessagesChange | 消息增删 | 更新 messages 数组,替换临时消息 |
onStreamMessageUpdate | 流式消息到达 | 更新 streamMessage,驱动打字机效果 |
onStatusChange | 对话状态变化 | 更新 status(done/streaming/error) |
onErrorMessage | 错误发生 | 设置 errorInfo,触发错误 UI |
onTitleChange | 对话标题更新 | 更新 title,尝试重命名项目 |
onMessageDone | 消息处理完成 | 记录 credits 消耗 |
用户发送消息后,前端立即创建一条临时消息(temp-* UUID)显示在界面上,不等后端确认。当后端返回真正的用户消息时,通过内容匹配替换临时消息。这保证了即时反馈体验。
src/app/state.ts — RootStateManager 完整实现src/app/agent/service/AgentSDKService.ts — SDK 初始化与工具注册src/app/agent/manager/ConversationManager.ts — 对话管理器核心逻辑src/app/agent/MCP/index.ts — 前端 MCP 工具定义