048 ai-home 前端深度追踪

从 App.tsx 入口出发,追踪 URL 路由、状态管理、MCP 工具桥接、AI 对话通信的完整链路

1. App.tsx 入口与 URL 参数路由

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=mainPageMainPage编辑器主界面 — 2D 画布 + 3D 视图 + AI 对话
?page=feedbackProductFeedbackPage反馈页
无参数 / 其他HomePage项目列表首页
为什么不用 React Router?

ai-home 嵌入在 Coohom 主站的 iframe 中,URL 参数路由更轻量,且与主站的路由机制天然兼容。页面切换不需要 history 管理。

2. reactive-framework 状态管理

ai-home 没有用 Redux 或 Zustand,而是基于内部的 @qunhe/reactive-framework(简称 KAF)构建了一套 响应式状态管理 体系。

核心类:RootStateManager

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
}

@observable 装饰器的工作原理

@observable 声明 → KAF Proxy 拦截读写 → 自动收集依赖 → 变更时通知订阅者 → 组件 re-render

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 中的状态规范

项目 AGENTS.md 明确规定:

3. MCP 工具桥接机制

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;
    }
}

MCP 工具的执行流程

后端 Agent 决策 → WebSocket 下发 Tool Call → SDK 匹配 tool name → 前端 callback 执行 → 结果回传后端

工具示例:capture3DScreenshot

以 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 工具都需要在 MCP 中台注册,类型选择 postMessage。工具的 name 必须与中台注册的 toolName 保持一致,否则后端 Agent 无法找到对应的前端工具。

4. AI 对话通信链路

AI 对话是 ai-home 的核心功能。整个通信链路由三层组成:

层级类职责
SDK 层AgentConversationSDKWebSocket 连接管理、消息收发、MCP 工具分发
服务层AgentSDKServiceSDK 初始化、连接状态管理、单例封装
管理层ConversationManager对话状态、消息列表、流式消息、错误处理

完整通信流程

用户输入消息 → sendMessage() → 乐观更新 UI → WebSocket 发送 → 后端处理 → 流式回调 → UI 更新

sendMessage 的细节

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)显示在界面上,不等后端确认。当后端返回真正的用户消息时,通过内容匹配替换临时消息。这保证了即时反馈体验。

5. 自检 Quiz

Q1: ai-home 的页面路由使用什么方案?
Q2: 前端 MCP 工具注册到 SDK 的方法是?
Q3: 用户发送消息后,ConversationManager 如何实现即时反馈?

推荐阅读