跳到主要内容

状态存储

源码: state/AppStateStore.ts (22KB) | state/store.ts (836B)

1. 状态管理架构

store.ts (发布订阅原语)


AppStateStore.ts (统一状态)


87 个 React Hooks (业务逻辑)

2. 发布订阅原语

state/store.ts 提供极简的 pub/sub 机制:

// 发布订阅原语
function createStore<State>(initial: State) {
let state = initial
const listeners = new Set<() => void>()

return {
getState: () => state,
setState: (next: State) => {
state = next
listeners.forEach(fn => fn())
},
subscribe: (fn: () => void) => {
listeners.add(fn)
return () => listeners.delete(fn)
}
}
}

3. AppState

AppStateStore.ts 管理整个应用的统一状态:

  • 当前对话消息列表
  • 工具调用状态
  • 模型响应状态
  • 设置和配置
  • 成本追踪

上一节:05 记忆系统 | 下一节:07 UI 渲染