Claude Code 源码分析Claude Code 源码分析
首页
源码统计
系统架构
UML 图表
工具系统
CodeGraph
首页
源码统计
系统架构
UML 图表
工具系统
CodeGraph
  • 概览

    • Claude Code 源码分析
    • 源码统计
    • CodeGraph 图谱
  • 架构

    • 系统架构
    • UML 图表索引
    • 查询引擎
    • 核心流程
    • 消息系统
    • 状态管理
  • 功能模块

    • 工具系统
    • 斜杠命令
    • 服务层
    • MCP 协议
    • Skills 技能
    • 子代理系统
  • 分层深度

    • 入口层
    • UI / Ink 层
    • utils 基础设施
    • 桥接 / 远程
    • 上下文压缩
  • 原理与安全

    • 底层原理
    • 技术难点
    • 权限与安全
    • 内部机制
    • 遥测与分析
  • 深度专题

    • Hooks 系统
    • 插件系统
    • 记忆系统
    • API 通信层
    • Ink 终端 UI
    • 认证系统
    • 构建与发布
    • 术语表
  • 调用分析

    • 调用链分析
    • 核心文件索引
  • 模块详解

    • utils

      • 模块: utils
      • messages · 消息工厂与规范化
      • session-storage · JSONL 会话持久化
      • permissions · 工具权限决策
      • shell-hooks · 用户 Shell Hook 系统
    • components

      • 模块: components
      • REPL · 主屏编排
      • messages · 消息行渲染
      • PermissionRequest · 权限弹窗
      • PromptInput · 底部输入
    • services

      • 模块: services
      • api-claude · Anthropic API 流式与重试
      • mcp-client · MCP 连接与工具调用
      • compact · 上下文压缩与自动触发
      • analytics · GrowthBook、Datadog 与 1P 事件
    • tools

      • 模块: tools
      • tool-interface · Tool 契约与注册表
      • bash-tool · Shell 执行与权限
      • streaming-executor · 流式工具并发调度
      • agent-tool · 子 Agent 委派
    • commands

      • 模块: commands
      • command-registry · commands.ts 注册与分派
      • model-command · /model 模型选择
      • mcp-commands · /mcp 服务器管理
      • compact-memory-commands · /compact 与 /memory
    • ink

      • 模块: ink
      • Ink 渲染管线 · Screen 与终端输出
      • 终端事件 · resize、paste、stdin
      • Ink Hooks · 输入、搜索、终端状态
      • Ink 组件 · Box、Text、ScrollBox 原语
    • hooks

      • 模块: hooks
      • useCanUseTool · 权限 UI 接缝
      • 输入与快捷键 Hook
      • 合并态 Hook(MCP + 本地)
      • notifs 通知 Hook
    • bridge

      • 模块: bridge
      • repl-bridge · REPL 桥初始化与传输
      • bridge-messaging · 桥消息路由与入站处理
      • remote-bridge-core · env-less 核心与守护主循环
      • bridge-permissions-ui · 权限、API 与 TUI
    • cli

      • 模块: cli
      • Structured IO · NDJSON SDK 协议
      • CLI Transports · Session Ingress 传输层
      • CLI Handlers · 子命令懒加载实现
      • Update & Upload · 自更新与串行上传原语
    • screens

      • 模块: screens
      • REPL 屏 · Screen 类型与顶层路由
      • ResumeConversation · 会话恢复选择器
      • Doctor · 安装诊断全屏
    • entrypoints

      • 模块: entrypoints
      • cli-entrypoint · Bootstrap 与快路径
      • sdk-types · core / control / runtime 类型体系
      • mcp-entrypoint · MCP stdio 服务器
      • sandbox-types · 沙箱配置单一真相源
    • skills

      • 模块: skills
      • skills-loading · 磁盘加载与 bundled 注册表
      • bundled-skills · 内置 skill 与 initBundledSkills
      • mcp-skills · MCP prompt 转 skill
      • skill-tool-integration · SkillTool 与命令注册
    • types

      • 模块: types
      • message-types · Message 联合与 content blocks
      • tool-permission-types · Tool、Permission、Command 类型
      • api-sdk-types · API 与 Hooks 协议类型
      • misc-types · ids、plugin、generated 与其余类型
    • tasks

      • 模块: tasks
      • local-agent-task · 本地 Agent 与主会话后台化
      • remote-agent-task · 远程 CCR 与 In-Process Teammate
      • shell-workflow-tasks · Bash 后台、Workflow 与 stopTask
      • dream-monitor-tasks · Dream、Monitor MCP 与 pill 文案
    • keybindings

      • 模块: keybindings
      • keybinding-registry · 注册、Provider 与 useKeybinding
      • default-bindings · 默认键位表与平台差异
      • command-bindings · command:* 动态斜杠命令绑定
      • vim-bindings · Vim 模式与 keybindings 边界
    • memdir

      • 模块: memdir
      • memdir-core · 路径、加载与 MEMORY.md
      • memory-extraction · extractMemories 与 SessionMemory
      • memdir-commands · /memory、/remember 与命令集成
    • state

      • 模块: state
      • app-state-core · store、AppState 类型与 Provider
      • app-state-selectors · selectors 与 onChangeAppState
      • teammate-state · 队友视图与 swarm 状态
      • state-boundaries · bootstrap、sessionStorage、FileStateCache
    • query

      • 模块: query
      • query config 与 deps · 配置快照与依赖注入
      • query tokenBudget · +500k 自动续跑
      • query transitions · Continue / Terminal 状态机
      • query stopHooks · Stop 事件与 turn 结束编排
  • 模块详解(扩展)

    • messages · 消息工厂与规范化
    • session-storage · JSONL 会话持久化
    • permissions · 工具权限决策
    • shell-hooks · 用户 Shell Hook 系统
    • REPL · 主屏编排
    • messages · 消息行渲染
    • PermissionRequest · 权限弹窗
    • PromptInput · 底部输入
    • api-claude · Anthropic API 流式与重试
    • mcp-client · MCP 连接与工具调用
    • compact · 上下文压缩与自动触发
    • analytics · GrowthBook、Datadog 与 1P 事件
    • tool-interface · Tool 契约与注册表
    • bash-tool · Shell 执行与权限
    • streaming-executor · 流式工具并发调度
    • agent-tool · 子 Agent 委派
    • command-registry · commands.ts 注册与分派
    • model-command · /model 模型选择
    • mcp-commands · /mcp 服务器管理
    • compact-memory-commands · /compact 与 /memory
    • Ink 渲染管线 · Screen 与终端输出
    • 终端事件 · resize、paste、stdin
    • Ink Hooks · 输入、搜索、终端状态
    • Ink 组件 · Box、Text、ScrollBox 原语
    • useCanUseTool · 权限 UI 接缝
    • 输入与快捷键 Hook
    • 合并态 Hook(MCP + 本地)
    • notifs 通知 Hook
    • repl-bridge · REPL 桥初始化与传输
    • bridge-messaging · 桥消息路由与入站处理
    • remote-bridge-core · env-less 核心与守护主循环
    • bridge-permissions-ui · 权限、API 与 TUI
    • Structured IO · NDJSON SDK 协议
    • CLI Transports · Session Ingress 传输层
    • CLI Handlers · 子命令懒加载实现
    • Update & Upload · 自更新与串行上传原语
    • REPL 屏 · Screen 类型与顶层路由
    • ResumeConversation · 会话恢复选择器
    • Doctor · 安装诊断全屏
    • cli-entrypoint · Bootstrap 与快路径
    • sdk-types · core / control / runtime 类型体系
    • mcp-entrypoint · MCP stdio 服务器
    • sandbox-types · 沙箱配置单一真相源
    • skills-loading · 磁盘加载与 bundled 注册表
    • bundled-skills · 内置 skill 与 initBundledSkills
    • mcp-skills · MCP prompt 转 skill
    • skill-tool-integration · SkillTool 与命令注册
    • message-types · Message 联合与 content blocks
    • tool-permission-types · Tool、Permission、Command 类型
    • api-sdk-types · API 与 Hooks 协议类型
    • misc-types · ids、plugin、generated 与其余类型
    • local-agent-task · 本地 Agent 与主会话后台化
    • remote-agent-task · 远程 CCR 与 In-Process Teammate
    • shell-workflow-tasks · Bash 后台、Workflow 与 stopTask
    • dream-monitor-tasks · Dream、Monitor MCP 与 pill 文案
    • keybinding-registry · 注册、Provider 与 useKeybinding
    • default-bindings · 默认键位表与平台差异
    • command-bindings · command:* 动态斜杠命令绑定
    • vim-bindings · Vim 模式与 keybindings 边界
    • memdir-core · 路径、加载与 MEMORY.md
    • memory-extraction · extractMemories 与 SessionMemory
    • memdir-commands · /memory、/remember 与命令集成
    • app-state-core · store、AppState 类型与 Provider
    • app-state-selectors · selectors 与 onChangeAppState
    • teammate-state · 队友视图与 swarm 状态
    • state-boundaries · bootstrap、sessionStorage、FileStateCache
    • query config 与 deps · 配置快照与依赖注入
    • query tokenBudget · +500k 自动续跑
    • query transitions · Continue / Terminal 状态机
    • query stopHooks · Stop 事件与 turn 结束编排
  • 工具详解

    • tool-interface · Tool 契约与注册表
    • tool-permission-types · Tool、Permission、Command 类型
    • 工具: Bash
    • 工具: PowerShell
    • 工具: Agent
    • 工具: LSP
    • 工具: FileEdit
    • 工具: FileRead
    • 工具: Skill
    • 工具: WebFetch
    • 工具: MCP
    • 工具: SendMessage
    • 工具: FileWrite
    • 工具: Config
    • 工具: Grep
    • 工具: Brief
    • 工具: ExitPlanMode
    • 工具: ToolSearch
    • 工具: NotebookEdit
    • 工具: TaskOutput
    • 工具: WebSearch
    • 工具: ScheduleCron

本章总览

src/state/ 是 Claude Code 的「React 可订阅全局状态层」:用轻量 createStore 实现 Zustand 风格的 getState / setState / subscribe,AppStateStore.ts 定义约 450 行巨型 AppState 类型与默认值,AppState.tsx 提供 Provider 与 useAppState 切片订阅(6 个文件,约 1196 行)。务必区分:bootstrap/state.ts(进程级 session/cost 全局单例)≠ state/ 目录(Ink REPL 的 React 状态树)。

总览图

渲染图表中…

学完本章你应该能

  • 建立 AppState 与 bootstrap/state 双轨心智模型
  • 理解 useAppState 切片订阅与 Object.is 相等性约束
  • 能从 REPL 反查 viewingAgentTaskId、teamContext 等字段来源
  • 知道 onChangeAppState 如何把 UI 变更同步到磁盘与 CCR

建议学习步骤

  1. 浏览下方子章节导航表,选择入口主题
  2. 点击 SourceTree 中的 state/ 文件跳转到对应讲解
  3. 建议顺序:app-state-core → app-state-selectors → teammate-state → state-boundaries

模块在架构中的位置

state 是 src/ 下的一级目录,共 6 个文件、1,196 行。建议结合「系统架构」章节理解它与其他层的调用关系。

模块 UML 图表

状态更新路径

渲染图表中…

概览

指标数值
行数1,196
文件6

子章节导航

子章节主题核心路径
app-state-corestore、AppState 类型、Providerstore.ts、AppStateStore.ts、AppState.tsx
app-state-selectors纯函数 selector、副作用同步selectors.ts、onChangeAppState.ts
teammate-state队友 transcript 视图、swarmteammateViewHelpers.ts、useSwarmInitialization.ts
state-boundariesbootstrap、持久化、文件缓存bootstrap/state.ts、sessionStorage.ts、fileStateCache.ts

双轨状态:AppState vs bootstrap/state

Claude Code 刻意把状态拆成两层,避免 React 树之外的业务代码 import Ink:

层位置生命周期典型字段
AppStatestate/AppStateStore.ts随 AppStateProvider 存在;headless 用 createStore 无 ProvidermainLoopModel、tasks、mcp.clients、viewingAgentTaskId
bootstrap STATEbootstrap/state.ts进程级单例;注释「DO NOT ADD MORE STATE HERE」sessionId、totalCostUSD、mainLoopModelOverride、cwd

onChangeAppState 是两条轨道的接缝之一:当 mainLoopModel 在 AppState 中变化时,同步调用 setMainLoopModelOverride 写入 bootstrap,并 updateSettingsForSource 落盘。

非 React 代码(query 循环、Tool 执行、sessionStorage)应读 bootstrap 或接收 getState() 快照,而不是 import useAppState。

store 与订阅模型

store.ts 的 createStore 实现极简:

setState(updater):
  prev = state
  next = updater(prev)
  if Object.is(next, prev) return   // 无变化则静默
  state = next
  onChange?.({ newState, oldState })
  notify all listeners

AppStateProvider 用 useState(() => createStore(...)) 保证 store 实例稳定——Provider 自身不因 setState 重渲染;消费者通过 useSyncExternalStore 订阅。

useAppState(selector) 要求 selector 返回已有子对象引用或原始值,禁止 s => ({ ...s.foo }) 这种每次新建对象的选择器,否则 Object.is 永远为 false 导致无限重渲染。

AppState 字段簇概览

AppState 不是扁平 KV,而是按产品域分簇(节选):

簇代表字段消费方
模型与模式mainLoopModel、toolPermissionContext、fastMode/model、Shift+Tab、query config
任务与队友tasks、viewingAgentTaskId、teamContextBackgroundTasksDialog、SendMessage
MCP / 插件mcp.*、plugins.*useManageMCPConnections、/reload-plugins
Bridge / RemotereplBridge*、remoteConnectionStatusreplBridge、/remote-control
UI 壳层expandedView、footerSelection、activeOverlaysPromptInputFooter、Escape 协调

tasks 与 agentNameRegistry 被 DeepImmutable 排除函数类型;Map / Set 字段(fileHistory.trackedFiles、activeOverlays)在 setState 时需替换引用以触发订阅。

目录树展示 src/state/ 全部 6 个文件。相关边界文件(bootstrap/state.ts、utils/sessionStorage.ts)在 state-boundaries 子章节通过 highlightFiles 与高亮锚点跳转。

与其他模块的边界

协作方关系
screens/REPL.tsx包裹 AppStateProvider;大量 useAppState 切片
main.tsxheadless createStore(initialState, onChangeAppState)
hooks/useSwarmInitialization.tsresume 时写入 teamContext
hooks/useTeammateViewAutoExit.ts监听 viewed task status,调用 exitTeammateView
utils/sessionStorage.ts持久化 transcript;与 bootstrap sessionId 对齐
utils/fileStateCache.tsTool 读文件缓存;compact 时 clone/merge
services/mcp/*连接状态写入 appState.mcp

调试「状态不同步」:先确认改的是 AppState 还是 bootstrap;再查 onChangeAppState 是否覆盖该字段;最后看 setState 是否返回同一引用导致订阅未触发。

本章小结与延伸

state 模块 = REPL 与 Ink 组件的单一可订阅真相源。先懂 store + AppState 形状,再读 selectors 与 teammate 视图切换,最后理解 bootstrap / sessionStorage / FileStateCache 三条边界。 继续学习:

  • app-state-core
Next
app-state-core · store、AppState 类型与 Provider