Skip to content

CodexBar 是一个 macOS 菜单栏应用,用于查看本机 Codex 账号状态、额度、Token 用量、详细统计信息

fix: 完善 Hook 兼容与统计重建

Bobcbd4cc025405
diff --git a/AGENTS.md b/AGENTS.md
index e74aa56..ec34476 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -29,17 +29,19 @@ CodexBar 是面向 macOS 15+ 的 `LSUIElement` 菜单栏应用, 使用 Swift 6,
## 架构与编码约定
-启动时必须先调用 `WorkflowHookEventRecorder.handleIfRequested()` 方法. `--hook-event` 模式只读取 stdin, 加锁写入 JSONL 并立即退出, 不初始化 UI, 失败也不能阻断 Codex. 普通模式由 `CodexBarAppDelegate` 统一装配长期服务
+启动时必须先调用 `WorkflowHookEventRecorder.handleIfRequested()` 方法. `--hook-event` 模式只读取 stdin, 加锁写入 JSONL 并立即退出, 不初始化 UI, 失败也不能阻断 Codex. Handler 超时按事件从 `hookTimeoutSeconds(for:)` 取得, `SessionEnd` 为 3 秒, 其他事件为 5 秒. 普通模式由 `CodexBarAppDelegate` 统一装配长期服务
工程默认采用 `MainActor` 隔离. UI, Controller, ViewModel 和 Settings 依赖默认隔离, 共享可变状态放入 actor, DTO 和跨 actor 值类型按需添加 `nonisolated` 标记, 禁止在主 actor 执行阻塞 I/O. 类型命名使用 `UpperCamelCase` 风格, 成员命名使用 `lowerCamelCase` 风格. 注释只解释非显然的生命周期, 焦点, actor 或系统 API 约束
-保持三条数据链路独立: app-server 额度与用量, Hook 历史聚合, `CodexActivityMonitor` 实时任务; helper 只能控制睡眠, 不得增加网络, 任意命令执行或额外文件访问; 修改 Hook 配置时必须保留用户和其他应用已有的 handler; 新增网络访问, 日志数据或 CloudKit 字段前先核对隐私边界
+保持三条数据链路独立: app-server 额度与用量, Hook 历史聚合, `CodexActivityMonitor` 实时任务; helper 只能控制睡眠, 不得增加网络, 任意命令执行或额外文件访问; 修改 Hook 配置时必须保留用户和其他应用已有的 handler; 启用和校验 Hook 必须检查当前 app-server 的实际版本不低于 `0.145.0`; 新增网络访问, 日志数据或 CloudKit 字段前先核对隐私边界
+
+需要从原始 Hook 事件重新计算的聚合算法, 输出字段, 字段含义或去重规则变化时必须递增 `WorkflowMaintenanceState.currentAggregationSchema`, 统一从保留期内的原始 JSONL 完整重建, 不新增字段级历史迁移. Hook 计数字段缺失表示历史来源不可用, 不能解码成明确的 0
## 测试规范
仓库没有 XCTest target 或覆盖率门槛. 每次改动至少应完成构建, 运行 `swiftformat` 和 `swiftlint` 两项检查, 并手动验证受影响流程. 菜单, 窗口焦点, Hook, 同步, 通知和防睡眠改动必须说明手动验证场景. Debug 与 Release 使用不同 App 和 helper bundle ID, 排查时不要混用
-## Commit 与 Pull Request 规范
+## Git 规范
不要主动 push, 不要回滚, 覆盖或丢弃他人的未提交修改. 用户只要求提交时, 不要顺带格式化或修改文件
@@ -52,4 +54,13 @@ CodexBar 是面向 macOS 15+ 的 `LSUIElement` 菜单栏应用, 使用 Swift 6,
- body 中的 bullet 连续排列, 每条缩进 4 个空格
- commit message 中不要出现版本号, Release 标记或其他发布版本相关内容
-PR 应说明用户影响, 实现范围, 关联 issue 和验证结果, UI 改动附截图或录屏. 涉及旧数据, 持久化 key, 云端格式, 最低系统版本或新旧共存的兼容性决策, 必须先说明选项与代价并询问用户
+Tag 名 `v{MARKETING_VERSION}` 里的版本号从 `Config/Version.xcconfig` 读取, 使用附注 tag `git tag -a v3.x.y -m "Release v3.x.y"`
+
+## 代码修改原则
+
+- 优先结合现有文件结构和类型职责, 不为小改动新建抽象
+- 改 shared controller, shared service, 模型解析或持久化 key 时, 要考虑旧数据和降级路径; 用户设置要保持默认值; 持久化 key 和旧版本迁移兼容
+- **任何兼容性问题都必须主动询问用户, 不要自行决定**; 只要改动会影响新旧共存就适用, 不限于旧数据迁移或丢弃, 持久化 key 改名或改结构, 老版本升上来的降级路径, 最低系统版本与 API 可用性取舍, 云端记录格式变更; 先说清影响面和几种做法的代价, 等用户选定再动手
+- 处理窗口, 菜单, 快捷键, App 激活或事件监听时, 特别注意 `LSUIElement` 应用特有的焦点行为
+- 注释保持克制, 只解释非显然的生命周期, 焦点, actor 或系统 API 约束; 现有注释多为解释为什么的类型, 沿用同样风格
+- 改动涉及菜单面板, 窗口焦点, Hook, 同步, 通知或防睡眠时, 构建通过之外还要说明应手动覆盖的交互场景; 防睡眠额外要验证 App 包内 helper 与 plist 位置, 签名, 首次系统授权, 运行/等待切换和异常退出后的恢复
diff --git a/CLAUDE.md b/CLAUDE.md
index 27cd6cf..2bf0d17 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -81,7 +81,7 @@ fix: 修复 Codex 状态刷新
- 保留当前运行版本与磁盘安装版本不一致时的更新提示
```
-Tag 名 `v{MARKETING_VERSION}` 里的版本号从 Xcode build settings 读取, 使用附注 tag `git tag -a v3.x.y -m "Release v3.x.y"`
+Tag 名 `v{MARKETING_VERSION}` 里的版本号从 `Config/Version.xcconfig` 读取, 使用附注 tag `git tag -a v3.x.y -m "Release v3.x.y"`
## 架构
@@ -89,7 +89,8 @@ Tag 名 `v{MARKETING_VERSION}` 里的版本号从 Xcode build settings 读取,
`CodexBar/App/CodexBarApp.swift` 的 `init()` 最先调用 `WorkflowHookEventRecorder.handleIfRequested()`
-- 带 `--hook-event` 启动 -> **Hook 子进程模式**: 从 stdin 读 JSON payload, 在 `flock` 锁内追加一行 JSONL 后立即 `exit(EXIT_SUCCESS)` 退出, 绝不初始化菜单栏 UI; 写入失败静默吞掉, 不阻断 Codex; Hook handler 超时由 `hookTimeoutSeconds` 定为 5 秒, 等锁预算据此推算为 3 秒, 两者必须一起改
+- 带 `--hook-event` 启动 -> **Hook 子进程模式**: 从 stdin 读 JSON payload, 在 `flock` 锁内追加一行 JSONL 后立即 `exit(EXIT_SUCCESS)` 退出, 绝不初始化菜单栏 UI; 写入失败静默吞掉, 不阻断 Codex
+- Hook handler 超时统一由 `WorkflowHookEventRecorder.hookTimeoutSeconds(for:)` 提供, `SessionEnd` 是 3 秒, 其他事件是 5 秒; 等锁预算固定比对应事件超时少 2 秒, 当前分别是 1 秒和 3 秒
- 普通启动 -> `CodexBarAppDelegate` 创建全部长期对象, 它在 `Controllers/StatusItemController.swift` 内, 再由 `StatusItemController.install()` 装配菜单栏; AppDelegate 是唯一的装配点, 新增服务在这里注入
### 三条数据链路
@@ -107,7 +108,12 @@ Tag 名 `v{MARKETING_VERSION}` 里的版本号从 Xcode build settings 读取,
Hook 子进程按天写入 `~/Library/Application Support/CodexBar/HookEvents/events/YYYY-MM-DD.jsonl` 这类文件, 主 App 的 `WorkflowService` (actor) 增量聚合出 `daily.jsonl` 与 `WorkflowSnapshot` 供热力图详情面板展示; 可选跨设备同步由 `WorkflowSyncScheduler` (唯一调度者) 与 `WorkflowSyncService` 负责, 走 `iCloud.app.zabrian.codexbar` 容器的 CloudKit private database, 只上传脱敏 daily 聚合
-`WorkflowStorage` 管理的存储目录含 `events/` `daily.jsonl` `stats.lock` `maintenance.json` `Sync/` 五项; 保留期 210 天, 对原始事件文件和 daily 聚合同时生效, 清理由 `pruneExpiredEventFiles` 执行; 聚合里的会话与轮次标识额外只保留 3 天, 过期后被 compact 掉
+- `WorkflowStorage` 管理的存储目录含 `events/` `daily.jsonl` `stats.lock` `maintenance.json` `Sync/` 五项
+- 原始事件文件与 daily 聚合统一保留 210 天, 聚合里的会话与轮次标识只保留 3 天, 到期后只留下去重计数
+- `WorkflowDailyAccumulator` 的全量与增量路径始终在内存收集完整 ID, 只有 `finalized(identifierStorage:)` 才决定保留或压缩; 已压缩的日期收到新事件时不能安全去重, 必须降级为从原始 JSONL 完整重建
+- `WorkflowMaintenanceState.currentAggregationSchema` 是原始事件到 daily 聚合的算法版本; 缺少版本按 0 处理, 版本不一致时把仍有原始事件的日期全部标脏并走通用完整重建, 不写字段级历史迁移
+- 需要从原始事件重新计算的聚合算法, 输出字段, 字段含义或去重规则变化时必须递增 `currentAggregationSchema`, 统一走相同的完整重建入口
+- daily 与 CloudKit 中的 Hook 计数字段都是可选值; `nil` 表示来源版本没有提供或无法确认, 明确的 `0` 才表示已知没有对应事件, 解码和重建都不能把两者混为一谈
**链路三: 实时任务, 由 `CodexActivityMonitor` 驱动**
@@ -115,6 +121,8 @@ Hook 子进程按天写入 `~/Library/Application Support/CodexBar/HookEvents/ev
- `HookEventTailReader` (actor) 的 bootstrap 覆盖滚动 24 小时并作为单次事务发送, 之后按当日文件 offset 增量 tail
- `CodexSessionLifecycleReader` (actor) 增量读取 `~/.codex/sessions` 与 `archived_sessions` 下的 rollout JSONL, 只提取 turn 生命周期字段, 不解码会话或工具内容
+- 任务监控只在 `codexHookSettings.isOperable` 为 true 时运行, 即本地已安装且最近一次明确校验没有失败; 链路失效时立即停 reader 并清空实时状态
+- `SessionEnd` 没有 `turn_id`, 收到后按 session 把对应任务立即移出活跃列表并放进 5 秒终态确认窗口; rollout 在窗口内补回准确的完成或终止分类, 超时后按终止处理
系统唤醒时 `NSWorkspace.didWakeNotification` 会触发立即 drain 并重置生命周期解析回退
@@ -125,7 +133,7 @@ Hook 子进程按天写入 `~/Library/Application Support/CodexBar/HookEvents/ev
- `SystemSleepService` 用进程内 `IOPMAssertion` 建立 `PreventUserIdleSystemSleep` 断言, 只挡空闲睡眠, 不需要提权; 断言名必须是 ASCII, 否则 `pmset -g assertions` 显示不出标识
- `CodexBarHelper` 是 root LaunchDaemon, 通过 XPC 接受 `setSleepDisabled` 请求, 执行 `/usr/bin/pmset -a disablesleep` 覆盖合盖睡眠
-链路: `KeepAliveController` (MainActor) 订阅 `activityMonitor.$snapshot` 与 `codexHookSettings.$isEnabled` -> `SMAppService.daemon(plistName:)` 注册 -> `NSXPCConnection` -> helper
+链路: `KeepAliveController` (MainActor) 订阅 `activityMonitor.$snapshot` 以及合成 `codexHookSettings.isOperable` 的两个发布值 -> `SMAppService.daemon(plistName:)` 注册 -> `NSXPCConnection` -> helper
关键约束
@@ -251,11 +259,15 @@ Hook 子进程按天写入 `~/Library/Application Support/CodexBar/HookEvents/ev
`~/.codex/hooks.json` 的读写全部在 `CodexHookSettings` 里完成, Codex 目录优先取 `CODEX_HOME` 环境变量, 找不到时回退真实用户 HOME 下的 `.codex` 目录
- 只识别并移除 command 同时包含当前 CodexBar 可执行路径与 `--hook-event` 的 handler, 必须保留用户已有 Hook 以及其他 App 的 Hook 和同事件下的其他 handler
+- 每个 `CodexHookEvent.allCases` 事件追加一个独立 group, handler 超时从 `WorkflowHookEventRecorder.hookTimeoutSeconds(for:)` 取得; 新增事件时不得复制一份超时常量
+- 启用和校验 Hook 前要求当前 app-server 握手版本至少为 `0.145.0`; 必须检查 `readyConnectionInfo()` 返回的实际连接版本, 不能用磁盘版本代替, 否则升级后尚未重连的旧进程会被误判为可用
- 写入前通过 app-server `config/read` 确认全局未禁用 Hook, 写入后用 `hooks/list` 验证; 两处读取共用 `readGlobalHookDisabled`, 开关流程与校验流程对"全局禁用"的判断不会分叉
- 读取失败 (I/O 或 JSON 格式错误) 不提供 Hook 装没装的信息, 必须保留上次已知值, 不能当成用户关闭了 Hook
-- `isEnabled` 只表示 `hooks.json` 里装着, `isVerified` 是最近一次校验的明确结论, 两者与出来的 `isOperable` 才是"事件真的送得过来"; 依赖 Hook 的下游一律看 `isOperable`
+- `isEnabled` 只表示 `hooks.json` 里至少装着一个当前 CodexBar handler, `isVerified` 是最近一次校验的明确结论, 两者合成的 `isOperable` 才表示事件链路可用
+- 实时任务, 防睡眠和任务类通知必须看 `isOperable`; 历史聚合与同步仍可消费已落盘数据, 其调度只看 `isEnabled`, 不要把两类依赖混在一起
- `isVerified` 乐观默认为 true 且只由明确结论写入两个方向: 校验只在设置窗口打开与 App 激活时跑, 而 RPC 失败属于"验不了"不是"确认不通", 那时置灰会把好用的功能关掉
- 全局禁用要排在 `hooks/list` 之前判: 它一关列表里必然找不到我们的 handler, 那时报"已不完整"会把用户引去翻本来就完好的 `hooks.json`
+- `refresh()` 只判断是否存在任一当前 CodexBar handler, `hooks/list` 校验才要求所有事件完整; 新增事件后旧配置不会自动补齐, 当前恢复方式是让用户关闭再开启 Hook
- 校验不通过时防睡眠那一行的说明写"CodexBar Hook 未生效"而不是"需要启用 CodexBar Hook", 后者会让用户去开一个已经开着的开关; 具体病因由 Hook 那一行自己的说明给出
## 隐私与数据边界
@@ -266,6 +278,7 @@ Hook 子进程按天写入 `~/Library/Application Support/CodexBar/HookEvents/ev
- 只读查询打到 `https://chatgpt.com/backend-api/wham/rate-limit-reset-credits` 这一个地址, 也是全仓库唯一的 `URLSession` 调用点, 位于 `CodexResetCreditsService` 内; Sparkle 更新走 `https://codexbar.zabrian.app/appcast.xml` 这个 feed
- 不展示 app-server stderr; 不展示或记录 Codex OAuth token 与 `auth.json` 内容; 不把原始敏感 RPC 响应写进文档
- CloudKit 只同步去掉 `sessionIds` 与 `turnIds` 的 daily 聚合, 不同步原始 Hook events, 账号, 额度或 Token 用量
+- CloudKit 的 `sessionEndCount` `userPromptSubmitCount` 与其他 Hook 计数字段保持可选, 远端缺失表示历史来源没有提供, 不能在读取时补成 0; 改变远端格式时同时评估并更新 `syncSchemaVersion`
- 系统日志不写用户数据: 额度与 Token 用量只记 `state=` 这类结果分类, 任务内容, 项目名, 会话与轮次标识一律不记; 可执行文件路径含用户名, 用 `source=global|bundled` 之类的标识代替
- 事件数, 任务数, 日期这类聚合数字可以记, 它们是判断重建是否正确和定位哪天出问题的依据, 不含任何内容
diff --git a/CodexBar/Models/CodexHookEvent.swift b/CodexBar/Models/CodexHookEvent.swift
index 7dd69c0..284e872 100644
--- a/CodexBar/Models/CodexHookEvent.swift
+++ b/CodexBar/Models/CodexHookEvent.swift
@@ -1,8 +1,9 @@
import Foundation
/// Codex Hook 事件名的统一枚举, 负责在 hooks.json 与 app-server 命名间转换
-nonisolated enum CodexHookEvent: String, CaseIterable {
+nonisolated enum CodexHookEvent: String, CaseIterable, Hashable {
case sessionStart = "SessionStart"
+ case sessionEnd = "SessionEnd"
case userPromptSubmit = "UserPromptSubmit"
case preToolUse = "PreToolUse"
case postToolUse = "PostToolUse"
diff --git a/CodexBar/Models/CodexWorkflowModels.swift b/CodexBar/Models/CodexWorkflowModels.swift
index c7c2451..0487319 100644
--- a/CodexBar/Models/CodexWorkflowModels.swift
+++ b/CodexBar/Models/CodexWorkflowModels.swift
@@ -29,6 +29,15 @@ private nonisolated enum WorkflowJSON {
}
return text
}
+
+ static func presentCountFields(_ values: [(String, Int?)]) throws -> [String] {
+ try values.compactMap { name, value in
+ guard let value else {
+ return nil
+ }
+ return try field(name, value)
+ }
+ }
}
private nonisolated enum WorkflowCountResolution {
@@ -40,11 +49,11 @@ private nonisolated enum WorkflowCountResolution {
return compactedCount
}
- guard let identifiers, !identifiers.isEmpty else {
- return nil
+ if let identifiers, !identifiers.isEmpty {
+ return Set(identifiers).count
}
- return Set(identifiers).count
+ return compactedCount == 0 ? 0 : nil
}
static func resolvedCount(
@@ -358,7 +367,7 @@ nonisolated struct WorkflowSnapshot: Equatable {
}
if let matchingIndex,
- remoteRecords[matchingIndex].daily.eventCount > local.eventCount {
+ (remoteRecords[matchingIndex].daily.eventCount ?? 0) > (local.eventCount ?? 0) {
merge(remoteRecords[matchingIndex].daily.metrics, into: &metricsByDate)
} else {
merge(local.metrics, into: &metricsByDate)
@@ -404,17 +413,139 @@ nonisolated struct WorkflowSnapshot: Equatable {
}
}
-// MARK: - 会话与轮次标识缓存
+// MARK: - 每日事件聚合
+
+/// ID 保留期限只决定最终存储形态, 不能影响聚合结果
+nonisolated enum WorkflowIdentifierStorage {
+ case retained
+ case compacted
+}
-/// 聚合时保留 Set 缓存, 避免同一会话或轮次重复计数
-nonisolated struct WorkflowDailyIdentifierCache {
- var sessionIds: Set<String>
- var turnIds: Set<String>
+/// 从原始事件生成每日聚合的纯内存累加器
+/// 全量和增量路径都收集 ID, 只有 finalize 时才按保留策略决定是否落盘
+nonisolated struct WorkflowDailyAccumulator {
+ private var aggregate: WorkflowDailyAggregate
+ private var sessionIds: Set<String> = []
+ private var turnIds: Set<String> = []
- init(aggregate: WorkflowDailyAggregate) {
+ init(
+ rebuilding date: String,
+ sourceGeneration: String?,
+ sourceIsFresh: Bool,
+ hookCountAvailability: WorkflowHookCountAvailability
+ ) {
+ aggregate = WorkflowDailyAggregate(
+ date: date,
+ sourceGeneration: sourceGeneration,
+ sourceIsFresh: sourceIsFresh,
+ hookCountAvailability: hookCountAvailability
+ )
+ }
+
+ init(
+ appending aggregate: WorkflowDailyAggregate,
+ sourceGeneration: String?,
+ sourceIsFresh: Bool
+ ) {
+ var aggregate = aggregate
+ aggregate.sourceGeneration = sourceGeneration
+ aggregate.sourceIsFresh = sourceIsFresh
+ self.aggregate = aggregate
sessionIds = Set(aggregate.sessionIds ?? [])
turnIds = Set(aggregate.turnIds ?? [])
}
+
+ mutating func record(_ event: WorkflowHookEvent) {
+ Self.increment(&aggregate.eventCount)
+
+ switch event.hookEvent {
+ case .sessionStart: Self.increment(&aggregate.sessionStartCount)
+ case .sessionEnd: Self.increment(&aggregate.sessionEndCount)
+ case .userPromptSubmit: Self.increment(&aggregate.userPromptSubmitCount)
+ case .stop: Self.increment(&aggregate.stopCount)
+ case .preToolUse: Self.increment(&aggregate.preToolUseCount)
+ case .postToolUse: Self.increment(&aggregate.postToolUseCount)
+ case .permissionRequest: Self.increment(&aggregate.permissionRequestCount)
+ case .preCompact: Self.increment(&aggregate.preCompactCount)
+ case .postCompact: Self.increment(&aggregate.postCompactCount)
+ case .subagentStart: Self.increment(&aggregate.subagentStartCount)
+ case .subagentStop: Self.increment(&aggregate.subagentStopCount)
+ case .none: break
+ }
+
+ if let sessionId = event.sessionId {
+ sessionIds.insert(sessionId)
+ }
+ if let turnId = event.turnId {
+ turnIds.insert(turnId)
+ }
+
+ if let projectDisplayName = event.projectDisplayName {
+ aggregate.projectCounts[projectDisplayName, default: 0] += 1
+ }
+ if let modelName = event.modelName {
+ aggregate.modelCounts[modelName, default: 0] += 1
+ }
+ }
+
+ func finalized(identifierStorage: WorkflowIdentifierStorage) -> WorkflowDailyAggregate {
+ var aggregate = aggregate
+ switch identifierStorage {
+ case .retained:
+ aggregate.sessionCount = nil
+ aggregate.turnCount = nil
+ aggregate.sessionIds = Self.normalizedIdentifiers(sessionIds)
+ aggregate.turnIds = Self.normalizedIdentifiers(turnIds)
+ case .compacted:
+ aggregate.sessionCount = sessionIds.isEmpty
+ ? aggregate.sessionStartCount
+ : sessionIds.count
+ aggregate.turnCount = turnIds.isEmpty
+ ? aggregate.stopCount
+ : turnIds.count
+ aggregate.sessionIds = nil
+ aggregate.turnIds = nil
+ }
+ return aggregate
+ }
+
+ private static func increment(_ count: inout Int?) {
+ count = (count ?? 0) + 1
+ }
+
+ private static func normalizedIdentifiers(_ identifiers: Set<String>) -> [String]? {
+ let normalized = identifiers.sorted()
+ return normalized.isEmpty ? nil : normalized
+ }
+}
+
+/// 全量重放时保留每个 Hook 计数字段原有的可用性
+nonisolated struct WorkflowHookCountAvailability {
+ static let all = WorkflowHookCountAvailability(
+ includesEventCount: true,
+ events: Set(CodexHookEvent.allCases)
+ )
+
+ private let includesEventCount: Bool
+ private let events: Set<CodexHookEvent>
+
+ init(aggregate: WorkflowDailyAggregate) {
+ includesEventCount = aggregate.eventCount != nil
+ events = Set(CodexHookEvent.allCases.filter { aggregate.hookCount(for: $0) != nil })
+ }
+
+ private init(includesEventCount: Bool, events: Set<CodexHookEvent>) {
+ self.includesEventCount = includesEventCount
+ self.events = events
+ }
+
+ var initialEventCount: Int? {
+ includesEventCount ? 0 : nil
+ }
+
+ func initialCount(for event: CodexHookEvent) -> Int? {
+ events.contains(event) ? 0 : nil
+ }
}
/// daily.jsonl 中的持久化聚合行, 同时兼容保留 ID 和只保留计数两种形态
@@ -422,16 +553,18 @@ nonisolated struct WorkflowDailyAggregate: Codable, Equatable, Identifiable {
let date: String
var sourceGeneration: String?
var sourceIsFresh: Bool
- var eventCount: Int
- var sessionStartCount: Int
- var stopCount: Int
- var preToolUseCount: Int
- var postToolUseCount: Int
- var permissionRequestCount: Int
- var preCompactCount: Int
- var postCompactCount: Int
- var subagentStartCount: Int
- var subagentStopCount: Int
+ var eventCount: Int?
+ var sessionStartCount: Int?
+ var sessionEndCount: Int?
+ var userPromptSubmitCount: Int?
+ var stopCount: Int?
+ var preToolUseCount: Int?
+ var postToolUseCount: Int?
+ var permissionRequestCount: Int?
+ var preCompactCount: Int?
+ var postCompactCount: Int?
+ var subagentStartCount: Int?
+ var subagentStopCount: Int?
var sessionCount: Int?
var turnCount: Int?
var projectCounts: [String: Int]
@@ -443,24 +576,32 @@ nonisolated struct WorkflowDailyAggregate: Codable, Equatable, Identifiable {
date
}
+ /// 增量路径只有在完整 ID 集合仍然存在时才能继续安全去重
+ var supportsIncrementalAggregation: Bool {
+ sessionCount == nil && turnCount == nil
+ }
+
init(
date: String,
sourceGeneration: String? = nil,
- sourceIsFresh: Bool = false
+ sourceIsFresh: Bool = false,
+ hookCountAvailability: WorkflowHookCountAvailability = .all
) {
self.date = date
self.sourceGeneration = sourceGeneration
self.sourceIsFresh = sourceIsFresh
- eventCount = 0
- sessionStartCount = 0
- stopCount = 0
- preToolUseCount = 0
- postToolUseCount = 0
- permissionRequestCount = 0
- preCompactCount = 0
- postCompactCount = 0
- subagentStartCount = 0
- subagentStopCount = 0
+ eventCount = hookCountAvailability.initialEventCount
+ sessionStartCount = hookCountAvailability.initialCount(for: .sessionStart)
+ sessionEndCount = hookCountAvailability.initialCount(for: .sessionEnd)
+ userPromptSubmitCount = hookCountAvailability.initialCount(for: .userPromptSubmit)
+ stopCount = hookCountAvailability.initialCount(for: .stop)
+ preToolUseCount = hookCountAvailability.initialCount(for: .preToolUse)
+ postToolUseCount = hookCountAvailability.initialCount(for: .postToolUse)
+ permissionRequestCount = hookCountAvailability.initialCount(for: .permissionRequest)
+ preCompactCount = hookCountAvailability.initialCount(for: .preCompact)
+ postCompactCount = hookCountAvailability.initialCount(for: .postCompact)
+ subagentStartCount = hookCountAvailability.initialCount(for: .subagentStart)
+ subagentStopCount = hookCountAvailability.initialCount(for: .subagentStop)
sessionCount = nil
turnCount = nil
projectCounts = [:]
@@ -474,16 +615,18 @@ nonisolated struct WorkflowDailyAggregate: Codable, Equatable, Identifiable {
date = try container.decode(String.self, forKey: .date)
sourceGeneration = try container.decodeIfPresent(String.self, forKey: .sourceGeneration)
sourceIsFresh = try container.decodeIfPresent(Bool.self, forKey: .sourceIsFresh) ?? false
- eventCount = try container.decodeIfPresent(Int.self, forKey: .eventCount) ?? 0
- sessionStartCount = try container.decodeIfPresent(Int.self, forKey: .sessionStartCount) ?? 0
- stopCount = try container.decodeIfPresent(Int.self, forKey: .stopCount) ?? 0
- preToolUseCount = try container.decodeIfPresent(Int.self, forKey: .preToolUseCount) ?? 0
- postToolUseCount = try container.decodeIfPresent(Int.self, forKey: .postToolUseCount) ?? 0
- permissionRequestCount = try container.decodeIfPresent(Int.self, forKey: .permissionRequestCount) ?? 0
- preCompactCount = try container.decodeIfPresent(Int.self, forKey: .preCompactCount) ?? 0
- postCompactCount = try container.decodeIfPresent(Int.self, forKey: .postCompactCount) ?? 0
- subagentStartCount = try container.decodeIfPresent(Int.self, forKey: .subagentStartCount) ?? 0
- subagentStopCount = try container.decodeIfPresent(Int.self, forKey: .subagentStopCount) ?? 0
+ eventCount = try container.decodeIfPresent(Int.self, forKey: .eventCount)
+ sessionStartCount = try container.decodeIfPresent(Int.self, forKey: .sessionStartCount)
+ sessionEndCount = try container.decodeIfPresent(Int.self, forKey: .sessionEndCount)
+ userPromptSubmitCount = try container.decodeIfPresent(Int.self, forKey: .userPromptSubmitCount)
+ stopCount = try container.decodeIfPresent(Int.self, forKey: .stopCount)
+ preToolUseCount = try container.decodeIfPresent(Int.self, forKey: .preToolUseCount)
+ postToolUseCount = try container.decodeIfPresent(Int.self, forKey: .postToolUseCount)
+ permissionRequestCount = try container.decodeIfPresent(Int.self, forKey: .permissionRequestCount)
+ preCompactCount = try container.decodeIfPresent(Int.self, forKey: .preCompactCount)
+ postCompactCount = try container.decodeIfPresent(Int.self, forKey: .postCompactCount)
+ subagentStartCount = try container.decodeIfPresent(Int.self, forKey: .subagentStartCount)
+ subagentStopCount = try container.decodeIfPresent(Int.self, forKey: .subagentStopCount)
sessionCount = try container.decodeIfPresent(Int.self, forKey: .sessionCount)
turnCount = try container.decodeIfPresent(Int.self, forKey: .turnCount)
projectCounts = try container.decodeIfPresent([String: Int].self, forKey: .projectCounts) ?? [:]
@@ -492,66 +635,31 @@ nonisolated struct WorkflowDailyAggregate: Codable, Equatable, Identifiable {
turnIds = try container.decodeIfPresent([String].self, forKey: .turnIds)
}
- mutating func record(
- _ event: WorkflowHookEvent,
- keepsIdentifiers: Bool,
- identifierCache: inout WorkflowDailyIdentifierCache
- ) {
- eventCount += 1
-
- switch event.hookEvent {
- case .sessionStart: sessionStartCount += 1
- case .stop: stopCount += 1
- case .preToolUse: preToolUseCount += 1
- case .postToolUse: postToolUseCount += 1
- case .permissionRequest: permissionRequestCount += 1
- case .preCompact: preCompactCount += 1
- case .postCompact: postCompactCount += 1
- case .subagentStart: subagentStartCount += 1
- case .subagentStop: subagentStopCount += 1
- case .userPromptSubmit:
- break
- case .none: break
- }
-
- if keepsIdentifiers {
- if let sessionId = event.sessionId {
- Self.append(sessionId, to: &sessionIds, using: &identifierCache.sessionIds)
- }
-
- if let turnId = event.turnId {
- Self.append(turnId, to: &turnIds, using: &identifierCache.turnIds)
- }
- }
-
- if let projectDisplayName = event.projectDisplayName {
- projectCounts[projectDisplayName, default: 0] += 1
- }
-
- if let modelName = event.modelName {
- modelCounts[modelName, default: 0] += 1
- }
- }
-
- mutating func compactIdentifiersIfNeeded(keepsIdentifiers: Bool) {
- guard !keepsIdentifiers else {
+ mutating func normalizeIdentifierStorage(retainsIdentifiers: Bool) {
+ guard !retainsIdentifiers else {
sessionIds = Self.normalizedIdentifiers(sessionIds)
turnIds = Self.normalizedIdentifiers(turnIds)
return
}
- sessionCount = resolvedSessionCount
- turnCount = resolvedTurnCount
+ sessionCount = WorkflowCountResolution.preferredCount(
+ compactedCount: sessionCount,
+ identifiers: sessionIds
+ ) ?? sessionStartCount
+ turnCount = WorkflowCountResolution.preferredCount(
+ compactedCount: turnCount,
+ identifiers: turnIds
+ ) ?? stopCount
sessionIds = nil
turnIds = nil
}
- /// 只有正数压缩计数或非空 ID 集合是有效去重结果, 否则使用起止事件计数兜底
+ /// 正数压缩计数和非空 ID 集合优先, 明确的 0 在没有 ID 时同样有效
private var resolvedSessionCount: Int {
WorkflowCountResolution.resolvedCount(
compactedCount: sessionCount,
identifiers: sessionIds,
- fallback: sessionStartCount
+ fallback: sessionStartCount ?? 0
)
}
@@ -559,7 +667,7 @@ nonisolated struct WorkflowDailyAggregate: Codable, Equatable, Identifiable {
WorkflowCountResolution.resolvedCount(
compactedCount: turnCount,
identifiers: turnIds,
- fallback: stopCount
+ fallback: stopCount ?? 0
)
}
@@ -568,13 +676,13 @@ nonisolated struct WorkflowDailyAggregate: Codable, Equatable, Identifiable {
startDate: date,
sessionCount: resolvedSessionCount,
turnCount: resolvedTurnCount,
- preToolUseCount: preToolUseCount,
- postToolUseCount: postToolUseCount,
- permissionRequestCount: permissionRequestCount,
- preCompactCount: preCompactCount,
- postCompactCount: postCompactCount,
- subagentStartCount: subagentStartCount,
- subagentStopCount: subagentStopCount,
+ preToolUseCount: preToolUseCount ?? 0,
+ postToolUseCount: postToolUseCount ?? 0,
+ permissionRequestCount: permissionRequestCount ?? 0,
+ preCompactCount: preCompactCount ?? 0,
+ postCompactCount: postCompactCount ?? 0,
+ subagentStartCount: subagentStartCount ?? 0,
+ subagentStopCount: subagentStopCount ?? 0,
modelCounts: modelCounts
)
}
@@ -593,7 +701,9 @@ nonisolated struct WorkflowDailyAggregate: Codable, Equatable, Identifiable {
}
var mutableAggregate = aggregate
- mutableAggregate.compactIdentifiersIfNeeded(keepsIdentifiers: date >= identifierCutoffDate)
+ mutableAggregate.normalizeIdentifierStorage(
+ retainsIdentifiers: date >= identifierCutoffDate
+ )
return mutableAggregate
}
.sorted { $0.date < $1.date }
@@ -606,37 +716,52 @@ nonisolated struct WorkflowDailyAggregate: Codable, Equatable, Identifiable {
}
func jsonLineData() throws -> Data {
- let fields = try [
+ var fields = try [
WorkflowJSON.field("date", date),
WorkflowJSON.field("sourceGeneration", sourceGeneration),
- WorkflowJSON.field("sourceIsFresh", sourceIsFresh),
- WorkflowJSON.field("eventCount", eventCount),
- WorkflowJSON.field("sessionStartCount", sessionStartCount),
- WorkflowJSON.field("stopCount", stopCount),
- WorkflowJSON.field("preToolUseCount", preToolUseCount),
- WorkflowJSON.field("postToolUseCount", postToolUseCount),
- WorkflowJSON.field("permissionRequestCount", permissionRequestCount),
- WorkflowJSON.field("preCompactCount", preCompactCount),
- WorkflowJSON.field("postCompactCount", postCompactCount),
- WorkflowJSON.field("subagentStartCount", subagentStartCount),
- WorkflowJSON.field("subagentStopCount", subagentStopCount),
+ WorkflowJSON.field("sourceIsFresh", sourceIsFresh)
+ ]
+ try fields.append(contentsOf: WorkflowJSON.presentCountFields(hookCountFields))
+ try fields.append(contentsOf: [
WorkflowJSON.field("sessionCount", sessionCount),
WorkflowJSON.field("turnCount", turnCount),
WorkflowJSON.field("projectCounts", projectCounts),
WorkflowJSON.field("modelCounts", modelCounts),
WorkflowJSON.field("sessionIds", sessionIds),
WorkflowJSON.field("turnIds", turnIds)
- ]
+ ])
return WorkflowJSON.lineData(fields)
}
+ var hookCountAvailability: WorkflowHookCountAvailability {
+ WorkflowHookCountAvailability(aggregate: self)
+ }
+
+ func hookCount(for event: CodexHookEvent) -> Int? {
+ switch event {
+ case .sessionStart: sessionStartCount
+ case .sessionEnd: sessionEndCount
+ case .userPromptSubmit: userPromptSubmitCount
+ case .stop: stopCount
+ case .preToolUse: preToolUseCount
+ case .postToolUse: postToolUseCount
+ case .permissionRequest: permissionRequestCount
+ case .preCompact: preCompactCount
+ case .postCompact: postCompactCount
+ case .subagentStart: subagentStartCount
+ case .subagentStop: subagentStopCount
+ }
+ }
+
var syncedAggregate: WorkflowSyncedDailyAggregate {
WorkflowSyncedDailyAggregate(
date: date,
sourceGeneration: sourceGeneration,
eventCount: eventCount,
sessionStartCount: sessionStartCount,
+ sessionEndCount: sessionEndCount,
+ userPromptSubmitCount: userPromptSubmitCount,
stopCount: stopCount,
preToolUseCount: preToolUseCount,
postToolUseCount: postToolUseCount,
@@ -666,19 +791,21 @@ nonisolated struct WorkflowDailyAggregate: Codable, Equatable, Identifiable {
)
}
- private static func append(
- _ identifier: String,
- to identifiers: inout [String]?,
- using identifierSet: inout Set<String>
- ) {
- guard identifierSet.insert(identifier).inserted else {
- return
- }
-
- if identifiers == nil {
- identifiers = []
- }
- identifiers?.append(identifier)
+ private var hookCountFields: [(String, Int?)] {
+ [
+ ("eventCount", eventCount),
+ ("sessionStartCount", sessionStartCount),
+ ("sessionEndCount", sessionEndCount),
+ ("userPromptSubmitCount", userPromptSubmitCount),
+ ("stopCount", stopCount),
+ ("preToolUseCount", preToolUseCount),
+ ("postToolUseCount", postToolUseCount),
+ ("permissionRequestCount", permissionRequestCount),
+ ("preCompactCount", preCompactCount),
+ ("postCompactCount", postCompactCount),
+ ("subagentStartCount", subagentStartCount),
+ ("subagentStopCount", subagentStopCount)
+ ]
}
private static func normalizedIdentifiers(_ identifiers: [String]?) -> [String]? {
@@ -696,6 +823,8 @@ nonisolated struct WorkflowDailyAggregate: Codable, Equatable, Identifiable {
case sourceIsFresh
case eventCount
case sessionStartCount
+ case sessionEndCount
+ case userPromptSubmitCount
case stopCount
case preToolUseCount
case postToolUseCount
@@ -717,20 +846,22 @@ nonisolated struct WorkflowDailyAggregate: Codable, Equatable, Identifiable {
nonisolated struct WorkflowSyncedDailyAggregate: Codable, Equatable, Identifiable {
let date: String
var sourceGeneration: String?
- var eventCount: Int
- var sessionStartCount: Int
- var stopCount: Int
- var preToolUseCount: Int
- var postToolUseCount: Int
- var permissionRequestCount: Int
- var preCompactCount: Int
- var postCompactCount: Int
- var subagentStartCount: Int
- var subagentStopCount: Int
+ var eventCount: Int?
+ var sessionStartCount: Int?
+ var sessionEndCount: Int?
+ var userPromptSubmitCount: Int?
+ var stopCount: Int?
+ var preToolUseCount: Int?
+ var postToolUseCount: Int?
+ var permissionRequestCount: Int?
+ var preCompactCount: Int?
+ var postCompactCount: Int?
+ var subagentStartCount: Int?
+ var subagentStopCount: Int?
var sessionCount: Int?
var turnCount: Int?
var projectCounts: [String: Int]
- var modelCounts: [String: Int]?
+ var modelCounts: [String: Int]
var id: String {
date
@@ -741,46 +872,56 @@ nonisolated struct WorkflowSyncedDailyAggregate: Codable, Equatable, Identifiabl
startDate: date,
sessionCount: WorkflowCountResolution.resolvedCount(
compactedCount: sessionCount,
- fallback: sessionStartCount
+ fallback: sessionStartCount ?? 0
),
turnCount: WorkflowCountResolution.resolvedCount(
compactedCount: turnCount,
- fallback: stopCount
+ fallback: stopCount ?? 0
),
- preToolUseCount: preToolUseCount,
- postToolUseCount: postToolUseCount,
- permissionRequestCount: permissionRequestCount,
- preCompactCount: preCompactCount,
- postCompactCount: postCompactCount,
- subagentStartCount: subagentStartCount,
- subagentStopCount: subagentStopCount,
- modelCounts: modelCounts ?? [:]
+ preToolUseCount: preToolUseCount ?? 0,
+ postToolUseCount: postToolUseCount ?? 0,
+ permissionRequestCount: permissionRequestCount ?? 0,
+ preCompactCount: preCompactCount ?? 0,
+ postCompactCount: postCompactCount ?? 0,
+ subagentStartCount: subagentStartCount ?? 0,
+ subagentStopCount: subagentStopCount ?? 0,
+ modelCounts: modelCounts
)
}
func jsonLineData() throws -> Data {
- let fields = try [
+ var fields = try [
WorkflowJSON.field("date", date),
- WorkflowJSON.field("sourceGeneration", sourceGeneration),
- WorkflowJSON.field("eventCount", eventCount),
- WorkflowJSON.field("sessionStartCount", sessionStartCount),
- WorkflowJSON.field("stopCount", stopCount),
- WorkflowJSON.field("preToolUseCount", preToolUseCount),
- WorkflowJSON.field("postToolUseCount", postToolUseCount),
- WorkflowJSON.field("permissionRequestCount", permissionRequestCount),
- WorkflowJSON.field("preCompactCount", preCompactCount),
- WorkflowJSON.field("postCompactCount", postCompactCount),
- WorkflowJSON.field("subagentStartCount", subagentStartCount),
- WorkflowJSON.field("subagentStopCount", subagentStopCount),
+ WorkflowJSON.field("sourceGeneration", sourceGeneration)
+ ]
+ try fields.append(contentsOf: WorkflowJSON.presentCountFields(hookCountFields))
+ try fields.append(contentsOf: [
WorkflowJSON.field("sessionCount", sessionCount),
WorkflowJSON.field("turnCount", turnCount),
WorkflowJSON.field("projectCounts", projectCounts),
WorkflowJSON.field("modelCounts", modelCounts)
- ]
+ ])
return WorkflowJSON.lineData(fields)
}
+ private var hookCountFields: [(String, Int?)] {
+ [
+ ("eventCount", eventCount),
+ ("sessionStartCount", sessionStartCount),
+ ("sessionEndCount", sessionEndCount),
+ ("userPromptSubmitCount", userPromptSubmitCount),
+ ("stopCount", stopCount),
+ ("preToolUseCount", preToolUseCount),
+ ("postToolUseCount", postToolUseCount),
+ ("permissionRequestCount", permissionRequestCount),
+ ("preCompactCount", preCompactCount),
+ ("postCompactCount", postCompactCount),
+ ("subagentStartCount", subagentStartCount),
+ ("subagentStopCount", subagentStopCount)
+ ]
+ }
+
func hasSameContent(as other: WorkflowSyncedDailyAggregate) -> Bool {
var lhs = self
var rhs = other
@@ -796,6 +937,51 @@ nonisolated struct WorkflowSyncedDailyAggregate: Codable, Equatable, Identifiabl
}
return remote.sourceGeneration == nil && hasSameContent(as: remote)
}
+
+ private enum CodingKeys: String, CodingKey {
+ case date
+ case sourceGeneration
+ case eventCount
+ case sessionStartCount
+ case sessionEndCount
+ case userPromptSubmitCount
+ case stopCount
+ case preToolUseCount
+ case postToolUseCount
+ case permissionRequestCount
+ case preCompactCount
+ case postCompactCount
+ case subagentStartCount
+ case subagentStopCount
+ case sessionCount
+ case turnCount
+ case projectCounts
+ case modelCounts
+ }
+}
+
+extension WorkflowSyncedDailyAggregate {
+ nonisolated init(from decoder: Decoder) throws {
+ let container = try decoder.container(keyedBy: CodingKeys.self)
+ date = try container.decode(String.self, forKey: .date)
+ sourceGeneration = try container.decodeIfPresent(String.self, forKey: .sourceGeneration)
+ eventCount = try container.decodeIfPresent(Int.self, forKey: .eventCount)
+ sessionStartCount = try container.decodeIfPresent(Int.self, forKey: .sessionStartCount)
+ sessionEndCount = try container.decodeIfPresent(Int.self, forKey: .sessionEndCount)
+ userPromptSubmitCount = try container.decodeIfPresent(Int.self, forKey: .userPromptSubmitCount)
+ stopCount = try container.decodeIfPresent(Int.self, forKey: .stopCount)
+ preToolUseCount = try container.decodeIfPresent(Int.self, forKey: .preToolUseCount)
+ postToolUseCount = try container.decodeIfPresent(Int.self, forKey: .postToolUseCount)
+ permissionRequestCount = try container.decodeIfPresent(Int.self, forKey: .permissionRequestCount)
+ preCompactCount = try container.decodeIfPresent(Int.self, forKey: .preCompactCount)
+ postCompactCount = try container.decodeIfPresent(Int.self, forKey: .postCompactCount)
+ subagentStartCount = try container.decodeIfPresent(Int.self, forKey: .subagentStartCount)
+ subagentStopCount = try container.decodeIfPresent(Int.self, forKey: .subagentStopCount)
+ sessionCount = try container.decodeIfPresent(Int.self, forKey: .sessionCount)
+ turnCount = try container.decodeIfPresent(Int.self, forKey: .turnCount)
+ projectCounts = try container.decodeIfPresent([String: Int].self, forKey: .projectCounts) ?? [:]
+ modelCounts = try container.decodeIfPresent([String: Int].self, forKey: .modelCounts) ?? [:]
+ }
}
nonisolated struct WorkflowSyncedDailyRecord: Codable, Equatable, Identifiable {
diff --git a/CodexBar/Resources/Localizable.xcstrings b/CodexBar/Resources/Localizable.xcstrings
index 58dea51..b654428 100644
--- a/CodexBar/Resources/Localizable.xcstrings
+++ b/CodexBar/Resources/Localizable.xcstrings
@@ -306,6 +306,22 @@
}
}
},
+ "Codex" : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Codex"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Codex"
+ }
+ }
+ }
+ },
"Codex app-server 日志" : {
"localizations" : {
"en" : {
@@ -547,7 +563,6 @@
}
},
"codex-cli.version.launch-failed" : {
- "extractionState" : "extracted_with_value",
"localizations" : {
"en" : {
"stringUnit" : {
@@ -564,7 +579,6 @@
}
},
"codex-cli.version.not-found" : {
- "extractionState" : "extracted_with_value",
"localizations" : {
"en" : {
"stringUnit" : {
@@ -581,7 +595,6 @@
}
},
"codex-cli.version.parse-failed" : {
- "extractionState" : "extracted_with_value",
"localizations" : {
"en" : {
"stringUnit" : {
@@ -598,7 +611,6 @@
}
},
"codex-cli.version.read-failed" : {
- "extractionState" : "extracted_with_value",
"localizations" : {
"en" : {
"stringUnit" : {
@@ -615,7 +627,6 @@
}
},
"codex-cli.version.read-timeout" : {
- "extractionState" : "extracted_with_value",
"localizations" : {
"en" : {
"stringUnit" : {
@@ -632,7 +643,6 @@
}
},
"codex-cli.version.unknown" : {
- "extractionState" : "extracted_with_value",
"localizations" : {
"en" : {
"stringUnit" : {
@@ -648,8 +658,39 @@
}
}
},
+ "codex-hook.version.unavailable" : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Enabling CodexBar Hook requires Codex %@ or later"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "启用 CodexBar Hook 需要 Codex %@ 或更高版本"
+ }
+ }
+ }
+ },
+ "codex-hook.version.unsupported" : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Enabling CodexBar Hook requires Codex %@ or later"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "启用 CodexBar Hook 需要 Codex %@ 或更高版本"
+ }
+ }
+ }
+ },
"codex-status.error.connection-closed" : {
- "extractionState" : "extracted_with_value",
"localizations" : {
"en" : {
"stringUnit" : {
@@ -666,7 +707,6 @@
}
},
"codex-status.error.executable-not-found" : {
- "extractionState" : "extracted_with_value",
"localizations" : {
"en" : {
"stringUnit" : {
@@ -683,7 +723,6 @@
}
},
"codex-status.error.invalid-response" : {
- "extractionState" : "extracted_with_value",
"localizations" : {
"en" : {
"stringUnit" : {
@@ -700,7 +739,6 @@
}
},
"codex-status.error.not-logged-in" : {
- "extractionState" : "extracted_with_value",
"localizations" : {
"en" : {
"stringUnit" : {
@@ -717,7 +755,6 @@
}
},
"codex-status.error.server-timeout" : {
- "extractionState" : "extracted_with_value",
"localizations" : {
"en" : {
"stringUnit" : {
@@ -734,7 +771,6 @@
}
},
"codex-status.error.unsupported-method" : {
- "extractionState" : "extracted_with_value",
"localizations" : {
"en" : {
"stringUnit" : {
@@ -927,7 +963,6 @@
}
},
"hotkey.validation.minimum-modifiers" : {
- "extractionState" : "extracted_with_value",
"localizations" : {
"en" : {
"stringUnit" : {
@@ -944,7 +979,6 @@
}
},
"hotkey.validation.system-reserved" : {
- "extractionState" : "extracted_with_value",
"localizations" : {
"en" : {
"stringUnit" : {
@@ -961,7 +995,6 @@
}
},
"keep-alive.duration.hours" : {
- "extractionState" : "extracted_with_value",
"localizations" : {
"en" : {
"stringUnit" : {
@@ -978,7 +1011,6 @@
}
},
"keep-alive.duration.unlimited" : {
- "extractionState" : "extracted_with_value",
"localizations" : {
"en" : {
"stringUnit" : {
@@ -995,7 +1027,6 @@
}
},
"keep-alive.error.connection-failed" : {
- "extractionState" : "extracted_with_value",
"localizations" : {
"en" : {
"stringUnit" : {
@@ -1012,7 +1043,6 @@
}
},
"keep-alive.error.connection-interrupted" : {
- "extractionState" : "extracted_with_value",
"localizations" : {
"en" : {
"stringUnit" : {
@@ -1029,7 +1059,6 @@
}
},
"keep-alive.error.helper-assets-missing" : {
- "extractionState" : "extracted_with_value",
"localizations" : {
"en" : {
"stringUnit" : {
@@ -1046,7 +1075,6 @@
}
},
"keep-alive.error.invalid-helper-interface" : {
- "extractionState" : "extracted_with_value",
"localizations" : {
"en" : {
"stringUnit" : {
@@ -1063,7 +1091,6 @@
}
},
"keep-alive.error.no-response" : {
- "extractionState" : "extracted_with_value",
"localizations" : {
"en" : {
"stringUnit" : {
@@ -1080,7 +1107,6 @@
}
},
"keep-alive.error.prevent-idle-sleep-failed" : {
- "extractionState" : "extracted_with_value",
"localizations" : {
"en" : {
"stringUnit" : {
@@ -1097,7 +1123,6 @@
}
},
"keep-alive.error.registration-failed" : {
- "extractionState" : "extracted_with_value",
"localizations" : {
"en" : {
"stringUnit" : {
@@ -1114,7 +1139,6 @@
}
},
"keep-alive.error.request-system-sleep-failed" : {
- "extractionState" : "extracted_with_value",
"localizations" : {
"en" : {
"stringUnit" : {
@@ -1131,7 +1155,6 @@
}
},
"keep-alive.error.restore-idle-sleep-failed" : {
- "extractionState" : "extracted_with_value",
"localizations" : {
"en" : {
"stringUnit" : {
@@ -1148,7 +1171,6 @@
}
},
"keep-alive.error.retry-limit-reached" : {
- "extractionState" : "extracted_with_value",
"localizations" : {
"en" : {
"stringUnit" : {
@@ -1165,7 +1187,6 @@
}
},
"keep-alive.error.toggle-sleep-failed" : {
- "extractionState" : "extracted_with_value",
"localizations" : {
"en" : {
"stringUnit" : {
@@ -1182,7 +1203,6 @@
}
},
"keep-alive.error.update-failed" : {
- "extractionState" : "extracted_with_value",
"localizations" : {
"en" : {
"stringUnit" : {
@@ -1199,7 +1219,6 @@
}
},
"keep-alive.low-battery.off" : {
- "extractionState" : "extracted_with_value",
"localizations" : {
"en" : {
"stringUnit" : {
@@ -1216,7 +1235,6 @@
}
},
"menu-bar-quota.selection.off" : {
- "extractionState" : "extracted_with_value",
"localizations" : {
"en" : {
"stringUnit" : {
@@ -1233,7 +1251,6 @@
}
},
"menu-bar-quota.selection.primary" : {
- "extractionState" : "extracted_with_value",
"localizations" : {
"en" : {
"stringUnit" : {
@@ -1250,7 +1267,6 @@
}
},
"menu-bar-quota.selection.secondary" : {
- "extractionState" : "extracted_with_value",
"localizations" : {
"en" : {
"stringUnit" : {
@@ -1267,7 +1283,6 @@
}
},
"notification.credit-expiry.body" : {
- "extractionState" : "extracted_with_value",
"localizations" : {
"en" : {
"stringUnit" : {
@@ -1284,7 +1299,6 @@
}
},
"notification.credit-expiry.title" : {
- "extractionState" : "extracted_with_value",
"localizations" : {
"en" : {
"stringUnit" : {
@@ -1301,7 +1315,6 @@
}
},
"notification.keep-alive-ended.duration-limit" : {
- "extractionState" : "extracted_with_value",
"localizations" : {
"en" : {
"stringUnit" : {
@@ -1318,7 +1331,6 @@
}
},
"notification.keep-alive-ended.low-battery" : {
- "extractionState" : "extracted_with_value",
"localizations" : {
"en" : {
"stringUnit" : {
@@ -1335,7 +1347,6 @@
}
},
"notification.keep-alive-ended.title" : {
- "extractionState" : "extracted_with_value",
"localizations" : {
"en" : {
"stringUnit" : {
@@ -1352,7 +1363,6 @@
}
},
"notification.low-quota.body" : {
- "extractionState" : "extracted_with_value",
"localizations" : {
"en" : {
"stringUnit" : {
@@ -1369,7 +1379,6 @@
}
},
"notification.low-quota.title" : {
- "extractionState" : "extracted_with_value",
"localizations" : {
"en" : {
"stringUnit" : {
@@ -1386,7 +1395,6 @@
}
},
"notification.quota-reset.body" : {
- "extractionState" : "extracted_with_value",
"localizations" : {
"en" : {
"stringUnit" : {
@@ -1403,7 +1411,6 @@
}
},
"notification.quota-reset.title" : {
- "extractionState" : "extracted_with_value",
"localizations" : {
"en" : {
"stringUnit" : {
@@ -1420,7 +1427,6 @@
}
},
"notification.sound.default" : {
- "extractionState" : "extracted_with_value",
"localizations" : {
"en" : {
"stringUnit" : {
@@ -1437,7 +1443,6 @@
}
},
"notification.sound.silent" : {
- "extractionState" : "extracted_with_value",
"localizations" : {
"en" : {
"stringUnit" : {
@@ -1454,7 +1459,6 @@
}
},
"notification.task-completed.body.codex" : {
- "extractionState" : "extracted_with_value",
"localizations" : {
"en" : {
"stringUnit" : {
@@ -1471,7 +1475,6 @@
}
},
"notification.task-completed.body.project" : {
- "extractionState" : "extracted_with_value",
"localizations" : {
"en" : {
"stringUnit" : {
@@ -1488,7 +1491,6 @@
}
},
"notification.task-completed.title" : {
- "extractionState" : "extracted_with_value",
"localizations" : {
"en" : {
"stringUnit" : {
@@ -1505,7 +1507,6 @@
}
},
"notification.task-waiting.body.codex" : {
- "extractionState" : "extracted_with_value",
"localizations" : {
"en" : {
"stringUnit" : {
@@ -1522,7 +1523,6 @@
}
},
"notification.task-waiting.body.codex-tool" : {
- "extractionState" : "extracted_with_value",
"localizations" : {
"en" : {
"stringUnit" : {
@@ -1539,7 +1539,6 @@
}
},
"notification.task-waiting.body.project" : {
- "extractionState" : "extracted_with_value",
"localizations" : {
"en" : {
"stringUnit" : {
@@ -1556,7 +1555,6 @@
}
},
"notification.task-waiting.body.project-tool" : {
- "extractionState" : "extracted_with_value",
"localizations" : {
"en" : {
"stringUnit" : {
@@ -1573,7 +1571,6 @@
}
},
"notification.task-waiting.title" : {
- "extractionState" : "extracted_with_value",
"localizations" : {
"en" : {
"stringUnit" : {
@@ -1590,7 +1587,6 @@
}
},
"quota.window.fallback" : {
- "extractionState" : "extracted_with_value",
"localizations" : {
"en" : {
"stringUnit" : {
@@ -1607,7 +1603,6 @@
}
},
"request-log.error.exit-timeout-killed" : {
- "extractionState" : "extracted_with_value",
"localizations" : {
"en" : {
"stringUnit" : {
@@ -1624,7 +1619,6 @@
}
},
"request-log.error.exit-timeout-running" : {
- "extractionState" : "extracted_with_value",
"localizations" : {
"en" : {
"stringUnit" : {
@@ -1641,7 +1635,6 @@
}
},
"request-log.error.initialization-failed" : {
- "extractionState" : "extracted_with_value",
"localizations" : {
"en" : {
"stringUnit" : {
@@ -1658,7 +1651,6 @@
}
},
"request-log.error.launch-failed" : {
- "extractionState" : "extracted_with_value",
"localizations" : {
"en" : {
"stringUnit" : {
@@ -1675,7 +1667,6 @@
}
},
"request-log.error.response-connection-closed" : {
- "extractionState" : "extracted_with_value",
"localizations" : {
"en" : {
"stringUnit" : {
@@ -1692,7 +1683,6 @@
}
},
"request-log.error.response-timeout" : {
- "extractionState" : "extracted_with_value",
"localizations" : {
"en" : {
"stringUnit" : {
@@ -1709,7 +1699,6 @@
}
},
"request-log.error.write-connection-closed" : {
- "extractionState" : "extracted_with_value",
"localizations" : {
"en" : {
"stringUnit" : {
@@ -1726,7 +1715,6 @@
}
},
"updater.status.check-failed" : {
- "extractionState" : "extracted_with_value",
"localizations" : {
"en" : {
"stringUnit" : {
@@ -1743,7 +1731,6 @@
}
},
"updater.status.checking" : {
- "extractionState" : "extracted_with_value",
"localizations" : {
"en" : {
"stringUnit" : {
@@ -1760,7 +1747,6 @@
}
},
"updater.status.missing-configuration" : {
- "extractionState" : "extracted_with_value",
"localizations" : {
"en" : {
"stringUnit" : {
@@ -1777,7 +1763,6 @@
}
},
"updater.status.up-to-date" : {
- "extractionState" : "extracted_with_value",
"localizations" : {
"en" : {
"stringUnit" : {
@@ -1794,7 +1779,6 @@
}
},
"updater.status.update-available" : {
- "extractionState" : "extracted_with_value",
"localizations" : {
"en" : {
"stringUnit" : {
@@ -1811,7 +1795,6 @@
}
},
"workflow.metric.tool-calls" : {
- "extractionState" : "extracted_with_value",
"localizations" : {
"en" : {
"stringUnit" : {
@@ -1828,7 +1811,6 @@
}
},
"workflow.rebuild.error.source-changed" : {
- "extractionState" : "extracted_with_value",
"localizations" : {
"en" : {
"stringUnit" : {
@@ -1845,7 +1827,6 @@
}
},
"workflow.rebuild.error.source-unavailable" : {
- "extractionState" : "extracted_with_value",
"localizations" : {
"en" : {
"stringUnit" : {
@@ -1862,7 +1843,6 @@
}
},
"workflow.rebuild.summary.sync-replacement-marking-failed" : {
- "extractionState" : "extracted_with_value",
"localizations" : {
"en" : {
"stringUnit" : {
@@ -2422,22 +2402,6 @@
}
}
},
- "初始化失败" : {
- "localizations" : {
- "en" : {
- "stringUnit" : {
- "state" : "translated",
- "value" : "Initialization failed"
- }
- },
- "zh-Hans" : {
- "stringUnit" : {
- "state" : "translated",
- "value" : "初始化失败"
- }
- }
- }
- },
"单日峰值" : {
"localizations" : {
"en" : {
@@ -4344,4 +4308,4 @@
}
},
"version" : "1.0"
-}
+}
\ No newline at end of file
diff --git a/CodexBar/Services/CodexCLI/CodexCLIVersionService.swift b/CodexBar/Services/CodexCLI/CodexCLIVersionService.swift
index 55bd880..a86e473 100644
--- a/CodexBar/Services/CodexCLI/CodexCLIVersionService.swift
+++ b/CodexBar/Services/CodexCLI/CodexCLIVersionService.swift
@@ -360,6 +360,105 @@ nonisolated enum CodexCLIVersionReader {
.first { $0.first?.isNumber == true }
.map(String.init) ?? output
}
+
+ /// 返回 nil 表示任一版本不是可识别的语义版本
+ static func isVersion(_ version: String, atLeast minimumVersion: String) -> Bool? {
+ guard let parsedVersion = SemanticVersion(version),
+ let parsedMinimumVersion = SemanticVersion(minimumVersion) else {
+ return nil
+ }
+
+ return parsedVersion >= parsedMinimumVersion
+ }
+
+ private struct SemanticVersion: Comparable {
+ let core: [Int]
+ let prerelease: [PrereleaseIdentifier]?
+
+ init?(_ rawValue: String) {
+ let displayVersion = CodexCLIVersionReader.displayVersion(from: rawValue)
+ let versionWithoutBuild = displayVersion.split(
+ separator: "+",
+ maxSplits: 1,
+ omittingEmptySubsequences: false
+ )[0]
+ let versionParts = versionWithoutBuild.split(
+ separator: "-",
+ maxSplits: 1,
+ omittingEmptySubsequences: false
+ )
+ let coreParts = versionParts[0].split(
+ separator: ".",
+ omittingEmptySubsequences: false
+ )
+ guard coreParts.count == 3 else {
+ return nil
+ }
+
+ let core = coreParts.compactMap { Int($0) }
+ guard core.count == coreParts.count else {
+ return nil
+ }
+ self.core = core
+
+ guard versionParts.count == 2 else {
+ prerelease = nil
+ return
+ }
+
+ let identifiers = versionParts[1].split(
+ separator: ".",
+ omittingEmptySubsequences: false
+ )
+ guard !identifiers.isEmpty, identifiers.allSatisfy({ !$0.isEmpty }) else {
+ return nil
+ }
+ prerelease = identifiers.map(PrereleaseIdentifier.init)
+ }
+
+ static func < (lhs: Self, rhs: Self) -> Bool {
+ if lhs.core != rhs.core {
+ return lhs.core.lexicographicallyPrecedes(rhs.core)
+ }
+
+ switch (lhs.prerelease, rhs.prerelease) {
+ case (nil, nil):
+ return false
+ case (nil, _?):
+ return false
+ case (_?, nil):
+ return true
+ case let (lhsIdentifiers?, rhsIdentifiers?):
+ return lhsIdentifiers.lexicographicallyPrecedes(rhsIdentifiers)
+ }
+ }
+ }
+
+ private enum PrereleaseIdentifier: Comparable {
+ case numeric(Int)
+ case text(String)
+
+ init(_ value: Substring) {
+ if let number = Int(value) {
+ self = .numeric(number)
+ } else {
+ self = .text(String(value))
+ }
+ }
+
+ static func < (lhs: Self, rhs: Self) -> Bool {
+ switch (lhs, rhs) {
+ case let (.numeric(lhsValue), .numeric(rhsValue)):
+ lhsValue < rhsValue
+ case (.numeric, .text):
+ true
+ case (.text, .numeric):
+ false
+ case let (.text(lhsValue), .text(rhsValue)):
+ lhsValue < rhsValue
+ }
+ }
+ }
}
/// 设置页持有的版本检测状态, 负责节流和丢弃过期刷新结果
diff --git a/CodexBar/Services/CodexStatus/CodexStatusService.swift b/CodexBar/Services/CodexStatus/CodexStatusService.swift
index 22f6c9b..48bdc99 100644
--- a/CodexBar/Services/CodexStatus/CodexStatusService.swift
+++ b/CodexBar/Services/CodexStatus/CodexStatusService.swift
@@ -161,6 +161,11 @@ actor CodexStatusService {
return connection.commandInfo
}
+ /// 需要以实际运行版本做能力检查时建立或复用连接
+ func readyConnectionInfo() throws -> CodexCLIConnectionInfo {
+ try readyConnection().commandInfo
+ }
+
func readCodexConfig() async throws -> CodexConfigReadResponse {
let connection = try readyConnection()
return try connection.session.request(
diff --git a/CodexBar/Services/Settings/CodexHookSettings.swift b/CodexBar/Services/Settings/CodexHookSettings.swift
index f45a0f0..44bbedc 100644
--- a/CodexBar/Services/Settings/CodexHookSettings.swift
+++ b/CodexBar/Services/Settings/CodexHookSettings.swift
@@ -5,6 +5,8 @@ import os
/// 设置页的 Codex Hook 开关状态机, 同时管理 hooks.json 和 Codex 信任状态
@MainActor
final class CodexHookSettings: ObservableObject {
+ static let minimumSupportedCodexVersion = "0.145.0"
+
@Published private(set) var isEnabled = false
@Published private(set) var isUpdating = false
/// 最近一次校验的明确结论: Codex 会不会真的执行 CodexBar 的 Hook
@@ -104,6 +106,8 @@ final class CodexHookSettings: ObservableObject {
private func applyEnabled(_ enabled: Bool, generation: Int) async {
do {
if enabled {
+ try await ensureCodexHookVersionSupported()
+ try ensureCurrentUpdate(generation)
try await ensureCodexHooksGloballyEnabled()
try ensureCurrentUpdate(generation)
}
@@ -132,6 +136,9 @@ final class CodexHookSettings: ObservableObject {
private func verifyInstalledHooksWithAppServer(generation: Int) async {
do {
+ try await ensureCodexHookVersionSupported()
+ try ensureCurrentUpdate(generation)
+
// 全局开关排在 hooks/list 之前: 它一关, 列表里必然找不到我们的 handler,
// 那时报"已不完整"会把用户引去翻本来就完好的 hooks.json
let globallyDisabled = try await readGlobalHookDisabled()
@@ -259,7 +266,6 @@ private extension CodexHookSettings {
static let hookCommandKey = "command"
static let hookTimeoutKey = "timeout"
static let hookCommandType = "command"
- static let hookTimeout = WorkflowHookEventRecorder.hookTimeoutSeconds
static let configMergeStrategyReplace = "replace"
static let configMergeStrategyUpsert = "upsert"
static let hookTrustStateKeyPath = "hooks.state"
@@ -288,6 +294,8 @@ private extension CodexHookSettings {
enum HookConfigError: LocalizedError {
case invalidFormat
case hooksGloballyDisabled
+ case codexVersionUnavailable(minimum: String)
+ case unsupportedCodexVersion(minimum: String)
case hookValidationFailed(String)
var errorDescription: String? {
@@ -296,16 +304,28 @@ private extension CodexHookSettings {
String(localized: "hooks.json 文件格式错误")
case .hooksGloballyDisabled:
String(localized: "Codex 配置已禁用 Hook")
+ case let .codexVersionUnavailable(minimum):
+ String(
+ localized: "codex-hook.version.unavailable",
+ defaultValue: "启用 CodexBar Hook 需要 Codex \(minimum) 或更高版本"
+ )
+ case let .unsupportedCodexVersion(minimum):
+ String(
+ localized: "codex-hook.version.unsupported",
+ defaultValue: "启用 CodexBar Hook 需要 \(minimum) 或更高版本"
+ )
case let .hookValidationFailed(message):
message
}
}
var isPreflightFailure: Bool {
- if case .hooksGloballyDisabled = self {
- return true
+ switch self {
+ case .hooksGloballyDisabled, .codexVersionUnavailable, .unsupportedCodexVersion:
+ true
+ case .invalidFormat, .hookValidationFailed:
+ false
}
- return false
}
}
@@ -336,6 +356,27 @@ private extension CodexHookSettings {
}
}
+ /// 检查实际用于 hooks/list 的 app-server 握手版本
+ /// 不能只看磁盘版本, 否则升级后尚未重连的旧进程会被误判为可用
+ func ensureCodexHookVersionSupported() async throws {
+ let minimumVersion = Self.minimumSupportedCodexVersion
+ let connectionInfo = try await codexStatusService.readyConnectionInfo()
+ guard let currentVersion = connectionInfo.version,
+ let isSupported = CodexCLIVersionReader.isVersion(
+ currentVersion,
+ atLeast: minimumVersion
+ ) else {
+ throw HookConfigError.codexVersionUnavailable(minimum: minimumVersion)
+ }
+
+ guard isSupported else {
+ AppLog.hooks.notice(
+ "Hook 版本不支持: current=\(currentVersion, privacy: .public); minimum=\(minimumVersion, privacy: .public)"
+ )
+ throw HookConfigError.unsupportedCodexVersion(minimum: minimumVersion)
+ }
+ }
+
func validateInstalledHooksWithAppServer() async throws {
var response = try await codexStatusService.listCodexHooks(cwds: [hooksListWorkingDirectory])
// 只信任 command/sourcePath/event 都匹配当前 CodexBar 的 Hook
@@ -549,7 +590,7 @@ private extension CodexHookSettings {
for event in CodexHookEvent.allCases {
var groups = try eventGroups(named: event.configName, from: hooks)
groups.append([
- hooksKey: [codexBarHookHandler(executablePath: executablePath)]
+ hooksKey: [codexBarHookHandler(for: event, executablePath: executablePath)]
])
hooks[event.configName] = groups
}
@@ -841,11 +882,14 @@ private extension CodexHookSettings {
return command
}
- static func codexBarHookHandler(executablePath: String) -> JSONObject {
+ static func codexBarHookHandler(
+ for event: CodexHookEvent,
+ executablePath: String
+ ) -> JSONObject {
[
hookTypeKey: hookCommandType,
hookCommandKey: hookCommand(executablePath: executablePath),
- hookTimeoutKey: hookTimeout
+ hookTimeoutKey: WorkflowHookEventRecorder.hookTimeoutSeconds(for: event)
]
}
diff --git a/CodexBar/Services/Workflow/CodexActivityMonitor.swift b/CodexBar/Services/Workflow/CodexActivityMonitor.swift
index 9c3c166..d945608 100644
--- a/CodexBar/Services/Workflow/CodexActivityMonitor.swift
+++ b/CodexBar/Services/Workflow/CodexActivityMonitor.swift
@@ -46,10 +46,11 @@ final class CodexActivityMonitor: ObservableObject {
}
isStarted = true
- codexHookSettings.$isEnabled
+ Publishers.CombineLatest(codexHookSettings.$isEnabled, codexHookSettings.$isVerified)
+ .map { $0 && $1 }
.removeDuplicates()
- .sink { [weak self] isEnabled in
- self?.setMonitoringEnabled(isEnabled)
+ .sink { [weak self] isOperable in
+ self?.setMonitoringEnabled(isOperable)
}
.store(in: &cancellables)
@@ -82,9 +83,9 @@ final class CodexActivityMonitor: ObservableObject {
stopReaderAndClearState()
}
- private func setMonitoringEnabled(_ enabled: Bool) {
- guard enabled else {
- AppLog.activity.notice("任务监控已停止: reason=hookDisabled")
+ private func setMonitoringEnabled(_ isOperable: Bool) {
+ guard isOperable else {
+ AppLog.activity.notice("任务监控已停止: reason=hookInoperable")
stopReaderAndClearState()
return
}
@@ -93,7 +94,7 @@ final class CodexActivityMonitor: ObservableObject {
return
}
- AppLog.activity.notice("任务监控已启动: reason=hookEnabled")
+ AppLog.activity.notice("任务监控已启动: reason=hookOperable")
tailReaderGeneration &+= 1
let generation = tailReaderGeneration
@@ -412,6 +413,8 @@ final class CodexActivityMonitor: ObservableObject {
return waitForApproval(from: event)
case .stop:
return completeTask(from: event)
+ case .sessionEnd:
+ terminateSession(from: event)
case .sessionStart, .none:
break
}
@@ -676,6 +679,38 @@ final class CodexActivityMonitor: ObservableObject {
return .completed(completion)
}
+ /// SessionEnd 没有 turn_id, 以 session 为边界把活跃任务移入终态确认窗口
+ /// 任务会立即退出活跃列表, rollout 仍有 5 秒补回准确的完成或终止分类
+ private func terminateSession(from event: WorkflowHookEvent) {
+ guard let sessionId = event.sessionId else {
+ return
+ }
+
+ let deadline = Date().addingTimeInterval(Self.supersededTerminalGracePeriod)
+ let matchingPendingTasks = pendingTerminalTasks.filter { key, pending in
+ key.sessionId == sessionId && pending.task.lastActivityAt <= event.timestamp
+ }
+ for (key, pending) in matchingPendingTasks {
+ pendingTerminalTasks[key] = PendingTerminalTask(
+ task: pending.task,
+ supersededAt: max(pending.supersededAt, event.timestamp),
+ deadline: min(pending.deadline, deadline)
+ )
+ }
+
+ let matchingActiveTasks = tasks.filter { key, task in
+ key.sessionId == sessionId && task.lastActivityAt <= event.timestamp
+ }
+ for (key, task) in matchingActiveTasks {
+ tasks.removeValue(forKey: key)
+ pendingTerminalTasks[key] = PendingTerminalTask(
+ task: task,
+ supersededAt: event.timestamp,
+ deadline: deadline
+ )
+ }
+ }
+
/// 精确 turn 失败后回退同 session 最近活动, 再回退同项目匿名任务
private func matchingTaskKey(for event: WorkflowHookEvent) -> CodexActivityTaskKey? {
let exactKey = CodexActivityTaskKey(event: event)
diff --git a/CodexBar/Services/Workflow/WorkflowHookEventRecorder.swift b/CodexBar/Services/Workflow/WorkflowHookEventRecorder.swift
index b92fb11..0c23aab 100644
--- a/CodexBar/Services/Workflow/WorkflowHookEventRecorder.swift
+++ b/CodexBar/Services/Workflow/WorkflowHookEventRecorder.swift
@@ -5,12 +5,14 @@ import Foundation
nonisolated enum WorkflowHookEventRecorder {
static let hookArgument = "--hook-event"
- /// 写进 hooks.json 的 handler 超时, 超时后 Codex 会杀掉本子进程
- /// 定义在这里而不是 CodexHookSettings: 需要据此推算下面的等锁预算, 两者必须一起改
- static let hookTimeoutSeconds = 5
+ /// SessionEnd 在 Codex 中最多允许 3 秒, 其他事件沿用 5 秒
+ /// 超时定义在这里而不是 CodexHookSettings: 写配置与下面的等锁预算必须同源
+ private static let defaultHookTimeoutSeconds = 5
+ private static let sessionEndHookTimeoutSeconds = 3
- /// 留出余量在被 Codex 杀掉之前主动收工: 被杀可能发生在写入中途并留下半截坏行
- private static let lockWaitLimitSeconds = Double(hookTimeoutSeconds) - 2
+ static func hookTimeoutSeconds(for event: CodexHookEvent) -> Int {
+ event == .sessionEnd ? sessionEndHookTimeoutSeconds : defaultHookTimeoutSeconds
+ }
static func handleIfRequested() -> Bool {
guard CommandLine.arguments.contains(hookArgument) else {
@@ -31,6 +33,7 @@ nonisolated enum WorkflowHookEventRecorder {
}
private static func record(payload: WorkflowHookPayload, eventName: String) throws {
+ let hookEvent = CodexHookEvent(eventName: eventName)
let timestamp = payload.date(for: "timestamp") ?? Date()
let cwd = payload.string(for: "cwd") ?? FileManager.default.currentDirectoryPath
let tool = payload.string(for: "tool_name")
@@ -41,7 +44,7 @@ nonisolated enum WorkflowHookEventRecorder {
let agentId = payload.string(for: "agent_id")
let turnContext = readTurnContext(
from: payload,
- eventName: eventName,
+ hookEvent: hookEvent,
turnId: turnId
)
let event = WorkflowHookEvent(
@@ -58,15 +61,18 @@ nonisolated enum WorkflowHookEventRecorder {
agentId: agentId
)
- try recordWorkflowTransaction(event: event)
+ try recordWorkflowTransaction(
+ event: event,
+ lockWaitLimitSeconds: lockWaitLimitSeconds(for: hookEvent)
+ )
}
private static func readTurnContext(
from payload: WorkflowHookPayload,
- eventName: String,
+ hookEvent: CodexHookEvent?,
turnId: String?
) -> WorkflowTurnContext? {
- guard let hookEvent = CodexHookEvent(eventName: eventName),
+ guard let hookEvent,
hookEvent == .userPromptSubmit || hookEvent == .permissionRequest,
let turnId,
let transcriptPath = payload.string(for: "transcript_path") else {
@@ -78,7 +84,16 @@ nonisolated enum WorkflowHookEventRecorder {
)
}
- private static func recordWorkflowTransaction(event: WorkflowHookEvent) throws {
+ /// 留出 2 秒在 Codex 杀掉子进程前主动收工, 避免写入中途留下半截坏行
+ private static func lockWaitLimitSeconds(for event: CodexHookEvent?) -> TimeInterval {
+ let timeout = event.map(hookTimeoutSeconds(for:)) ?? defaultHookTimeoutSeconds
+ return max(0, Double(timeout) - 2)
+ }
+
+ private static func recordWorkflowTransaction(
+ event: WorkflowHookEvent,
+ lockWaitLimitSeconds: TimeInterval
+ ) throws {
try WorkflowStorage.withExclusiveLock(waitLimitSeconds: lockWaitLimitSeconds) {
let dateKey = WorkflowStorage.dateKey(for: event.timestamp)
let eventLogURL = WorkflowStorage.eventLogURL(for: dateKey)
diff --git a/CodexBar/Services/Workflow/WorkflowService.swift b/CodexBar/Services/Workflow/WorkflowService.swift
index 5a83ed7..d53fe3d 100644
--- a/CodexBar/Services/Workflow/WorkflowService.swift
+++ b/CodexBar/Services/Workflow/WorkflowService.swift
@@ -157,7 +157,7 @@ actor WorkflowService {
)
let summary = await WorkflowDataRebuildSummary(
rebuiltDateCount: rebuildResults.count,
- eventCount: rebuildResults.reduce(0) { $0 + $1.aggregate.eventCount },
+ eventCount: rebuildResults.reduce(0) { $0 + ($1.aggregate.eventCount ?? 0) },
corruptLineCount: rebuildResults.reduce(0) { $0 + $1.corrupt },
isSyncReplacementPending: syncService.hasPendingReplacement(for: normalizedDateKeys),
failedDateKeys: failedDateKeys,
@@ -186,8 +186,14 @@ actor WorkflowService {
// MARK: - 重建与维护调度
private func rebuildLocalData(for dateKey: String) throws -> WorkflowMaintenanceResult {
- let task = try prepareRebuildTask(for: dateKey)
var aggregates = loadDailyAggregates() ?? []
+ let hookCountAvailability = aggregates
+ .first(where: { $0.date == dateKey })?
+ .hookCountAvailability ?? .all
+ let task = try prepareRebuildTask(
+ for: dateKey,
+ hookCountAvailability: hookCountAvailability
+ )
do {
let result = try buildDailyAggregate(for: task)
@@ -202,7 +208,10 @@ actor WorkflowService {
}
}
- private func prepareRebuildTask(for dateKey: String) throws -> WorkflowMaintenanceTask {
+ private func prepareRebuildTask(
+ for dateKey: String,
+ hookCountAvailability: WorkflowHookCountAvailability
+ ) throws -> WorkflowMaintenanceTask {
let retentionCutoffKey = WorkflowStorage.dateKey(for: WorkflowStorage.retentionCutoffDate())
guard WorkflowStorage.isValidDateKey(dateKey), dateKey >= retentionCutoffKey else {
throw WorkflowDataRebuildError.sourceUnavailable
@@ -225,7 +234,12 @@ actor WorkflowService {
guard let day = state.days[dateKey] else {
throw WorkflowDataRebuildError.sourceUnavailable
}
- return dirtyTask(for: dateKey, day: day, size: stat.size)
+ return dirtyTask(
+ for: dateKey,
+ day: day,
+ size: stat.size,
+ hookCountAvailability: hookCountAvailability
+ )
}
}
@@ -256,9 +270,9 @@ actor WorkflowService {
do {
let tasks = try prepareMaintenanceTasks()
stage = .write
- let didWriteDailyLog = perform(tasks, counts: &counts)
- // 每次落盘前都已整体归一化, 写入过就不必再做一轮全量解码比对
- if !didWriteDailyLog {
+ let didCommitDailyLog = perform(tasks, counts: &counts)
+ // 成功提交前已整体归一化, 没有完整提交时再做一次稳态检查
+ if !didCommitDailyLog {
try normalizeDailyAggregatesIfNeeded()
}
stage = .prune
@@ -282,7 +296,8 @@ actor WorkflowService {
return counts
}
- /// 返回是否写入过 daily.jsonl; 批次内共享同一份内存聚合, 避免每个任务重新读盘
+ /// 返回是否至少完整提交一个聚合与维护状态
+ /// 批次内共享同一份内存聚合, 避免每个任务重新读盘
private func perform(
_ tasks: [WorkflowMaintenanceTask],
counts: inout WorkflowMaintenanceCounts
@@ -299,16 +314,16 @@ actor WorkflowService {
: oldestDateKey + ".." + newestDateKey
var aggregates = loadDailyAggregates() ?? []
- var didWrite = false
+ var didCommit = false
for task in tasks {
do {
let result = try buildDailyAggregate(for: task)
if try commit(result, aggregates: &aggregates) {
- didWrite = true
+ didCommit = true
counts.written += 1
// 记本轮新摄入的量; 累加 eventCount 会变成当日总数, Hook 停写也看不出来
// dirty 任务没有 base, 差值即整天重算的量, 与"这轮处理了多少"仍然一致
- counts.events += result.aggregate.eventCount - (task.baseAggregate?.eventCount ?? 0)
+ counts.events += (result.aggregate.eventCount ?? 0) - task.baseEventCount
} else {
counts.skipped += 1
}
@@ -321,7 +336,7 @@ actor WorkflowService {
}
}
- return didWrite
+ return didCommit
}
private func prepareMaintenanceTasks() throws -> [WorkflowMaintenanceTask] {
@@ -366,9 +381,9 @@ actor WorkflowService {
) -> Bool {
var changed = false
- if state.schema != WorkflowMaintenanceState.currentSchema {
+ if state.schema != WorkflowMaintenanceState.currentAggregationSchema {
changed = state.markDirty(contentsOf: eventDateKeys) || changed
- state.schema = WorkflowMaintenanceState.currentSchema
+ state.schema = WorkflowMaintenanceState.currentAggregationSchema
changed = true
}
@@ -471,7 +486,12 @@ actor WorkflowService {
guard let day = state.days[dateKey] else {
return nil
}
- return dirtyTask(for: dateKey, day: day)
+ return dirtyTask(
+ for: dateKey,
+ day: day,
+ hookCountAvailability: dailyByDate[dateKey]?
+ .hookCountAvailability ?? .all
+ )
}
for dateKey in state.pending where !dirty.contains(dateKey) {
@@ -483,11 +503,33 @@ actor WorkflowService {
continue
}
- guard let baseAggregate = dailyByDate[dateKey],
+ let existingAggregate = dailyByDate[dateKey]
+ guard let baseAggregate = existingAggregate,
baseAggregate.sourceGeneration == day.sourceGeneration else {
state.markDirty(dateKey)
changedState = true
- tasks.append(dirtyTask(for: dateKey, day: day, size: size))
+ tasks.append(dirtyTask(
+ for: dateKey,
+ day: day,
+ size: size,
+ hookCountAvailability: existingAggregate?
+ .hookCountAvailability ?? .all
+ ))
+ continue
+ }
+
+ // ID 已压缩的聚合无法判断追加事件是否属于已有 session 或 turn
+ // 任何不能证明与全量结果等价的增量任务都降级为完整重建
+ guard retainsIdentifiers(for: dateKey),
+ baseAggregate.supportsIncrementalAggregation else {
+ state.markDirty(dateKey)
+ changedState = true
+ tasks.append(dirtyTask(
+ for: dateKey,
+ day: day,
+ size: size,
+ hookCountAvailability: baseAggregate.hookCountAvailability
+ ))
continue
}
@@ -507,14 +549,15 @@ actor WorkflowService {
private func dirtyTask(
for dateKey: String,
day: WorkflowDayMaintenanceState,
- size: UInt64? = nil
+ size: UInt64? = nil,
+ hookCountAvailability: WorkflowHookCountAvailability = .all
) -> WorkflowMaintenanceTask {
let stat = WorkflowStorage.fileStat(at: eventLogURL(for: dateKey))
return WorkflowMaintenanceTask(
dateKey: dateKey,
startOffset: 0,
size: size ?? stat?.size ?? 0,
- baseAggregate: nil,
+ mode: .rebuild(hookCountAvailability),
existingCorrupt: 0,
sourceGeneration: day.sourceGeneration,
sourceIsFresh: day.sourceIsFresh,
@@ -532,7 +575,7 @@ actor WorkflowService {
dateKey: dateKey,
startOffset: day.offset,
size: size,
- baseAggregate: baseAggregate,
+ mode: .append(baseAggregate),
existingCorrupt: day.corrupt,
sourceGeneration: day.sourceGeneration,
sourceIsFresh: day.sourceIsFresh,
@@ -590,30 +633,35 @@ actor WorkflowService {
private func buildDailyAggregate(
for task: WorkflowMaintenanceTask
) throws -> WorkflowMaintenanceResult {
- var aggregate = task.baseAggregate ?? WorkflowDailyAggregate(
- date: task.dateKey,
- sourceGeneration: task.sourceGeneration,
- sourceIsFresh: task.sourceIsFresh
- )
- aggregate.sourceGeneration = task.sourceGeneration
- aggregate.sourceIsFresh = task.sourceIsFresh
+ var accumulator = switch task.mode {
+ case let .rebuild(hookCountAvailability):
+ WorkflowDailyAccumulator(
+ rebuilding: task.dateKey,
+ sourceGeneration: task.sourceGeneration,
+ sourceIsFresh: task.sourceIsFresh,
+ hookCountAvailability: hookCountAvailability
+ )
+ case let .append(baseAggregate):
+ WorkflowDailyAccumulator(
+ appending: baseAggregate,
+ sourceGeneration: task.sourceGeneration,
+ sourceIsFresh: task.sourceIsFresh
+ )
+ }
var corrupt = task.existingCorrupt
- var identifierCache = WorkflowDailyIdentifierCache(aggregate: aggregate)
- let keepsIdentifiers = keepsIdentifiers(for: task.dateKey)
corrupt += try readEvents(
at: eventLogURL(for: task.dateKey),
from: task.startOffset,
upTo: task.size
) { event in
- aggregate.record(
- event,
- keepsIdentifiers: keepsIdentifiers,
- identifierCache: &identifierCache
- )
+ accumulator.record(event)
}
- aggregate.compactIdentifiersIfNeeded(keepsIdentifiers: keepsIdentifiers)
+ let identifierStorage: WorkflowIdentifierStorage = retainsIdentifiers(for: task.dateKey)
+ ? .retained
+ : .compacted
+ let aggregate = accumulator.finalized(identifierStorage: identifierStorage)
return try WorkflowMaintenanceResult(
dateKey: task.dateKey,
aggregate: aggregate,
@@ -695,7 +743,7 @@ actor WorkflowService {
// MARK: - 落盘与状态提交
- /// 返回是否写入了 daily.jsonl
+ /// 返回聚合与维护状态是否都基于同一份事件源完成提交
private func commit(
_ result: WorkflowMaintenanceResult,
aggregates: inout [WorkflowDailyAggregate]
@@ -707,8 +755,7 @@ actor WorkflowService {
// daily.jsonl 和 maintenance.json 分开写
// 每次提交前后都检查事件文件是否被并发追加
try writeDailyAggregate(result.aggregate, into: &aggregates)
- try commitMaintenanceState(result)
- return true
+ return try commitMaintenanceState(result)
}
private func eventLogSourceIsValid(for result: WorkflowMaintenanceResult) throws -> Bool {
@@ -805,12 +852,13 @@ actor WorkflowService {
}
}
- private func commitMaintenanceState(_ result: WorkflowMaintenanceResult) throws {
+ /// 返回第二次源校验后是否真正推进了维护状态
+ private func commitMaintenanceState(_ result: WorkflowMaintenanceResult) throws -> Bool {
try WorkflowStorage.withExclusiveLock {
var state = WorkflowStorage.loadMaintenanceState()
guard let currentSize = try validatedEventLogSize(for: result, state: &state) else {
- return
+ return false
}
state.days[result.dateKey] = WorkflowDayMaintenanceState(
@@ -831,6 +879,7 @@ actor WorkflowService {
}
try WorkflowStorage.saveMaintenanceState(state)
+ return true
}
}
@@ -890,7 +939,7 @@ actor WorkflowService {
return expiredDateKeys.count
}
- private func keepsIdentifiers(for dateKey: String) -> Bool {
+ private func retainsIdentifiers(for dateKey: String) -> Bool {
guard let date = CodexDateFormat.dayDate(from: dateKey) else {
return true
}
@@ -1166,7 +1215,8 @@ nonisolated struct WorkflowDayMaintenanceState: Codable, Equatable {
/// maintenance.json 的全局状态, pending 表示可增量, dirty 表示需全量重建
nonisolated struct WorkflowMaintenanceState: Codable, Equatable {
- static let currentSchema = 4
+ /// 原始事件到每日聚合的算法版本, 变化时统一从原始 JSONL 重建
+ static let currentAggregationSchema = 5
var schema: Int
var pending: [String]
@@ -1174,7 +1224,7 @@ nonisolated struct WorkflowMaintenanceState: Codable, Equatable {
var days: [String: WorkflowDayMaintenanceState]
init(
- schema: Int = Self.currentSchema,
+ schema: Int = Self.currentAggregationSchema,
pending: [String] = [],
dirty: [String] = [],
days: [String: WorkflowDayMaintenanceState] = [:]
@@ -1187,7 +1237,8 @@ nonisolated struct WorkflowMaintenanceState: Codable, Equatable {
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
- schema = try container.decodeIfPresent(Int.self, forKey: .schema) ?? Self.currentSchema
+ // 缺少版本只能说明来源更旧, 不能乐观视为当前算法
+ schema = try container.decodeIfPresent(Int.self, forKey: .schema) ?? 0
pending = try Self.normalizedDates(container.decodeIfPresent([String].self, forKey: .pending) ?? [])
dirty = try Self.normalizedDates(container.decodeIfPresent([String].self, forKey: .dirty) ?? [])
days = try container.decodeIfPresent([String: WorkflowDayMaintenanceState].self, forKey: .days) ?? [:]
@@ -1326,16 +1377,31 @@ private nonisolated struct WorkflowDailyLogStamp: Equatable {
let dayKey: String
}
+/// 全量重建与安全增量使用不同初始状态, 避免用 nil 隐含任务语义
+private nonisolated enum WorkflowMaintenanceMode {
+ case rebuild(WorkflowHookCountAvailability)
+ case append(WorkflowDailyAggregate)
+}
+
// 单次维护任务: 从 startOffset 读到 size, 可基于已有聚合继续追加
private nonisolated struct WorkflowMaintenanceTask {
let dateKey: String
let startOffset: UInt64
let size: UInt64
- let baseAggregate: WorkflowDailyAggregate?
+ let mode: WorkflowMaintenanceMode
let existingCorrupt: Int
let sourceGeneration: String?
let sourceIsFresh: Bool
let fileIdentifier: UInt64?
+
+ var baseEventCount: Int {
+ switch mode {
+ case .rebuild:
+ 0
+ case let .append(aggregate):
+ aggregate.eventCount ?? 0
+ }
+ }
}
/// 维护任务的提交结果, corrupt 统计保留给后续诊断
diff --git a/CodexBar/Services/Workflow/WorkflowSyncService.swift b/CodexBar/Services/Workflow/WorkflowSyncService.swift
index a99644c..0004f4b 100644
--- a/CodexBar/Services/Workflow/WorkflowSyncService.swift
+++ b/CodexBar/Services/Workflow/WorkflowSyncService.swift
@@ -282,7 +282,7 @@ private extension WorkflowSyncService {
}
enum Metrics {
- static let syncSchemaVersion = 4
+ static let syncSchemaVersion = 5
static let syncZoneName = "CodexBarZone"
static let saltByteCount = 32
static let recordFetchLimit = 200
@@ -304,6 +304,8 @@ private extension WorkflowSyncService {
static let sourceGeneration = "sourceGeneration"
static let eventCount = "eventCount"
static let sessionStartCount = "sessionStartCount"
+ static let sessionEndCount = "sessionEndCount"
+ static let userPromptSubmitCount = "userPromptSubmitCount"
static let stopCount = "stopCount"
static let preToolUseCount = "preToolUseCount"
static let postToolUseCount = "postToolUseCount"
@@ -548,7 +550,7 @@ private extension WorkflowSyncService {
if let matchingRecord,
let remoteAggregate = Self.remoteDailyRecord(from: matchingRecord)?.daily,
- remoteAggregate.eventCount > pendingRecord.upload.aggregate.eventCount,
+ (remoteAggregate.eventCount ?? 0) > (pendingRecord.upload.aggregate.eventCount ?? 0),
pendingRecord.upload.aggregate.sourceGeneration != nil {
return .skip
}
@@ -997,20 +999,22 @@ private extension WorkflowSyncService {
record[FieldKeys.deviceId] = deviceId as CKRecordValue
record[FieldKeys.date] = aggregate.date as CKRecordValue
record[FieldKeys.sourceGeneration] = aggregate.sourceGeneration as CKRecordValue?
- record[FieldKeys.eventCount] = aggregate.eventCount as CKRecordValue
- record[FieldKeys.sessionStartCount] = aggregate.sessionStartCount as CKRecordValue
- record[FieldKeys.stopCount] = aggregate.stopCount as CKRecordValue
- record[FieldKeys.preToolUseCount] = aggregate.preToolUseCount as CKRecordValue
- record[FieldKeys.postToolUseCount] = aggregate.postToolUseCount as CKRecordValue
- record[FieldKeys.permissionRequestCount] = aggregate.permissionRequestCount as CKRecordValue
- record[FieldKeys.preCompactCount] = aggregate.preCompactCount as CKRecordValue
- record[FieldKeys.postCompactCount] = aggregate.postCompactCount as CKRecordValue
- record[FieldKeys.subagentStartCount] = aggregate.subagentStartCount as CKRecordValue
- record[FieldKeys.subagentStopCount] = aggregate.subagentStopCount as CKRecordValue
+ record[FieldKeys.eventCount] = aggregate.eventCount as CKRecordValue?
+ record[FieldKeys.sessionStartCount] = aggregate.sessionStartCount as CKRecordValue?
+ record[FieldKeys.sessionEndCount] = aggregate.sessionEndCount as CKRecordValue?
+ record[FieldKeys.userPromptSubmitCount] = aggregate.userPromptSubmitCount as CKRecordValue?
+ record[FieldKeys.stopCount] = aggregate.stopCount as CKRecordValue?
+ record[FieldKeys.preToolUseCount] = aggregate.preToolUseCount as CKRecordValue?
+ record[FieldKeys.postToolUseCount] = aggregate.postToolUseCount as CKRecordValue?
+ record[FieldKeys.permissionRequestCount] = aggregate.permissionRequestCount as CKRecordValue?
+ record[FieldKeys.preCompactCount] = aggregate.preCompactCount as CKRecordValue?
+ record[FieldKeys.postCompactCount] = aggregate.postCompactCount as CKRecordValue?
+ record[FieldKeys.subagentStartCount] = aggregate.subagentStartCount as CKRecordValue?
+ record[FieldKeys.subagentStopCount] = aggregate.subagentStopCount as CKRecordValue?
record[FieldKeys.sessionCount] = aggregate.sessionCount as CKRecordValue?
record[FieldKeys.turnCount] = aggregate.turnCount as CKRecordValue?
record[FieldKeys.projectCounts] = Self.countsData(aggregate.projectCounts) as CKRecordValue
- record[FieldKeys.modelCounts] = Self.countsData(aggregate.modelCounts ?? [:]) as CKRecordValue
+ record[FieldKeys.modelCounts] = Self.countsData(aggregate.modelCounts) as CKRecordValue
record[FieldKeys.updatedAt] = Date() as CKRecordValue
}
@@ -1196,16 +1200,18 @@ private extension WorkflowSyncService {
let aggregate = WorkflowSyncedDailyAggregate(
date: date,
sourceGeneration: record[FieldKeys.sourceGeneration] as? String,
- eventCount: intValue(record[FieldKeys.eventCount]),
- sessionStartCount: intValue(record[FieldKeys.sessionStartCount]),
- stopCount: intValue(record[FieldKeys.stopCount]),
- preToolUseCount: intValue(record[FieldKeys.preToolUseCount]),
- postToolUseCount: intValue(record[FieldKeys.postToolUseCount]),
- permissionRequestCount: intValue(record[FieldKeys.permissionRequestCount]),
- preCompactCount: intValue(record[FieldKeys.preCompactCount]),
- postCompactCount: intValue(record[FieldKeys.postCompactCount]),
- subagentStartCount: intValue(record[FieldKeys.subagentStartCount]),
- subagentStopCount: intValue(record[FieldKeys.subagentStopCount]),
+ eventCount: optionalIntValue(record[FieldKeys.eventCount]),
+ sessionStartCount: optionalIntValue(record[FieldKeys.sessionStartCount]),
+ sessionEndCount: optionalIntValue(record[FieldKeys.sessionEndCount]),
+ userPromptSubmitCount: optionalIntValue(record[FieldKeys.userPromptSubmitCount]),
+ stopCount: optionalIntValue(record[FieldKeys.stopCount]),
+ preToolUseCount: optionalIntValue(record[FieldKeys.preToolUseCount]),
+ postToolUseCount: optionalIntValue(record[FieldKeys.postToolUseCount]),
+ permissionRequestCount: optionalIntValue(record[FieldKeys.permissionRequestCount]),
+ preCompactCount: optionalIntValue(record[FieldKeys.preCompactCount]),
+ postCompactCount: optionalIntValue(record[FieldKeys.postCompactCount]),
+ subagentStartCount: optionalIntValue(record[FieldKeys.subagentStartCount]),
+ subagentStopCount: optionalIntValue(record[FieldKeys.subagentStopCount]),
sessionCount: optionalIntValue(record[FieldKeys.sessionCount]),
turnCount: optionalIntValue(record[FieldKeys.turnCount]),
projectCounts: counts(from: record[FieldKeys.projectCounts]),
@@ -1251,10 +1257,6 @@ private extension WorkflowSyncService {
}
}
- static func intValue(_ value: CKRecordValue?) -> Int {
- optionalIntValue(value) ?? 0
- }
-
static func optionalIntValue(_ value: CKRecordValue?) -> Int? {
if let number = value as? NSNumber {
return number.intValue
diff --git a/Config/Version.xcconfig b/Config/Version.xcconfig
index 00bb681..7871598 100644
--- a/Config/Version.xcconfig
+++ b/Config/Version.xcconfig
@@ -1,2 +1,2 @@
-MARKETING_VERSION = 3.5.11
-CURRENT_PROJECT_VERSION = 65
+MARKETING_VERSION = 3.5.12
+CURRENT_PROJECT_VERSION = 66
diff --git a/README.md b/README.md
index 02add0c..1bcd90f 100644
--- a/README.md
+++ b/README.md
@@ -114,7 +114,13 @@ CodexBar 提供简体中文和英文界面, 默认跟随 macOS 的 App 语言偏
实时任务展示, 热力图统计数据与防睡眠都依赖 CodexBar Hook
> [!NOTE]
-> 不会影响任何原本的 Codex Hook
+> CodexBar Hook 需要 Codex 0.145.0 或更高版本. CodexBar 按当前连接的 app-server 运行版本校验, 更新 Codex 后如果仍提示版本过低, 请先重启 CodexBar 以建立新连接
+
+> [!NOTE]
+> CodexBar 只增删自己的 handler, 不会影响用户或其他 App 原本的 Codex Hook
+
+> [!TIP]
+> 升级后如果设置页提示 `CodexBar Hook 已不完整`, 将 CodexBar Hook 关闭后重新开启即可补齐新增事件
### 关于防睡眠
@@ -132,7 +138,7 @@ CodexBar 对外网络请求只有以下四项
| 与本机 `codex app-server` 通信 | 获取账户, 额度信息, 获取&修改本机 codex 配置等 |
| 查询额度重置次数和过期时间 | 请求 OpenAI 接口获取数据 |
| Sparkle 更新检查 | 获取 appcast 检查新版本 |
-| CloudKit 同步 | 私有数据: 同步用量数据 |
+| CloudKit 同步 | 私有数据: 同步脱敏的每日 Hook 聚合数据 |
## 实现
@@ -173,6 +179,10 @@ flowchart LR
App 使用 `--hook-event` 参数启动时不初始化任何 UI, 只从 stdin 读一行 JSON, 在文件锁内追加到当日 JSONL 后立即退出
+**历史聚合**
+
+原始 Hook 事件与每日聚合保留 210 天, 会话和轮次 ID 只保留 3 天; 聚合算法版本变化或已压缩日期收到新事件时, 会从仍在保留期内的原始 JSONL 统一完整重建
+
**root helper 权限**
`CodexBarHelper` 是随 App 嵌入的 LaunchDaemon, 只暴露一个 XPC 方法, 只执行 `pmset -a disablesleep`
diff --git a/appcast.xml b/appcast.xml
index 08a1920..20ea615 100644
--- a/appcast.xml
+++ b/appcast.xml
@@ -7,6 +7,15 @@
<link>https://codexbar.zabrian.app/appcast.xml</link>
<description>CodexBar appcast feed</description>
<language>zh-CN</language>
+ <item>
+ <title>CodexBar.app 3.5.12</title>
+ <sparkle:version>66</sparkle:version>
+ <sparkle:shortVersionString>3.5.12</sparkle:shortVersionString>
+ <sparkle:minimumSystemVersion>15.0</sparkle:minimumSystemVersion>
+ <sparkle:releaseNotesLink>https://codexbar.zabrian.app/notes#3.5.12</sparkle:releaseNotesLink>
+ <pubDate>Tue, 04 Aug 2026 17:49:55 +0800</pubDate>
+ <enclosure url="https://codexbar.zabrian.app/download/CodexBar-v3.5.12.dmg" sparkle:edSignature="zeQWyGHg59V+G+jrTCgwEenEV3NZLDB6Cfz0HGkxon/4JewNFY3vPvfAuXIiO9Tiioh18Y7XlLyTBFW8VeiLBQ==" length="6680268" type="application/octet-stream"/>
+ </item>
<item>
<title>CodexBar.app 3.5.11</title>
<sparkle:version>65</sparkle:version>