Some checks failed
CI / Lint & TypeCheck (push) Has been cancelled
CI / Unit Tests (push) Has been cancelled
CI / Build Frontend (push) Has been cancelled
CI / Rust Check (push) Has been cancelled
CI / Security Scan (push) Has been cancelled
CI / E2E Tests (push) Has been cancelled
Update audit tracker, roadmap, architecture docs, add admin-v2 Roles page + Billing tests, sync CLAUDE.md, Cargo.toml, docker-compose.yml, add deep-research / frontend-design / chart-visualization skills Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
9.7 KiB
9.7 KiB
状态管理 (State Management)
分类: 架构层 优先级: P0 - 决定性 成熟度: L4 - 生产 最后更新: 2026-04-01 验证状态: ✅ 代码已验证
一、功能概述
1.1 基本信息
状态管理系统基于 Zustand 5.x,管理 ZCLAW 应用的全部业务状态,实现 UI 与业务逻辑的解耦。
| 属性 | 值 |
|---|---|
| 分类 | 架构层 |
| 优先级 | P0 |
| 成熟度 | L4 |
| 依赖 | 无 |
| Store 数量 | 14 |
| Domains 数量 | 4 (chat, hands, intelligence, saas) |
| 匁久化策略 | localStorage + IndexedDB (计划中) |
1.2 Store 清单 (14 个实际存在的 Store)
| Store | 路径 | 用途 | 验证状态 |
|---|---|---|---|
| agentStore | desktop/src/store/agentStore.ts |
Agent 克隆管理 | ✅ 存在 |
| browserHandStore | desktop/src/store/browserHandStore.ts |
Browser Hand 状态 | ✅ 存在 |
| chatStore | desktop/src/store/chatStore.ts |
消息和会话管理 (DeerFlow 视觉) | ✅ 存在 |
| configStore | desktop/src/store/configStore.ts |
配置持久化 | ✅ 存在 |
| connectionStore | desktop/src/store/connectionStore.ts |
连接状态管理 | ✅ 存在 |
| handStore | desktop/src/store/handStore.ts |
Hands 触发管理 | ✅ 存在 |
| memoryGraphStore | desktop/src/store/memoryGraphStore.ts |
记忆图谱状态 | ✅ 存在 |
| offlineStore | desktop/src/store/offlineStore.ts |
离线模式管理 | ✅ 存在 |
| saasStore | desktop/src/store/saasStore.ts |
SaaS 平台集成 (登录/配置/Prompt OTA) | ✅ 存在 |
| securityStore | desktop/src/store/securityStore.ts |
安全配置管理 | ✅ 存在 |
| sessionStore | desktop/src/store/sessionStore.ts |
会话持久化 | ✅ 存在 |
| workflowBuilderStore | desktop/src/store/workflowBuilderStore.ts |
工作流构建器状态 | ✅ 存在 |
| workflowStore | desktop/src/store/workflowStore.ts |
工作流管理 | ✅ 存在 |
注: 以下 Store 在早期文档中出现但已被移除或合并: teamStore (多 Agent 功能 feature-gated), meshStore, personaStore (合并到 identity 系统), activeLearningStore, skillMarketStore, gatewayStore (功能合并到 connectionStore)
1.3 Domain Stores (领域状态)
| Domain | 路径 | 用途 |
|---|---|---|
| Chat Domain | desktop/src/domains/chat/ |
聊天领域状态和 hooks |
| Hands Domain | desktop/src/domains/hands/ |
Hands 领域状态和状态机 |
| Intelligence Domain | desktop/src/domains/intelligence/ |
智能层状态 (Valtio) |
| Shared Utilities | desktop/src/shared/ |
共享类型和错误处理 |
二、设计初衷
2.1 问题背景
用户痛点:
- 组件间状态共享困难,prop drilling 严重
- 状态变化难以追踪和调试
- 页面刷新后状态丢失
系统缺失能力:
- 缺乏统一的状态管理中心
- 缺乏状态持久化机制
- 缺乏状态变化的可观测性
为什么需要: 复杂应用需要可预测的状态管理,Zustand 提供了简洁的 API 和优秀的性能。
2.2 设计目标
- 模块化: 每个 Store 职责单一
- 持久化: 关键状态自动保存
- 可观测: 状态变化可追踪
- 类型安全: TypeScript 完整支持
2.3 竞品参考
| 项目 | 参考点 |
|---|---|
| Redux | 单向数据流思想 |
| MobX | 响应式状态 |
| Jotai | 原子化状态 |
2.4 设计约束
- 性能约束: 状态更新不能阻塞 UI
- 存储约束: localStorage 有 5MB 限制
- 兼容性约束: 需要支持 React 19 并发渲染
三、技术设计
3.1 Store 架构
store/
├── connectionStore.ts # 连接状态管理
├── chatStore.ts # 聊天状态 (最复杂)
├── configStore.ts # 配置状态
├── agentStore.ts # Agent 状态
├── handStore.ts # Hand 状态
├── workflowStore.ts # 工作流状态
├── teamStore.ts # 团队状态
├── gatewayStore.ts # Gateway 客户端状态
├── securityStore.ts # 安全配置
├── sessionStore.ts # 会话持久化
├── memoryGraphStore.ts # 记忆图谱
├── offlineStore.ts # 离线模式
├── activeLearningStore.ts # 主动学习
├── browserHandStore.ts # Browser Hand
└── skillMarketStore.ts # 技能市场
3.2 核心 Store 设计
chatStore (最复杂的 Store):
interface ChatState {
// 消息
messages: Message[];
conversations: Conversation[];
currentConversationId: string | null;
// Agent
agents: Agent[];
currentAgent: Agent | null;
// 流式
isStreaming: boolean;
// 模型
currentModel: string;
sessionKey: string | null;
}
interface ChatActions {
// 消息操作
sendMessage(content: string): Promise<void>;
addMessage(message: Message): void;
clearMessages(): void;
// 会话操作
createConversation(): string;
switchConversation(id: string): void;
deleteConversation(id: string): void;
// Agent 操作
setCurrentAgent(agent: Agent): void;
syncAgents(): Promise<void>;
// 流式处理
appendStreamDelta(delta: string): void;
finishStreaming(): void;
}
workflowBuilderStore (工作流构建器):
interface WorkflowBuilderState {
// Canvas state
canvas: WorkflowCanvas | null;
workflows: WorkflowCanvas[];
// Selection
selectedNodeId: string | null;
selectedEdgeId: string | null;
// UI state
isDragging: boolean;
isDirty: boolean;
isPreviewOpen: boolean;
validation: ValidationResult | null;
// Templates
templates: WorkflowTemplate[];
// Available items for palette
availableSkills: Array<{ id: string; name: string; description: string }>;
availableHands: Array<{ id: string; name: string; actions: string[] }>;
}
meshStore (自适应智能网格):
interface MeshState {
recommendations: WorkflowRecommendation[];
patterns: BehaviorPattern[];
config: MeshConfig;
isLoading: boolean;
error: string | null;
lastAnalysis: string | null;
// Actions
analyze: () => Promise<void>;
acceptRecommendation: (recommendationId: string) => Promise<void>;
dismissRecommendation: (recommendationId: string) => Promise<void>;
recordActivity: (activity: ActivityType, context: PatternContext) => Promise<void>;
getPatterns: () => Promise<void>;
updateConfig: (config: Partial<MeshConfig>) => Promise<void>;
decayPatterns: () => Promise<void>;
}
personaStore (Persona 演化):
interface PersonaEvolutionStore {
currentAgentId: string;
proposals: EvolutionProposal[];
history: EvolutionResult[];
isLoading: boolean;
error: string | null;
config: PersonaEvolverConfig | null;
state: PersonaEvolverState | null;
showProposalsPanel: boolean;
// Actions
runEvolution: (memories: MemoryEntryForAnalysis[]) => Promise<EvolutionResult | null>;
loadEvolutionHistory: (limit?: number) => Promise<void>;
applyProposal: (proposal: EvolutionProposal) => Promise<boolean>;
dismissProposal: (proposalId: string) => void;
}
3.3 Store 协调器
// store/index.ts
export function initializeStores(client: GatewayClientInterface) {
// 注入客户端依赖
connectionStore.getState().setClient(client);
chatStore.getState().setClient(client);
configStore.getState().setClient(client);
// ... 其他 Store
// 建立跨 Store 通信
connectionStore.subscribe((state) => {
if (state.connectionState === 'connected') {
chatStore.getState().syncAgents();
configStore.getState().loadConfig();
}
});
}
3.4 持久化策略
// 使用 Zustand persist 中间件
export const useChatStore = create<ChatState & ChatActions>()(
persist(
(set, get) => ({
// ... state and actions
}),
{
name: 'zclaw-chat',
partialize: (state) => ({
conversations: state.conversations,
currentModel: state.currentModel,
// messages 不持久化,太大
}),
}
)
);
四、预期作用
4.1 用户价值
| 价值类型 | 描述 |
|---|---|
| 效率提升 | 状态共享无需 prop drilling |
| 体验改善 | 页面刷新后状态保留 |
| 能力扩展 | 跨组件协作成为可能 |
4.2 系统价值
| 价值类型 | 描述 |
|---|---|
| 架构收益 | UI 与业务逻辑解耦 |
| 可维护性 | 状态变化可预测 |
| 可扩展性 | 新功能只需添加 Store |
4.3 成功指标
| 指标 | 基线 | 目标 | 当前 |
|---|---|---|---|
| 测试覆盖 | 50% | 80% | 85% |
| Store 数量 | 5 | 10+ | 15 |
| 持久化比例 | 30% | 70% | 65% |
五、实际效果
5.1 已实现功能
- 15 个专用 Store
- 持久化中间件
- 依赖注入模式
- 跨 Store 通信
- TypeScript 类型安全
- 内部 Kernel 状态同步
- Gateway 客户端状态管理
5.2 测试覆盖
- chatStore: 42 tests
- gatewayStore: 35 tests
- teamStore: 28 tests
- 总覆盖率: ~85%
5.3 已知问题
| 问题 | 严重程度 | 状态 | 计划解决 |
|---|---|---|---|
| 消息不持久化 | 低 | 设计决策 | 不修复 |
5.4 用户反馈
状态管理清晰,调试方便。
六、演化路线
6.1 短期计划(1-2 周)
- 添加 Redux DevTools 支持
6.2 中期计划(1-2 月)
- 迁移到 IndexedDB 持久化
6.3 长期愿景
- 状态同步到云端
七、头脑风暴笔记
7.1 待讨论问题
- 是否需要引入状态机 (XState)?
- 大消息列表是否需要虚拟化?
7.2 创意想法
- 时间旅行调试:记录状态变更历史
- 状态快照:支持状态回滚
7.3 风险与挑战
- 技术风险: localStorage 容量限制
- 缓解措施: 只持久化关键状态