CodexBar 是一个 macOS 菜单栏应用,用于查看本机 Codex 账号状态、额度、Token 用量、详细统计信息
Swift appkitcodexcodex-clideveloper-toolsmacosmacos-appmenu-bar-appopenai-codexproductivityswiftswiftuiusage-tracker
feat: 支持代理配置并精简状态管理和文档
Bobe54d0cb7e29f
diff --git a/AGENTS.md b/AGENTS.mdindex 1a7f302..f1ce0f5 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -48,7 +48,7 @@ CodexBar 是面向 macOS 15+ 的 `LSUIElement` 菜单栏应用,使用 Swift 6,## 架构与编码约定-启动时必须先调用 `WorkflowHookEventRecorder.handleIfRequested()` 方法。`--hook-event` 模式只读取 `stdin`,加锁写入 JSONL 并立即退出,不初始化 UI,失败也不能阻断 Codex。Handler 超时按事件从 `hookTimeoutSeconds(for:)` 取得,`SessionEnd` 为 3 秒,其他事件为 5 秒。普通模式由 `CodexBarAppDelegate` 统一装配长期服务。+启动时必须先调用 `WorkflowHookEventRecorder.handleIfRequested()` 方法。`--hook-event` 模式从 `stdin` 接收事件,按需有界读取 rollout 元数据,加锁写入 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 约束。diff --git a/CLAUDE.md b/CLAUDE.mdindex 5e05c79..17b5b1c 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -2,36 +2,7 @@This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.-## 写作风格--代码、代码注释和项目文档使用彼此独立的规则,不得把一类内容的标点约定直接套用到另一类内容。提交信息由 Git 规范单独约束。--### 代码和注释--代码和注释统一遵守:--- 禁止使用中文标点,一律使用半角标点-- 句中停顿和并列项使用空格或者逗号,顿号的位置也用空格或者逗号-- 分号只用来断开完整句子,相当于句号;拿不准就把它换成句号读一遍,两边都能独立成句才保留-- 行末禁止使用标点-- 行内标点后如果还有文字,间隔一个英文空格-- 注释中引用类型、成员、参数或命令后尽量不要紧跟标点,需要断句时补一个词或者使用空格再断-- 一个注释段只解释一件事,需要说明多个独立主题时拆成多个注释段--### 项目文档--项目文档统一遵守:--- 代码标识符、命令、路径、配置键、原始字段值和需要精确复制的版本号使用行内代码-- 中文正文使用全角中文标点,包括 `,` `。` `;` `:` `!` `?` `“”` 和 `()`-- 中文短词或短语的并列使用 `、`;能独立表达语义的分句使用 `,`,两边都能独立成句时才考虑 `;`-- 中文标点前后不加空格;中文与英文、数字或行内代码之间按词语边界保留一个半角空格-- 不机械替换特殊内容中的英文标点。数字序列、行内代码序列或英文术语并列时,如果英文标点观感更好,使用英文标点并在其后保留一个半角空格-- 普通正文行末使用与语义匹配的中文标点;引出列表、表格或代码块的正文使用 `:`-- 标题、独立列表项、编号项和表格单元格行末不加标点-- 如果一行以 Markdown 格式的链接或行内代码结尾,后面不加任何标点;链接或行内代码位于句中时仍按句子结构使用中文标点-- Markdown 语法、代码块、命令、路径、URL、版本号和程序标识符内部的符号保持原样-- 如果某句话的作用只是防止被质疑,而不是推进论证,请删除+写作、构建、Git 与兼容性规则遵循 [AGENTS.md](AGENTS.md)## 项目概述@@ -78,29 +49,11 @@ Scripts/cleanup.swift --helpDebug 与 Release 使用不同 bundle ID,分别是 `app.zabrian.codexbar.debug` 与 `app.zabrian.codexbar`。helper 相应带 `.debug.helper` 与 `.helper` 后缀,所以 `CodexBarHelper/` 下有两份 LaunchDaemon plist,`cleanup.swift` 也需要同时处理两套。-## Git 规则--- 不要主动 push,除非用户明确要求-- 不要回滚、覆盖或丢弃不是你产生的未提交改动,工作树可能是脏的-- 被要求提交时,**禁止**顺带修改任何文件内容:不格式化、不清理、不补文档,只把当前已有改动原样提交+## Git 补充规则-Commit message 使用 Conventional Commits 前缀和中文标题,需要 body 时空一行后写 4 空格缩进 bullet:--- 标题写成 `<type>: <中文描述>` 的形式,不加句号;常用 type 有 `feat`、`fix`、`chore`、`refactor`、`docs`-- message 里不要出现版本号或发布字样,只描述改动本身,版本信息由 tag 承载-- 功能、修复、发布类提交必须写 body;简单文档或杂项可只写标题行-- body 中多条 bullet 连续排列,bullet 之间不空行-- 命令行提交时把完整 body 放进同一个 `-m` 参数或改用 `git commit -F` 传文件,不要为每条 bullet 单独 `-m`-- message 中禁止使用中文标点,行末禁止使用标点,行内标点后如果有文字则间隔一个英文空格--```text-fix: 修复 Codex 状态刷新-- - 合并设置页 onAppear 和 didBecomeActive 的重复版本检测- - 保留当前运行版本与磁盘安装版本不一致时的更新提示-```--Tag 名 `v{MARKETING_VERSION}` 里的版本号从 `Config/Version.xcconfig` 读取,使用附注 tag `git tag -a v3.x.y -m "Release v3.x.y"`+- 功能、修复和发布类提交必须写 body;简单文档或杂项可以只写标题+- commit message 使用半角标点,行末不加标点,行内标点后留一个英文空格+- 多条 body bullet 连续排列,使用同一个 `-m` 参数或通过 `git commit -F` 传入文件## 架构@@ -108,7 +61,7 @@ Tag 名 `v{MARKETING_VERSION}` 里的版本号从 `Config/Version.xcconfig` 读`CodexBar/App/CodexBarApp.swift` 的 `init()` 最先调用 `WorkflowHookEventRecorder.handleIfRequested()`-- 带 `--hook-event` 启动 -> **Hook 子进程模式**:从 `stdin` 读取 JSON payload,在 `flock` 锁内追加一行 JSONL 后立即调用 `exit(EXIT_SUCCESS)` 退出,绝不初始化菜单栏 UI;写入失败时静默吞掉,不阻断 Codex+- 带 `--hook-event` 启动 -> **Hook 子进程模式**:从 `stdin` 读取 JSON payload,按需有界读取 rollout 元数据,在 `flock` 锁内追加一行 JSONL 后立即调用 `exit(EXIT_SUCCESS)` 退出,绝不初始化菜单栏 UI;写入失败时静默吞掉,不阻断 Codex- Hook handler 超时统一由 `WorkflowHookEventRecorder.hookTimeoutSeconds(for:)` 提供,`SessionEnd` 是 3 秒,其他事件是 5 秒;等锁预算固定比对应事件超时少 2 秒,当前分别是 1 秒和 3 秒- 普通启动 -> `Controllers/CodexBarAppDelegate.swift` 中的 `CodexBarAppDelegate` 创建全部长期对象,再由 `StatusItemController.install()` 装配菜单栏;AppDelegate 是唯一的装配点,新增服务在这里注入@@ -123,6 +76,14 @@ Tag 名 `v{MARKETING_VERSION}` 里的版本号从 `Config/Version.xcconfig` 读- `SIGPIPE` 被忽略,app-server 退出后写管道由 write 抛错走重建路径- `stdout` 可能混有无关日志行,`AppServerSession` 先用轻量 `RPCIDEnvelope` 匹配 `id`,再完整解码+代理配置由 AppDelegate 持有的 `CodexProxySettings` 管理,配置和密码保存在当前构建的 UserDefaults 中,key 为 `CodexProxy.configuration`。只支持 HTTP/HTTPS,可选 Basic 认证,不使用 Keychain。停用保留字段,无法读取的记录可从配置窗口清除。++- 开关在异步提交前更新显示状态并禁用,重复操作被忽略,提交失败恢复原状态+- `CodexStatusService.applyProxy` 保存后关闭旧连接并清空缓存,随后触发刷新+- 手动和到期重连均先关闭旧连接,新连接失败后保持断开+- 代理测试使用草稿启动独立进程,请求共享 8 秒截止时间,取消后旧结果不得提交+- 配置错误写入 `AppLog.settings`,正式 RPC 响应中的代理 URL 认证信息脱敏后才进入内存交互日志+**链路二:Hook 统计(历史聚合)**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 聚合。@@ -153,7 +114,7 @@ Hook 子进程按天写入 `~/Library/Application Support/CodexBar/HookEvents/ev- `CodexActivityProtection.swift` 管理异常会话保护状态机,`ActivityProtectionSettings` 只保存静默阈值;保护开关跟随用户保存的 KeepAlive 主开关,不依赖 helper 是否已获系统授权- 静默阈值可选 30 分钟, 1, 2 或 4 小时,默认 1 小时,UserDefaults key 固定为 `KeepAlive.abnormalTaskInactivitySeconds`- 候选只包含非匿名 `.running` 任务,`.waitingApproval` 不参与异常判定;`lastProgressAt` 同时吸收 Hook 顶层事件、子 Agent 事件与 rollout 行时间-- 达到阈值后先持久化候选记录并尝试提交本地通知,通知使用系统默认声音且不重试;最多等待 3 秒后无论通知是否提交成功都隐藏任务+- 达到阈值后先更新内存候选记录并加入串行持久化队列,再提交本地通知;通知使用系统默认声音且不重试。通知处理返回或 3 秒宽限到期后重新校验候选,仍有效时隐藏任务;隐藏不等待磁盘写入成功- 通知以 task ID 与 attempt ID 共同标识,候选失效或任务恢复、终止、完成、过期时会撤回仍可识别的待处理和已送达通知;迟到的提交结果不得影响新的 attempt- 隐藏任务不进入 `CodexActivitySnapshot` 的运行中与等待批准列表,因而不参与 UI 和 KeepAlive 的活跃任务计算;后续进展会恢复任务并清除保护记录- KeepAlive 关闭时恢复当前进程内所有隐藏任务并撤回通知,已经隐藏任务的持久化记录保留;再次开启后按当前阈值和最近进展时间无通知对账@@ -277,7 +238,7 @@ Hook 子进程按天写入 `~/Library/Application Support/CodexBar/HookEvents/ev### 错误处理原则-- 菜单面板的 `CodexFetchOutcome` 只暴露有数据、未登录、初始化失败三种结果,而启动失败、超时、断连、解析失败等细节全部只进日志窗口,由 `RequestLogStorage` 保存,上限 500 条+- `CodexFetchOutcome` 包含有数据、未登录、版本不满足要求和初始化失败四种结果。主面板显示对应状态,关于页面显示连接失败原因;完整请求与响应由 `RequestLogStorage` 保存在内存日志中,上限 500 条- app-server 之外的模块走 `Services/Support/AppLog.swift` 写系统日志,用户可见文案只留步骤名,错误码与 `localizedDescription` 这类细节进 `os_log`;现有 `category` 为 `app`、`keepalive`、`activity`、`workflow`、`sync`、`hooks`、`codexcli`、`settings`、`notification`,helper 进程另用 `helper`- 日志的目标是出问题时能从中重建当时的状态,所以不只记失败,状态转换、关键操作与决策依据同样要记;启动时由 `logLaunchState` 记一条含全部开关的基线,后续变更日志都是相对它的增量- 进程终止靠 `AppProcessDiagnostics` 补线索,它和 `logLaunchState` 一样挂在 `app` category 下,ObjC 异常当场留痕,其余终止方式靠下次启动补记一条 `App 上次非正常退出`@@ -303,7 +264,7 @@ Hook 子进程按天写入 `~/Library/Application Support/CodexBar/HookEvents/ev- 菜单栏按钮左键切换主面板;右键或 Control+点击打开上下文菜单;`⌘,` 打开自定义设置窗口,菜单面板打开时 `⌘L` 打开日志窗口;默认全局快捷键 `⌘⇧W` 由 `GlobalHotKeySettings` 与 `GlobalHotKeyController` 管理- 主面板是锚定 status item 的 `NSPopover` 弹窗,锚点不可信时回退到 `FallbackPanelController` 提供的屏幕顶部居中 `NSPanel` 面板,处理快捷键、屏幕选择和焦点时要保留这两个分支-- 关闭逻辑统一由 `MenuSurfaceDismissMonitor` 管理,淡出由 `MenuSurfaceFadeCoordinator` 负责+- 关闭逻辑统一由 `MenuSurfaceDismissMonitor` 管理;`MenuSurfaceFadeCoordinator` 同时调整内容视图和窗口透明度,淡入 0.24 秒、淡出 0.18 秒,只保留一个完成任务,新动画取消旧任务- 主面板的热力图详情、重置次数和任务中心使用 `borderless nonactivating child panel`;设置窗口的主面板布局、通知、自动重置和防睡眠选项使用可获得键盘焦点的 `borderless child panel`- 设置窗口的子面板占同一位置,展开一个必须先 `hide(immediate: true)` 收掉其余的;动作走 `SettingsOptionsPanelAction` 并带上目标 `SettingsOptionsPanel`,互斥与 `closeAll` 都只写在 `SettingsWindowController.handleOptionsAction` 一处,新增面板不会漏配对- 面板控制器只在首次展开时构造,收起动作走 `existingOptionsPanelController` 而不触发构造:`NSHostingController` 与动态面板订阅会常驻到 App 结束,而用户可能一次子面板都没开过@@ -323,7 +284,7 @@ Hook 子进程按天写入 `~/Library/Application Support/CodexBar/HookEvents/ev- 设置子面板的公共内边距、间距与外观度量从 `SettingsOptionsPanelMetrics` 取;通知、自动重置和防睡眠面板的下拉控件共用 `SettingsOptionsPicker`;主面板布局使用独立的 28 点拖拽行高且不使用下拉控件- 设置子面板的内容工厂必须走 `SettingsOptionsPanelController.makeContentController(_:rebuiltBy:)`,否则首次展开时原生 Switch 只剩一条空轨道;重建信号由它接在内容外面,内容视图不必知道 `SidePanelEntryCue`- 原因是 thumb 由 `WindowPortal` 投射而不是画在开关上,面板首次布局那一轮 portal 建不起来,而且不会自愈,只有一次内容重建才补得上;第二次展开正常是因为 hosting controller 常驻,复用了已经建好的那份-- 不要再用 `@_optimize(none)` 规避这个漏绘:它当年在通知子面板管用只是因为逼着 body 重算时判定那些行变过,与优化等级无关,换个写法就失效;`SidePanelSupport` 里剩下那一处标注规避的是编译器崩溃,与此无关+- 开关首次绘制由内容重建处理;`SidePanelSupport` 中的 `@_optimize(none)` 用于规避编译器崩溃- 主面板的账户、任务中心、额度、Token 用量和底部状态由 `MainPanelSettings.layout` 统一保存顺序与显隐,模型始终保留至少一个区域;Hook 关闭时 `StatusItemController` 调用 `updateHookEnabled(_:)` 持久化关闭任务中心,任务中心原本是唯一可见区域时同步开启账户;设置面板只禁用任务中心开关,不能连带禁用拖拽手柄- 主面板布局排序由手柄上的自定义 `DragGesture` 驱动,悬浮副本跟手移动,其他行按预览顺序实时让位,松手后才通过 `setSectionOrder(_:)` 保存最终顺序;不要改回只在落点命中后换位的 `.draggable` 和 `.dropDestination`- 热力图详情面板跟随包含标题和方格矩阵的完整热力图区域定位,优先让两者顶边对齐;详情面板过高时通过 `SidePanelSupport.anchoredPosition` 上移到与主面板底边对齐,不能恢复为固定贴住主面板底边@@ -361,12 +322,6 @@ Hook 子进程按天写入 `~/Library/Application Support/CodexBar/HookEvents/ev- 系统日志不写用户数据:额度与 Token 用量只记 `state=` 这类结果分类,任务内容、项目名、会话与轮次标识一律不记;可执行文件路径含用户名,用 `source=global|bundled` 之类的标识代替- 事件数、任务数、日期这类聚合数字可以记,它们是判断重建是否正确和定位哪天出问题的依据,不含任何内容-## 代码修改原则+## 验证与文档-- 优先贴合现有文件结构和类型职责,不为小改动新建抽象-- 改 shared controller、shared service、模型解析或持久化 key 时,要考虑旧数据和降级路径;用户设置要保持默认值;持久化 key 和旧版本迁移兼容-- **任何兼容性问题都必须主动询问用户,不要自行决定**;只要改动会影响新旧共存就适用,不限于旧数据迁移或丢弃、持久化 key 改名或改结构、老版本升上来的降级路径、最低系统版本与 API 可用性取舍、云端记录格式变更;先说清影响面和几种做法的代价,等用户选定再动手-- 处理窗口、菜单、快捷键、App 激活或事件监听时,特别注意 `LSUIElement` 应用特有的焦点行为-- 注释保持克制,只解释非显然的生命周期、焦点、actor 或系统 API 约束;现有注释多为解释为什么的类型,沿用同样风格-- 改动涉及菜单面板、窗口焦点、Hook、同步、通知、自动重置唤醒或防睡眠时,构建通过之外还要说明应手动覆盖的交互场景;helper 相关改动额外要验证 App 包内 helper 与 plist 位置、签名、首次系统授权、运行/等待切换、唤醒计划替换与清理和异常退出后的恢复-- 不要把发布产物、DerivedData、临时 DMG、签名文件或个人凭据提交进仓库+构建、日志和各功能验证入口见 [开发与验证](Docs/DeveloperGuide/development.md)。不要提交发布产物、DerivedData、临时 DMG、签名文件或个人凭据。diff --git a/CodexBar/Controllers/CodexBarAppDelegate.swift b/CodexBar/Controllers/CodexBarAppDelegate.swiftindex 55f9981..6d84650 100644--- a/CodexBar/Controllers/CodexBarAppDelegate.swift+++ b/CodexBar/Controllers/CodexBarAppDelegate.swift@@ -5,6 +5,7 @@ import os@MainActorfinal class CodexBarAppDelegate: NSObject, NSApplicationDelegate {private let codexStatusService = CodexStatusService()+ lazy var proxySettings = CodexProxySettings(service: codexStatusService)lazy var viewModel = CodexStatusViewModel(service: codexStatusService)let workflowViewModel = WorkflowViewModel()lazy var codexHookSettings = CodexHookSettings(codexStatusService: codexStatusService)@@ -52,7 +53,8 @@ final class CodexBarAppDelegate: NSObject, NSApplicationDelegate {notificationSettings: notificationSettings,autoResetSettings: autoResetSettings,keepAliveController: keepAliveController,- appUpdater: appUpdater+ appUpdater: appUpdater,+ proxySettings: proxySettings)controller.install()statusItemController = controllerdiff --git a/CodexBar/Controllers/MenuSurfaceFadeCoordinator.swift b/CodexBar/Controllers/MenuSurfaceFadeCoordinator.swiftindex 9cfdbb8..c427988 100644--- a/CodexBar/Controllers/MenuSurfaceFadeCoordinator.swift+++ b/CodexBar/Controllers/MenuSurfaceFadeCoordinator.swift@@ -1,13 +1,11 @@import AppKit-/// 菜单面板淡入淡出的集中控制, 用 generation 丢弃过期动画完成回调+/// 菜单面板淡入淡出的集中控制, 新动画取消旧的完成任务@MainActorfinal class MenuSurfaceFadeCoordinator {private let contentViewProvider: () -> NSView?private let closeActiveMenuSurface: () -> Void- private var fadeInCompletionTask: Task<Void, Never>?- private var fadeOutCompletionTask: Task<Void, Never>?- private var fadeGeneration = 0+ private var completionTask: Task<Void, Never>?init(contentViewProvider: @escaping () -> NSView?,@@ -18,10 +16,8 @@ final class MenuSurfaceFadeCoordinator {}func cancel() {- fadeInCompletionTask?.cancel()- fadeInCompletionTask = nil- fadeOutCompletionTask?.cancel()- fadeOutCompletionTask = nil+ completionTask?.cancel()+ completionTask = nil}func prepareForFadeIn() {@@ -35,40 +31,40 @@ final class MenuSurfaceFadeCoordinator {}func fadeIn(duration: TimeInterval, completion: @escaping () -> Void) {- let operationGeneration = nextGeneration()+ cancel()fade(to: 1, duration: duration)- fadeInCompletionTask = Task { @MainActor [weak self] in+ completionTask = Task { @MainActor [weak self] intry? await Task.sleep(for: .milliseconds(Int(duration * 1000)))- guard let self, !Task.isCancelled, fadeGeneration == operationGeneration else {+ guard let self, !Task.isCancelled else {return}resetAlpha()- fadeInCompletionTask = nil+ completionTask = nilcompletion()}}func fadeOut(duration: TimeInterval, completion: @escaping () -> Void) -> Bool {+ cancel()guard let contentView else {return false}- let operationGeneration = nextGeneration()let activeMenuSurfaceWindow = contentView.windowfade(to: 0, duration: duration)- fadeOutCompletionTask = Task { @MainActor [weak self, weak contentView, weak activeMenuSurfaceWindow] in+ completionTask = Task { @MainActor [weak self, weak contentView, weak activeMenuSurfaceWindow] intry? await Task.sleep(for: .milliseconds(Int(duration * 1000)))- guard let self, !Task.isCancelled, fadeGeneration == operationGeneration else {+ guard let self, !Task.isCancelled else {return}closeActiveMenuSurface()contentView?.alphaValue = 1activeMenuSurfaceWindow?.alphaValue = 1- fadeOutCompletionTask = nil+ completionTask = nilcompletion()}@@ -79,11 +75,6 @@ final class MenuSurfaceFadeCoordinator {contentViewProvider()}- private func nextGeneration() -> Int {- fadeGeneration += 1- return fadeGeneration- }-private func fade(to alpha: CGFloat, duration: TimeInterval) {guard let contentView else {returndiff --git a/CodexBar/Controllers/SettingsWindowController.swift b/CodexBar/Controllers/SettingsWindowController.swiftindex 6f9f975..8cfd017 100644--- a/CodexBar/Controllers/SettingsWindowController.swift+++ b/CodexBar/Controllers/SettingsWindowController.swift@@ -6,6 +6,7 @@ import SwiftUI@MainActorfinal class SettingsWindowController: HostingWindowController {private let viewModel: CodexStatusViewModel+ private let proxySettings: CodexProxySettingsprivate let appUpdater: AppUpdaterprivate let codexHookSettings: CodexHookSettingsprivate let codexCLINotificationSettings: CodexCLINotificationSettings@@ -33,6 +34,7 @@ final class SettingsWindowController: HostingWindowController {init(viewModel: CodexStatusViewModel,appUpdater: AppUpdater,+ proxySettings: CodexProxySettings,codexHookSettings: CodexHookSettings,codexCLINotificationSettings: CodexCLINotificationSettings,syncSettings: WorkflowSyncSettings,@@ -49,6 +51,7 @@ final class SettingsWindowController: HostingWindowController {) {self.viewModel = viewModelself.appUpdater = appUpdater+ self.proxySettings = proxySettingsself.codexHookSettings = codexHookSettingsself.codexCLINotificationSettings = codexCLINotificationSettingsself.syncSettings = syncSettings@@ -74,6 +77,7 @@ final class SettingsWindowController: HostingWindowController {override func makeWindow() -> NSWindow {let hostingController = NSHostingController(rootView: AppSettingsView(+ proxySettings: proxySettings,codexHookSettings: codexHookSettings,syncSettings: syncSettings,globalHotKeySettings: globalHotKeySettings,diff --git a/CodexBar/Controllers/StatusItemController.swift b/CodexBar/Controllers/StatusItemController.swiftindex abaa0ca..462a00f 100644--- a/CodexBar/Controllers/StatusItemController.swift+++ b/CodexBar/Controllers/StatusItemController.swift@@ -18,6 +18,7 @@ final class StatusItemController: NSObject, NSMenuDelegate {private let notificationSettings: NotificationSettingsprivate let autoResetSettings: AutoResetSettingsprivate let keepAliveController: KeepAliveController+ private let proxySettings: CodexProxySettingsprivate let appUpdater: AppUpdaterprivate let statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength)private let popover = NSPopover()@@ -41,6 +42,7 @@ final class StatusItemController: NSObject, NSMenuDelegate {private lazy var settingsWindowController = SettingsWindowController(viewModel: viewModel,appUpdater: appUpdater,+ proxySettings: proxySettings,codexHookSettings: codexHookSettings,codexCLINotificationSettings: codexCLINotificationSettings,syncSettings: syncSettings,@@ -121,7 +123,8 @@ final class StatusItemController: NSObject, NSMenuDelegate {notificationSettings: NotificationSettings,autoResetSettings: AutoResetSettings,keepAliveController: KeepAliveController,- appUpdater: AppUpdater+ appUpdater: AppUpdater,+ proxySettings: CodexProxySettings) {self.viewModel = viewModelself.workflowViewModel = workflowViewModel@@ -136,6 +139,7 @@ final class StatusItemController: NSObject, NSMenuDelegate {self.autoResetSettings = autoResetSettingsself.keepAliveController = keepAliveControllerself.appUpdater = appUpdater+ self.proxySettings = proxySettingssuper.init()}diff --git a/CodexBar/Models/CodexProxyConfiguration.swift b/CodexBar/Models/CodexProxyConfiguration.swiftnew file mode 100644index 0000000..3b190f8--- /dev/null+++ b/CodexBar/Models/CodexProxyConfiguration.swift@@ -0,0 +1,152 @@+import Darwin+import Foundation++nonisolated struct CodexProxyConfiguration: Codable, Equatable, Sendable {+ enum Transport: String, Codable, CaseIterable, Sendable {+ case http+ case https+ }++ enum InputField: Hashable {+ case host+ case port+ case username+ }++ enum ValidationKind {+ case required+ case format+ }++ struct ValidationIssue: Equatable {+ let field: InputField+ let kind: ValidationKind++ var title: String {+ switch (field, kind) {+ case (.host, .required): String(localized: "proxy.validation.host.required")+ case (.port, .required): String(localized: "proxy.validation.port.required")+ case (.username, .required): String(localized: "proxy.validation.username.required")+ case (.host, .format): String(localized: "proxy.validation.host.invalid")+ case (.port, .format): String(localized: "proxy.validation.port.invalid")+ case (.username, .format): String(localized: "proxy.validation.username.invalid")+ }+ }+ }++ var isEnabled = false+ var transport = Transport.http+ var host = ""+ var port = ""+ var usesAuthentication = false+ var username = ""++ var validationIssues: [ValidationIssue] {+ var issues: [ValidationIssue] = []+ if host.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {+ issues.append(ValidationIssue(field: .host, kind: .required))+ }+ if port.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {+ issues.append(ValidationIssue(field: .port, kind: .required))+ }+ if usesAuthentication, username.isEmpty {+ issues.append(ValidationIssue(field: .username, kind: .required))+ }+ guard issues.isEmpty else { return issues }+ if (try? normalizedHost()) == nil {+ issues.append(ValidationIssue(field: .host, kind: .format))+ }+ if validPort == nil {+ issues.append(ValidationIssue(field: .port, kind: .format))+ }+ if !isUsernameValid {+ issues.append(ValidationIssue(field: .username, kind: .format))+ }+ return issues+ }++ func validated() throws -> Self {+ if let issue = validationIssues.first {+ throw issue.field == .username ? CodexProxyError.missingUsername : CodexProxyError.invalidAddress+ }+ var result = self+ result.host = try normalizedHost()+ guard let portNumber = validPort else { throw CodexProxyError.invalidAddress }+ result.port = String(portNumber)+ return result+ }++ private var validPort: Int? {+ guard let number = Int(port.trimmingCharacters(in: .whitespacesAndNewlines)),+ (1 ... 65535).contains(number) else { return nil }+ return number+ }++ private var isUsernameValid: Bool {+ !usesAuthentication || (!username.isEmpty && !username.contains(":")+ && !username.unicodeScalars.contains(where: { CharacterSet.controlCharacters.contains($0) }))+ }++ private func normalizedHost() throws -> String {+ var host = host.trimmingCharacters(in: .whitespacesAndNewlines)+ guard !host.isEmpty,+ !host.contains(where: \.isWhitespace),+ !host.contains(where: { "/?#@\\%".contains($0) }) else {+ throw CodexProxyError.invalidAddress+ }+ if host.contains(":") || host.contains("[") {+ let address = host.hasPrefix("[") && host.hasSuffix("]")+ ? String(host.dropFirst().dropLast()) : host+ var bytes = in6_addr()+ guard inet_pton(AF_INET6, address, &bytes) == 1 else { throw CodexProxyError.invalidAddress }+ host = "[\(address)]"+ } else {+ let allowed = CharacterSet.alphanumerics.union(CharacterSet(charactersIn: ".-"))+ guard host.unicodeScalars.allSatisfy({ allowed.contains($0) }) else {+ throw CodexProxyError.invalidAddress+ }+ }+ guard let components = URLComponents(string: "\(transport.rawValue)://\(host):1"),+ components.host != nil, components.port == 1,+ components.user == nil, components.password == nil,+ components.path.isEmpty, components.url != nil else {+ throw CodexProxyError.invalidAddress+ }+ return host+ }++ func environment(overriding base: [String: String], password: String) throws -> [String: String] {+ guard isEnabled else { return base }+ let configuration = try validated()+ var components = URLComponents(string: "\(transport.rawValue)://\(configuration.host):\(configuration.port)")!+ if usesAuthentication {+ let allowed = CharacterSet.alphanumerics.union(CharacterSet(charactersIn: "-._~"))+ components.percentEncodedUser = username.addingPercentEncoding(withAllowedCharacters: allowed)+ components.percentEncodedPassword = password.addingPercentEncoding(withAllowedCharacters: allowed)+ }+ guard let address = components.url?.absoluteString else { throw CodexProxyError.invalidAddress }+ var environment = base+ // 协议专用变量优先于系统设置, 清理继承的旁路和 WebSocket 变量以保持单一出口+ for key in ["HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "WS_PROXY", "WSS_PROXY"] {+ environment[key] = address+ environment[key.lowercased()] = address+ }+ environment["NO_PROXY"] = "localhost,127.0.0.1,::1"+ environment["no_proxy"] = environment["NO_PROXY"]+ return environment+ }+}++nonisolated enum CodexProxyError: LocalizedError {+ case invalidAddress+ case missingUsername+ case invalidStoredConfiguration++ var errorDescription: String? {+ switch self {+ case .invalidAddress: String(localized: "proxy.error.invalid-endpoint")+ case .missingUsername: String(localized: "proxy.error.invalid-username")+ case .invalidStoredConfiguration: String(localized: "proxy.error.configuration-unreadable")+ }+ }+}diff --git a/CodexBar/Resources/Localizable.xcstrings b/CodexBar/Resources/Localizable.xcstringsindex 4406b92..be03242 100644--- a/CodexBar/Resources/Localizable.xcstrings+++ b/CodexBar/Resources/Localizable.xcstrings@@ -3233,6 +3233,470 @@}}},+ "proxy.action.cancel-test" : {+ "localizations" : {+ "en" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Cancel Test"+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "取消测试"+ }+ }+ }+ },+ "proxy.action.clear-configuration" : {+ "localizations" : {+ "en" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Delete Configuration"+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "删除配置"+ }+ }+ }+ },+ "proxy.action.save" : {+ "localizations" : {+ "en" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Save"+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "保存"+ }+ }+ }+ },+ "proxy.action.test-connection" : {+ "localizations" : {+ "en" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Test Connection"+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "测试连接"+ }+ }+ }+ },+ "proxy.authentication" : {+ "localizations" : {+ "en" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Authentication"+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "身份验证"+ }+ }+ }+ },+ "proxy.configuration.title" : {+ "localizations" : {+ "en" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Proxy Configuration"+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "代理配置"+ }+ }+ }+ },+ "proxy.enabled" : {+ "localizations" : {+ "en" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Enable proxy"+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "启用代理"+ }+ }+ }+ },+ "proxy.error.configuration-unreadable" : {+ "localizations" : {+ "en" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Proxy error: unable to read configuration"+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "代理配置错误: 无法读取配置"+ }+ }+ }+ },+ "proxy.error.invalid-endpoint" : {+ "localizations" : {+ "en" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Proxy error: invalid server"+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "代理配置错误: 服务器无效"+ }+ }+ }+ },+ "proxy.error.invalid-username" : {+ "localizations" : {+ "en" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Proxy error: invalid username"+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "代理配置错误: 用户名无效"+ }+ }+ }+ },+ "proxy.feedback.clear-failed" : {+ "localizations" : {+ "en" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Could not clear proxy configuration"+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "清除代理配置失败"+ }+ }+ }+ },+ "proxy.feedback.load-failed" : {+ "localizations" : {+ "en" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Load failed"+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "读取失败"+ }+ }+ }+ },+ "proxy.feedback.save-failed" : {+ "localizations" : {+ "en" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Save failed"+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "保存失败"+ }+ }+ }+ },+ "proxy.password" : {+ "localizations" : {+ "en" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Password"+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "密码"+ }+ }+ }+ },+ "proxy.server" : {+ "localizations" : {+ "en" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Proxy server"+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "代理服务器"+ }+ }+ }+ },+ "proxy.test.codex-login-required" : {+ "localizations" : {+ "en" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Sign in to Codex"+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "请登录 Codex"+ }+ }+ }+ },+ "proxy.test.codex-unavailable" : {+ "localizations" : {+ "en" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Codex unavailable"+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Codex 不可用"+ }+ }+ }+ },+ "proxy.test.connected" : {+ "localizations" : {+ "en" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Connected"+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "连接成功"+ }+ }+ }+ },+ "proxy.test.connection-failed" : {+ "localizations" : {+ "en" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Connection failed"+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "连接失败"+ }+ }+ }+ },+ "proxy.test.proxy-authentication-failed" : {+ "localizations" : {+ "en" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Authentication failed"+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "身份验证失败"+ }+ }+ }+ },+ "proxy.test.timed-out" : {+ "localizations" : {+ "en" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Timed out"+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "连接超时"+ }+ }+ }+ },+ "proxy.title" : {+ "localizations" : {+ "en" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Proxy"+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "代理"+ }+ }+ }+ },+ "proxy.username" : {+ "localizations" : {+ "en" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Username"+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "用户名"+ }+ }+ }+ },+ "proxy.validation.host.invalid" : {+ "localizations" : {+ "en" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Invalid host"+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "主机错误"+ }+ }+ }+ },+ "proxy.validation.host.required" : {+ "localizations" : {+ "en" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Enter server"+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "请输入服务器地址"+ }+ }+ }+ },+ "proxy.validation.port.invalid" : {+ "localizations" : {+ "en" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Port 1–65535"+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "端口范围 1~65535"+ }+ }+ }+ },+ "proxy.validation.port.required" : {+ "localizations" : {+ "en" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Enter port"+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "请输入端口"+ }+ }+ }+ },+ "proxy.validation.username.invalid" : {+ "localizations" : {+ "en" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Invalid username"+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "用户名格式有误"+ }+ }+ }+ },+ "proxy.validation.username.required" : {+ "localizations" : {+ "en" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Enter username"+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "请输入用户名"+ }+ }+ }+ },"quota.credits.value" : {"localizations" : {"en" : {diff --git a/CodexBar/Services/CodexStatus/AppServerSession.swift b/CodexBar/Services/CodexStatus/AppServerSession.swiftindex 0de5223..2ecad8e 100644--- a/CodexBar/Services/CodexStatus/AppServerSession.swift+++ b/CodexBar/Services/CodexStatus/AppServerSession.swift@@ -1,4 +1,5 @@import Foundation+import os/// 对 app-server stdio JSON-RPC 的薄封装/// 负责日志记录, 超时和 unsupported 方法缓存@@ -18,21 +19,127 @@ final nonisolated class AppServerSession {private let lineReader: JSONLineReaderprivate let errorReader: PipeDrainprivate let timeout: TimeInterval+ private let deadline: Date?+ private let logStorage: RequestLogStorage?private var nextId = 1private var unsupportedMethods: Set<String> = []- init(+ private init(process: Process,input: Pipe,lineReader: JSONLineReader,errorReader: PipeDrain,- timeout: TimeInterval+ timeout: TimeInterval,+ deadline: Date?) {self.process = processself.input = inputself.lineReader = lineReaderself.errorReader = errorReaderself.timeout = timeout+ self.deadline = deadline+ logStorage = deadline == nil ? .shared : nil+ }++ static func launch(+ command: AppServerCommand,+ environment: [String: String],+ timeout: TimeInterval,+ deadline: Date? = nil,+ usesCustomProxy: Bool = false+ ) throws -> AppServerSession {+ let process = Process()+ process.executableURL = URL(fileURLWithPath: command.executablePath)+ // 只覆盖本次子进程, 避免系统优先策略盖过用户在 App 中指定的代理+ process.arguments = command.arguments + (usesCustomProxy ? ["-c", "features.respect_system_proxy=false"] : [])+ process.environment = environment+ let input = Pipe()+ let output = Pipe()+ let error = Pipe()+ process.standardInput = input+ process.standardOutput = output+ process.standardError = error+ let reader = JSONLineReader(fileHandle: output.fileHandleForReading)+ let errorReader = PipeDrain(fileHandle: error.fileHandleForReading)+ do {+ try process.run()+ } catch {+ reader.stop()+ errorReader.stop()+ throw error+ }+ return AppServerSession(+ process: process,+ input: input,+ lineReader: reader,+ errorReader: errorReader,+ timeout: timeout,+ deadline: deadline+ )+ }++ static func redactingProxyCredentials(_ text: String) -> String {+ func redact(_ value: Any) -> Any {+ switch value {+ case let string as String:+ string.replacingOccurrences(+ of: #"(?i)(https?://)[^\s/"@]+@"#,+ with: "$1<redacted>@",+ options: .regularExpression+ )+ case let object as [String: Any]: object.mapValues(redact)+ case let array as [Any]: array.map(redact)+ default: value+ }+ }++ // 先解码 JSON 转义, 避免 URL 中的斜杠或 Unicode 转义绕过脱敏+ if let object = try? JSONSerialization.jsonObject(with: Data(text.utf8), options: .fragmentsAllowed),+ let data = try? JSONSerialization.data(withJSONObject: redact(object), options: [.fragmentsAllowed, .sortedKeys, .withoutEscapingSlashes]),+ let result = String(data: data, encoding: .utf8) {+ return result+ }+ return redact(text) as? String ?? text+ }++ func initializeAccount() throws -> (version: String, account: AccountReadResponse) {+ let result = try request(+ "initialize",+ params: ["clientInfo": [+ "name": "codex_bar",+ "title": "Codex Bar",+ "version": Self.clientVersion()+ ]],+ as: InitializeResult.self+ )+ let version = Self.serverVersion(fromUserAgent: result.userAgent)+ let minimum = CodexCLIMinimumVersion.global+ guard let version, CodexCLIVersionReader.isVersion(version, atLeast: minimum) == true else {+ let error = CodexStatusError.unsupportedVersion(minimum: minimum)+ if let logStorage {+ let details = LogFields.joined("current=\(version ?? "unknown")", "minimum=\(minimum)")+ AppLog.codexCLI.notice("Codex 版本不支持: \(details, privacy: .public)")+ logStorage.recordFailure(message: error.localizedDescription)+ }+ throw error+ }+ try notify("initialized")+ let account = try request("account/read", params: ["refreshToken": false], as: AccountReadResponse.self)+ guard account.account != nil else { throw CodexStatusError.notLoggedIn }+ return (version, account)+ }++ private static func clientVersion() -> String {+ guard let version = Bundle.main.shortVersionString, !version.isEmpty else { return "1.0.0" }+ return version+ }++ /// userAgent 首个 token 中 "/" 之后的部分才是实际运行版本+ private static func serverVersion(fromUserAgent userAgent: String?) -> String? {+ guard let firstToken = userAgent?.split(separator: " ").first,+ let slashIndex = firstToken.firstIndex(of: "/") else { return nil }+ let version = firstToken[firstToken.index(after: slashIndex)...]+ return version.isEmpty ? nil : String(version)}func close() {@@ -49,11 +156,11 @@ final nonisolated class AppServerSession {case .alreadyExited, .terminated:breakcase .killed:- RequestLogStorage.shared.recordFailure(+ logStorage?.recordFailure(message: String(localized: "request-log.error.exit-timeout-killed"))case .stillRunning:- RequestLogStorage.shared.recordFailure(+ logStorage?.recordFailure(message: String(localized: "request-log.error.exit-timeout-running"))}@@ -64,9 +171,9 @@ final nonisolated class AppServerSession {let encoded = try encodeMessage(method: method, id: nil, params: params)try writeEncoded(encoded) {- RequestLogStorage.shared.recordFailure(method: method, message: Self.writeFailureMessage)+ logStorage?.recordFailure(method: method, message: Self.writeFailureMessage)}- RequestLogStorage.shared.recordRequestWithEmptyResponse(method: method, payload: encoded.text)+ logStorage?.recordRequestWithEmptyResponse(method: method, payload: encoded.text)}func request<Response: Decodable>(@@ -81,7 +188,7 @@ final nonisolated class AppServerSession {// app-server 偶发业务错误可重试一次; 传输错误由上层重建连接do {return try performRequestRememberingUnsupported(method, params: params, as: type)- } catch let error as CodexStatusError where error.isRetriableServerError {+ } catch let error as CodexStatusError where deadline == nil && error.isRetriableServerError {return try performRequestRememberingUnsupported(method, params: params, as: type)}}@@ -109,10 +216,10 @@ final nonisolated class AppServerSession {let id = nextIdnextId += 1let encoded = try encodeMessage(method: method, id: id, params: params)- let token = RequestLogStorage.shared.beginRequest(method: method, payload: encoded.text)+ let token = logStorage?.beginRequest(method: method, payload: encoded.text) ?? UUID()try writeEncoded(encoded) {- RequestLogStorage.shared.failRequest(token, message: Self.writeFailureMessage)+ logStorage?.failRequest(token, message: Self.writeFailureMessage)}return try waitForResponse(id: id, token: token, decode: type)@@ -164,11 +271,14 @@ final nonisolated class AppServerSession {token: UUID,decode type: Response.Type) throws -> Response {- let deadline = Date().addingTimeInterval(timeout)+ let deadline = min(deadline ?? .distantFuture, Date().addingTimeInterval(timeout))let decoder = JSONDecoder()// stdout 可能混有无关日志行, 只消费 id 匹配的 JSON-RPC 响应while Date() < deadline {+ if self.deadline != nil {+ try Task.checkCancellation()+ }guard let line = try nextResponseLine(matching: id,before: deadline,@@ -179,7 +289,7 @@ final nonisolated class AppServerSession {}let result = try decodeResponse(line, as: type, token: token, decoder: decoder)- RequestLogStorage.shared.finishRequest(token, response: line.text)+ logStorage?.finishRequest(token, response: Self.redactingProxyCredentials(line.text))return result}@@ -192,7 +302,9 @@ final nonisolated class AppServerSession {token: UUID,decoder: JSONDecoder) throws -> ResponseLine? {- guard let text = lineReader.nextLine(timeout: max(0, deadline.timeIntervalSinceNow)) else {+ let remaining = max(0, deadline.timeIntervalSinceNow)+ let wait = self.deadline == nil ? remaining : min(0.1, remaining)+ guard let text = lineReader.nextLine(timeout: wait) else {if lineReader.isClosed {try failRequest(token, message: Self.responseConnectionClosedMessage, error: .serverConnectionClosed)}@@ -225,7 +337,7 @@ final nonisolated class AppServerSession {}if let error = envelope.error {- try failRequest(token, message: line.text, error: .serverError(error.message))+ try failRequest(token, message: line.text, error: .serverError(Self.redactingProxyCredentials(error.message)))}if let result = envelope.result {return result@@ -235,11 +347,15 @@ final nonisolated class AppServerSession {}private func failRequest(_ token: UUID, message: String, error: CodexStatusError) throws -> Never {- RequestLogStorage.shared.failRequest(token, message: message)+ logStorage?.failRequest(token, message: Self.redactingProxyCredentials(message))throw error}}+private nonisolated struct InitializeResult: Decodable {+ let userAgent: String?+}+/// 先轻量读取 id, 避免把其他请求或日志行误当成本次响应private nonisolated struct RPCIDEnvelope: Decodable {let id: Int?diff --git a/CodexBar/Services/CodexStatus/CodexProxyConnectionTester.swift b/CodexBar/Services/CodexStatus/CodexProxyConnectionTester.swiftnew file mode 100644index 0000000..a50ee55--- /dev/null+++ b/CodexBar/Services/CodexStatus/CodexProxyConnectionTester.swift@@ -0,0 +1,25 @@+import Foundation++/// 独立于正式连接的探测, 所有请求共享截止时间且不写入额度交互日志+nonisolated enum CodexProxyConnectionTester {+ static func test(+ configuration: CodexProxyConfiguration,+ password: String,+ source: CodexCLISourceSelection+ ) throws {+ try Task.checkCancellation()+ let deadline = Date().addingTimeInterval(8)+ var configuration = configuration+ configuration.isEnabled = true+ let environment = try configuration.environment(overriding: CodexCLIResolver.environment, password: password)+ let command = try CodexCLIResolver.command(+ from: CodexCLIResolver.resolveInstallations(),+ source: source.source+ )+ let session = try AppServerSession.launch(command: command, environment: environment, timeout: 8, deadline: deadline, usesCustomProxy: true)+ defer { session.close() }+ _ = try session.initializeAccount()+ _ = try session.request("account/rateLimits/read", as: AccountRateLimitsResponse.self)+ try Task.checkCancellation()+ }+}diff --git a/CodexBar/Services/CodexStatus/CodexStatusService.swift b/CodexBar/Services/CodexStatus/CodexStatusService.swiftindex 6e13a9e..7fee265 100644--- a/CodexBar/Services/CodexStatus/CodexStatusService.swift+++ b/CodexBar/Services/CodexStatus/CodexStatusService.swift@@ -1,12 +1,21 @@import Foundationimport os-/// UI 只关心可展示数据, 未登录, 初始化失败; 更细的错误保留在交互日志中+/// 刷新结果携带连接失败原因, 请求响应细节保留在交互日志中nonisolated enum CodexFetchOutcome {case data(CodexQuotaSnapshot)case notLoggedIncase unsupportedVersion(minimum: String)- case initializationFailed+ case initializationFailed(message: String)++ var connectionErrorMessage: String? {+ switch self {+ case .data: nil+ case .notLoggedIn: CodexStatusError.notLoggedIn.localizedDescription+ case let .unsupportedVersion(minimum): CodexStatusError.unsupportedVersion(minimum: minimum).localizedDescription+ case let .initializationFailed(message): message+ }+ }}/// 一次刷新里各步的结果分类, 只用于日志@@ -50,7 +59,7 @@ private nonisolated enum ConnectionResolution {case ready(connection: AppServerConnection, reused: Bool)case notLoggedIncase unsupportedVersion(minimum: String)- case initializationFailed+ case initializationFailed(message: String)}// 单接口读取结果按后续动作分类: 跳过, 刷新认证, 重建连接@@ -151,6 +160,33 @@ actor CodexStatusService {_ = Self.ignoreBrokenPipeSignal}+ func applyProxy(_ configuration: CodexProxyConfiguration?, password: String) throws {+ try CodexProxyStore.save(configuration, password: password, to: defaults)+ // actor 内提交设置并回收旧进程, 后续所有业务入口统一按新配置建立连接+ teardownConnection()+ supplementalDataCache = SupplementalDataCache()+ }++ private func openConfiguredConnection(command: AppServerCommand) throws -> ConnectionResolution {+ let stored = try CodexProxyStore.load(from: defaults)+ let configuration = stored?.configuration+ let usesCustomProxy = configuration?.isEnabled == true+ let environment: [String: String] = if let configuration, usesCustomProxy {+ try configuration.environment(+ overriding: Self.environment,+ password: stored?.password ?? ""+ )+ } else {+ Self.environment+ }+ return Self.openConnection(+ command: command,+ environment: environment,+ timeout: Self.requestTimeout,+ usesCustomProxy: usesCustomProxy+ )+ }+// MARK: - 对外入口func fetchOutcome() async -> CodexFetchResult {@@ -176,22 +212,19 @@ actor CodexStatusService {try readyConnection().commandInfo}- /// 新连接完成握手和账户校验后才替换旧连接, 失败时继续保留原会话+ /// 重连先关闭旧会话, 新连接失败时保持断开func reconnect(selection: CodexCLISourceSelection? = nil,minimumVersion: String) throws -> CodexCLIConnectionInfo {+ teardownConnection()+ supplementalDataCache = SupplementalDataCache()let requestedSelection = selection ?? sourceSelectionlet command = try CodexCLIResolver.command(from: CodexCLIResolver.resolveInstallations(environment: Self.environment),source: requestedSelection.source)- let resolution = Self.openConnection(- command: command,- environment: Self.environment,- clientVersion: Self.clientVersion(),- timeout: Self.requestTimeout- )+ let resolution = try openConfiguredConnection(command: command)switch resolution {case let .ready(candidate, _):guard let version = candidate.commandInfo.version,@@ -200,13 +233,10 @@ actor CodexStatusService {throw CodexStatusError.unsupportedVersion(minimum: minimumVersion)}- let previous = connectionconnection = candidatesourceSelection = requestedSelectionsourceSelection.save(to: defaults)- supplementalDataCache = SupplementalDataCache()lastResolvedSource = command.source- previous?.close()AppLog.codexCLI.notice("Codex 连接已切换: source=\(command.source.rawValue, privacy: .public)")return candidate.commandInfocase .notLoggedIn:@@ -308,9 +338,9 @@ actor CodexStatusService {case let .unsupportedVersion(minimum):trace.failureStage = .connectreturn .unsupportedVersion(minimum: minimum)- case .initializationFailed:+ case let .initializationFailed(message):trace.failureStage = .connect- return .initializationFailed+ return .initializationFailed(message: message)case let .ready(connection, reused):trace.connection = reused ? .reused : .newdo {@@ -330,10 +360,10 @@ actor CodexStatusService {AppLog.app.notice("codex 连接已失效: reason=transportError")return resolveOutcome(allowRebuild: false, trace: &trace)}- return .initializationFailed+ return .initializationFailed(message: CodexStatusError.serverConnectionClosed.localizedDescription)} catch {teardownConnection()- return .initializationFailed+ return .initializationFailed(message: CodexStatusError.serverConnectionClosed.localizedDescription)}}}@@ -426,7 +456,7 @@ actor CodexStatusService {)AppLog.app.error("codex 连接失败: \(details, privacy: .public)")RequestLogStorage.shared.recordFailure(message: error.localizedDescription)- return .initializationFailed+ return .initializationFailed(message: error.localizedDescription)}// 可执行文件路径含用户名, 只记来源分类@@ -438,12 +468,16 @@ actor CodexStatusService {)}- let resolution = Self.openConnection(- command: command,- environment: Self.environment,- clientVersion: Self.clientVersion(),- timeout: Self.requestTimeout- )+ let resolution: ConnectionResolution+ do {+ resolution = try openConfiguredConnection(command: command)+ } catch let error as CodexProxyError {+ AppLog.settings.error("\(error.localizedDescription, privacy: .public)")+ return .initializationFailed(message: error.localizedDescription)+ } catch {+ RequestLogStorage.shared.recordFailure(message: error.localizedDescription)+ return .initializationFailed(message: error.localizedDescription)+ }switch resolution {case let .ready(newConnection, _):connection = newConnection@@ -700,26 +734,17 @@ actor CodexStatusService {private static func openConnection(command: AppServerCommand,environment: [String: String],- clientVersion: String,- timeout: TimeInterval+ timeout: TimeInterval,+ usesCustomProxy: Bool) -> ConnectionResolution {- let process = Process()- process.executableURL = URL(fileURLWithPath: command.executablePath)- process.arguments = command.arguments- process.environment = environment-- let standardInput = Pipe()- let standardOutput = Pipe()- let standardError = Pipe()- let lineReader = JSONLineReader(fileHandle: standardOutput.fileHandleForReading)- let errorReader = PipeDrain(fileHandle: standardError.fileHandleForReading)-- process.standardInput = standardInput- process.standardOutput = standardOutput- process.standardError = standardError-+ let session: AppServerSessiondo {- try process.run()+ session = try AppServerSession.launch(+ command: command,+ environment: environment,+ timeout: timeout,+ usesCustomProxy: usesCustomProxy+ )} catch {RequestLogStorage.shared.recordFailure(message: String(@@ -727,22 +752,13 @@ actor CodexStatusService {defaultValue: "\(error.localizedDescription)"))- return .initializationFailed+ return .initializationFailed(message: CodexStatusError.serverConnectionClosed.localizedDescription)}let openedAt = Date()- let session = AppServerSession(- process: process,- input: standardInput,- lineReader: lineReader,- errorReader: errorReader,- timeout: timeout- )-return initializeConnection(session: session,command: command,- clientVersion: clientVersion,openedAt: openedAt)}@@ -750,57 +766,31 @@ actor CodexStatusService {private static func initializeConnection(session: AppServerSession,command: AppServerCommand,- clientVersion: String,openedAt: Date) -> ConnectionResolution {do {- let initializeResult = try session.request(- "initialize",- params: [- "clientInfo": [- "name": "codex_bar",- "title": "Codex Bar",- "version": clientVersion- ]- ],- as: InitializeResult.self- )-- guard let serverVersion = Self.validatedServerVersion(- fromUserAgent: initializeResult.userAgent- ) else {- session.close()- return .unsupportedVersion(minimum: CodexCLIMinimumVersion.global)- }-- try session.notify("initialized")-- let accountResponse = try session.request(- "account/read",- params: ["refreshToken": false],- as: AccountReadResponse.self- )-- guard accountResponse.account != nil else {- session.close()- return .notLoggedIn- }-+ let initialized = try session.initializeAccount()let commandInfo = CodexCLIConnectionInfo(source: command.source,executablePath: command.executablePath,- version: serverVersion,+ version: initialized.version,openedAt: openedAt)return .ready(connection: AppServerConnection(session: session,- accountResponse: accountResponse,+ accountResponse: initialized.account,commandInfo: commandInfo),reused: false)+ } catch CodexStatusError.notLoggedIn {+ session.close()+ return .notLoggedIn+ } catch let CodexStatusError.unsupportedVersion(minimum) {+ session.close()+ return .unsupportedVersion(minimum: minimum)} catch {// app-server 链路的细节按既有分工进日志窗口, 不重复写系统日志RequestLogStorage.shared.recordFailure(@@ -810,46 +800,8 @@ actor CodexStatusService {))session.close()- return .initializationFailed- }- }-- private nonisolated static func clientVersion() -> String {- guard let version = Bundle.main.shortVersionString, !version.isEmpty else {- return "1.0.0"+ return .initializationFailed(message: CodexStatusError.serverConnectionClosed.localizedDescription)}-- return version- }-- private nonisolated static func validatedServerVersion(fromUserAgent userAgent: String?) -> String? {- let version = serverVersion(fromUserAgent: userAgent)- let minimumVersion = CodexCLIMinimumVersion.global- guard let version,- CodexCLIVersionReader.isVersion(version, atLeast: minimumVersion) == true else {- let details = LogFields.joined(- "current=\(version ?? "unknown")",- "minimum=\(minimumVersion)"- )- AppLog.codexCLI.notice("Codex 版本不支持: \(details, privacy: .public)")- RequestLogStorage.shared.recordFailure(- message: CodexStatusError.unsupportedVersion(minimum: minimumVersion).localizedDescription- )- return nil- }-- return version- }-- /// userAgent 形如 "codex_bar/0.139.0 (...)"; 取首个 token 中 "/" 之后的运行版本号- private nonisolated static func serverVersion(fromUserAgent userAgent: String?) -> String? {- guard let firstToken = userAgent?.split(separator: " ").first,- let slashIndex = firstToken.firstIndex(of: "/") else {- return nil- }-- let version = firstToken[firstToken.index(after: slashIndex)...]- return version.isEmpty ? nil : String(version)}}@@ -887,7 +839,3 @@ private final nonisolated class AppServerConnection {session.close()}}--private nonisolated struct InitializeResult: Decodable {- let userAgent: String?-}diff --git a/CodexBar/Services/CodexStatus/CodexStatusViewModel.swift b/CodexBar/Services/CodexStatus/CodexStatusViewModel.swiftindex 298584f..ad241ac 100644--- a/CodexBar/Services/CodexStatus/CodexStatusViewModel.swift+++ b/CodexBar/Services/CodexStatus/CodexStatusViewModel.swift@@ -136,6 +136,8 @@ final class CodexStatusViewModel: ObservableObject {)codexConnectionInfo = result.connectionInfocodexSourceSelection = result.selection+ connectionErrorMessage = result.fetch.outcome.connectionErrorMessage+ unavailableConnectionSource = nilautoRefreshCountdownStartedAt = Date()})@@ -249,6 +251,9 @@ final class CodexStatusViewModel: ObservableObject {}pendingCodexSourceSelection = selection ?? codexSourceSelection+ codexConnectionInfo = nil+ snapshot = nil+ loadState = .loadingconnectionErrorMessage = nilunavailableConnectionSource = nilconnectionInfoGeneration &+= 1@@ -268,15 +273,22 @@ final class CodexStatusViewModel: ObservableObject {minimumVersion: requiresHooks ? CodexCLIMinimumVersion.hook : CodexCLIMinimumVersion.global)codexSourceSelection = await service.currentSourceSelection()- snapshot = nil- loadState = .loadingdidReconnect = truereturn true- } catch let CodexStatusError.sourceUnavailable(source) {- unavailableConnectionSource = source- return false} catch {- connectionErrorMessage = error.localizedDescription+ loadState = switch error {+ case CodexStatusError.notLoggedIn: .notLoggedIn+ case let CodexStatusError.unsupportedVersion(minimum): .unsupportedVersion(minimum: minimum)+ default: .initializationFailed+ }+ if case let CodexStatusError.sourceUnavailable(source) = error {+ unavailableConnectionSource = source+ } else {+ connectionErrorMessage = error.localizedDescription+ }+ if let error = error as? CodexProxyError {+ AppLog.settings.error("\(error.localizedDescription, privacy: .public)")+ }return false}}diff --git a/CodexBar/Services/Settings/CodexProxySettings.swift b/CodexBar/Services/Settings/CodexProxySettings.swiftnew file mode 100644index 0000000..8349f22--- /dev/null+++ b/CodexBar/Services/Settings/CodexProxySettings.swift@@ -0,0 +1,223 @@+import Combine+import Foundation++@MainActor+final class CodexProxySettings: ObservableObject {+ enum TestResult: Equatable {+ case success+ case validation(CodexProxyConfiguration.ValidationIssue)+ case authenticationRequired+ case loginRequired+ case timeout+ case codexUnavailable+ case failed+ case loadFailed+ case saveFailed+ case clearFailed++ var title: String {+ switch self {+ case .success: String(localized: "proxy.test.connected")+ case let .validation(issue): issue.title+ case .authenticationRequired: String(localized: "proxy.test.proxy-authentication-failed")+ case .loginRequired: String(localized: "proxy.test.codex-login-required")+ case .timeout: String(localized: "proxy.test.timed-out")+ case .codexUnavailable: String(localized: "proxy.test.codex-unavailable")+ case .failed: String(localized: "proxy.test.connection-failed")+ case .loadFailed: String(localized: "proxy.feedback.load-failed")+ case .saveFailed: String(localized: "proxy.feedback.save-failed")+ case .clearFailed: String(localized: "proxy.feedback.clear-failed")+ }+ }++ static func failure(for error: Error) -> Self {+ guard let error = error as? CodexStatusError else { return .failed }+ if error.isAuthenticationRequired {+ return .loginRequired+ }+ switch error {+ case .serverTimeout:+ return .timeout+ case .executableNotFound, .sourceUnavailable, .unsupportedVersion, .unsupportedMethod:+ return .codexUnavailable+ case let .serverError(message):+ let message = message.lowercased()+ if message.contains("proxy authentication required") {+ return .authenticationRequired+ }+ if message.contains("401 unauthorized") {+ return .loginRequired+ }+ if message.contains("timed out") || message.contains("timeout") {+ return .timeout+ }+ return .failed+ default:+ return .failed+ }+ }+ }++ @Published private(set) var configuration: CodexProxyConfiguration?+ @Published private(set) var hasStoredConfiguration: Bool+ @Published var draft = CodexProxyConfiguration()+ @Published var password = ""+ @Published private(set) var isSaving = false+ @Published private(set) var testResult: TestResult?+ @Published private(set) var showsValidationErrors = false++ private let service: CodexStatusService+ private let defaults: UserDefaults+ @Published private var testTask: Task<Void, Never>?++ var isTesting: Bool {+ testTask != nil+ }++ init(service: CodexStatusService, defaults: UserDefaults = .standard) {+ self.service = service+ self.defaults = defaults+ hasStoredConfiguration = CodexProxyStore.containsConfiguration(in: defaults)+ configuration = try? CodexProxyStore.load(from: defaults)?.configuration+ }++ var invalidFields: Set<CodexProxyConfiguration.InputField> {+ Set(validationIssues.map(\.field))+ }++ var validationIssues: [CodexProxyConfiguration.ValidationIssue] {+ showsValidationErrors ? draft.validationIssues : []+ }++ var feedback: TestResult? {+ if let issue = validationIssues.first {+ return .validation(issue)+ }+ return testResult+ }++ func loadDraft(showValidationErrors: Bool = false) {+ showsValidationErrors = showValidationErrors+ cancelTest()+ password = ""+ hasStoredConfiguration = CodexProxyStore.containsConfiguration(in: defaults)+ do {+ let stored = try CodexProxyStore.load(from: defaults)+ configuration = stored?.configuration+ draft = configuration ?? CodexProxyConfiguration()+ password = stored?.password ?? ""+ } catch {+ configuration = nil+ draft = CodexProxyConfiguration()+ testResult = .loadFailed+ }+ }++ func draftChanged() {+ cancelTest()+ }++ func closeDraft() {+ showsValidationErrors = false+ cancelTest()+ password = ""+ }++ func cancelTest() {+ testTask?.cancel()+ testTask = nil+ testResult = nil+ }++ func testConnection(source: CodexCLISourceSelection) {+ cancelTest()+ showsValidationErrors = true+ guard validationIssues.isEmpty else { return }+ let configuration = draft+ let password = password+ testTask = Task { [weak self] in+ guard !Task.isCancelled else { return }+ let worker = Task.detached {+ try CodexProxyConnectionTester.test(configuration: configuration, password: password, source: source)+ }+ do {+ try await withTaskCancellationHandler {+ try await worker.value+ } onCancel: {+ worker.cancel()+ }+ guard let self, !Task.isCancelled else { return }+ testResult = .success+ } catch {+ guard let self, !Task.isCancelled else { return }+ testResult = TestResult.failure(for: error)+ }+ guard let self, !Task.isCancelled else { return }+ testTask = nil+ }+ }++ func setEnabled(_ enabled: Bool, onCompletion: @escaping (Bool) -> Void) {+ guard !isSaving else { return }+ showsValidationErrors = false+ do {+ guard let stored = try CodexProxyStore.load(from: defaults) else {+ onCompletion(false)+ return+ }+ var configuration = stored.configuration+ if enabled, !configuration.validationIssues.isEmpty {+ loadDraft(showValidationErrors: true)+ onCompletion(false)+ return+ }+ configuration.isEnabled = enabled+ // 在创建异步任务前提交显示状态并锁定开关, 连续点击不会重复排队+ isSaving = true+ self.configuration = configuration+ Task {+ let succeeded: Bool+ do {+ try await service.applyProxy(configuration, password: stored.password)+ hasStoredConfiguration = true+ draft.isEnabled = enabled+ succeeded = true+ } catch {+ self.configuration = stored.configuration+ succeeded = false+ }+ isSaving = false+ onCompletion(succeeded)+ }+ } catch {+ onCompletion(false)+ }+ }++ func save(clear: Bool = false) async -> Bool {+ guard !isSaving else { return false }+ cancelTest()+ if !clear {+ showsValidationErrors = true+ guard validationIssues.isEmpty else { return false }+ } else {+ showsValidationErrors = false+ }+ isSaving = true+ defer { isSaving = false }+ do {+ let configuration = clear ? nil : try draft.validated()+ try await service.applyProxy(configuration, password: password)+ self.configuration = configuration+ hasStoredConfiguration = configuration != nil+ if clear {+ draft = CodexProxyConfiguration()+ password = ""+ }+ return true+ } catch {+ testResult = clear ? .clearFailed : .saveFailed+ return false+ }+ }+}diff --git a/CodexBar/Services/Settings/CodexProxyStore.swift b/CodexBar/Services/Settings/CodexProxyStore.swiftnew file mode 100644index 0000000..0130d33--- /dev/null+++ b/CodexBar/Services/Settings/CodexProxyStore.swift@@ -0,0 +1,41 @@+import Foundation++/// 代理配置和密码作为一条本机偏好保存, 不参与云同步+nonisolated enum CodexProxyStore {+ private static let configurationKey = "CodexProxy.configuration"++ struct StoredConfiguration: Codable {+ let configuration: CodexProxyConfiguration+ let password: String+ }++ static func containsConfiguration(in defaults: UserDefaults) -> Bool {+ defaults.object(forKey: configurationKey) != nil+ }++ static func save(_ configuration: CodexProxyConfiguration?, password: String, to defaults: UserDefaults) throws {+ guard let configuration else {+ defaults.removeObject(forKey: configurationKey)+ return+ }+ // 停用时保留原始字段, 无效配置也必须能够关闭+ let stored = try StoredConfiguration(+ configuration: configuration.isEnabled ? configuration.validated() : configuration,+ password: configuration.usesAuthentication ? password : ""+ )+ try defaults.set(JSONEncoder().encode(stored), forKey: configurationKey)+ }++ static func load(from defaults: UserDefaults) throws -> StoredConfiguration? {+ guard containsConfiguration(in: defaults) else { return nil }+ guard let data = defaults.data(forKey: configurationKey),+ let stored = try? JSONDecoder().decode(StoredConfiguration.self, from: data) else {+ throw CodexProxyError.invalidStoredConfiguration+ }+ // 读取时保留原始输入, 让设置窗口能够回填并修正无效配置+ return StoredConfiguration(+ configuration: stored.configuration,+ password: stored.configuration.usesAuthentication ? stored.password : ""+ )+ }+}diff --git a/CodexBar/Services/Settings/WorkflowSyncSettings.swift b/CodexBar/Services/Settings/WorkflowSyncSettings.swiftindex 5dd1798..fcf9505 100644--- a/CodexBar/Services/Settings/WorkflowSyncSettings.swift+++ b/CodexBar/Services/Settings/WorkflowSyncSettings.swift@@ -45,9 +45,7 @@ final class WorkflowSyncSettings: ObservableObject {AppLog.sync.notice("同步开关变更: enabled=\(enabled ? 1 : 0)")}defaults.set(enabled, forKey: Self.enabledKey)- if enabled {- defaults.set(true, forKey: Self.needsBackfillKey)- } else {+ if !enabled {clearSyncActivity()}isEnabled = enabled@@ -102,14 +100,6 @@ final class WorkflowSyncSettings: ObservableObject {defaults.bool(forKey: enabledKey)}- nonisolated static func needsBackfill(defaults: UserDefaults = .standard) -> Bool {- defaults.bool(forKey: needsBackfillKey)- }-- nonisolated static func clearBackfillRequest(defaults: UserDefaults = .standard) {- defaults.set(false, forKey: needsBackfillKey)- }-private func observeSyncNotifications() {NotificationCenter.default.publisher(for: .workflowSyncDidStart).sink { [weak self] _ in@@ -208,7 +198,6 @@ final class WorkflowSyncSettings: ObservableObject {}private nonisolated static let enabledKey = "WorkflowSync.isEnabled"- private nonisolated static let needsBackfillKey = "WorkflowSync.needsBackfill"}/// 同步没生效时缺的是哪一项, 同时充当日志里的 reason= 取值diff --git a/CodexBar/Services/Workflow/WorkflowSyncService.swift b/CodexBar/Services/Workflow/WorkflowSyncService.swiftindex 5310d05..03597a7 100644--- a/CodexBar/Services/Workflow/WorkflowSyncService.swift+++ b/CodexBar/Services/Workflow/WorkflowSyncService.swift@@ -116,7 +116,6 @@ actor WorkflowSyncService {)stage = .upload- let forceBackfill = WorkflowSyncSettings.needsBackfill()let confirmedDates = try await uploadChangedAggregates(localByDate: localByDate,remoteRecords: loadCachedRecords(),@@ -124,8 +123,6 @@ actor WorkflowSyncService {)try finalizeUpload(confirmedDates: confirmedDates,- localByDate: localByDate,- forceBackfill: forceBackfill,state: &state)@@ -229,8 +226,6 @@ actor WorkflowSyncService {private func finalizeUpload(confirmedDates: Set<String>,- localByDate: [String: LocalSyncAggregate],- forceBackfill: Bool,state: inout WorkflowSyncState) throws {let completedReplacementDates = Set(state.replacementDates).intersection(confirmedDates)@@ -238,11 +233,6 @@ actor WorkflowSyncService {state.replacementDates.removeAll { completedReplacementDates.contains($0) }try saveState(state)}-- if forceBackfill,- backfillCompleted(localByDate: localByDate, confirmedDates: confirmedDates) {- WorkflowSyncSettings.clearBackfillRequest()- }}private func resetStateIfDeviceChanged(@@ -275,13 +265,6 @@ actor WorkflowSyncService {}}- private func backfillCompleted(- localByDate: [String: LocalSyncAggregate],- confirmedDates: Set<String>- ) -> Bool {- localByDate.keys.allSatisfy(confirmedDates.contains)- }-private func snapshot(from state: WorkflowSyncState) -> WorkflowSyncSnapshot {guard let deviceId = state.deviceId else {return .disabled@@ -416,7 +399,6 @@ private extension WorkflowSyncService {}let pendingUploads = makePendingUploads(- for: Set(localByDate.keys),localByDate: localByDate,localHashByDate: localHashByDate,state: state@@ -545,14 +527,12 @@ private extension WorkflowSyncService {/// hash 由调用方一次算好传进来, 这里只做筛选func makePendingUploads(- for candidateDates: Set<String>,localByDate: [String: LocalSyncAggregate],localHashByDate: [String: String],state: WorkflowSyncState) -> [PendingUpload] {- candidateDates.compactMap { date in- guard let local = localByDate[date],- let hash = localHashByDate[date],+ localByDate.compactMap { date, local in+ guard let hash = localHashByDate[date],state.hashByDate[date] != hash else {return nil}diff --git a/CodexBar/Views/Menu/CodexStatusMenuView.swift b/CodexBar/Views/Menu/CodexStatusMenuView.swiftindex a3e9def..daaaa3b 100644--- a/CodexBar/Views/Menu/CodexStatusMenuView.swift+++ b/CodexBar/Views/Menu/CodexStatusMenuView.swift@@ -39,7 +39,6 @@ struct CodexStatusMenuView: View {let onUsageHeatmapHoverChange: (UsageHeatmapHoverContext?) -> Voidlet onResetCreditsTap: (ResetCreditsPanelContext) -> Voidlet onActivityCenterTap: (CodexActivityCenterPanelContext) -> Void- @Environment(\.accessibilityReduceMotion) private var accessibilityReduceMotion@EnvironmentObject private var appUpdater: AppUpdatervar body: some View {@@ -48,7 +47,7 @@ struct CodexStatusMenuView: View {}.environment(\.mainPanelEntranceAnimationsEnabled,- mainPanelSettings.areEntranceAnimationsEnabled && !accessibilityReduceMotion+ mainPanelSettings.areEntranceAnimationsEnabled).padding(Metrics.padding).liquidGlassSurface(cornerRadius: Metrics.surfaceCornerRadius, isOuterSurface: true)diff --git a/CodexBar/Views/Settings/AppSettingsView.swift b/CodexBar/Views/Settings/AppSettingsView.swiftindex 52f1030..fcaa052 100644--- a/CodexBar/Views/Settings/AppSettingsView.swift+++ b/CodexBar/Views/Settings/AppSettingsView.swift@@ -7,6 +7,8 @@ struct AppSettingsView: View {@EnvironmentObject private var appUpdater: AppUpdater@StateObject private var loginItemSettings = LoginItemSettings()@StateObject private var codexVersions = CodexCLIVersionViewModel()+ @ObservedObject var proxySettings: CodexProxySettings+ @State private var isShowingProxySettings = false@ObservedObject var codexHookSettings: CodexHookSettings@ObservedObject var syncSettings: WorkflowSyncSettings@ObservedObject var globalHotKeySettings: GlobalHotKeySettings@@ -71,6 +73,11 @@ struct AppSettingsView: View {),isOuterSurface: true)+ .sheet(isPresented: $isShowingProxySettings) {+ ProxySettingsView(source: statusViewModel.codexSourceSelection, settings: proxySettings) {+ statusViewModel.refreshAfterCurrent(trigger: .settings)+ }+ }.onAppear {loginItemSettings.refresh()syncSettings.refresh()@@ -153,6 +160,7 @@ private extension AppSettingsView {static let tabBarHeight: CGFloat = 38static let tabBarPadding: CGFloat = 4static let tabSpacing: CGFloat = 4+ static let tabCornerRadius: CGFloat = 6static let tabVerticalPadding: CGFloat = 7static let tabContentSpacing = paddingstatic let windowChromeHeight = padding * 2 + tabBarHeight + tabContentSpacing@@ -177,6 +185,7 @@ private extension AppSettingsView {HStack(spacing: Metrics.tabSpacing) {ForEach(SettingsTab.allCases) { tab inlet isSelected = selectedTab == tab+ let shape = RoundedRectangle(cornerRadius: Metrics.tabCornerRadius, style: .continuous)Button {selectSettingsTab(tab)@@ -191,12 +200,12 @@ private extension AppSettingsView {.font(.subheadline.weight(.medium)).frame(maxWidth: .infinity).padding(.vertical, Metrics.tabVerticalPadding)- .contentShape(Capsule(style: .continuous))+ .contentShape(shape).background {if isSelected {- Capsule(style: .continuous)+ shape.fill(.clear)- .liquidGlassCapsule(tint: .accentColor)+ .liquidGlassBadge(tint: .accentColor, in: shape)}}}@@ -258,6 +267,11 @@ private extension AppSettingsView {var advancedSettingsPage: some View {VStack(alignment: .leading, spacing: Metrics.rowSpacing) {+ ProxySettingsRow(settings: proxySettings) {+ onOptionsAction(.closeAll)+ isShowingProxySettings = true+ }+ LiquidGlassDivider()codexHookRowLiquidGlassDivider()notificationRowdiff --git a/CodexBar/Views/Settings/CodexSourcePicker.swift b/CodexBar/Views/Settings/CodexSourcePicker.swiftindex a45dfde..a3ba2af 100644--- a/CodexBar/Views/Settings/CodexSourcePicker.swift+++ b/CodexBar/Views/Settings/CodexSourcePicker.swift@@ -2,28 +2,45 @@ import AppKitimport QuartzCoreimport SwiftUI-/// 开合和悬停状态留在选择器内部, 避免交互时重新计算整个版本区struct CodexSourcePicker: View {let selection: CodexCLISourceSelectionlet options: [CodexCLISourceSelection]let isEnabled: Boollet onSelect: (CodexCLISourceSelection) -> Void- @State private var isHovered = false- @State private var isPresented = false- @Environment(\.accessibilityReduceMotion) private var reduceMotion- private var title: String {- options.contains(selection) ? selection.title : String(localized: "settings.codex-version.source.select")+ var body: some View {+ SettingsDropdownPicker(+ selection: selection,+ options: options,+ isEnabled: isEnabled,+ title: options.contains(selection) ? selection.title : String(localized: "settings.codex-version.source.select"),+ optionTitle: { $0.title },+ onSelect: onSelect+ )}+}++/// 开合和悬停状态留在选择器内部, 避免交互时重新计算整个设置区域+struct SettingsDropdownPicker<Option: Hashable & Sendable>: View {+ let selection: Option+ let options: [Option]+ let isEnabled: Bool+ let title: String+ var height: CGFloat = SettingsRowMetrics.optionsButtonSize+ let optionTitle: (Option) -> String+ let onSelect: (Option) -> Void+ @State private var isHovered = false+ @State private var isPresented = falsevar body: some View {+ let shape = RoundedRectangle(cornerRadius: 5, style: .continuous)Button {isPresented.toggle()} label: {HStack(spacing: 6) {ZStack(alignment: .leading) {- ForEach(options) { option in- Text(option.title).hidden()+ ForEach(options, id: \.self) { option in+ Text(optionTitle(option)).hidden()}Text(title).foregroundStyle(isEnabled ? .primary : .secondary)@@ -35,32 +52,30 @@ struct CodexSourcePicker: View {.font(.system(size: 9, weight: .semibold)).foregroundStyle(.secondary).rotationEffect(.degrees(isPresented ? 180 : 0))- .animation(reduceMotion ? nil : .codexStatus, value: isPresented)- .accessibilityHidden(true)+ .animation(.codexStatus, value: isPresented)}.padding(.horizontal, 8)- .frame(height: SettingsRowMetrics.optionsButtonSize)+ .frame(height: height).background {- Capsule(style: .continuous)+ shape.fill(.primary.opacity((isHovered || isPresented) && isEnabled ? 0.06 : 0))- .animation(reduceMotion ? nil : .codexStatus, value: isHovered || isPresented)+ .animation(.codexStatus, value: isHovered || isPresented)}- .liquidGlassCapsule(tint: isEnabled ? .accentColor : .secondary)- .contentShape(Capsule(style: .continuous))+ .liquidGlassBadge(tint: isEnabled ? .accentColor : .secondary, in: shape)+ .contentShape(shape)}.buttonStyle(.plain).controlSize(.small).fixedSize().disabled(!isEnabled).onHover { isHovered = $0 }- .accessibilityValue(Text(title)).background {- CodexSourceDropdown(+ SettingsDropdown(isPresented: $isPresented,selection: selection,options: options,isEnabled: isEnabled,- animates: !reduceMotion,+ optionTitle: optionTitle,onSelect: onSelect)}@@ -79,13 +94,13 @@ struct CodexSourcePicker: View {}/// 浮层开合由同一处处理, 快速点击从当前呈现位置反向动画-private struct CodexSourceDropdown: NSViewRepresentable {+private struct SettingsDropdown<Option: Hashable & Sendable>: NSViewRepresentable {@Binding var isPresented: Bool- let selection: CodexCLISourceSelection- let options: [CodexCLISourceSelection]+ let selection: Option+ let options: [Option]let isEnabled: Bool- let animates: Bool- let onSelect: (CodexCLISourceSelection) -> Void+ let optionTitle: (Option) -> String+ let onSelect: (Option) -> Voidfunc makeCoordinator() -> Coordinator {Coordinator(configuration: self)@@ -113,6 +128,10 @@ private struct CodexSourceDropdown: NSViewRepresentable {final class AnchorView: NSView {var onWindowChange: (() -> Void)?+ /// Swift 6.3.3 的 EarlyPerfInliner 无法正确优化该泛型嵌套类型的合成析构函数+ @_optimize(none)+ deinit {}+override func hitTest(_: NSPoint) -> NSView? {nil}@@ -124,7 +143,7 @@ private struct CodexSourceDropdown: NSViewRepresentable {}final class Coordinator: NSObject, NSPopoverDelegate {- var configuration: CodexSourceDropdown+ var configuration: SettingsDropdownweak var anchorView: AnchorView?private let popover = NSPopover()private weak var observedWindow: NSWindow?@@ -137,7 +156,7 @@ private struct CodexSourceDropdown: NSViewRepresentable {private var isAnchorPressInProgress = falseprivate var isDisposed = false- init(configuration: CodexSourceDropdown) {+ init(configuration: SettingsDropdown) {self.configuration = configurationsuper.init()popover.delegate = self@@ -145,6 +164,10 @@ private struct CodexSourceDropdown: NSViewRepresentable {popover.animates = false}+ /// Swift 6.3.3 的 EarlyPerfInliner 无法正确优化该泛型嵌套类型的合成析构函数+ @_optimize(none)+ deinit {}+func scheduleReconcile() {guard reconcileTask == nil else { return }reconcileTask = Task { @MainActor [weak self] in@@ -185,9 +208,10 @@ private struct CodexSourceDropdown: NSViewRepresentable {}private func show(relativeTo anchor: NSView) -> Bool {- let content = CodexSourceOptions(+ let content = SettingsDropdownOptions(selection: configuration.selection,options: configuration.options,+ optionTitle: configuration.optionTitle,onSelect: { [weak self] selection inguard let self else { return }setPresented(false)@@ -225,7 +249,7 @@ private struct CodexSourceDropdown: NSViewRepresentable {// 整个窗口一起移动和淡入淡出, 避免系统边框和材质与内部图层变换不同步// animator 会从当前值转向新目标, 连续点击无需等待上一次动画结束NSAnimationContext.runAnimationGroup { context in- context.duration = configuration.animates ? 0.18 * abs(targetOpacity - window.alphaValue) : 0+ context.duration = 0.18 * abs(targetOpacity - window.alphaValue)context.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)window.animator().alphaValue = targetOpacitywindow.animator().setFrame(targetFrame, display: true)@@ -340,15 +364,16 @@ private struct CodexSourceDropdown: NSViewRepresentable {}}-private struct CodexSourceOptions: View {- let selection: CodexCLISourceSelection- let options: [CodexCLISourceSelection]- let onSelect: (CodexCLISourceSelection) -> Void- @State private var highlightedSelection: CodexCLISourceSelection?+private struct SettingsDropdownOptions<Option: Hashable & Sendable>: View {+ let selection: Option+ let options: [Option]+ let optionTitle: (Option) -> String+ let onSelect: (Option) -> Void+ @State private var highlightedSelection: Option?var body: some View {VStack(spacing: 3) {- ForEach(options) { option in+ ForEach(options, id: \.self) { option inButton {onSelect(option)} label: {@@ -358,16 +383,14 @@ private struct CodexSourceOptions: View {.foregroundStyle(.tint).opacity(option == selection ? 1 : 0).frame(width: 12)- .accessibilityHidden(true)- Text(option.title)+ Text(optionTitle(option)).font(.caption.weight(.medium)).lineLimit(1).frame(maxWidth: .infinity, alignment: .leading)Color.clear.frame(width: 12, height: 10)- .accessibilityHidden(true)}.padding(.horizontal, 8).frame(height: 28)@@ -384,7 +407,6 @@ private struct CodexSourceOptions: View {highlightedSelection = option}}- .accessibilityAddTraits(option == selection ? .isSelected : [])}}.padding(6)diff --git a/CodexBar/Views/Settings/CodexVersionSection.swift b/CodexBar/Views/Settings/CodexVersionSection.swiftindex b60d29b..c593f84 100644--- a/CodexBar/Views/Settings/CodexVersionSection.swift+++ b/CodexBar/Views/Settings/CodexVersionSection.swift@@ -22,9 +22,11 @@ struct CodexVersionSection: View {Text("settings.codex-version.title")+ reconnectButton+Spacer()- sourceSelectionControls+ sourcePicker}if !displayedItems.isEmpty {@@ -44,7 +46,6 @@ struct CodexVersionSection: View {.font(.caption).foregroundStyle(.red).fixedSize(horizontal: false, vertical: true)- .padding(.leading, Metrics.childIndent)}}.onDisappear {@@ -52,18 +53,14 @@ struct CodexVersionSection: View {}}- private var sourceSelectionControls: some View {- HStack(spacing: SettingsRowMetrics.spacing) {- CodexSourcePicker(- selection: sourceSelection,- options: availableSelections,- isEnabled: !isBusy- ) { selection in- guard !isBusy, availableSelections.contains(selection), selection != sourceSelection else { return }- onReconnect(selection)- }-- reconnectButton+ private var sourcePicker: some View {+ CodexSourcePicker(+ selection: sourceSelection,+ options: availableSelections,+ isEnabled: !isBusy+ ) { selection in+ guard !isBusy, availableSelections.contains(selection), selection != sourceSelection else { return }+ onReconnect(selection)}.frame(minHeight: SettingsRowMetrics.optionsButtonSize)}diff --git a/CodexBar/Views/Settings/ProxyPasswordField.swift b/CodexBar/Views/Settings/ProxyPasswordField.swiftnew file mode 100644index 0000000..1d5c27d--- /dev/null+++ b/CodexBar/Views/Settings/ProxyPasswordField.swift@@ -0,0 +1,160 @@+import AppKit+import QuartzCore+import SwiftUI++struct ProxyPasswordField: NSViewRepresentable {+ @Binding var text: String+ @Binding var isFocused: Bool+ let isRevealed: Bool+ @Environment(\.isEnabled) private var isEnabled++ func makeNSView(context _: Context) -> PasswordInputView {+ PasswordInputView()+ }++ func updateNSView(_ view: PasswordInputView, context _: Context) {+ view.onChange = { text = $0 }+ view.onFocusChange = { focused in+ if isFocused != focused {+ isFocused = focused+ }+ }+ view.update(text: text, isEnabled: isEnabled, isRevealed: isRevealed)+ }++ final class PasswordInputView: NSView, NSTextFieldDelegate {+ var onChange: ((String) -> Void)?+ var onFocusChange: ((Bool) -> Void)?+ private let secureField = NSSecureTextField()+ private let plainField = NSTextField()+ private var isRevealed = false+ private var lastText = ""+ private var isSwitching = false+ private var requestedReveal = false+ private var hasPendingReveal = false+ private var activeField: NSTextField {+ isRevealed ? plainField : secureField+ }++ override init(frame: NSRect) {+ super.init(frame: frame)+ wantsLayer = true+ for field in [secureField, plainField] {+ field.isBordered = false+ field.isBezeled = false+ field.drawsBackground = false+ field.focusRingType = .none+ field.font = .systemFont(ofSize: NSFont.systemFontSize)+ field.placeholderString = String(localized: "proxy.password")+ field.cell?.usesSingleLineMode = true+ field.cell?.isScrollable = true+ field.delegate = self+ addSubview(field)+ }+ plainField.isHidden = true+ }++ @available(*, unavailable)+ required init?(coder _: NSCoder) {+ fatalError()+ }++ override func layout() {+ super.layout()+ secureField.frame = bounds+ plainField.frame = bounds+ }++ func update(text: String, isEnabled: Bool, isRevealed: Bool) {+ for field in [secureField, plainField] {+ if text != lastText {+ field.stringValue = text+ }+ field.isEnabled = isEnabled+ }+ lastText = text+ requestedReveal = isRevealed && isEnabled+ guard !hasPendingReveal else { return }+ hasPendingReveal = true+ // makeFirstResponder 会同步更新 SwiftUI 焦点图, 必须离开 updateNSView 的更新周期+ // 快速悬停只应用最后一次请求, 避免排队切换过期状态+ DispatchQueue.main.async { [weak self] in+ guard let self else { return }+ hasPendingReveal = false+ setRevealed(requestedReveal)+ }+ }++ private func setRevealed(_ revealed: Bool) {+ guard revealed != isRevealed else { return }+ let editor = activeField.currentEditor() as? NSTextView+ let selection = editor?.selectedRange()+ let value = editor?.string ?? activeField.stringValue+ let hasMarkedText = editor?.hasMarkedText() == true+ isSwitching = true+ defer { isSwitching = false }++ // 两个原生控件保持挂载, 在同一轮更新中交接编辑器和选区+ // 淡化仅作用于文字所在的图层, 外部边框和焦点环不参与动画+ if !NSWorkspace.shared.accessibilityDisplayShouldReduceMotion {+ let transition = CATransition()+ transition.type = .fade+ transition.duration = 0.1+ transition.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)+ layer?.add(transition, forKey: "passwordVisibility")+ }+ // 安全编辑器不能继续输入法组合, 交接时确认现有文字并保留完整内容+ if hasMarkedText {+ editor?.unmarkText()+ }+ activeField.isHidden = true+ isRevealed = revealed+ activeField.stringValue = value+ activeField.isHidden = false+ if let selection, let window {+ window.makeFirstResponder(activeField)+ if let newEditor = activeField.currentEditor() as? NSTextView {+ let length = (newEditor.string as NSString).length+ let location = min(selection.location, length)+ newEditor.setSelectedRange(NSRange(location: location, length: min(selection.length, length - location)))+ newEditor.scrollRangeToVisible(newEditor.selectedRange())+ }+ }+ if hasMarkedText, value != lastText {+ lastText = value+ onChange?(value)+ }+ }++ func controlTextDidChange(_ notification: Notification) {+ guard !isSwitching, let field = notification.object as? NSTextField else { return }+ lastText = field.stringValue+ onChange?(field.stringValue)+ }++ func controlTextDidBeginEditing(_ notification: Notification) {+ if let field = notification.object as? NSTextField,+ let editor = field.currentEditor() as? NSTextView {+ editor.isAutomaticTextCompletionEnabled = false+ editor.isAutomaticSpellingCorrectionEnabled = false+ editor.isAutomaticTextReplacementEnabled = false+ editor.isAutomaticQuoteSubstitutionEnabled = false+ editor.isAutomaticDashSubstitutionEnabled = false+ editor.isContinuousSpellCheckingEnabled = false+ }+ updateFocus()+ }++ func controlTextDidEndEditing(_: Notification) {+ updateFocus()+ }++ private func updateFocus() {+ // 编辑器交接也会发送结束通知, 等交接完成后统一读取焦点+ Task { @MainActor [weak self] in+ guard let self else { return }+ onFocusChange?(activeField.currentEditor() != nil)+ }+ }+ }+}diff --git a/CodexBar/Views/Settings/ProxySettingsView.swift b/CodexBar/Views/Settings/ProxySettingsView.swiftnew file mode 100644index 0000000..c55f4a7--- /dev/null+++ b/CodexBar/Views/Settings/ProxySettingsView.swift@@ -0,0 +1,331 @@+import SwiftUI++struct ProxySettingsRow: View {+ @EnvironmentObject private var statusViewModel: CodexStatusViewModel+ @ObservedObject var settings: CodexProxySettings+ let action: () -> Void+ @State private var showsSaveError = false++ var body: some View {+ Group {+ if settings.configuration == nil {+ Button(action: action) {+ HStack(spacing: SettingsRowMetrics.spacing) {+ rowLabel+ Toggle("proxy.enabled", isOn: .constant(false))+ .labelsHidden()+ .toggleStyle(.switch)+ .controlSize(.small)+ .allowsHitTesting(false)+ }+ .contentShape(Rectangle())+ }+ .buttonStyle(.plain)+ } else {+ HStack(spacing: 0) {+ Button(action: action) {+ rowLabel+ .padding(.trailing, SettingsRowMetrics.spacing)+ .contentShape(Rectangle())+ }+ .buttonStyle(.plain)+ enabledToggle+ }+ }+ }+ .disabled(settings.isSaving)+ .alert("proxy.feedback.save-failed", isPresented: $showsSaveError) {+ Button("common.action.close", role: .cancel) {}+ }+ }++ private var rowLabel: some View {+ HStack(spacing: SettingsRowMetrics.spacing) {+ Image(systemName: "personalhotspot")+ .frame(width: SettingsRowMetrics.iconWidth)+ .foregroundStyle(.tint)+ Text("proxy.title")+ Spacer()+ }+ .frame(minHeight: SettingsRowMetrics.optionsButtonSize)+ }++ private var enabledToggle: some View {+ Toggle("proxy.enabled", isOn: Binding(+ get: { settings.configuration?.isEnabled == true },+ set: { enabled in+ settings.setEnabled(enabled) { succeeded in+ if succeeded {+ statusViewModel.refreshAfterCurrent(trigger: .settings)+ } else if settings.showsValidationErrors {+ action()+ } else {+ showsSaveError = true+ }+ }+ }+ ))+ .labelsHidden()+ .toggleStyle(.switch)+ .controlSize(.small)+ }+}++struct ProxySettingsView: View {+ let source: CodexCLISourceSelection+ @ObservedObject var settings: CodexProxySettings+ let onApplied: () -> Void+ @Environment(\.dismiss) private var dismiss+ @Environment(\.controlActiveState) private var controlActiveState+ @State private var showsPassword = false+ @State private var serverFieldHeight: CGFloat = 24+ @State private var isPasswordFocused = false++ var body: some View {+ VStack(alignment: .leading, spacing: 18) {+ VStack(spacing: 14) {+ configurationHeader+ LiquidGlassDivider()+ configurationFields+ LiquidGlassDivider()+ authenticationFields+ }+ .disabled(settings.isSaving)++ actions+ }+ .padding(20)+ .frame(width: 550)+ .liquidGlassSurface(cornerRadius: 16, isOuterSurface: true)+ .onAppear {+ showsPassword = false+ settings.loadDraft(showValidationErrors: settings.showsValidationErrors)+ }+ .onChange(of: settings.draft.usesAuthentication) { _, enabled in+ if !enabled {+ showsPassword = false+ }+ }+ .onDisappear {+ showsPassword = false+ settings.closeDraft()+ }+ .interactiveDismissDisabled(settings.isSaving)+ }++ private var configurationHeader: some View {+ HStack {+ Text("proxy.configuration.title")+ .font(.headline)+ Spacer()+ if settings.hasStoredConfiguration {+ Menu {+ Button(role: .destructive) {+ Task {+ if await settings.save(clear: true) {+ showsPassword = false+ dismiss()+ onApplied()+ }+ }+ } label: {+ Label("proxy.action.clear-configuration", systemImage: "trash")+ }+ } label: {+ Image(systemName: "ellipsis")+ .frame(width: SettingsRowMetrics.optionsButtonSize, height: SettingsRowMetrics.optionsButtonSize)+ .contentShape(Rectangle())+ }+ .menuStyle(.borderlessButton)+ .menuIndicator(.hidden)+ .fixedSize()+ .foregroundStyle(.secondary)+ }+ }+ }++ private func draftBinding<Value>(_ keyPath: WritableKeyPath<CodexProxyConfiguration, Value>) -> Binding<Value> {+ Binding(+ get: { settings.draft[keyPath: keyPath] },+ set: {+ settings.draftChanged()+ settings.draft[keyPath: keyPath] = $0+ }+ )+ }++ private var configurationFields: some View {+ VStack(alignment: .leading, spacing: 10) {+ HStack(spacing: 12) {+ Text("proxy.server")+ .fixedSize()+ Spacer(minLength: 0)+ HStack(spacing: 6) {+ SettingsDropdownPicker(+ selection: settings.draft.transport,+ options: CodexProxyConfiguration.Transport.allCases,+ isEnabled: !settings.isSaving,+ title: settings.draft.transport.rawValue,+ height: serverFieldHeight,+ optionTitle: { $0.rawValue },+ onSelect: { transport in+ draftBinding(\.transport).wrappedValue = transport+ }+ )+ Text(verbatim: "://")+ .foregroundStyle(.secondary)+ TextField(text: draftBinding(\.host)) {+ Text(verbatim: "127.0.0.1")+ }+ .textContentType(.URL)+ .autocorrectionDisabled()+ .frame(minWidth: 140, maxWidth: .infinity, alignment: .leading)+ .onGeometryChange(for: CGFloat.self) { $0.size.height } action: { serverFieldHeight = $0 }+ .overlay { validationBorder(for: .host) }+ Text(verbatim: ":")+ .foregroundStyle(.secondary)+ TextField(text: draftBinding(\.port)) {+ Text(verbatim: "2048")+ }+ .frame(width: 64, alignment: .leading)+ .overlay { validationBorder(for: .port) }+ }+ }+ }+ .textFieldStyle(.roundedBorder)+ }++ private var authenticationFields: some View {+ VStack(alignment: .leading, spacing: 14) {+ HStack(spacing: 12) {+ Text("proxy.authentication")+ Spacer()+ Toggle("proxy.authentication", isOn: draftBinding(\.usesAuthentication))+ .labelsHidden()+ .toggleStyle(.switch)+ .controlSize(.small)+ }+ LiquidGlassDivider()+ VStack(alignment: .leading, spacing: 12) {+ VStack(alignment: .leading, spacing: 6) {+ Text("proxy.username")+ .font(.caption.weight(.medium))+ .foregroundStyle(.secondary)+ TextField("proxy.username", text: draftBinding(\.username))+ .textContentType(.username)+ .autocorrectionDisabled()+ .overlay { validationBorder(for: .username) }+ }+ .frame(maxWidth: .infinity)+ VStack(alignment: .leading, spacing: 6) {+ Text("proxy.password")+ .font(.caption.weight(.medium))+ .foregroundStyle(.secondary)+ passwordField+ }+ .frame(maxWidth: .infinity)+ }+ .disabled(!settings.draft.usesAuthentication)+ .opacity(settings.draft.usesAuthentication ? 1 : 0.5)+ }+ .textFieldStyle(.roundedBorder)+ }++ private var passwordField: some View {+ ProxyPasswordField(+ text: passwordBinding,+ isFocused: $isPasswordFocused,+ isRevealed: showsPassword && controlActiveState != .inactive+ )+ .frame(height: max(18, serverFieldHeight - 6))+ .padding(.horizontal, 6)+ .padding(.vertical, 3)+ .contentShape(Rectangle())+ .onHover { showsPassword = $0 }+ .background(Color(nsColor: .textBackgroundColor), in: RoundedRectangle(cornerRadius: 5))+ .overlay {+ RoundedRectangle(cornerRadius: 5)+ .strokeBorder(Color(nsColor: .separatorColor), lineWidth: 1)+ .allowsHitTesting(false)+ }+ .overlay {+ if isPasswordFocused {+ RoundedRectangle(cornerRadius: 5)+ .stroke(Color.accentColor.opacity(0.5), lineWidth: 3)+ .allowsHitTesting(false)+ }+ }+ }++ private func validationBorder(for field: CodexProxyConfiguration.InputField) -> some View {+ RoundedRectangle(cornerRadius: 5)+ .strokeBorder(settings.invalidFields.contains(field) ? Color.red : Color.clear, lineWidth: 1)+ .allowsHitTesting(false)+ }++ private var passwordBinding: Binding<String> {+ Binding(+ get: { settings.password },+ set: {+ settings.draftChanged()+ settings.password = $0+ }+ )+ }++ private var testStatus: some View {+ HStack(spacing: 8) {+ Button(settings.isTesting ? "proxy.action.cancel-test" : "proxy.action.test-connection") {+ if settings.isTesting {+ settings.cancelTest()+ } else {+ settings.testConnection(source: source)+ }+ }+ .fixedSize()+ if settings.isTesting || settings.isSaving {+ ProgressView()+ .controlSize(.small)+ } else if let result = settings.feedback {+ HStack(spacing: 6) {+ Image(systemName: result == .success ? "checkmark" : "xmark")+ .font(.callout.weight(.semibold))+ .foregroundStyle(result == .success ? Color.green : Color.red)+ .frame(width: 14)+ Text(result.title)+ .font(.caption)+ .foregroundStyle(.secondary)+ .fixedSize()+ }+ }+ }+ }++ private var actions: some View {+ HStack(spacing: 0) {+ testStatus+ Spacer(minLength: 16)+ actionButtons+ }+ .disabled(settings.isSaving)+ }++ private var actionButtons: some View {+ HStack(spacing: 8) {+ Button("common.action.cancel") { dismiss() }+ .keyboardShortcut(.cancelAction)+ Button("proxy.action.save") { apply() }+ .keyboardShortcut(.defaultAction)+ }+ .fixedSize()+ }++ private func apply() {+ Task {+ if await settings.save() {+ onApplied()+ dismiss()+ }+ }+ }+}diff --git a/CodexBar/Views/Shared/LiquidGlassStyle.swift b/CodexBar/Views/Shared/LiquidGlassStyle.swiftindex 9b00fd0..4afd2fc 100644--- a/CodexBar/Views/Shared/LiquidGlassStyle.swift+++ b/CodexBar/Views/Shared/LiquidGlassStyle.swift@@ -53,8 +53,12 @@ extension View {}func liquidGlassCapsule(tint: Color) -> some View {+ liquidGlassBadge(tint: tint, in: Capsule(style: .continuous))+ }++ func liquidGlassBadge(tint: Color, in shape: some InsettableShape) -> some View {background {- LiquidGlassCapsule(tint: tint)+ LiquidGlassBadge(tint: tint, shape: shape)}}@@ -311,24 +315,25 @@ private struct LiquidGlassFrostedTexture: View {}/// 小徽章背景, 用于计划名和当前运行状态-private struct LiquidGlassCapsule: View {+private struct LiquidGlassBadge<S: InsettableShape>: View {let tint: Color+ let shape: S@Environment(\.colorScheme) private var colorSchemevar body: some View {- Capsule(style: .continuous)+ shape.fill(fillColor).overlay {LiquidGlassFrostedTexture(isOuterSurface: false)- .clipShape(Capsule(style: .continuous))+ .clipShape(shape).opacity(0.55)}.overlay {- Capsule(style: .continuous)+ shape.strokeBorder(borderColor, lineWidth: 0.8)}.overlay {- Capsule(style: .continuous)+ shape.strokeBorder(innerRimColor, lineWidth: 0.45).padding(0.8)}diff --git a/Config/Version.xcconfig b/Config/Version.xcconfigindex fcec4d9..a7c73aa 100644--- a/Config/Version.xcconfig+++ b/Config/Version.xcconfig@@ -1,2 +1,2 @@-MARKETING_VERSION = 3.6.16-CURRENT_PROJECT_VERSION = 83+MARKETING_VERSION = 3.7.0+CURRENT_PROJECT_VERSION = 84diff --git a/Docs/DeveloperGuide/README.md b/Docs/DeveloperGuide/README.mdindex e62a9e0..7122781 100644--- a/Docs/DeveloperGuide/README.md+++ b/Docs/DeveloperGuide/README.md@@ -2,56 +2,13 @@简体中文 | [English](../en/DeveloperGuide/README.md)-本指南面向希望理解 CodexBar 架构、调试数据链路或参与开发的开发者。--内容不仅描述模块做什么,还解释为什么这样划分职责,哪些失败路径是刻意保守处理,以及修改实现时必须继续维持哪些不变量。--产品功能和操作方式见 [用户指南](../UserGuide/README.md)--## 文档目标--开发者指南需要帮助读者完成 4 类工作:--- 建立系统模型,理解数据从哪里来,在哪里变成状态,最终由谁消费-- 定位修改入口,知道某个行为的唯一状态所有者和副作用边界-- 理解设计取舍,避免把看似多余的 generation, stale 标记或恢复步骤简化掉-- 验证改动,能从不变量和故障场景推导验收范围--每篇专题文档尽量按同一顺序组织:--```text-目标与约束- -> 数据或控制流- -> 状态所有权- -> 关键设计理由- -> 失败与恢复- -> 修改指南- -> 验证场景-```--## 阅读路线--第一次了解项目时,建议按以下顺序阅读:--1. [整体架构](architecture.md)-2. [设计原则与关键决策](design-decisions.md)-3. [app-server 数据链路](app-server.md)-4. [Hook 采集与历史聚合](hook-and-aggregation.md)-5. [实时任务监控](activity-monitor.md)-6. [防睡眠系统](sleep-prevention.md)-7. [CloudKit 同步](sync.md)-8. [通知系统](notifications.md)-9. [UI 与应用生命周期](ui-and-lifecycle.md)-10. [数据与隐私边界](data-and-privacy.md)-11. [开发与验证](development.md)-## 按职责查找| 文档 | 内容 || --- | --- || [整体架构](architecture.md) | 进程、模块、生命周期、actor 边界和 3 条数据链路 |-| [设计原则与关键决策](design-decisions.md) | 跨模块设计动机、系统不变量、失败优先级和实现小巧思 |-| [app-server 数据链路](app-server.md) | CLI 定位、JSON-RPC 会话、账户、额度、用量刷新和自动重置状态机 |+| [设计原则与关键决策](design-decisions.md) | 状态所有权、并发提交、数据恢复和特权边界 |+| [app-server 数据链路](app-server.md) | CLI 定位、代理配置与测试、JSON-RPC 会话、账户、额度、用量刷新和自动重置状态机 || [Hook 采集与历史聚合](hook-and-aggregation.md) | Hook 安装、事件落盘、聚合、保留期和 schema 演进 || [实时任务监控](activity-monitor.md) | 增量读取、rollout 对账、状态机和异常会话保护 || [防睡眠系统](sleep-prevention.md) | IOKit assertion、CodexBarHelper、XPC 租约、自动重置唤醒计划和恢复策略 |@@ -61,32 +18,6 @@| [数据与隐私边界](data-and-privacy.md) | 本地文件、网络访问、云端字段和日志边界 || [开发与验证](development.md) | 工程结构、构建检查、调试和变更验收 |-## 按修改目标查找--| 修改目标 | 先读 | 同时核对 |-| --- | --- | --- |-| 新增账户或用量字段 | [app-server 数据链路](app-server.md) | [数据与隐私边界](data-and-privacy.md) |-| 新增 Hook 事件或历史指标 | [Hook 采集与历史聚合](hook-and-aggregation.md) | [CloudKit 同步](sync.md) |-| 修改任务状态或 terminal 判定 | [实时任务监控](activity-monitor.md) | [通知系统](notifications.md)、[防睡眠系统](sleep-prevention.md) |-| 修改菜单、窗口或快捷键 | [UI 与应用生命周期](ui-and-lifecycle.md) | [开发与验证](development.md) |-| 修改通知触发或去重 | [通知系统](notifications.md) | 对应的数据来源专题 |-| 修改防睡眠策略或 helper | [防睡眠系统](sleep-prevention.md) | [数据与隐私边界](data-and-privacy.md) |-| 修改自动重置调度或唤醒计划 | [app-server 数据链路](app-server.md) | [防睡眠系统](sleep-prevention.md)、[数据与隐私边界](data-and-privacy.md) |-| 修改同步字段或合并规则 | [CloudKit 同步](sync.md) | [Hook 采集与历史聚合](hook-and-aggregation.md) |-| 修改持久化结构或默认值 | [开发与验证](development.md) | [设计原则与关键决策](design-decisions.md) |--## 核心设计约束--- 启动时必须先处理 `--hook-event` 模式,该模式不能初始化 UI-- app-server 额度与用量、Hook 历史聚合、实时任务监控是 3 条独立数据链路-- `CodexActivityMonitor` 是任务状态的唯一来源-- UI, Controller, ViewModel 和 Settings 默认在 `MainActor` 上运行-- 阻塞 I/O 和共享可变状态必须离开主 actor-- CodexBarHelper 只负责固定的睡眠控制和自动重置唤醒计划,不增加网络、任意命令执行或额外文件访问-- Hook 配置修改必须保留用户和其他应用已有的 handler-- 聚合语义变化必须递增聚合 schema,并从原始事件完整重建-- 缺失的 Hook 计数字段表示历史来源不可用,不能解释为明确的 `0`-## 核心术语| 术语 | 在本项目中的准确含义 |@@ -98,26 +29,9 @@| unavailable | 当前无法得到可信来源,不能等价为空或 `0` || generation | 数据源或异步操作的代际,用于拒绝迟到结果 || source generation | 某日原始 Hook 文件的来源身份,与代码 schema 不同 |-| owned | 系统状态由 CodexBar 完成切换并有权恢复 |+| owned | CodexBar 已持久化系统睡眠恢复责任 || external | 系统状态已经由 CodexBar 之外的来源设置 |-## 阅读源码的建议--先确认状态所有者,再沿消费者反向阅读。--例如修改等待批准行为时,推荐顺序是:--```text-CodexActivityTask- -> CodexActivityMonitor- -> CodexActivitySnapshot / transition- -> CodexNotificationService- -> KeepAliveController- -> SwiftUI View-```--从 View 开始搜索通常只能看到最终展示条件,容易漏掉 bootstrap、去重和恢复语义。-## 主要入口- App 启动入口:[`CodexBarApp.swift`](../../CodexBar/App/CodexBarApp.swift)diff --git a/Docs/DeveloperGuide/activity-monitor.md b/Docs/DeveloperGuide/activity-monitor.mdindex d6f81ff..507404d 100644--- a/Docs/DeveloperGuide/activity-monitor.md+++ b/Docs/DeveloperGuide/activity-monitor.md@@ -2,19 +2,6 @@简体中文 | [English](../en/DeveloperGuide/activity-monitor.md)-## 设计出发点--实时任务不是 Hook 事件的直接映射。--同一个 turn 可能出现事件缺失、迟到、重复、只有 session ID、新 prompt 覆盖旧 turn、`Stop` 与 rollout terminal 先后到达,或 App 在任务已经运行一段时间后才启动。--`CodexActivityMonitor` 的工作是把这些不完整观察合并成一个保守的任务状态机,并同时提供两种不同输出:--- snapshot 表示现在可以展示什么-- transition 表示刚刚发生了什么,可以驱动一次性副作用--如果消费者各自从 Hook 列表推断任务,菜单栏、通知和防睡眠会在边界场景下得出不同结论。-## 目标实时任务链路需要回答 4 个问题:@@ -27,9 +14,9 @@Hook 事件提供低延迟信号,rollout 文件提供权威生命周期补充。[`CodexActivityMonitor.swift`](../../CodexBar/Services/Workflow/CodexActivityMonitor.swift) 合并两者并发布唯一任务快照:```text-Hook JSONL -> HookEventTailReader -----+- +-> CodexActivityMonitor -> ActivitySnapshot-rollout JSONL -> SessionLifecycleReader++Hook JSONL -> HookEventTailReader ---------++ +-> CodexActivityMonitor -> CodexActivitySnapshot+rollout JSONL -> CodexSessionLifecycleReader+```### 两种来源的分工@@ -45,7 +32,7 @@ rollout JSONL -> SessionLifecycleReader+Hook 优先解决低延迟,rollout 优先解决语义准确性。两者不是简单按时间戳覆盖,每个字段都有自己的可信来源。-### snapshot 和 transition 为什么分开+### 快照与转场snapshot 可以在 View 重建、新消费者订阅或设置变化时反复读取。transition 只允许 live 数据产生一次。@@ -86,7 +73,7 @@ monitor 在 `.bootstrapStart` 时先清空上一次恢复态并暂停副作用中间 batch 不应让 UI 或通知看到半恢复状态。-### 稳定边界为什么要重试 3 次+### 稳定边界重试reader 在每次尝试开始时固定所有日期文件的 inode 和 size,读取到这些上界后再次验证:@@ -94,9 +81,9 @@ reader 在每次尝试开始时固定所有日期文件的 inode 和 size,读- 当前日期允许在固定上界之后继续 append- 当前自然日不能在读取期间跨过零点-任何条件不成立都从新的基线重试。连续 3 次失败后跳到当前文件末尾,是为了避免 App 永远卡在 bootstrap。代价通过 degraded health 明确传给异常保护,而不是假装成功。+任何条件不成立都从新的基线重试。连续 3 次失败后跳到当前文件末尾,并发布 degraded health,暂停异常会话保护判断。-### 为什么只推进完整行 offset+### 完整行游标Hook recorder 可能正在写最后一行。reader 只把最后一个 newline 之前的字节计入 `completeOffset`@@ -110,7 +97,7 @@ Hook recorder 可能正在写最后一行。reader 只把最后一个 newline### drainNow 读取屏障-`drainNow()` 不是普通的立即刷新提示。每个调用方必须等待一轮在本次请求之后开始的读取:+`drainNow()` 的每个调用方必须等待一轮在本次请求之后开始的读取:```text调用 drainNow@@ -158,7 +145,7 @@ resume 可能继续很早以前创建的 session。快速路径找不到时,文件被移到 archive 后,已缓存 URL 不存在会清除 cursor 并允许重新完整定位。-### rollout cursor 为什么从尾部 512 KB 开始+### Rollout 读取预算实时任务只需要活跃 turn 附近的 lifecycle,全量读取一个长期 session 会增加常驻 I/O。@@ -166,7 +153,7 @@ resume 可能继续很早以前创建的 session。快速路径找不到时,effort backfill 只针对至少运行 2 秒,尚未 terminal 且仍缺 effort 的任务,同一 turn 重试间隔 10 秒。这避免刚创建任务时立刻做大范围回查。-### 为什么只解析结构事件+### Rollout 解析字段共享的 `CodexRolloutLineEnvelope` 只提取 turn context, lifecycle 和 progress 所需字段。prompt, response 和 tool 内容不会进入活动模型。@@ -184,7 +171,7 @@ effort backfill 只针对至少运行 2 秒,尚未 terminal 且仍缺 effortsubagent 事件更新父任务的 subagent 活动,不创建独立顶层任务卡片。-### 身份选择为什么按精度降级+### 身份精度与回退`session ID + turn ID` 能精确区分同一 session 中顺序执行的 turn,是首选身份。@@ -207,11 +194,11 @@ subagent 事件更新父任务的 subagent 活动,不创建独立顶层任务明确的 `main` 或 `auxiliary` 事件随后命中同一 key 时,来源事实优先并清除这条忽略记忆。Auto-review 事件缺少 turn ID 时只忽略当前事件,不建立 session 级黑名单。-其他 subagent 统一归类为 `auxiliary` 并保持原有行为,Memories 不因这项规则改变。原始 Hook 事件仍进入历史聚合,因此实时任务过滤不会改变统计或 CloudKit 数据。+其他 subagent(包括 Memories)归类为 `auxiliary`,按辅助任务事件参与关联。原始 Hook 事件仍进入历史聚合,实时 Auto-review 过滤不改变统计或 CloudKit 数据。-JSONL 中缺少 `origin` 或来源枚举无法识别时,来源字段先解码为 `unknown`。如果同一记录的 model 精确匹配 `codex-auto-review`,事件模型将 `origin` 归一化为 `.autoReview`;其他记录保持 `.unknown`。monitor 只回放最近 24 小时,不扫描历史 rollout,也不回写原始 Hook 记录。+JSONL 中缺少 `origin` 或来源枚举无法识别时,来源字段先解码为 `unknown`。同一记录的 model 精确匹配 `codex-auto-review` 时,事件模型将来源归一化为 `.autoReview`;其他记录保持 `.unknown`。这一步只使用记录已有字段,不为来源分类额外扫描历史 rollout,也不回写原始 Hook 记录。-### 为什么新 prompt 不直接把旧 turn 判为中断+### 新 prompt 与终态宽限同一 session 的 turn 顺序执行。新 prompt 到来时旧 turn 必须立即离开活跃列表,否则 UI 会短暂显示两个顶层任务。@@ -248,19 +235,6 @@ JSONL 中缺少 `origin` 或来源枚举无法识别时,来源字段先解码匿名任务不向通知消费者发布等待批准或完成 transition、不触发任务触觉反馈、不进入 KeepAlive 的运行中或等待任务集合、不参与异常会话保护。`activityProtectionIdentifier` 对匿名 key 返回 nil,保护状态文件不会保存匿名任务记录。-### 为什么匿名任务仍保留在 UI--缺少 session ID 不等于任务不存在。完全丢弃会让用户看到 Codex 正在工作,CodexBar 却显示空闲。--保留 UI 展示同时禁止高影响副作用,是对不确定身份的分层处理:--- 可见性错误可以由后续事件自动修正-- 错误通知会打扰用户-- 错误防睡眠可能持续数小时-- 持久化匿名 project key 可能压制未来另一个真实任务--因此匿名任务使用橙色虚线人物图标明确表达能力受限,而不是伪装成普通精确任务。-## 状态机内部活动任务主要有以下状态:@@ -294,7 +268,7 @@ JSONL 中缺少 `origin` 或来源枚举无法识别时,来源字段先解码| running | 静默超过阈值 | suppressed | 隐藏并退出防睡眠贡献 || suppressed | 新进展 | running | 清除持久化保护与旧通知 |-### waiting approval 为什么采用两阶段确认+### 等待批准的两阶段确认`PermissionRequest` 说明进入审批流程,但 reviewer 可能是 user, policy 或 auto review。@@ -302,13 +276,11 @@ Hook event 到达时如果已经带有 reviewer,task 可以立即确认。revi只有 reviewer 明确为 user 才发布 waiting transition。不确定时维持 running 比误报用户正在被等待更符合事实。-### effort 为什么可能变成 `mixed`+### Effort 合并同一 turn 的多个上下文事件可能报告不同 reasoning effort。Task 不让最后一条静默覆盖前一条,而是在观察到冲突后标记为 `mixed`-这向 UI 表达任务生命周期内确实出现过多个值,避免展示一个看似精确但只代表最后观察的 effort。--### subagent 数为什么允许 unknown+### Subagent 计数可靠性subagent 的 turn ID 属于 subagent 自己,父任务只能通过共享 session 关联。@@ -334,21 +306,15 @@ subagent 的 turn ID 属于 subagent 自己,父任务只能通过共享 sessio- 通知系统- 防睡眠控制器-### 为什么最近完成和最近中断有不同展示权重--完成会在菜单栏保留 30 秒绿色高亮,这是短时正反馈。中断只进入最近记录、不发布完成 transition,也不显示绿色状态。--任务中心保留 terminal 10 分钟,但用于防止迟到事件重复完成的 key 会保留 24 小时。展示期限和去重期限解决不同问题,不能为了“统一缓存”合并。--### 为什么只在快照变化时发布+### 快照发布monitor 每秒 poll rollout,还会按多个 deadline 自行刷新。如果每轮都给 `@Published` 赋相同值,SwiftUI 和所有 Combine 消费者会重复计算。新快照先与当前值比较,只有结构变化才发布。运行时长文案由 View 使用当前时间格式化,不要求每秒修改任务对象。-### 排序为什么有稳定兜底+### 稳定排序-同一 batch 中多个任务可能具有相同时间戳,Swift sort 又不是稳定排序。+同一 batch 中多个任务可能具有相同时间戳,仅按时间比较无法确定它们之间的顺序。所有列表先按最近时间降序,时间相同再按 display UUID 字符串排序。稳定顺序让 SwiftUI diff 不会因为等价任务随机交换位置而产生跳动。@@ -372,11 +338,11 @@ monitor 同时管理完成高亮、terminal grace、活动保留、历史保留如果新一轮读取失败、reader 被更换或数据源不可用,不得使用睡眠前快照继续判断任务静默。-### 为什么系统睡眠期间必须暂停静默计时+### 系统睡眠期间暂停判定-系统睡眠时 Hook 与 rollout 都不会正常产生进展。如果只比较墙上时间,一次两小时睡眠会让所有运行任务在唤醒瞬间被判为异常静默。+系统睡眠期间不进行异常静默判定。恢复后,monitor 根据新读取的 Hook 与 rollout 进展静默对账,再恢复正常判定。-保护计时使用 `SuspendingClock` 安排下一次检查,但系统时间变化和数据源恢复仍需要显式重算。will-sleep 先进入 recovery,did-wake 再通过新的数据读取屏障恢复判定。+检查任务使用 `SuspendingClock` 等待,但静默时长仍按 `Date` 与 `lastProgressAt` 的差值计算,不扣除系统睡眠经过的时间。will-sleep 进入 recovery,did-wake 通过新的数据读取屏障后重新判定。### 唤醒顺序为何不能交换@@ -401,7 +367,7 @@ rollout 对账必须发生在 Hook drain 成功之后。任务达到阈值后:-1. 先持久化保护记录+1. 先更新内存保护记录并加入串行持久化队列2. 同时启动通知提交和 3 秒 grace3. 通知提交完成或 grace 到期后再次校验候选4. 候选仍有效时从活动快照隐藏任务@@ -417,14 +383,6 @@ rollout 对账必须发生在 Hook drain 成功之后。- Hook 数据源不可用- reader 正在更换-### 保护针对的故障模型--Hook 或 Codex 异常退出后,可能缺少 `Stop`, `SessionEnd` 和 rollout terminal。任务会一直停在 running,进而让防睡眠永久生效。--异常会话保护不是判断 Codex 是否“真的卡住”,它只处理一个可观察事实:非匿名 running 任务在可信数据源下超过阈值没有任何 Hook 或 rollout 进展。--等待批准被排除,因为等待用户本来就是合法静默。匿名任务被排除,因为 project key 不足以证明保护记录属于哪一个具体任务。-### progress generation 的作用只比较时间戳不足以保护异步尝试。两条进展可能具有相同秒级时间,设置阈值也可能在通知提交期间变化。@@ -438,22 +396,11 @@ Hook 或 Codex 异常退出后,可能缺少 `Stop`, `SessionEnd` 和 rollout t通知返回或 3 秒 grace 到期时,四项都必须仍匹配才允许 suppress。任意新进展或阈值变化都会让旧尝试失效。-### 为什么先持久化再隐藏+### 保护记录的保存顺序-一旦任务从快照隐藏,App 可能随即退出或系统休眠。如果保护记录还没有进入持久化队列,重启 bootstrap 会再次展示并重新支撑防睡眠。+候选开始时同步更新内存记录,再由 Task 按顺序调用 `ActivityProtectionStateStore.apply`。磁盘写入失败会记录日志,不阻止任务隐藏。-因此候选开始时先写入记录、再等待通知提交、最后隐藏。通知权限或系统服务失败不影响 suppress,因为释放错误防睡眠才是保护的核心目标。--### 3 秒通知宽限的含义--保护通知是有价值的解释,但不能无限阻塞释放防睡眠:--- 通知先成功提交时立即完成 suppress-- 3 秒内仍未完成时直接 suppress-- 通知稍后成功返回但 attempt 已失效时立即撤回-- grace 内出现新进展时取消 attempt 和持久化记录--这个窗口只约束通知副作用,不改变静默阈值本身。+已保存的记录用于下次 bootstrap 恢复保护状态。隐藏动作不等待磁盘提交,因此跨重启恢复取决于记录是否成功写入。### 阈值改变如何对账@@ -461,7 +408,7 @@ Hook 或 Codex 异常退出后,可能缺少 `Stop`, `SessionEnd` 和 rollout t阈值变长时,尚未超过新阈值的 suppressed 任务会静默恢复,清除对应保护记录和通知。已经仍超过新阈值的任务继续 suppressed,不制造重复通知。-关闭防睡眠主开关会关闭异常保护并恢复全部 suppressed 任务,因为保护存在的目的就是避免错误防睡眠,不是永久隐藏任务。+关闭防睡眠主开关会停用异常保护,并恢复当前进程内所有 suppressed 任务。## 保护状态持久化@@ -485,9 +432,7 @@ turn 和 session key 先使用带类型前缀与 NUL 分隔的 canonical 字符类型和分隔符避免不同字段拼接后产生边界歧义。domain separator 避免同一原始 ID 在其他用途中的 hash 被直接关联。-这不是用来抵抗已知 session ID 的穷举,而是避免状态文件直接泄露可读身份并限制跨用途关联。--### Debug 与 Release 为什么共享文件还要加锁+### 跨进程状态合并两个 App bundle ID 可以同时运行,但都观察同一份 Codex Hook 数据。如果各自保存独立保护状态,一个版本隐藏的异常任务可能被另一个版本重新用于防睡眠。@@ -517,18 +462,6 @@ Monitor 为 reader 和异步恢复任务维护 generation:每一项都对应不同的“当前性”问题,不能合并成一个全局计数。例如 reader 没变但任务有新进展时,只需要让 protection attempt 失效,不应丢弃整个 reader。-## 扩展任务状态机的步骤--1. 先确定新输入是事实、metadata、progress 还是 terminal-2. 定义 bootstrap 与 live 是否产生相同 snapshot,是否允许 transition-3. 定义事件缺少 turn 或 session ID 时的降级行为-4. 定义迟到和重复输入如何用 timestamp, terminal memory 或 generation 拒绝-5. 如果读取 rollout 新字段,扩展最小 envelope 而不是读取正文-6. 在 `CodexActivityTask` 中维护领域状态,在 monitor 中维护跨任务关联-7. 更新 snapshot 前确认通知和防睡眠是否应该消费新状态-8. 为系统睡眠、reader 替换和数据源不健康定义恢复路径-9. 匿名任务默认不能获得新的高影响副作用,除非身份可靠性发生根本变化-## 建议验证的故障场景- App 在任务已运行时启动,bootstrap 展示任务但不补发通知diff --git a/Docs/DeveloperGuide/app-server.md b/Docs/DeveloperGuide/app-server.mdindex 0bbfa28..95b8e10 100644--- a/Docs/DeveloperGuide/app-server.md+++ b/Docs/DeveloperGuide/app-server.md@@ -2,25 +2,12 @@简体中文 | [English](../en/DeveloperGuide/app-server.md)-## 设计出发点--CodexBar 不重新实现 Codex 登录、token 刷新和账户协议,而是把本机 `codex app-server` 作为账户能力边界。--这样做的原因是:--- 认证和服务端协议由 Codex 自己维护,CodexBar 不复制一套容易漂移的客户端-- App 通过 stdio 与本机子进程通信,账户主链路不需要直接暴露额外网络实现-- 当前真正运行的 Codex 版本可以从 handshake 获得,能用于全局和 Hook 能力判断-- 全局 CLI 与 App 内置 CLI 可以共享同一套上层数据模型--代价是菜单栏 App 必须自己解决 shell 环境缺失、子进程生命周期、pipe 背压、混杂 stdout、超时和升级后的连接换代。-## 职责app-server 链路负责读取 Codex 账户和服务端状态:- 当前账户和套餐-- 5 小时额度和周额度+- Codex 返回的额度分组和窗口- token 用量与用量历史- Reset Credits 状态- Hook 功能开关、handler 列表和配置写入能力@@ -69,7 +56,7 @@ CodexCLIResolver数据目录优先使用 `CODEX_HOME`,未设置时使用真实用户主目录下的 `~/.codex`-### 为什么不能直接信任进程环境+### 进程环境归一化从 Finder 或登录项启动的 `LSUIElement` App 通常没有用户交互式 shell 注入的完整 `PATH`。如果只调用 `/usr/bin/env codex`,Homebrew, Volta 或 npm 全局安装会在 Terminal 中可用,在 CodexBar 中却不可见。@@ -81,12 +68,35 @@ resolver 会做 3 层归一化:`CodexCLISourceSelection.automatic` 优先使用全局 CLI,找不到时使用 App 内置 CLI。手动选择 `global` 或 `bundled` 后只使用指定来源,缺失时返回 `sourceUnavailable`。来源选择由 `CodexStatusService` 保存,重建连接时沿用。-### 磁盘版本和运行版本为什么分开+### 磁盘版本与运行版本设置页可以读取磁盘上两个候选 CLI 的版本,但全局和 Hook 最低版本检查只使用 `initialize` 返回的 app-server `userAgent`原因是连接最长复用 1 小时。用户在连接存活期间升级磁盘 binary 后,当前进程仍然是旧版本。用磁盘版本判断会让 UI 声称能力可用,实际调用的旧 app-server 却不支持对应方法。+## App 内代理++代理由以下类型协作完成:++| 类型 | 职责 |+| --- | --- |+| [`CodexProxyConfiguration`](../../CodexBar/Models/CodexProxyConfiguration.swift) | HTTP/HTTPS 配置、输入校验和子进程环境变量 |+| [`CodexProxyStore`](../../CodexBar/Services/Settings/CodexProxyStore.swift) | 在 UserDefaults 的 `CodexProxy.configuration` 中保存配置和密码 |+| [`CodexProxySettings`](../../CodexBar/Services/Settings/CodexProxySettings.swift) | 已保存配置、编辑草稿、开关提交和测试状态 |+| [`CodexProxyConnectionTester`](../../CodexBar/Services/CodexStatus/CodexProxyConnectionTester.swift) | 使用草稿启动独立测试进程 |++未配置或未启用时,正式连接沿用 `CodexCLIResolver.environment`。启用后写入 `HTTP_PROXY`、`HTTPS_PROXY`、`ALL_PROXY`、`WS_PROXY`、`WSS_PROXY` 及其小写形式,`NO_PROXY` 和 `no_proxy` 设为 `localhost,127.0.0.1,::1`。只有自定义代理进程追加 `-c features.respect_system_proxy=false`,配置不写入 Codex 全局文件。++读取存储时保留可解码的原始输入。启用代理和保存编辑表单时校验地址、端口和认证用户名;停用时允许保存无效字段。无法解码的记录仍保留清除入口。++开关在创建异步任务前更新显示状态并设置 `isSaving`,处理期间重复切换被忽略。`CodexStatusService.applyProxy` 串行保存设置、关闭旧连接并清空补充缓存,完成后恢复交互并触发刷新;失败时恢复原开关状态。配置对话框使用独立草稿,只有保存或清除才提交。++### 连接测试++测试将草稿临时视为启用,解析所选 Codex 来源,并通过 `AppServerSession.initializeAccount()` 执行与正式连接相同的握手和账户检查,随后调用 `account/rateLimits/read`。正式连接在握手之后继续读取额度和用量。++测试请求共享 8 秒截止时间,不重试服务端业务错误,不记录交互日志。退出时关闭临时进程;进程清理仍使用 session 的关闭等待预算。编辑字段、取消测试或关闭窗口会取消外层任务和 worker,已取消任务返回的结果不会更新 UI。+## 进程与协议CodexBar 启动以下命令并通过 stdio 通信:@@ -126,7 +136,7 @@ stdout 可能包含非 JSON 输出。pipe reader 会持续读取完整行,只只有实际版本满足全局门槛,并且 handshake 与首次账户读取都成功,connection 才进入 service 状态。版本低于 `0.143.0` 或无法解析时按不支持处理,关闭半初始化 session,不继续发送账户请求。-### 为什么 stdout reader 只暴露完整行+### Stdout 分行与响应匹配app-server 的 framing 是一行一个 JSON message。pipe 回调收到的 `Data` 块可能:@@ -135,24 +145,24 @@ app-server 的 framing 是一行一个 JSON message。pipe 回调收到的 `Data- 在 JSON 行之间混有普通日志- 在进程结束时留下没有换行的最后一行-`PipeReadBuffer` 因而自己维护 byte buffer,只在看到换行时发布完整非空行。会话层先轻量解码 response id,只有 id 匹配才完整解码 result 或 error。+`PipeReadBuffer` 维护 byte buffer,读取期间按换行发布非空行,在 EOF 或停止读取时也会发布末尾尚未换行的非空内容。会话层先轻量解码 response ID,只有 ID 匹配才完整解码 result 或 error。这既避免把日志误判成协议错误,也让大响应只进行一次完整泛型解码。-### 为什么 stderr 也必须持续读取+### Stderr 排空即使 CodexBar 不展示 stderr 正文,也必须 drain pipe。子进程 pipe buffer 有上限,如果父进程从不读取 stderr,app-server 写满后会阻塞,随后的 stdout response 也不会到达。-`PipeDrain` 不解析内容,只消除背压。这是进程正确性要求,不是日志功能。+`PipeDrain` 不解析内容,只负责持续排空 stderr。### 关闭策略session 关闭时按以下顺序收口:1. 停止 stdout 和 stderr reader-2. 关闭 stdin 写端,给 app-server 正常感知 EOF 的机会-3. 最多等待 1 秒优雅退出-4. 仍未退出时发送强制终止,再等待 0.5 秒+2. 关闭 stdin 写端+3. 向仍在运行的进程发送 `SIGTERM`,最多等待 1 秒+4. 仍未退出时发送 `SIGKILL`,再等待 0.5 秒5. 仍存活则记录诊断错误进程提前退出后继续写 pipe 可能触发 `SIGPIPE`。service 在初始化时忽略该 signal,让写入以 Swift error 返回并进入 transport failure 重建路径,而不是杀死整个菜单栏 App。@@ -171,28 +181,22 @@ session 关闭时按以下顺序收口:每个 session 会缓存不支持的方法。一旦 app-server 明确返回 method unsupported,当前连接后续不会重复请求该方法。-### 为什么 unsupported 只按 session 缓存+### Session 能力缓存method unsupported 通常代表当前 app-server 版本缺少能力。每分钟重复调用只会制造日志和延迟。但这个结论不能永久保存到 UserDefaults。新连接可能来自升级后的 binary,因此 unsupported 集合只属于 `AppServerSession`,连接重建后重新探测。-### 为什么配置也复用这条连接--`config/read`, `hooks/list` 和 `config/batchWrite` 需要与账户刷新使用同一个实际 app-server 来源。--如果设置页另起一套 resolver 或进程,可能出现主面板连接全局 CLI,Hook 校验却连接内置 CLI 的分裂状态。统一 service 保证能力检查、配置来源和运行版本来自同一个进程选择。-## 会话生命周期[`CodexStatusService.swift`](../../CodexBar/Services/CodexStatus/CodexStatusService.swift) 是 actor,持有连接和刷新状态:- 单次请求超时为 20 秒-- 连接最长复用 1 小时+- 请求时检查连接年龄,达到 1 小时则重建- 业务错误在 session 内最多重试 1 次- transport 失败最多重建连接 1 次- 认证需要刷新时,`account/read` 最多使用 `refreshToken = true` 再试 1 次-- service 关闭或进程退出时终止子进程并完成所有挂起请求+- 连接关闭或释放时执行子进程终止流程;请求读取遇到关闭时按连接错误处理业务错误与 transport 错误分开处理。前者可能是某个方法暂时失败,后者代表当前 stdio 会话已经不可信。@@ -212,7 +216,9 @@ ready-> account missing after refresh: close and notLoggedIn```-1 小时不是数据刷新周期,而是连接最长寿命。定期重建的主要价值是让后台升级后的 Codex binary 最迟在一个连接周期后生效。+1 小时是请求时检查的连接复用上限。达到上限后的下一次请求会重建连接并使用当时磁盘上的 Codex binary,没有独立的定时销毁任务。++手动重连、切换来源和连接到期重建都先关闭旧连接;新连接失败时保持断开。来源选择只在手动重连成功后保存。自动刷新和手动重连的错误都会更新 `CodexStatusViewModel.connectionErrorMessage`,关于页面直接展示该状态。### 错误分类矩阵@@ -226,7 +232,7 @@ ready限制重建次数是为了避免故障状态下反复拉起子进程。一轮刷新结束后,下一次正常定时刷新仍有新的尝试机会。-### 为什么认证刷新全程只有一次+### 认证刷新预算一次刷新会读取 account、rate limits 和 usage,Reset Credits 明细包含在 rate limits 响应中。多个接口可能同时发现 token 过期。@@ -236,7 +242,7 @@ ready## 刷新模型-状态 ViewModel 默认每 60 秒刷新。用户也可以在主面板双击刷新按钮立即触发。+状态 ViewModel 默认每 60 秒刷新。用户也可以在主面板双击账户图标立即触发。一次刷新先解析账户,再读取额度和用量。补充数据缓存严格绑定到账户身份:@@ -245,7 +251,7 @@ ready- 服务端明确不支持的方法显示为来源缺失- 来源缺失不能转换为业务值 `0`-刷新任务通过协调器合并,避免定时刷新、面板打开和手动刷新并发创建重复请求。+刷新或重连进行中会忽略普通刷新触发。需要补刷的操作通过 `refreshAfterCurrent` 保留一个待执行触发,待当前请求结束后执行;协调器负责取消和校验过期结果。### 一次刷新如何组装快照@@ -284,7 +290,7 @@ method unsupported 不使用旧缓存,因为它是明确能力结论。普通stale 是数据可信度的一部分,新增展示时不能只复制数值而丢掉标记。-### 刷新协调器为什么还需要 generation+### 刷新结果的代际校验`isRefreshing` guard 可以阻止普通重复触发,但 cancellation 和对象生命周期仍可能让旧 Task 返回。@@ -292,7 +298,7 @@ stale 是数据可信度的一部分,新增展示时不能只复制数值而自动刷新每轮按距离上次完成的剩余时间等待。手动刷新完成后倒计时自然重新对齐,不会在几秒后又被原来的 timer 立刻刷新一次。-### 模型层的小优化+### 数据模型与展示投影`CodexUsageSnapshot` 构造时把可能重复的 daily bucket 聚合成 `tokensByDate`@@ -352,7 +358,7 @@ account/rateLimitResetCredit/consume| `nothingToReset` | 当前没有可重置的额度窗口 | 凭证未消费,继续使用同一幂等键重试 || `noCredit` | 当前账户没有可用凭证 | 强制刷新;目标消失时静默停止,否则按暂时不一致重试 |-`alreadyRedeemed` 不是失败,也不是再次消费。它是同一逻辑请求已经成功的确认,因此收到这个结果的设备会停止重试并发送本机的“自动重置”通知。+`alreadyRedeemed` 确认同一逻辑请求此前已成功;收到后停止重试,并按通知设置发送本机成功通知。### 跨设备幂等契约@@ -400,7 +406,6 @@ namespace、UUID 版本、原始 UTF-8 输入和小写输出共同构成跨版自动重置触发完整额度刷新时,如果普通额度刷新正在执行,新刷新会排队到当前刷新结束后运行,不能被 `isRefreshing` guard 丢弃。-## Hook 版本与配置校验Hook 设置也复用 app-server 链路,但采用独立的可用性状态:@@ -431,7 +436,9 @@ Hook 设置也复用 app-server 链路,但采用独立的可用性状态:日志用于观察进程启动、JSON-RPC 方法、重试和错误分类。不应写入 access token 或 Hook prompt 内容。-### 两套日志为什么分开+`CodexProxyError` 的配置错误只写入系统日志 `settings` 分类,不创建 app-server 请求日志。RPC 响应及错误写入交互日志前,先解析 JSON 转义并遍历字符串值,对 HTTP/HTTPS URL 的认证信息脱敏;非 JSON 文本使用文本脱敏。++### 请求日志与系统日志系统统一日志只保存控制流分类,适合长期排查 App 是否在刷新,失败在哪个阶段。@@ -439,17 +446,6 @@ App 内 `RequestLog` 保存最多 500 条请求交互预览,只存在进程内Reset Credits 明细包含 opaque credit ID。系统日志不能记录 ID 或原始响应,App 内请求日志仍只按既有规则保存在当前进程内存。对新 RPC 增加日志时,需要检查 payload 是否可能包含凭据或内容字段。-## 扩展 app-server 字段的步骤--1. 在外部 DTO 中按协议可选性建模,不先用展示默认值填充-2. 在 `CodexStatusService` 决定该方法是账户核心还是补充数据-3. 明确普通失败、unsupported 和认证失败各自如何降级-4. 如果缓存该值,必须绑定账户 identity 并携带 stale 语义-5. 在领域 snapshot 中转换时间戳、百分比和排序等稳定规则-6. UI 只消费 snapshot,不直接访问原始 response-7. 通知等副作用只使用可信快照-8. 核对请求和日志是否扩大隐私边界-## 建议验证的故障场景- Finder 启动时仍能找到 Homebrew, npm 或 Volta 安装的 Codex@@ -482,6 +478,8 @@ Reset Credits 明细包含 opaque credit ID。系统日志不能记录 ID 或原- 消费成功后的完整额度刷新不会被并发普通刷新丢弃- 手动刷新后 60 秒倒计时重新对齐+代理相关验证还包括:停用无效配置、清除损坏记录、测试取消后旧结果隔离、快速连续切换只提交一次、提交失败回滚,以及普通 URL 和 JSON 转义 URL 的日志脱敏。+## 关键源码- [`CodexCLIResolver.swift`](../../CodexBar/Services/CodexCLI/CodexCLIResolver.swift)diff --git a/Docs/DeveloperGuide/architecture.md b/Docs/DeveloperGuide/architecture.mdindex b20a417..5f0655f 100644--- a/Docs/DeveloperGuide/architecture.md+++ b/Docs/DeveloperGuide/architecture.md@@ -2,23 +2,6 @@简体中文 | [English](../en/DeveloperGuide/architecture.md)-## 这套架构要解决什么--CodexBar 的核心挑战不是绘制菜单栏界面,而是在一个长期运行的 `LSUIElement` App 中同时协调短命 Hook 子进程、本机 app-server、持续追加的文件、CloudKit、系统通知和 root helper。--完整的组件关系、数据链路和源码依据可在 [交互式运行时架构图](https://codexbar.zabrian.app/architecture) 中查看。--架构需要持续满足以下目标:--- 任意一条数据链路失败时,不连带关闭其他功能-- 短命 Hook 模式和普通 App 模式共用可执行文件,但生命周期完全隔离-- UI 只观察可解释的快照,不直接承担 I/O、去重或恢复逻辑-- 特权操作保持最小接口,业务策略留在普通 App 进程-- 每个异步结果都能证明自己仍属于当前配置和数据源代际-- 可重建数据与不可重放副作用分开处理--更完整的取舍背景见 [设计原则与关键决策](design-decisions.md)-## 技术基线CodexBar 是 macOS 15+ 菜单栏应用,使用 Swift 6, SwiftUI, AppKit 和 MVVM。@@ -64,7 +47,7 @@ CodexBar executable| --- | --- | --- | --- || Hook 子进程 | 单个事件,最长几秒 | 读取 stdin、提取最小字段、追加本地 JSONL | 初始化 UI、建立网络连接、等待长期服务 || 主 App | 用户登录会话内长期运行 | 编排 UI、数据链路和副作用 | 直接以 root 修改系统设置 |-| app-server | 最长复用 1 小时 | 通过 JSON-RPC 提供账户和配置能力 | 成为 Hook 历史或实时任务的替代来源 |+| app-server | 达到 1 小时后的下一次请求重建 | 通过 JSON-RPC 提供账户和配置能力 | 成为 Hook 历史或实时任务的替代来源 || CodexBarHelper | LaunchDaemon | 执行固定 `pmset` 操作、管理固定 owner 的 `wake` 事件并恢复系统状态 | 访问账户、Hook、rollout、网络或任意命令 |## 目录职责@@ -85,7 +68,7 @@ Scripts/ 构建, DMG, appcast 和 CodexBarHelper 清理脚本## 启动顺序-[`CodexBarApp.swift`](../../CodexBar/App/CodexBarApp.swift) 的初始化顺序是架构约束,不是实现细节:+[`CodexBarApp.swift`](../../CodexBar/App/CodexBarApp.swift) 按以下顺序分流启动:```text进程启动@@ -103,6 +86,7 @@ Scripts/ 构建, DMG, appcast 和 CodexBarHelper 清理脚本普通模式由 `CodexBarAppDelegate` 统一创建和持有长期对象,主要包括:- `CodexStatusService` 和 `CodexStatusViewModel`+- `CodexProxySettings`- `WorkflowService` 和对应 ViewModel- `CodexHookSettings`- `CodexActivityMonitor`@@ -114,7 +98,7 @@ Scripts/ 构建, DMG, appcast 和 CodexBarHelper 清理脚本App 退出时需要先取消自动重置唤醒计划并释放防睡眠状态。如果 CodexBarHelper 尚未回读确认两类系统状态都已恢复,终止流程会等待或取消退出。helper 启动时还会在接受新连接前清除固定 owner 的遗留唤醒事件,用于收敛突然断电或强制终止留下的状态。-### 为什么 Hook 判断必须放在 `App.init`+### Hook 启动分流`@NSApplicationDelegateAdaptor` 会把 AppKit 生命周期接入 SwiftUI App。一旦普通生命周期开始,可能创建菜单栏对象、注册通知 delegate 或访问 CloudKit。@@ -122,20 +106,7 @@ Hook handler 在 Codex 的关键路径上,它需要的是接近命令行工具这个顺序还保证 Hook 采集失败不会污染正常退出诊断。`AppProcessDiagnostics.install()` 只在 `applicationDidFinishLaunching` 中执行,Hook 子进程不会被误记为一次异常退出的完整 App。-### 为什么由 AppDelegate 持有长期对象--SwiftUI View 会因为布局、条件分支和窗口重建而重复创建。如果 service 的所有权落在 View 中,一个看似普通的界面变化就可能终止 reader, app-server 或 XPC 连接。--`CodexBarAppDelegate` 因而承担 composition root 职责:--- 只在这里创建长期 service, settings 和 ViewModel-- 在这里建立 monitor, notification 和 keep-alive 之间的回调-- View 只接收已经创建好的引用-- App 退出时从同一个所有者反向停止服务--这不是要求所有逻辑都堆进 AppDelegate。它只负责装配和生命周期,业务规则仍在各自 service 或 controller 中。--### 退出为什么可以被取消+### 退出协调`applicationShouldTerminate` 先调用 `KeepAliveController.prepareForTermination()` 并返回 `.terminateLater`@@ -153,13 +124,6 @@ CodexBar 不使用一个聚合服务承载所有状态。3 条链路的输入、| Hook 历史 | Hook JSONL | 日级事件、session, turn, tool, model 聚合 | 活跃度热力图、历史统计、CloudKit || 实时任务 | Hook 增量事件加 rollout 生命周期 | 运行、等待批准、完成、中断 | 菜单栏状态、任务中心、通知、防睡眠 |-链路之间可以共享基础设施和模型,但不能互相替代:--- app-server 不提供完整的实时任务状态-- 历史聚合允许延迟和重建,实时任务不能等待聚合完成-- 实时任务快照不可作为历史统计的持久来源-- 某条链路不可用时,其他链路仍应保持可用-### 依赖方向```text@@ -180,9 +144,7 @@ Hook + rollout --------> CodexActivityMonitor --------> UI箭头表示数据或只读状态的消费方向。下游不能反向成为上游的事实来源。-例如,菜单栏可以把额度进度和任务状态画在同一个图标上,但图标是否存在不能决定任务 monitor 是否运行。同步 scheduler 可以复用历史维护的触发时机,但 CloudKit 是否可用不能决定本地聚合是否执行。--### 共享触发不等于数据依赖+### 共享刷新触发历史维护默认挂在 60 秒额度刷新完成事件上,这是为了减少常驻 timer 和日志噪音。两条链路共享调度时机,但没有共享事实。@@ -219,7 +181,7 @@ Hook + rollout --------> CodexActivityMonitor --------> UI跨 actor 传递的 DTO 必须是不可变值类型,并按需要声明 `Sendable` 或 `nonisolated`-### 为什么 monitor 仍在 MainActor+### Monitor 的 MainActor 边界`CodexActivityMonitor` 的输入读取在 actor 中完成,但状态机本身与多个 Combine 消费者紧密相连。@@ -231,23 +193,6 @@ Hook + rollout --------> CodexActivityMonitor --------> UI前提是 monitor 不能直接执行阻塞文件读取。`HookEventTailReader`, `CodexSessionLifecycleReader` 和 `ActivityProtectionStateStore` 各自承担 I/O 边界。-### 非隔离 pipe reader 为什么使用锁--app-server 是 stdio 协议,底层需要组合 `FileHandle`, `DispatchSourceRead` 和 semaphore。这些类型不是天然 `Sendable`,也不适合每读取一行都跨 Swift actor hop。--`PipeReadBuffer` 把不安全边界收口在一个 `@unchecked Sendable` 类型中,所有可变状态由 `NSLock` 保护,读事件固定在专用 queue 上。上层只看到完整行和关闭状态。--这里的 `@unchecked` 是经过封装的局部承诺,不是关闭整个模块的并发检查。--### 跨进程文件不能只依赖 actor--Hook recorder 是另一个进程,所以 `WorkflowService` actor 无法保护它。`stats.lock` 使用 `flock` 对事件文件和维护状态的联合修改提供进程级排他事务。--同一个流程中会同时出现 actor 和 `flock`--- actor 保证主 App 内多项维护不会并行改状态-- `flock` 保证主 App 与短命 Hook 子进程不会同时提交冲突文件修改-## 模型分层项目没有让 app-server DTO、持久化模型和 View 直接共用同一个大对象:@@ -258,7 +203,7 @@ Hook recorder 是另一个进程,所以 `WorkflowService` actor 无法保护| 持久化模型 | 保存可恢复状态和 schema | 兼容旧值,明确 missing 语义 || 领域快照 | 向消费者表达当前可信状态 | 不可变、可比较、跨 actor 安全 || transition | 表达一次 live 状态变化 | 不从历史快照反推,需要上游去重 |-| 展示格式 | 日期、百分比、文案和颜色 | 跟随 locale,不反向参与业务判定 |+| 展示格式 | 日期、百分比、文案和颜色 | 按各展示字段的地区设置或固定格式输出,不参与业务判定 |例如 `CodexQuotaSnapshot` 可以同时携带当前值和 stale 标记。`CodexActivitySnapshot` 只保存展示需要的任务字段,原始 session ID 不进入 View。@@ -268,7 +213,7 @@ Hook recorder 是另一个进程,所以 `WorkflowService` actor 无法保护| 状态 | 生命周期 | 原因 || --- | --- | --- |-| app-server connection | 最长 1 小时 | 复用降低启动成本,定期重建让磁盘升级生效 |+| app-server connection | 请求时检查 1 小时复用上限 | 后续请求重建连接时使用磁盘上的 binary || app-server supplemental cache | 当前账户内 | 避免跨账户串值 || Hook live bootstrap window | 24 小时 | 覆盖可能仍在运行的长任务 || 完成高亮 | 30 秒 | 菜单栏短时反馈 |@@ -282,23 +227,10 @@ Hook recorder 是另一个进程,所以 `WorkflowService` actor 无法保护## 状态所有权-实时任务状态只有一个权威来源,即 [`CodexActivityMonitor.swift`](../../CodexBar/Services/Workflow/CodexActivityMonitor.swift)--它的快照被以下模块消费:--- 菜单栏图标和主面板任务卡片-- 活动中心-- 完成和等待批准通知-- 防睡眠是否存在有效任务的判断-- 异常会话保护--消费者只能基于快照展示或执行副作用,不能各自重建一套任务状态机。--### 状态所有权表-| 状态 | 唯一所有者 | 其他模块的权限 || --- | --- | --- |-| app-server 连接与同账户缓存 | `CodexStatusService` | 请求只读结果 |+| app-server 连接与同账户缓存 | `CodexStatusService` | 通过服务方法读取数据、修改配置或重连 |+| 代理草稿、测试和开关交互 | `CodexProxySettings` | 设置页通过方法提交,`CodexStatusService` 应用正式连接配置 || 主面板账户加载状态 | `CodexStatusViewModel` | 观察发布值 || 自动重置的目标、deadline 和重试 | `AutoResetController` | 设置页只修改开关和提前量 || 自动重置唤醒时间同步 | `AutoResetWakeScheduler` | `AutoResetController` 只提交下一次时间,`KeepAliveController` 只提交 helper 就绪状态 |@@ -322,7 +254,7 @@ Hook recorder 是另一个进程,所以 `WorkflowService` actor 无法保护- 恢复流程必须完成新的读取屏障后才能继续判定- 持久化文件写入需要原子替换或文件锁,避免 Debug 与 Release 并发破坏-### 错误分类比统一重试更重要+### 错误分类| 错误类别 | 典型处理 | 不应采取的处理 || --- | --- | --- |@@ -334,45 +266,6 @@ Hook recorder 是另一个进程,所以 `WorkflowService` actor 无法保护| 特权状态不确定 | 保留可能租约或唤醒事件并主动确认清理 | 假定 helper 没有执行 || Hook recorder 失败 | 吞掉本次采集并退出成功 | 阻断 Codex 或弹 UI |-### 日志为什么记录阶段而不是用户数据--系统日志使用 `trigger`, `stage`, `reason`, `counts` 和 `elapsed` 解释流程,避免记录额度数值、项目路径或任务身份。--这种日志结构允许区分:--- 同步是在 zone, device, fetch, upload 还是 prune 阶段失败-- app-server 使用新连接还是复用连接-- 聚合是空转、增量写入还是标脏重建-- 防睡眠被哪一个条件阻断--诊断需要的是控制流证据,不需要复制用户数据。--## 变更一个核心流程时怎么落点--### 新增数据来源--1. 先确定它是否属于现有 3 条链路-2. 定义来源缺失、stale 和失败语义-3. 在 actor service 内完成 I/O 和缓存-4. 通过不可变快照进入 MainActor-5. 单独审查网络和隐私边界--### 新增一次性副作用--1. 找到能证明“刚刚发生”的 live transition-2. 不从当前快照或历史列表反推-3. 定义进程内和跨重启去重范围-4. 提交前检查事件是否仍相关-5. 定义副作用失败是否可以影响主状态--### 新增持久化状态--1. 说明为什么内存状态不足-2. 定义 schema、原子性和并发访问边界-3. 定义旧版本读取新文件和新版本读取旧文件的行为-4. 限制保存字段和保留时间-5. 先确认兼容策略再修改格式-## 系统集成| 能力 | 系统接口 |diff --git a/Docs/DeveloperGuide/data-and-privacy.md b/Docs/DeveloperGuide/data-and-privacy.mdindex 61ef0d4..59e76e5 100644--- a/Docs/DeveloperGuide/data-and-privacy.md+++ b/Docs/DeveloperGuide/data-and-privacy.md@@ -2,17 +2,6 @@简体中文 | [English](../en/DeveloperGuide/data-and-privacy.md)-## 原则--CodexBar 只读取实现账户展示、自动重置、Hook 统计、实时任务和防睡眠所需的数据:--- 原始数据能留在本机时不上传-- 可以保存聚合时不保存正文-- 可以保存哈希身份时不保存原始身份-- 数据源不可用时显式标记缺失--隐私边界不是一份静态字段黑名单,而是每条数据链路的架构约束。新字段即使技术上容易读取,也必须先回答“它是否是完成产品目标所必需的”。-## 数据分类模型数据按以下类别确定存储和传播范围:@@ -23,8 +12,6 @@ CodexBar 只读取实现账户展示、自动重置、Hook 统计、实时任务| 身份和上下文 | session ID、完整路径、project 名 | 仅在必要链路最小化使用,上传前脱敏或删除 || 聚合指标 | 每日事件数、model 计数 | 可本地持久化,用户 opt-in 后上传规定字段 |-“只保存在本机”不等于没有隐私成本。本地日志、crash report、备份和同机其他进程仍可能扩大暴露面,所以不需要的数据应在解析入口就丢弃。-## 信任边界```text@@ -49,8 +36,6 @@ Codex hook stdin / rollout / app-server## 最小化发生在采集入口-只在上传时删除敏感字段不够,因为原始字段可能已经进入本地 JSONL、内存日志或错误信息。-CodexBar 的最小化顺序是:1. Hook recorder 从 stdin 只提取白名单结构字段@@ -59,8 +44,6 @@ CodexBar 的最小化顺序是:4. sync model 再投影成 CloudKit 允许字段5. 日志层只记录阶段、分类和非敏感计数-每一层都收窄一次数据形状,因此下游新增一个字段不能自动获得上游所有原文。-## 数据流总览| 来源 | CodexBar 使用方式 | 是否持久化 | 是否上传 CloudKit |@@ -73,17 +56,6 @@ CodexBar 的最小化顺序是:| CodexBarHelper ownership | 系统睡眠恢复 | root 状态文件 | 否 || 自动重置唤醒计划 | 固定 owner、`wake` 类型和下一次时间 | 系统电源管理 | 否 |-### 为什么 3 条业务链路保持独立--app-server、Hook 历史和实时活动读取不同事实,具有不同的新鲜度与失败模式:--- app-server 失败不应让本地历史消失-- Hook 聚合维护失败不应冻结实时任务-- rollout 暂时不可用不应把额度标成错误-- CloudKit 失败不应阻断当前设备聚合--如果把它们压成一个“全局加载成功”状态,任一低敏感度或低优先级链路都会扩大另一条链路的数据访问和可用性影响面。-## 本地读取### Codex app-server@@ -118,8 +90,6 @@ Hook recorder 通过 `transcript_path` 读取当前 rollout,实时活动 readerollout reader 从文件尾部按预算扫描,一方面减少 I/O,另一方面降低无关历史内容进入进程内存的范围。解析 DTO 只声明所需字段,JSONDecoder 自动忽略其余内容。-这不是对 rollout 文件的完整隐私隔离,因为 reader 仍需打开原文件。因此如果未来加入全文搜索或 prompt 展示,应视为新的产品隐私能力,不能当作现有 reader 的自然扩展。-### Reset Credits 明细`account/rateLimits/read` 在 app-server 响应中返回 Reset Credits 数量和可选明细。@@ -161,14 +131,6 @@ rollout reader 从文件尾部按预算扫描,一方面减少 I/O,另一方最近 3 天的日聚合可以保留 session 和 turn ID 明细用于准确去重。更早数据只保留计数。-3 天 identity 明细是精确去重与长期最小化之间的折中:--- 近期 Hook 文件仍可能补写或重复,需要 identity 集合正确合并-- 远期数据变化概率低,只保留总数可显著缩小长期身份暴露-- 压缩后不能从计数恢复 identity,因此算法变化统一从仍在 210 天保留期内的原始 JSONL 重建--原始事件和日聚合使用相同的 210 天上限,避免派生数据已经清理但更敏感的原始数据仍无限保留。-匿名任务不生成异常会话保护标识,因此不会写入 `ActivityProtection/state.json`### UserDefaults@@ -178,14 +140,20 @@ UserDefaults 保存:- 功能开关和设置选项- 通知阈值和声音名称- 全局快捷键+- 代理启用状态、协议、服务器、端口、认证用户名和密码- 菜单栏显示选择- 自动重置开关和提前量- 有界的通知去重 key- CodexBarHelper fingerprint 等运行配置-持久化 key 改名、结构变化或默认值变化需要考虑旧版本升级行为。+持久化 key、数据结构、枚举 raw value 或缺失默认值的变化属于兼容性问题,修改前必须确定迁移和降级策略。++代理使用 `CodexProxy.configuration` 保存一条包含 `configuration` 和 `password` 的 JSON 数据。密码明文保存在本机 UserDefaults,保存关闭身份验证的配置或删除配置时删除。Debug 与 Release 使用各自的偏好域,不共享代理配置:++- Debug:`~/Library/Preferences/app.zabrian.codexbar.debug.plist`+- Release:`~/Library/Preferences/app.zabrian.codexbar.plist`-UserDefaults 不是无 schema 存储。对已有 key 改名、枚举 raw value 变化或缺失默认值变化都会改变升级用户行为。这类修改属于兼容性问题,必须先确定迁移和降级策略。+`CodexProxyStore` 区分记录不存在与解码失败;解码失败时保留记录,以便配置窗口提供清除入口。### CodexBarHelper 目录@@ -205,8 +173,6 @@ App 内 [`RequestLog.swift`](../../CodexBar/Services/CodexStatus/RequestLog.swif请求日志用于诊断 app-server 协议。即使只存在内存,也不应写入 OAuth token 或 Hook 内容。-ring buffer 的 500 条上限既控制内存,也限制打开日志窗口时的渲染成本。它不是审计日志,不能承担跨启动问题追踪。需要跨启动诊断时使用统一系统日志,仍需遵守相同字段边界。-统一系统日志 subsystem 为 `app.zabrian.codexbar`,Debug 版本带 `.debug` 后缀。系统日志只应记录:@@ -224,17 +190,22 @@ ring buffer 的 500 条上限既控制内存,也限制打开日志窗口时的- 完整项目路径或敏感项目名- 账户额度和 token 用量明细+`CodexProxyError` 的固定错误文案写入系统日志的 `settings` 分类,不包含配置值。app-server 响应写入 App 交互日志前会解析 JSON 转义,对字符串值中的 HTTP/HTTPS URL 认证信息脱敏;其他账户和协议字段仍按请求日志规则保留。+## 网络访问| 目标 | 用途 | 触发条件 || --- | --- | --- || CloudKit private database | 同步日级 Hook 聚合 | 用户主动开启同步 |+| Codex 服务(app-server 子进程) | 认证、额度、用量和 Reset Credit 消费 | 正式刷新、代理测试或自动重置 || Sparkle appcast 和更新资源 | 检查或安装更新 | 自动检查或用户手动检查 |账户、额度、token 用量、Reset Credits 明细和用户明确开启的 Reset Credit 消费通过本机 app-server stdio 完成。CodexBar 不为自动重置增加独立 HTTP 客户端。CodexBarHelper 不进行任何网络访问。+启用代理后,地址及可选认证信息仅通过环境变量交给 CodexBar 启动的 app-server。配置不会修改系统网络设置、Sparkle、CloudKit 或其他 Codex 进程。连接测试另起临时 app-server,结束后关闭且不写入 App 交互日志。+## CloudKit 边界CloudKit 只上传日级聚合字段:@@ -258,11 +229,10 @@ CloudKit 不上传:- access token- App 请求日志- Activity Protection 状态+- 代理配置和代理密码project 显示名可能由目录名派生,仍可能包含用户敏感信息。同步开关必须保持用户主动选择。-HMAC 设备 pseudonym 只降低硬件身份关联,不会自动匿名化 project 名。private database 也不等于“数据不离开设备”。因此设置文案和开发文档都必须继续说明同步内容,不能因为 CloudKit 属于用户账户就改成默认开启。-## root helper 的数据隔离CodexBarHelper 只需要知道 4 类状态:@@ -274,7 +244,7 @@ CodexBarHelper 只需要知道 4 类状态:它不需要 task ID、project 名、Hook 路径、账户状态、`creditId` 或用户设置全文。XPC 只传布尔请求、client session ID、generation、update identifier 和有限 Unix 时间戳。-这种能力最小化意味着即使普通 App 层以后新增网络或数据功能,root 进程也不会自动获得这些能力。不应为了复用文件读取或网络代码把业务 service 链接进 helper。+helper target 只包含受限电源操作和共享 XPC 协议,不链接 App 的业务 service。helper 的 ownership 文件不是用户偏好,而是 crash recovery 事务记录。它必须由 root 拥有,拒绝 group 或 world 可写目录,并通过 full sync 加原子 rename 确保重启后能判断是否需要恢复。@@ -287,20 +257,6 @@ helper 的 ownership 文件不是用户偏好,而是 crash recovery 事务记- CodexBarHelper 状态通过 root owner、权限检查、full sync 和原子 rename 提交- Debug 和 Release 共享的数据必须使用锁和兼容 schema-## 缺失、陈旧和不可用的隐私含义--数据不可用时不能用看似友好的默认值掩盖:--| 状态 | 正确表达 | 错误做法 |-| --- | --- | --- |-| 字段从旧来源缺失 | `nil` 或 unavailable | 解码成明确的 0 |-| app-server 缓存过期 | stale 快照 | 继续触发通知 |-| rollout 补充读取不可用 | 保留已有 Hook 任务状态,后续轮询继续补充生命周期 | 把缺少 rollout 结果解释为任务已结束 |-| CloudKit 离线 | 保留带来源的旧 cache | 当作当前账户新数据 |-| 电池读取失败 | 保留上次判定并标记 unreadable | 当作没有电池 |--显式降级不仅提升正确性,也避免为了填满 UI 而读取更多备用来源或保存额外数据。-## 新增数据字段前的审查清单1. 写明产品目标以及没有该字段时无法完成的行为diff --git a/Docs/DeveloperGuide/design-decisions.md b/Docs/DeveloperGuide/design-decisions.mdindex e9fcc0e..ef5f362 100644--- a/Docs/DeveloperGuide/design-decisions.md+++ b/Docs/DeveloperGuide/design-decisions.md@@ -2,316 +2,58 @@简体中文 | [English](../en/DeveloperGuide/design-decisions.md)-这篇文档解释 CodexBar 为什么采用现在的结构,以及这些结构在解决什么问题。+## 状态所有权-它不是源码目录索引,也不是功能列表。阅读目标是建立一套判断标准:当实现需要变化时,哪些只是可以替换的手段,哪些是必须继续成立的系统不变量。+每条数据链路由一个服务维护事实,消费者读取快照或转场:-## 从产品目标推导架构--CodexBar 看起来只是一个菜单栏 App,但它同时横跨 4 个性质完全不同的边界:--- Codex 自己的本机协议和配置-- 持续变化的 Hook 与 rollout 文件-- macOS 窗口、通知和电源管理-- 带 root 权限的系统级睡眠与定时唤醒控制--这些边界不能用同一种失败策略处理。--例如,额度刷新失败时保留上一次数据通常比清空更有价值。Hook 采集失败时必须立即放弃,因为统计不能阻塞 Codex。防睡眠释放失败时则不能静默退出,因为系统设置可能仍被 CodexBar 持有。--因此项目没有追求一个包办所有工作的全局 service,而是先按输入来源和失败语义拆开,再在 UI 和副作用层组合只读快照。--## 决策优先级--遇到实现取舍时,按以下顺序判断:--1. 不阻断用户正在执行的 Codex 任务-2. 不遗留或误改系统级状态-3. 不把旧数据、缺失数据或不确定状态伪装成当前事实-4. 不让迟到的异步结果覆盖更新的用户意图-5. 不扩大特权进程、网络和持久化数据的边界-6. 在上述条件成立后再优化延迟、文件大小和 UI 动画--这个顺序解释了很多看起来不对称的处理:--- Hook recorder 获取锁超时后丢弃本次统计,而不是继续等待-- App 退出时可以被延后,直到 helper 确认释放由 CodexBar 拥有的睡眠状态并取消自动重置唤醒计划-- app-server 补充接口失败时可以展示带陈旧标记的缓存,但 method unsupported 必须展示来源缺失-- 唤醒恢复如果没有通过新的 Hook 读取屏障,异常会话保护继续暂停--## 事实、快照与副作用--项目中的状态分为 3 层:--| 层级 | 含义 | 示例 |+| 链路 | 状态来源 | 输出用途 || --- | --- | --- |-| 事实 | 外部系统或本地日志已经发生的输入 | Hook 事件、rollout terminal、app-server 响应 |-| 快照 | 对一组事实按当前规则得到的可展示状态 | `CodexQuotaSnapshot`, `WorkflowSnapshot`, `CodexActivitySnapshot` |-| 副作用 | 因可信状态变化而执行的一次性动作 | 通知、触觉反馈、XPC 租约、CloudKit 上传 |--设计上刻意不让 View 从原始事实直接执行副作用。--例如,通知服务不扫描任务中心列表猜测哪个任务刚完成,而是消费 monitor 发布的 transition。防睡眠控制器也不解析 Hook,它只消费活动快照中的运行和等待任务。--这样做有两个原因:--- 快照可以重复读取,transition 必须最多消费一次-- 同一个状态机可以统一处理 bootstrap、去重、迟到事件和 rollout 对账,消费者不需要各自实现一套近似规则--## 3 条数据链路为什么必须独立--### app-server 链路--app-server 提供账户、额度和 token 用量的周期性快照。它适合按分钟刷新,允许在短暂故障时展示同账户缓存。--### Hook 历史链路--历史链路把 append-only 原始事件转成日级聚合。它允许延迟,可以从原始 JSONL 重建,主要目标是长期一致性。--### 实时任务链路--实时链路关心秒级任务状态和一次性转场。它需要组合 Hook 与 rollout,不能等待日级聚合完成,也不能把十分钟前的终态当成一条新通知。--如果把三者合并成一条链路,会产生错误耦合:--- app-server 暂时失败会让本来仍可读取的本地任务状态消失-- 聚合重建会阻塞实时任务更新-- 为通知设计的 terminal 去重会污染历史计数-- CloudKit 或网络故障会反向影响本地 Hook 展示--允许它们在 UI 层组合,但不允许互相充当事实来源,是 CodexBar 最重要的架构边界之一。--## 用户意图、依赖可用性与实际效果--设置类功能通常同时存在 3 种状态:--```text-用户意图 -> 依赖是否可用 -> 实际效果-```--防睡眠是最完整的例子:--- `isEnabled` 表示用户愿意让 CodexBar 管理睡眠-- Hook、helper、电量和时长共同决定当前是否具备执行条件-- `isPreventingSleep` 表示 App 与 helper 已经确认实际效果--依赖暂时不可用时不能把 `isEnabled` 写回 `false`。否则一次 RPC 故障就会永久修改用户偏好,恢复后也无法自动继续。--Hook 设置同样区分:--- `isEnabled` 表示配置文件中安装了 handler-- `isVerified` 表示 app-server 最近一次给出明确可用结论-- `isOperable` 才是下游依赖应使用的状态--这个三层模型比一个布尔值多一些状态,但避免了把配置、诊断和效果混成不可解释的开关。--## 不确定性必须进入类型和 UI--项目中多处保留 `nil`, stale 或 degraded,而不是统一回落为零或空数组。--### 缺失不等于零--旧 Hook 数据没有某个计数字段时,`nil` 表示当时没有采集能力。`0` 才表示数据源明确确认没有发生。--如果把两者合并,历史图表会把不可知数据画成真实零值,后续无法再修复解释。--### 陈旧不等于失败--同一账户的 app-server 补充接口暂时失败时,旧额度或用量仍有参考价值。快照用 `isRateLimitsStale` 和 `isUsageStale` 标记它们,UI 通过透明度表达可信度下降,通知则完全跳过陈旧额度。--### 降级 bootstrap 不等于空闲--实时 reader 无法获得稳定文件边界时会跳到文件末尾,但同时发布 degraded 和数据源不健康。这不是“确认当前没有任务”,而是“无法可靠恢复现有任务”。--## 为什么大量使用 generation--CodexBar 的 I/O 大多具有以下共同风险:--1. 请求 A 开始-2. 用户改变设置或 reader 被替换-3. 请求 B 开始并先完成-4. 请求 A 最后返回--只取消 Task 不足以解决这个问题。某些系统 API 和同步桥接不能真正取消,旧回调仍可能到达。--因此关键异步路径同时维护单调递增 generation:--- 刷新协调器只允许当前 generation 提交-- Hook 设置只允许最新操作更新 UI-- tail reader 替换后丢弃旧 reader batch-- 唤醒恢复同时校验 reader generation 和 recovery generation-- XPC 租约请求用 generation 防止迟到的 acquire 覆盖 release-- helper 状态请求和 CloudKit 可用性检查也按 generation 丢弃旧结果--generation 的价值不是“更容易取消”,而是让提交资格成为可以验证的显式条件。--## 为什么使用 actor、MainActor 和锁三种并发手段--三者解决的问题不同:--| 手段 | 解决范围 | 典型对象 |-| --- | --- | --- |-| `MainActor` | UI 可观察状态和 AppKit 生命周期 | Controller, ViewModel, Settings, Monitor |-| Swift actor | 单进程内异步可变状态 | app-server、聚合、reader、CloudKit service |-| `flock` | 多进程共享文件事务 | Hook recorder 与主 App 的统计文件 |--actor 不能保护另一个 CodexBar Hook 子进程。`flock` 也不适合承载 UI 状态。选择并发工具时先确认竞争发生在哪个边界,不要因为项目已经使用 actor 就把所有同步问题都塞进 actor。--默认 `MainActor` 让 UI 类型更安全,代价是任何阻塞式文件或 pipe 等待都必须显式移出主 actor。`AppServerSession` 和底层 pipe reader 使用受锁保护的非隔离边界,上层 `CodexStatusService` actor 再串行管理连接。--## 为什么原始日志与派生缓存分开--Hook 原始 JSONL 是可审计事实,`daily.jsonl` 是当前算法生成的缓存。--这种结构提供 3 个长期收益:--- 聚合算法修正后可以重建历史,不需要为每个旧字段设计迁移-- 写入关键路径只追加一行,不需要在 Codex 等待的几秒内读改写整份统计-- CloudKit 同步可以只上传聚合,保持原始身份和路径留在本机--代价是必须明确管理 schema、offset 和来源替换。因此维护状态保存 `sourceGeneration`, inode, size, boundary hash 和 dirty/pending 状态。--## `sourceGeneration` 解决的不是版本号问题--同一天的事件文件可能被替换、截断或由用户重建。日期相同并不代表它还是同一份事实来源。--`sourceGeneration` 给“这份日期数据来自哪一代原始文件”一个稳定身份:--- 正常追加保持同一 generation-- inode 变化、文件缩小或已消费边界被改写时创建新 generation-- CloudKit record name 可以区分不同 generation-- 展示层只把明确独立的贡献相加,同源结果按替换处理--如果只用日期作为身份,重建后的新值会和旧云端值叠加,产生永久双重计数。--## 为什么实时任务同时读取 Hook 和 rollout--两种来源各自只解决一半问题:--| 来源 | 优势 | 缺口 |-| --- | --- | --- |-| Hook | 延迟低、事件类型清楚、适合实时 UI | `Stop` 不能总是区分完成与中断,部分上下文字段可能缺失 |-| rollout | terminal, effort 和 reviewer 更权威 | 文件定位和解析更慢,不适合作为唯一低延迟信号 |--monitor 先用 Hook 建立活动状态,再用 rollout 补齐生命周期。`Stop` 形成完成候选,`SessionEnd` 或新 prompt 会把任务移入短暂终态确认窗口,rollout 在宽限期内给出准确分类。--这不是简单的“双源合并”。冲突时需要按语义决定谁更权威,还要防止迟到事件复活已经完成的任务。--## 为什么特权 helper 只接受受限电源操作--App 需要 root 权限修改 `pmset disablesleep` 和登记系统 `wake` 事件,但任务识别、自动重置判断、网络和文件解析不需要 root。--把策略放进 helper 会显著扩大攻击面和故障恢复范围。当前边界把 helper 限制为一个小型执行器:--- 输入只有睡眠租约、generation、状态查询、更新恢复标识和有限的 Unix 唤醒时间戳-- 睡眠命令固定为 `/usr/bin/pmset` 的固定参数组合,唤醒计划固定为 CodexBar owner 和 `wake` 类型-- 客户端通过 code-signing requirement 校验-- helper 不读取 Codex 文件、不访问网络、不接受任意路径或命令--App 决定“应该怎样”,helper 只负责“以受限权限执行并验证”。--## 为什么租约还需要所有权记录--租约解决“还有没有活跃 App 请求”,所有权解决“当前系统值是不是 CodexBar 改的”。--两者不能互相替代:--- 没有租约时 helper 应撤销自己的效果-- 但如果 `SleepDisabled=1` 原本由用户或其他 App 设置,CodexBar 没有权恢复为 `0`-- 如果 CodexBar 完成了 `0 -> 1`,helper 必须先持久化 owned,崩溃后才能恢复--因此释放条件是“最后一个租约结束并且 ownership 为 owned”,而不是简单看到没有客户端就写 `0`--## 为什么 CloudKit 同步聚合而不是原始事件--跨设备展示只需要日级统计。上传原始事件会带来额外身份信息、更大的数据量和更复杂的去重,却不增加当前产品能力。--同步聚合的收益包括:--- session, turn 和 agent ID 保留在本机-- 网络和 CloudKit 操作量由事件数降为日期数-- 本机仍然可以独立重建,云端只保存各设备贡献-- 设备间合并规则可以围绕 `deviceId + date + sourceGeneration` 定义--project 显示名仍可能敏感,所以同步必须由用户主动开启,不能因为已经登录 iCloud 就默认上传。--## 容易忽略的小巧思--### `@Published` 回调参数比现场回读更可靠--Combine 的发布发生在 `willSet`。订阅闭包执行时,属性本身可能仍是旧值。--因此 Hook 可用性、同步 activation 和防睡眠依赖在订阅路径中使用闭包参数计算,而不是立刻回读对象属性。这是多个看似重复的状态镜像存在的原因。--### 边界 hash 只覆盖已经消费的尾部--历史聚合不对每个文件每轮全量 hash。它只保存 offset 前 4 KB 的 boundary hash,再用 mtime 判断是否需要重算。--正常追加只发生在 offset 之后,不会改变这个边界。这既能发现已消费内容被原地改写,又避免长期持有 `stats.lock`,让 Hook 子进程更快落盘。--### 状态排序有 UUID 兜底--多个任务时间戳可能相同,而 Swift sort 不稳定。快照在时间相等时再按 UUID 字符串排序,避免 SwiftUI diff 因无意义的顺序抖动反复刷新。--### 通知提交前再次检查相关性--等待批准和异常保护通知从判定到系统真正接收之间存在异步窗口。任务可能已经恢复运行。--通知服务在每次提交和重试前调用 `isStillRelevant`,失效则撤回 pending 与 delivered notification。这比只在状态变化时尝试删除更可靠。+| app-server | 账户、额度和用量响应 | 周期性展示,同账户内可使用 stale 缓存 |+| Hook 历史 | 原始 JSONL | 可重建的日级统计与跨设备同步 |+| 实时任务 | Hook 增量事件与 rollout 生命周期 | 活动快照、任务通知和防睡眠 |-### XPC 请求超时不能清除“可能持有租约”+快照可以反复读取;通知使用 live transition,bootstrap 只建立基线,不补发历史通知。历史聚合与额度刷新共享部分触发时机,但读取和失败处理独立。组件关系见 [整体架构](architecture.md)-请求超时只能说明回复没有到达,不能证明 helper 没有执行 acquire。`mayHaveHelperLease` 因此一直保留到一次明确成功的 release。+## 用户意图与实际效果-如果超时就直接清零,App 退出时可能跳过释放,让 helper 等到 watchdog 才恢复系统状态。+保存的开关表示用户意图,依赖状态决定是否能执行,结果状态表示已经确认的效果。依赖临时不可用时保留用户开关,恢复后重新协调。-### 外部睡眠来源需要持续观察+防睡眠的 `isEnabled`、`sleepBlockReason` 和 `isPreventingSleep` 分别对应这三层。Hook 的 `isEnabled` 与 `isVerified` 共同决定 `isOperable`;实时任务依赖可操作状态,历史聚合仍可处理已落盘数据。-任务开始时如果系统已经 `SleepDisabled=1`,helper 将来源标记为 external。但外部来源可能在任务仍运行时自行撤销。+## 缺失、陈旧与不可信数据-helper 定期读取实际值。一旦 external 消失而租约仍有效,CodexBar 可以安全完成自己的 `0 -> 1` 并取得 owned,防睡眠不会悄悄失效。+| 状态 | 当前处理 |+| --- | --- |+| app-server 补充接口暂时失败 | 使用同账户缓存并标记 stale,降低 UI 透明度,不触发额度通知或自动消费 |+| method unsupported | 当前 session 缓存能力缺失,重建连接后重新探测 |+| 历史 Hook 计数字段缺失 | 持久化和同步模型保留 `nil`;当前展示投影仍会按规则回退为计数 |+| 实时 reader 无法取得稳定边界 | 发布 degraded health,暂停异常会话保护 |-### 菜单栏锚点必须先验证+这些状态由来源层给出,消费方按用途决定是否展示或执行副作用。计数投影见 [Hook 聚合](hook-and-aggregation.md),账户缓存见 [app-server](app-server.md)-全局快捷键触发时,`NSStatusBarButton` 可能暂时没有可用 window 或位于另一块屏幕。直接展示 popover 会出现位置错误或完全不显示。+## 并发与过期结果-控制器先验证锚点尺寸和屏幕交集,不可信时在鼠标所在屏幕使用 fallback panel。两种容器共享同一个 SwiftUI 内容,业务层不用知道当前是哪一种。+| 手段 | 保护范围 |+| --- | --- |+| `MainActor` | UI、控制器及可观察状态的提交顺序 |+| actor | 服务进程内的共享状态和 I/O 协调 |+| `NSLock` 等锁 | 非隔离 pipe reader 等同步接口的可变状态 |+| `flock` | Hook 子进程、主 App、Debug 与 Release 之间的共享文件事务 |-### 只调度最近一个真实截止时间+异步调用返回时,配置或 reader 可能已经变化。不能取消的系统回调通过 generation 校验后才提交;请求取消与代际检查各自处理任务生命周期和结果归属。-任务过期、完成高亮、terminal grace 和异常静默都不是靠高频 UI timer 扫描。monitor 收集所有截止时间,只为最近一个建立 Task,到点后重算并安排下一次。+菜单淡入淡出的完成任务在取消检查后同步提交,因此只保存一个可取消 Task。XPC、reader 更换和系统唤醒路径仍需 generation;各路径的具体字段见对应专题。-这样能减少菜单栏 App 常驻时的无意义唤醒,也让每个保留期在代码中有明确来源。+Combine 的 `@Published` 在 `willSet` 发布。组合设置状态时使用订阅闭包收到的新值,避免回读尚未更新的属性。-## 修改设计时的检查方法+## 可重建数据与恢复记录-新增功能或修改核心语义前,依次回答以下问题:+Hook 原始 JSONL 是历史重建来源,日聚合是派生结果。聚合语义变化通过 schema 递增触发保留期内完整重建。文件替换由 `sourceGeneration` 区分,同日同源数据按替换合并,独立来源才累加。-1. 新数据来自哪条链路,它的权威来源是什么-2. 数据缺失、旧值、明确零值和失败是否被区分-3. 这是可重复读取的状态,还是最多执行一次的 transition-4. 异步结果返回时如何证明自己仍属于当前 generation-5. 是否扩大了网络、持久化、CloudKit 或 root helper 的边界-6. 是否影响旧 UserDefaults、本地 schema、CloudKit record 或 Debug 与 Release 共存-7. 崩溃、强制退出、系统睡眠和文件替换后如何恢复-8. 哪些日志足以区分正常降级和真实故障,同时不泄露用户数据-9. 哪些手动场景能验证设计不变量,而不只是验证理想路径+异常会话保护记录和 helper ownership 则用于恢复已经发生的状态变化。前者异步保存,隐藏不等待落盘;后者必须先持久化恢复责任,再修改系统睡眠值。具体顺序见 [实时任务监控](activity-monitor.md) 和 [防睡眠系统](sleep-prevention.md)-如果其中任何一项没有明确答案,说明实现还没有形成完整的生命周期设计。+## 特权与上传范围-## 不应轻易改变的不变量+任务识别、自动重置策略和网络访问在主 App 中执行。root helper 只接受固定的睡眠租约与唤醒操作,通过签名校验客户端,并回读系统结果。-- Hook 子进程失败不能阻断 Codex-- 3 条数据链路保持独立-- `CodexActivityMonitor` 是实时任务唯一状态来源-- bootstrap 不发布历史 transition-- `drainNow()` 保证请求后的新读取屏障-- 缺失的计数字段不解释为 `0`-- 原始事件是聚合缓存的重建来源-- 聚合语义变化递增 schema 并完整重建-- root helper 不获得网络、任意命令或额外文件读取能力-- 只有 CodexBar 自己取得的睡眠所有权可以由 CodexBar 恢复-- 自动重置只替换或取消 CodexBar 固定 owner 的 `wake` 事件,不修改其他计划事件-- 通知描述系统效果时,必须在效果已经确认后发送-- 匿名任务不进入通知、防睡眠和异常会话保护-- 兼容性变化必须先确定迁移与降级策略+CloudKit 只同步日级聚合。原始事件、会话标识、账户和代理密码留在本机;项目显示名属于上传内容,必须由用户开启同步。字段和存储范围见 [数据与隐私边界](data-and-privacy.md)diff --git a/Docs/DeveloperGuide/development.md b/Docs/DeveloperGuide/development.mdindex 713e854..bbc2b5c 100644--- a/Docs/DeveloperGuide/development.md+++ b/Docs/DeveloperGuide/development.md@@ -2,494 +2,115 @@简体中文 | [English](../en/DeveloperGuide/development.md)-## 环境要求+## 环境与构建-- macOS 15 或更高版本-- Xcode 和 macOS SDK-- Swift 6 toolchain-- `swiftformat`-- `swiftlint`-- 本机可用的 Codex CLI 或包含内置 Codex 的 App--工程使用 `CodexBar` scheme,日常构建不需要 Developer ID 或公证凭据。--## 工程结构--| 目录 | 职责 |-| --- | --- |-| `CodexBar/App` | App 启动入口 |-| `CodexBar/Controllers` | AppKit 生命周期、菜单栏和窗口控制 |-| `CodexBar/Models` | 业务 DTO、快照和展示模型 |-| `CodexBar/Services` | app-server、Hook、任务、同步、通知和系统服务 |-| `CodexBar/Views` | SwiftUI 界面 |-| `CodexBar/Resources` | plist、entitlement、本地化和资源 |-| `CodexBarHelper` | root LaunchDaemon |-| `Shared` | XPC 共享接口 |-| `Config` | 版本配置 |-| `Scripts` | 发布和维护脚本 |--## 第一次阅读代码的建议顺序--不要从 View 反向猜业务状态。推荐沿事实流阅读:--1. 从 [`CodexBarApp.swift`](../../CodexBar/App/CodexBarApp.swift) 确认 Hook 子进程分流-2. 从 [`CodexBarAppDelegate.swift`](../../CodexBar/Controllers/CodexBarAppDelegate.swift) 查看普通模式 composition root-3. 从 [`StatusItemController.swift`](../../CodexBar/Controllers/StatusItemController.swift) 查看菜单栏和窗口编排-4. 选择一条数据链路阅读 source, service, snapshot 和 ViewModel-5. 再看通知或防睡眠如何订阅上游结果-6. 最后查看 SwiftUI 如何展示状态和发出用户意图--以实时任务为例:--```text-WorkflowHookEventRecorder- -> HookEventTailReader- -> CodexActivityMonitor- -> CodexActivitySnapshot / CodexActivityTransition- -> StatusItemController 组装- -> UI- -> CodexNotificationService- -> KeepAliveController-```--先找到 authoritative state 能避免把 UI 缓存、通知去重集合或 controller 中间态误认为业务事实。--## 修改前先写清楚 5 件事--实现一个非纯视觉变化前,至少在设计或开发笔记中回答:--| 问题 | 示例 |-| --- | --- |-| 目标事实 | “任务已经等待用户批准”,而不是“显示橙点” |-| 权威来源 | reviewer 确认后的 Hook event |-| 派生消费者 | 活动卡片、通知、防睡眠 |-| 失败语义 | reader 不可用时暂停判定 |-| 验收证据 | 转场一次、不补发 bootstrap、恢复后对账 |--这一步的价值不是增加流程,而是提前发现一个字段被 3 个副作用消费者赋予了不同含义。--## 常见改动应该落在哪一层--| 改动 | 首选位置 | 避免放置 |-| --- | --- | --- |-| app-server 协议 method | `CodexStatus/` service 和 DTO | SwiftUI View |-| Hook 原始字段 | recorder model 和 aggregation projection | CloudKit record 直接读取 stdin |-| 实时任务转场 | `CodexActivityMonitor` | 通知服务从历史列表推断 |-| 日统计展示 | `WorkflowViewModel` 投影 | View 重新合并 raw event |-| 系统通知 | `CodexNotificationService` | 按钮 action 或 View lifecycle |-| 防睡眠条件 | `KeepAliveController.sleepBlockReason` | 多个 UI computed property |-| 窗口行为 | AppKit Controller | service 或 model |-| 用户默认值 | 对应 Settings 类型 | 分散的 `UserDefaults.standard` 调用 |--小改动优先延伸现有类型职责。只有当新能力拥有独立生命周期、状态所有权或故障边界时才值得新建 service。--## 日常检查--### 构建--```bash-xcodebuild \- -project CodexBar.xcodeproj \- -scheme CodexBar \- -destination 'generic/platform=macOS' \- build-```--### 格式化+需要 macOS 15+、Xcode、Swift 6、`swiftformat` 和 `swiftlint`。唯一 scheme 为 `CodexBar`,包含 App 与 `CodexBarHelper` 两个 target,没有 XCTest target。```bash+xcodebuild -project CodexBar.xcodeproj -scheme CodexBar -destination 'generic/platform=macOS' buildswiftformat .-```--工程使用 Swift 6 和 4 空格缩进,配置位于 `.swiftformat`--### 静态检查--```bashswiftlint```-规则位于 `.swiftlint.yml`--仓库当前没有 XCTest target 或覆盖率门槛。构建、格式化和 lint 不能替代受影响流程的手动验证。--### 推荐检查顺序--```text-检查工作树范围- -> 完成最小实现- -> swiftformat- -> 审查格式化 diff- -> swiftlint- -> xcodebuild- -> 针对性手动验证- -> git diff --check-```--先格式化再构建可以让最终验证覆盖真正准备提交的代码。但仓库已有用户未提交改动时,不应无差别格式化整个仓库造成无关修改。先用 `git status --short` 和 `git diff --name-only` 确认范围,必要时只格式化本次触及的 Swift 文件。--`xcodebuild` 验证 Swift 6 并发检查、target membership、entitlement 和资源引用。`swiftlint` 验证风格与部分静态规则。两者不能验证 AppKit focus、XPC crash recovery 或通知 relevance。--纯文档变更仍按仓库约定运行格式化、lint 和构建。这些检查不验证文档内容,因此还要额外检查 Markdown 相对链接、`git diff --check` 和仓库中文标点规则。+格式配置见 `.swiftformat`,使用 Swift 6 和 4 空格缩进。`swiftlint` 只检查 `CodexBar/`,不覆盖 `Shared/`、`CodexBarHelper/` 和 `Scripts/`-### 如何读构建失败+修改前检查 `git status --short`。已有未提交改动时,仅格式化本次涉及的 Swift 文件,或使用 `swiftformat --lint . --cache ignore` 检查。`swiftlint --no-cache` 可避免写入缓存。-优先找第一条实际 `error:` 而不是最后的 `BUILD FAILED`+日常构建不需要 Developer ID 或公证凭据。写作、Git 和兼容性规则见 [AGENTS.md](../../AGENTS.md)-- actor isolation error 通常说明状态所有权不清,不应先加 `nonisolated(unsafe)` 压掉-- missing file 或 resource error 先检查 target membership 和 Xcode project 引用-- helper protocol error 需要同时检查 App target、Helper target 和 `Shared` 接口-- entitlement 或 signing error 要先确认当前是 Debug 还是 Release identity+## 修改入口-修复第一处根因后重新构建,后续大量泛型或 module error 往往只是级联结果。+| 功能 | 主要位置 | 实现说明 |+| --- | --- | --- |+| app-server、代理、自动重置 | `Services/CodexStatus` 与对应 Settings | [app-server 数据链路](app-server.md) |+| Hook 安装与统计 | `CodexHookSettings`、`WorkflowService`、聚合模型 | [Hook 采集与历史聚合](hook-and-aggregation.md) |+| 实时任务与异常保护 | `CodexActivityMonitor` 和 readers | [实时任务监控](activity-monitor.md) |+| 防睡眠与系统唤醒 | `KeepAliveController`、`AutoResetWakeScheduler`、helper | [防睡眠系统](sleep-prevention.md) |+| 通知与音效 | `CodexNotificationService`、通知 Settings | [通知系统](notifications.md) |+| 同步 | `WorkflowSyncService` 与 scheduler | [CloudKit 同步](sync.md) |+| 菜单、窗口、快捷键 | `Controllers` 与对应 View | [UI 与应用生命周期](ui-and-lifecycle.md) |-## 日志+长期对象由 `CodexBarAppDelegate` 装配。新增状态优先放入现有所有者,View 消费快照并发出操作意图。源码阅读入口见 [整体架构](architecture.md)-查看 Release 系统日志:+## 变更检查-```bash-/usr/bin/log stream \- --predicate 'subsystem == "app.zabrian.codexbar"' \- --style compact-```+涉及持久化 key、schema、身份计算、最低系统版本或新旧版本共存时,先说明影响和可选兼容方案,等待用户选定。新增网络访问、日志字段或 CloudKit 字段时核对 [数据与隐私边界](data-and-privacy.md)-Debug subsystem 带 `.debug` 后缀。+聚合算法、输出字段含义或去重规则变化时,递增 `WorkflowMaintenanceState.currentAggregationSchema`,从保留期内原始 JSONL 完整重建,不增加字段级历史迁移。-App 内日志窗口展示当前进程最近 500 条 app-server 交互日志,适合排查 CLI 定位、handshake、method unsupported 和重试。+异步修改需要检查取消、结果提交时的资格和 generation。跨进程文件仍使用 `flock`;actor 只保护单进程。`@Published` 订阅使用闭包的新值参与判断,避免 `willSet` 阶段回读旧属性。-### 日志应回答什么+## 验证流程-一条有用状态机日志应至少能回答:+1. 检查修改范围,确认未覆盖已有工作+2. 格式化并运行 `swiftlint`+3. 构建 App 与 helper+4. 手动验证受影响的正常、失败和恢复流程+5. 检查文档及 `git diff --check`-- 谁触发了本轮操作-- 当前想达到什么状态-- 哪个阶段失败-- 采取了什么降级或重试动作-- 操作耗时和处理规模+构建失败时先定位第一条实际 `error:`。签名或 entitlement 错误要核对 Debug/Release 身份;helper 协议修改同时检查两个 target 与 `Shared`。编译和静态检查不覆盖窗口焦点、系统授权或硬件电源行为。-仓库使用 `LogTrigger`, `LogDuration` 和 `LogFields.joined` 统一这些字段。高频轮询只在状态翻转或结果变化时记录,避免真正异常被空转日志覆盖。+纯文档修改运行格式检查、lint 和构建,并检查相对链接与中英文内容。-推荐用稳定英文 key 加受控值,例如:+### 手动场景-```text-trigger=wake want=0 reason=lowBattery elapsed=0.183s-```--不要记录通知正文、完整路径、identity 或 token。如果错误的 `localizedDescription` 可能包含敏感请求信息,应先做错误分类再记录。+| 改动范围 | 重点场景 |+| --- | --- |+| 菜单与窗口 | 快速开关、淡出中重开、popover/fallback、多屏与 Space、设置和日志焦点、通知点击和快捷键 |+| Hook 与聚合 | 保留已有 handler、最低版本、并发追加、半行和损坏行、文件替换与截断、完整重建 |+| 实时任务 | bootstrap 不补通知、等待审批、迟到终态、匿名任务、唤醒读取屏障失败与恢复 |+| 通知 | 授权拒绝与恢复、阈值跨越、同周期去重、任务恢复撤回、声音缺失 |+| 代理 | 首次配置、启停、无效配置停用、损坏记录删除、测试取消、快速操作与失败回滚 |+| 同步 | 首次上传、多设备合并、断网续传、部分上传失败、重建替换、iCloud 账户切换 |+| 系统电源与 helper | 首次授权、任务运行/等待切换、低电量、时长上限、外部睡眠来源、异常退出与重启 |+| 自动重置唤醒 | 计划替换、关闭与退出清理、连接中断、helper 重启、注销前清零、到点重新读取 |-### 按 subsystem 和阶段排查+helper 改动还需检查 App 包内可执行文件和 plist 的位置、签名与注册指纹。各专题末尾列出更细的状态转换场景。-| 症状 | 优先日志和状态 |-| --- | --- |-| 额度不刷新 | app-server handshake, method, retry, stale |-| Hook 没有统计 | hooks 配置、recorder timeout、maintenance counts |-| 实时任务卡住 | tail reader generation, rollout reconcile, data source availability |-| 同步缺数据 | sync stage、local 和 confirmed 数量、replacement dates |-| 通知不出现 | authorization, kind, duplicate 或 obsolete |-| 防睡眠不生效 | block reason, helper registration, XPC generation, source |-| 自动重置未执行 | target、threshold、retry window、helper registration、wake schedule |+记录验证使用的构建、前置设置、操作序列、实际结果和相关日志,便于复现。## Debug 与 Release-两种配置使用不同身份:--| 配置 | App bundle ID | CodexBarHelper bundle ID |+| 配置 | App bundle ID | Helper bundle ID || --- | --- | --- |-| Release | `app.zabrian.codexbar` | `app.zabrian.codexbar.helper` || Debug | `app.zabrian.codexbar.debug` | `app.zabrian.codexbar.debug.helper` |+| Release | `app.zabrian.codexbar` | `app.zabrian.codexbar.helper` |-排查 CodexBarHelper 安装、LaunchDaemon 或系统授权时不要混用两个配置。--Hook handler 绑定当前 App 可执行文件路径。在 Debug 和 Release 之间切换时,先确认实际安装的 handler 指向目标版本。--### 为什么两个构建仍会共享部分状态--Debug 和 Release bundle ID 分离是为了让 App、helper 注册和系统授权互不覆盖。但 Hook 原始数据与 Activity Protection 需要观察同一个 Codex 工作事实,因而按设计共享文件。--共享意味着:--- 文件写入必须使用 `flock`,actor 只保护单进程-- schema 必须在两个版本共存时可解释-- identity hash 算法变化会同时影响两个构建-- 排查时要记录哪个 App 正在写,哪个 helper 正在控制系统--不要用修改目录名的方式临时隔离 Debug,这会改变产品定义的数据来源并掩盖真实共存问题。--## 架构规则--### 启动入口--`WorkflowHookEventRecorder.handleIfRequested()` 必须是 App 初始化的第一项工作。--`--hook-event` 模式只读取 stdin,加锁写入 JSONL 并立即退出。不初始化 UI、通知、CloudKit 或其他长期服务。--### MainActor--UI, Controller, ViewModel 和 Settings 依赖默认隔离。阻塞文件、子进程和网络 I/O 放入 actor 或异步服务。--共享可变状态放入 actor。DTO 和跨 actor 值类型按需要补充并发声明,不通过关闭检查绕过 Swift 6 诊断。--#### MainActor 不是 I/O 队列--工程默认隔离让 UI 状态修改更清晰,但不意味着文件和子进程工作可以同步执行在主线程。--合适的模式是:--```text-MainActor 捕获不可变输入- -> actor 或 async API 执行 I/O- -> 返回 Sendable 结果- -> MainActor 校验 generation- -> 提交快照-```--不要把可变 controller 或 non-Sendable AppKit 对象传入后台 closure。需要跨 actor 的 DTO 应尽量是小型 value type,并让 `nonisolated` 表达类型本身不依赖 actor,而不是绕开某个具体访问错误。--#### actor 与 `flock` 解决的问题不同--- actor 串行化同一进程中的 task-- `flock` 协调 App、Hook 子进程、Debug 和 Release 等多个进程--一个 actor 内安全的 read-modify-write 仍可能被另一个进程打断。反过来,只有 `flock` 也不能自动保护 actor reentrancy 中 await 前后的内存状态。--#### `@Published` 的 `willSet` 语义--Combine sink 收到新值时,发布对象的属性可能仍是旧值。需要基于变化后组合状态决策时:--- 使用 sink 参数作为正在变化的值-- 其余未变化依赖可以从对象读取-- 或把完整新状态封装成一个快照再发布--仓库中的同步 activation 和低额度阈值重判都依赖这一规则。将回调参数改成现场读取会产生一帧反向决策。--### 数据链路--保持以下链路独立:--- app-server 账户、额度与用量-- Hook 历史聚合-- `CodexActivityMonitor` 实时任务--新增 UI 可以组合 3 条链路的快照,但不能让一条链路成为另一条链路的隐式前置条件。--组合只能发生在展示或显式业务策略层。例如菜单栏可以同时展示额度条和活动点,但 app-server 失败不能阻止 activity monitor 更新,Hook maintenance 也不能等待 CloudKit 才发布本机统计。--新增跨链路行为时应写出 truth table。防睡眠就是一个合法例子:它明确声明需要 Hook 可用和非匿名实时任务,而不是因为两个对象恰好在同一 controller 中就形成依赖。--### Hook--- handler 修改保留现有用户和第三方配置-- 启用与校验检查实际 app-server 版本不低于 `0.145.0`-- Hook 子进程失败不能阻断 Codex-- `SessionEnd` 超时为 3 秒,其他事件为 5 秒-- `drainNow()` 必须维持读取屏障语义-- 数据源不可用时不能使用旧快照继续判定--新增 Hook event 时要同时审查:--1. Codex 配置中的 handler group 和 timeout-2. recorder 白名单字段与 fail-open 路径-3. raw JSONL 解码的前后兼容-4. aggregation 的计数和 missing 语义-5. realtime monitor 是否消费该事件-6. CloudKit 投影是否需要新字段-7. 隐私文档和日志字段--不是每个 event 都需要进入全部层。明确写“不消费”比让下游依赖默认 decoder 行为更容易维护。--### 聚合--原始事件到聚合结果的算法、字段、含义或去重规则变化时:--1. 递增 `WorkflowMaintenanceState.currentAggregationSchema`-2. 从保留期内原始 JSONL 完整重建-3. 不增加字段级历史迁移-4. 保留 missing 与 `0` 的区别-5. 标记 CloudKit 当前设备 replacement 日期--schema 递增的判断标准是语义输出是否会因同一份 raw event 得到不同结果,而不是 Codable 是否还能解码。即使只修正去重规则,也必须重建,因为旧 daily 文件已经固化了错误结果。--完整重建优于字段级迁移,因为 raw JSONL 才是事实来源。字段级迁移必须猜测旧算法中丢失的信息,长期会堆积不可组合的历史分支。--### 系统电源控制--- CodexBarHelper 只控制固定的睡眠状态和自动重置 `wake` 事件-- CodexBarHelper 不增加网络或任意命令能力-- 外部 `SleepDisabled=1` 不能被 CodexBar 声明或恢复-- 租约、watchdog 和 owned 持久化必须共同成立-- 自动重置唤醒接口只接受有限时间戳,owner 和事件类型由 helper 固定-- App 退出前确认睡眠状态恢复并取消自动重置唤醒计划--修改防睡眠时先写出 acquire, release, timeout, crash 和 external-owner 5 条时序。只验证正常开关无法证明全局系统状态可恢复。--修改自动重置唤醒时先写出 schedule、replace、cancel、connection-loss、helper-startup 和 unregister 6 条时序。系统回读必须证明固定 owner 最终只有一个匹配事件或已经清零。--任何新增 helper 方法都要先证明必须由 root 执行。能在普通 App 完成的读取、网络或文件操作不得因为“方便复用”放进 helper。--### 兼容性--以下变化属于兼容性问题:--- 持久化 key 改名或结构变化-- 本地 schema 变化-- CloudKit record 或字段变化-- CodexBarHelper ownership 格式变化-- 自动重置唤醒事件的 owner 或类型变化-- Debug 与 Release 共享身份计算变化-- 最低系统版本或 API 可用性变化--这些变化会影响旧数据、旧 App 或 Debug 与 Release 共存,需要配套的迁移和降级设计。--根据仓库约定,任何兼容性问题都不能由实现者默默选择。在修改前向用户说明:--- 受影响版本和数据范围-- 保留旧格式、一次迁移、完整重建或明确丢弃的可选方案-- 每种方案的失败模式和未来维护成本-- 是否支持旧 App 与新 App 同时运行-- 如何验证升级和必要时降级--得到选择后再实现。文档中记录最终不变量,不只记录迁移步骤。--## 常见改动配方--### 新增设置项--1. 在对应 Settings 或 controller 中定义唯一 key 和缺失时默认值-2. 明确旧用户升级后的值,不依赖 Swift 属性默认值碰巧一致-3. 把设置变化接入唯一 reconcile 入口-4. 避免 View 自己写 `UserDefaults`-5. 验证首次安装、已有安装和切换后立即生效--### 新增状态字段--1. 确认字段是事实、派生状态还是展示格式-2. 放入最靠近权威来源的 model-3. 定义 `nil`, empty, zero 和 stale-4. 检查 Equatable snapshot 是否应因它变化-5. 检查通知、防睡眠和 UI 是否需要消费-6. 如需持久化或同步,先走兼容性与隐私审查--### 新增异步刷新--1. 确定触发来源和 freshness 规则-2. 使用 single-flight 或 coordinator 合并同类请求-3. 为连接或 source replacement 增加 generation-4. 在 await 后重新验证当前资格-5. 定义取消、超时和最后可用快照策略-6. 只在状态变化或最终结果记录日志--### 新增窗口或侧边面板--1. 决定它属于菜单交互表面还是独立辅助窗口-2. 复用 `HostingWindowController` 或 `MenuSideDetailPanel`-3. 加入互斥名册和 extra hit region-4. 处理多屏 visible frame 和 Space-5. 验证 key focus、activation 和关闭动画中间态--## 按改动类型验证--### 菜单和窗口--- 左键、右键和 Control 点击行为-- popover 外部点击关闭-- 侧边面板 hit region 和互斥-- 设置与日志窗口焦点-- 全局快捷键和 fallback panel-- 多显示器与不同菜单栏位置--### Hook 和聚合--- 保留已有 handler-- 版本不满足时拒绝启用-- 所有事件能在超时内落盘-- 文件替换、截断和跨日读取-- schema 升级完整重建-- missing 字段不会显示为 `0`+App 偏好和系统授权按身份隔离,Hook 数据与异常会话保护文件共享。排查时确认正在运行的 App、helper 和已安装 Hook 的可执行路径。-### 实时任务+## 日志-- 运行、等待批准、完成和中断转场-- auto review 不进入等待状态-- subagent 归属父任务-- bootstrap 不发送通知-- 系统唤醒完成新读取后再对账-- reader 更换时丢弃旧结果--### 同步+Release 系统日志:-- 首次 backfill-- 多设备合并不重复本机贡献-- 重建只替换当前设备日期-- iCloud 离线、账户切换和恢复-- 保留期清理--### 通知--- 系统权限允许和拒绝-- 阈值 crossing 和持久化去重-- 前台展示与点击激活-- 自定义声音缺失回退-- TUI 通知与 App 通知互不影响--### 系统电源与 helper--- App 包内 CodexBarHelper 和 plist 位置-- App 与 CodexBarHelper 签名-- 首次系统授权-- 运行与等待批准切换-- 低电量和最长时长停止-- 外部 `SleepDisabled` 共存-- 正常退出和异常退出恢复-- 自动重置与防睡眠每次开启时的确认框,以及取消后保持关闭-- Helper 未注册、等待批准和已批准状态对应的确认文案-- 自动重置选项入口只在开关开启且 Helper 已批准时显示-- 自动重置开启时的 helper 注册与系统批准-- 自动重置阈值和重试时间只保留最近一个固定 owner 的 `wake` 事件-- 自动重置关闭、目标变化、正常退出、连接中断和 helper 重启时清理唤醒事件-- helper 注销前确认固定 owner 的唤醒事件已经清零-- Debug 与 Release 分离--## 手动验证如何留下可复查证据--每个受影响流程至少记录:--- 使用的 Debug 或 Release 构建-- 前置设置和数据状态-- 操作序列-- 预期 UI 与实际 UI-- 对应日志关键字段-- 是否检查重启、失败和恢复路径--例如 Hook 唤醒恢复可以记录:--```text-前置: 1 个非匿名 running task, 防睡眠开启-操作: 让 Mac 睡眠后唤醒, rollout 在睡眠期间写入 terminal-预期: drainNow 新一轮成功后任务结束, 不发 bootstrap 通知, helper lease 释放-日志: trigger=wake, reader generation 更新, rollout reconcile 完成+```bash+/usr/bin/log stream --predicate 'subsystem == "app.zabrian.codexbar"' --style compact```-这种记录比“手测通过”更容易在未来回归时重现。+Debug 使用 `app.zabrian.codexbar.debug`,helper 的 subsystem 使用对应 helper bundle ID。-## 完成定义+App 内日志窗口保留最近 500 条 app-server 交互。代理配置错误在系统日志的 `settings` 分类中,临时代理测试不写交互日志。-一项改动只有同时满足以下条件才算完成:+| 问题 | 查看内容 |+| --- | --- |+| 额度未刷新 | handshake、method、retry、stale |+| Hook 未生效 | hooks 配置、版本、信任与完整性 |+| 任务未结束 | reader generation、rollout 对账、数据源健康 |+| 同步缺数据 | zone、fetch、upload、replacement、prune 阶段 |+| 通知未出现 | authorization、kind、duplicate、obsolete |+| 防睡眠未生效 | block reason、helper 注册、XPC generation、source |+| 自动重置未执行 | target、threshold、retry window、wake schedule |-- 代码放在正确状态所有者中,没有复制第二份规则-- 正常、缺失、stale、失败和恢复语义明确-- 并发请求有取消或 generation 边界-- 兼容性和隐私影响已确认-- 格式化、lint 和构建按变更范围通过-- 受影响流程完成手动验证-- DeveloperGuide 与实际常量、schema 和行为一致-- `git diff` 中没有无关用户改动或意外格式化+日志使用 `LogTrigger`、`LogDuration` 和 `LogFields.joined`,记录阶段、分类、计数及耗时。请求内容和身份信息的限制见 [数据与隐私边界](data-and-privacy.md)-## 发布脚本+## 发布与清理脚本-以下脚本需要 Developer ID、签名、公证或 appcast 凭据,不用于日常验证:+| 脚本 | 用途 |+| --- | --- |+| `Scripts/build.sh` | Release archive、Developer ID 导出、公证、staple 与 Gatekeeper 校验 |+| `Scripts/dmg.sh` | 打包 DMG |+| `Scripts/appcast.sh` | 签名更新并生成 appcast |+| `Scripts/cleanup.swift` | 注销 helper;先退出所有 CodexBar 实例,`--check` 只检查,`--debug` 或 `--release` 限定范围 |-- `Scripts/build.sh`-- `Scripts/dmg.sh`-- `Scripts/appcast.sh`+发布脚本需要签名和公证凭据,不用于日常验证。版本号从 [`Version.xcconfig`](../../Config/Version.xcconfig) 读取。-版本号从 [`Version.xcconfig`](../../Config/Version.xcconfig) 读取。+helper 清理先取消并确认系统唤醒计划清零,再注销服务;失败时停止。详细行为见 [防睡眠系统](sleep-prevention.md)diff --git a/Docs/DeveloperGuide/hook-and-aggregation.md b/Docs/DeveloperGuide/hook-and-aggregation.mdindex f2506c9..fea9f64 100644--- a/Docs/DeveloperGuide/hook-and-aggregation.md+++ b/Docs/DeveloperGuide/hook-and-aggregation.md@@ -2,17 +2,6 @@简体中文 | [English](../en/DeveloperGuide/hook-and-aggregation.md)-## 设计出发点--Hook 链路同时服务两个看似接近但要求相反的目标:--- 在 Codex 关键路径上尽快记录事实-- 在主 App 中可靠地维护长期统计--采集端必须短小、有界和允许失败。聚合端则可以异步运行,需要检测文件变化、修复损坏缓存并支持完整重建。--因此实现采用 append-only 原始 JSONL 加可重建日聚合,而不是让 Hook 子进程直接更新一份复杂统计对象。-## 链路职责Hook 链路把 Codex 生命周期事件转换为可重建的本地历史统计:@@ -28,31 +17,11 @@ Codex Hook原始事件是事实来源,日级聚合是可重建缓存。聚合算法或字段语义变化时,必须从保留期内的原始事件完整重建。-### 为什么不在 Hook 子进程里直接聚合--直接读改写 `daily.jsonl` 看起来少一层文件,实际会带来 4 个问题:--- 每个 Hook 都要解码和重写历史数据,事件越多延迟越高-- 子进程在 Codex 的超时预算内,聚合失败会放大成任务延迟-- 算法升级后没有原始事实可重算-- 多个并发 Codex session 更容易在读改写之间丢失更新--当前方案把关键路径缩成一条 append。主 App 可以在自己的节奏里批量聚合,失败时保留原始事件等待下一轮修复。--### 原始事实和缓存的责任--| 文件 | 是否权威 | 允许怎样恢复 |-| --- | --- | --- |-| `events/YYYY-MM-DD.jsonl` | 是 | 只追加,超过保留期后清理 |-| `daily.jsonl` | 否 | 可从原始事件完整重建 |-| `maintenance.json` | 否 | 缺失或 schema 变化时重新对账 |-| `stats.lock` | 不保存业务数据 | 只协调跨进程事务 |-## 安装与校验-[`CodexHookSettings.swift`](../../CodexBar/Services/Settings/CodexHookSettings.swift) 通过 app-server 读取和修改 Hook 配置。+[`CodexHookSettings.swift`](../../CodexBar/Services/Settings/CodexHookSettings.swift) 直接读写本地 `hooks.json`,通过 app-server 读取或修改相关配置,并在写入后调用 `hooks/list` 校验安装结果。-启用前必须满足:+启用流程检查以下条件,其中来源、信任和事件完整性在写入后校验:- 当前可执行文件路径可解析- 实际 app-server 版本不低于 `0.145.0`@@ -72,21 +41,9 @@ Codex Hook`isEnabled` 表示当前进程中的 Hook 开启状态,首次从现有 CodexBar handler 恢复。`isVerified` 表示最近一次 app-server 校验通过。UI 只有在 `isOperable` 成立时把 Hook 当作可工作数据源。-### 为什么安装和验证是两件事--`hooks.json` 中存在命令只能证明配置写在磁盘上,不能证明 Codex 会执行它。--实际执行还可能被以下条件阻止:--- 当前 app-server 版本过低-- `features.hooks` 被全局关闭-- handler 事件集合不完整-- app-server 解析到其他来源文件-- handler 处于 untrusted 或 modified+### 校验状态-因此 `isEnabled` 是当前进程的开关状态,`isVerified` 是 Codex 对当前来源的最近明确结论。防睡眠和任务通知只依赖两者合成的 `isOperable`--临时 RPC 失败只代表本轮无法验证,不能反推 handler 已失效。此时保留上一次明确结论,同时展示操作错误供用户排查。+`hooks.json` 中有 handler 不代表 Codex 会执行。`isOperable` 由开启状态和最近明确校验结果共同决定。临时 RPC 失败保留上次结论并显示操作错误;版本、全局开关、来源、信任或事件集合不满足要求时校验失败。### 已开启 Hook 的对账@@ -115,11 +72,9 @@ App 启动、设置状态刷新、菜单面板打开以及每轮额度刷新完-> 再次 hooks/list 完整校验```-前置检查发生在文件修改之前。版本或全局开关不满足时,用户文件一个字都不会改变。-信任匹配同时要求 command 和 `sourcePath`。只按 executable 匹配可能误信任另一份配置中的相同命令,只按 source 匹配则可能碰到用户自己的 handler。-### 禁用为什么先查询信任 key+### 禁用与信任清理app-server 的 Hook key 来自它当前解析到的 handler。如果先从 `hooks.json` 删除命令,后续 `hooks/list` 已经无法反查对应 key。@@ -127,11 +82,11 @@ app-server 的 Hook key 来自它当前解析到的 handler。如果先从 `hook信任清理失败不会把 handler 重新装回去。UI 会表达“Hook 已关闭,但清理未完成”,因为停止采集的用户意图已经成功。-### 为什么每个事件使用独立 group+### 事件分组CodexBar 不把命令塞进用户已有 group。独立 group 让卸载时可以只删除自身 handler,不需要理解用户 matcher 或其他 handler 之间的组合语义。-对于结构异常的同级条目,移除逻辑选择跳过而不是让整个开关失败。CodexBar 只负责识别自己的命令,不把自己变成用户 Hook 配置的全局校验器。+移除时跳过结构异常的同级条目,只处理能精确识别的 CodexBar 命令。### 异步设置操作的代际@@ -189,13 +144,13 @@ handler 超时由事件决定:stdin 无效、文件锁超时或写入失败都会被吞掉。Hook 子进程不能因为统计失败而阻断 Codex。-### 为什么仍然返回成功+### 失败退出Hook 统计是 CodexBar 的辅助能力,不是 Codex 完成任务的必要步骤。如果 recorder 把解析或磁盘错误作为非零退出码返回,一次统计故障就可能让用户的 Codex 流程失败。因此显式进入 `--hook-event` 后,无论输入是否有效都返回已处理并退出成功。失败只意味着少一条统计,不升级为上游任务故障。-### 锁内事务为什么同时写事件和维护状态+### 事件与维护状态的锁内事务一次采集在同一把 `stats.lock` 内完成:@@ -211,7 +166,7 @@ Hook 统计是 CodexBar 的辅助能力,不是 Codex 完成任务的必要步锁内联合提交让“文件已经增长”和“维护知道需要读取”保持一致。-### 为什么锁等待只使用超时预算的一部分+### 锁等待预算Codex 对 `SessionEnd` 最多等待 3 秒,其他事件最多 5 秒。recorder 把锁等待限制为总预算减 2 秒。@@ -219,7 +174,7 @@ Codex 对 `SessionEnd` 最多等待 3 秒,其他事件最多 5 秒。recorder等待从 1 ms 指数退避到最多 20 ms。主 App 的正常持锁区很短,小步起始能在锁刚释放时迅速继续,上限则避免高竞争时 busy loop。-### 锁文件为什么用一次 `open(O_CREAT)` 创建并打开+### 锁文件创建不能先判断文件不存在,创建后再打开。两个进程可能分别创建不同 inode,后创建的一方替换目录项后,双方会各自锁住不同文件并都认为自己独占。@@ -235,7 +190,7 @@ Codex 对 `SessionEnd` 最多等待 3 秒,其他事件最多 5 秒。recorder- model 和 reasoning effort- permission 与 approval reviewer- session ID 和 turn ID-- agent 与 parent 关系+- agent ID- 归一化来源 `origin`对于 `UserPromptSubmit` 和 `PermissionRequest`,输入事件可能不包含 reviewer 或 effort。recorder 会在必要时从 rollout transcript 尾部回查匹配的 `turn_context`@@ -316,31 +271,17 @@ HookEvents/原始事件和日聚合最长保留 210 天。session ID 和 turn ID 的明细列表只保留 3 天,更早日期压缩为计数,降低本地文件体积和身份信息留存。-### 为什么选择 JSONL--JSONL 与这一链路的写入模式匹配:--- recorder 只需要在文件尾追加一条完整记录-- 单行损坏可以被隔离,不必让整个文件解码失败-- 文件可以按日切分和保留期清理-- 人工排查时仍可检查单条结构-- 聚合缓存和远端缓存也能使用相同的逐行恢复策略--普通 JSON 数组每次 append 都要改写尾部结构。数据库会增加 schema、锁和部署复杂度,但当前查询只按日期顺序扫描,没有足够收益。-### 完整行是提交单位reader 只推进到最后一个 newline 对应的 offset。文件尾如果正在写入半行,本轮保留旧 offset,下一轮等完整行出现后再处理。`JSONLines.decodeWithFailures` 按行解码。一条坏行只增加 corrupt count,不会连带丢掉同一读取块中的其他正确事件。-### 为什么身份明细只保留 3 天+### 身份明细压缩session 和 turn ID 用于近期精确去重,但长期展示只需要计数。-3 天后把 identifiers 压缩为 count,可以同时降低文件体积和身份信息保留。聚合模型必须记录该字段当前是 retained 还是 compacted,否则无法判断后续新事件能否继续用 ID 精确去重。--原始事件仍在 210 天保留期内,所以算法升级时可以完整重建。CloudKit 从不上传这些原始身份。+3 天后把 identifiers 压缩为 count。累加器在 `finalized(identifierStorage:)` 中选择保留 ID 列表或只保存计数;`retained` 和 `compacted` 是此次输出的选择,不是单独持久化的模式字段。## 增量读取与来源代际@@ -377,7 +318,7 @@ source generation 让同一天的不同原始来源可被区分。同源结果inode 与 size 能发现替换和截断,boundary hash 能发现保持相同长度的原地改写。-### boundary hash 为什么还配合 mtime+### Boundary hash 与 mtime每轮都给 210 天内所有文件重算 hash 会长时间持有 `stats.lock`,直接增加 Hook recorder 的等待概率。@@ -385,7 +326,7 @@ inode 与 size 能发现替换和截断,boundary hash 能发现保持相同长正常 append 只修改 offset 之后的字节,所以 boundary 仍匹配,maintenance 可以继续增量处理。boundary 改变则创建新 generation 并标脏。-### build 和 commit 为什么分开+### 构建与提交校验聚合器不能在读取整天文件时一直持有 `stats.lock`,否则 Hook 子进程可能连续超时。@@ -434,9 +375,9 @@ session 数使用当天除 `SessionEnd` 外所有事件中的非空 session ID- 缺失表示该日期的历史来源无法提供该指标- `0` 表示来源可用且明确没有发生-解码和 UI 展示必须保留这个区别。+解码和持久化保留可选值。展示层通过 `WorkflowDailyMetrics` 把缺失的单项事件计数转换为 `0`;session 和 turn 计数优先使用 ID 去重结果或已压缩计数,再回退到对应事件计数。-### 为什么成对事件使用 `max`+### 成对事件计数`PreToolUse` 和 `PostToolUse` 描述同一次工具调用的两侧。recorder 允许失败后,任意一侧都可能缺失:@@ -447,18 +388,13 @@ session 数使用当天除 `SessionEnd` 外所有事件中的非空 session IDcompaction 和 subagent 成对事件使用相同规则。-如果未来 Hook 协议提供稳定 operation ID,去重算法可以升级为集合去重,但这属于聚合语义变化,必须递增 schema 并完整重建。-### 可用性如何穿过旧数据旧版本聚合可能没有某类 Hook count。重建时不能因为当前代码认识该事件,就假定旧来源也采集过。`WorkflowHookCountAvailability` 保存每类计数是否有来源。重建会继承现有日期对旧字段的可用性,新鲜来源则可以声明当前字段全部可用。-这使 UI 能区分:--- 明确发生 0 次-- 当前日期的历史采集没有这个指标+这种可用性保留在聚合和同步字段中,当前 UI 不逐项展示历史字段是否缺失。## Schema 演进与重建@@ -487,18 +423,9 @@ schema 变化通常把保留期内所有事件日期标脏。source generation两者都不能用 App 版本号替代。一个 App 版本可能不改变聚合,开发构建也可能在不变更版本号时多次迭代 schema。-### 为什么不做字段级迁移--`daily.jsonl` 本来就是派生缓存,原始 JSONL 又在保留期内。为每个旧字段编写迁移会同时维护旧算法和新算法,更容易产生混合语义。--完整重建的一次性成本可控,换来以下保证:+### 重建来源-- 同一 schema 下所有日期由同一套代码生成-- 删除或改变字段语义时没有残留值-- 损坏的聚合行也能一起修复-- CloudKit replacement 可以统一跟随 source generation--只有原始来源本身缺少字段时,才通过 missing 保留历史能力差异。+聚合语义变化后使用原始 JSONL 完整重建。旧聚合已经丢失的身份或事件关系无法靠补字段恢复;只有原始来源缺少字段时,才保留 missing 语义。### 用户手动重建的提交语义@@ -514,7 +441,7 @@ schema 变化通常把保留期内所有事件日期标脏。source generation维护任务与额度刷新周期协调,但两条数据链路没有数据依赖。Workflow ViewModel 对 UI 的最短刷新间隔为 5 秒,避免频繁文件变更造成重复渲染。-### 为什么空转维护不写普通日志+### 维护日志维护默认跟随 60 秒刷新。空闲机器一天会执行上千次没有变化的检查。@@ -532,19 +459,6 @@ schema 变化通常把保留期内所有事件日期标脏。source generationUI 打开只读取当前本地快照,不自动越过 scheduler 发起无条件 CloudKit 请求。-## 新增 Hook 事件或指标的步骤--1. 在 `CodexHookEvent` 登记协议名、配置名和 handler timeout-2. 确认 recorder 只持久化计算所需的最小字段-3. 更新 Hook 安装完整性校验-4. 在 accumulator 中定义计数和去重语义-5. 更新 aggregate 的 Codable 与 JSONL 编码,保留旧字段 missing 语义-6. 递增 `WorkflowMaintenanceState.currentAggregationSchema`-7. 更新 CloudKit record schema、上传和下载映射-8. 确认旧 App 与新 record 共存策略后再修改兼容格式-9. 补充 UI 展示和隐私边界-10. 手动验证正常 append、单侧事件缺失、文件替换和完整重建-## 建议验证的故障场景- 多个 Codex session 并发写入时每行完整且无覆盖@@ -555,7 +469,7 @@ UI 打开只读取当前本地快照,不自动越过 scheduler 发起无条件- inode 变化、文件缩小和 boundary 改写都触发新 generation- build 期间继续 append 时只提交固定上界,尾部保留 pending- schema 变化后保留期内日期全部用当前算法重建-- 旧日期缺失字段仍显示 unavailable,不变成 `0`+- 旧日期缺失字段在解码及持久化中保留可选值,展示投影按当前回退规则生成计数- 禁用 CodexBar Hook 不删除用户 handler 和信任项- 快速开关 Hook 时旧 RPC 结果不能覆盖最后一次操作diff --git a/Docs/DeveloperGuide/notifications.md b/Docs/DeveloperGuide/notifications.mdindex ca54535..86f408a 100644--- a/Docs/DeveloperGuide/notifications.md+++ b/Docs/DeveloperGuide/notifications.md@@ -6,50 +6,14 @@[`CodexNotificationService.swift`](../../CodexBar/Services/Notifications/CodexNotificationService.swift) 是通知副作用的统一入口。-它接收三类状态:+它接收四类状态:-- app-server 账户、额度和 Reset Credits 快照-- `CodexActivityMonitor` 任务转场和防睡眠恢复事件+- app-server 账户与额度快照+- `CodexActivityMonitor` 任务转场与异常会话保护候选+- `KeepAliveController` 防睡眠恢复结果- `AutoResetController` 已确认的消费结果或需要告知用户的失败状态-View 和其他服务不直接创建系统通知。它们发布状态变化,通知服务负责资格判断、去重、声音和点击行为。--## 设计原则--通知不是状态本身,而是状态变化触发的一次外部副作用。一条可靠通知至少要同时满足 4 个条件:--```text-事件真实发生- + 用户允许这一分类- + 事件仍然相关- + 本生命周期或持久化周期尚未发送-```--把这些条件集中到一个服务有两个目的:--- 上游只发布事实和转场,不需要知道系统授权、声音或去重存储-- 所有提交都经过同一套 relevance 检查、retry 和隐私日志规则--如果 View 直接发通知,SwiftUI 重建、面板重复打开或快照重新发布都可能重复触发。因此 View 只能修改设置或展示状态,不能拥有通知副作用。--## 快照与转场不能混用--不同通知需要不同类型的证据:--| 通知 | 输入类型 | 原因 |-| --- | --- | --- |-| 低额度 | 连续可信快照 | 需要比较阈值上下两帧 |-| 额度重置 | 连续可信快照 | 需要先观察消费再观察归零 |-| Reset Credits 到期 | 当前快照加时间调度 | 到期提醒由未来 deadline 触发 |-| 自动重置 | app-server mutation 结果 | 只有明确结果才能说明本机自动操作发生过 |-| 任务完成 | monitor 转场 | 历史 terminal 快照不能补发 |-| 等待批准 | monitor 转场加当前快照 | 先通知新等待,再撤回过时等待 |-| 异常会话保护 | 达到静默阈值且仍有效的保护候选 | 提交通知与隐藏前分别校验候选 |-| 防睡眠停止 | 已确认系统恢复结果 | 不能在恢复请求前预告成功 |--从当前快照推导任务完成看起来更简单,但 App 每次启动都会把历史完成任务当作新事件。相反,对低额度只看单次转场又无法识别 App 在阈值穿越后才启动的场景。--## 设置和系统授权是两层门槛+## 设置与系统授权`NotificationSettings` 分开保存 App 内意图与 macOS 授权:@@ -59,7 +23,7 @@ View 和其他服务不直接创建系统通知。它们发布状态变化,通| `authorizationStatus` | 系统是否允许通知 || `canDeliver` | 两者同时允许后的实际资格 |-总开关默认关闭,因此 App 首次运行不会无缘由弹出系统权限请求。用户主动开启后才调用 authorization API。+总开关默认关闭,用户开启时才请求系统授权。App 激活、设置窗口重新获得焦点或显式打开时会重新读取系统状态。系统返回 `denied` 时保留 App 内的通知开关,显示灰色未授权提示和“打开系统设置”按钮。实际查询返回 `notDetermined` 时关闭 App 内开关,用户再次开启后重新申请授权;初始化时的占位值不修改已保存的开关。@@ -67,7 +31,7 @@ App 激活、设置窗口重新获得焦点或显式打开时会重新读取系授权请求结束后,权限读取统一走普通刷新流程。查询期间再次收到焦点刷新时,新查询替换旧查询,旧结果不会覆盖最新权限状态。-触觉反馈不依赖 `UNUserNotificationCenter` 授权,但仍服从 App 内总开关。这是能力边界的区别,不是绕过用户意图。+触觉反馈不依赖 `UNUserNotificationCenter` 授权,但仍服从 App 内总开关。## 通知开关@@ -93,15 +57,11 @@ App 激活、设置窗口重新获得焦点或显式打开时会重新读取系额度重置通知需要先观察到窗口被消费,再观察到新窗口恢复为未消费状态。-这避免 App 第一次启动时仅因为当前额度是 100% 就发送重置通知。-判断状态按账户和额度窗口隔离。账户变化时不把前一账户的消费状态延续到新账户。每个额度窗口还带一个会话内 lifecycle token。窗口从可信快照消失后再出现会得到新 token。如果旧窗口的通知提交失败回调迟到,只有 token 仍相同时才把 `hasObservedConsumption` 恢复为 true。-这避免一个竞态:旧窗口通知正在提交时 app-server 切换账户或窗口,随后失败回调把新窗口错误标成“已经消费过”。--重置状态不持久化。App 启动时必须重新观察到消费后才通知重置,这是主动接受漏掉离线期间重置,以换取绝不在启动时对 0% 用量误报。+重置状态不持久化。App 每次启动后重新观察消费和归零,不补发离线期间发生的重置通知。## 自动重置@@ -110,7 +70,7 @@ App 激活、设置窗口重新获得焦点或显式打开时会重新读取系- “自动重置”说明 CodexBar 的自动操作收到 `reset` 或 `alreadyRedeemed`- “额度已重置”说明普通额度快照先观察到消耗,随后观察到归零-一次自动重置可能同时满足两者,所以同一台设备可以先后收到两条通知。不能因为内容接近就合并:前者证明自动化动作,后者是额度生命周期通知,来源和开关都不同。+一次自动重置可能同时满足两者,同一台设备可以先后收到两条通知,分别服从各自的开关。成功通知正文优先带上消费后新鲜读取的剩余重置次数,包括明确的 `0`。后置读取失败时仍保留已经明确的成功结果,并发送只有标题、没有正文的通知。@@ -130,15 +90,11 @@ App 激活、设置窗口重新获得焦点或显式打开时会重新读取系低额度阈值可选 5%, 10% 或 25%,默认 10%。-通知只在剩余额度从阈值上方跨到阈值或下方时发送。持续停留在低额度区域不会每次刷新都重复通知。--首次可信快照已经低于阈值时也视为一次向下穿越,用于覆盖 App 在穿越后才启动的情况。-持久化去重 key 保留 app-server 返回的秒级重置时间。相同账户和额度窗口的重置时间与已记录值相差不超过 60 秒时视为同一周期,只有差值超过 60 秒才视为新的重置周期。额度恢复到阈值上方后会重新启用穿越判定,但同一重置周期仍只通知一次。进入新的重置周期后,下一次向下跨越可以再次通知。-### 为什么使用剩余比例的向下穿越+### 阈值穿越判定“当前低于 10%”是一个持续状态,“刚刚低于 10%”才是通知事件。服务为每个 `account + limit + window` 保存上一帧剩余比例:@@ -151,7 +107,7 @@ App 激活、设置窗口重新获得焦点或显式打开时会重新读取系stale app-server 快照不会推进上一帧,也不会触发低额度或重置。旧缓存只能用于展示连续性,不能成为一次新副作用的证据。-### 重置时间为何允许 60 秒漂移+### 重置周期匹配app-server 连接重建后,同一窗口的 `resetsAt` 可能出现秒级修正。如果 dedup key 使用绝对相等,同一周期会被当成新周期再次通知。@@ -163,7 +119,7 @@ app-server 连接重建后,同一窗口的 `resetsAt` 可能出现秒级修正去重 key 包含账户、到期日和剩余天数。同一天多次刷新不会重复发送。-提醒不是建立 7 个长期系统 pending request。服务只调度最近一个未来检查点,到点后根据当前快照重新计算并安排下一次。+服务只调度最近一个未来检查点,到点后根据当前快照重新计算并安排下一次。这样做可以处理:@@ -187,8 +143,6 @@ app-server 连接重建后,同一窗口的 `resetsAt` 可能出现秒级修正任务完成最短持续时间可选 30, 60, 120 或 300 秒,默认 60 秒。持续时间较短的完成任务不会通知,但仍可以在 UI 中短暂展示。-任务通知入口再次过滤匿名任务,即使 monitor 已保证不发布匿名转场。这是副作用边界的纵深保护:上游未来重构或新增 transition 类型时,缺少 session ID 的任务仍不会意外产生系统通知或触觉。-触觉在每个 task transition 到达时启动,新 transition 会取消上一串 10 次脉冲并重新开始。每次脉冲前重新检查设置,用户关闭开关后不会继续完成旧序列。## 等待批准@@ -213,7 +167,7 @@ app-server 连接重建后,同一窗口的 `resetsAt` 可能出现秒级修正## 异常会话保护-非匿名运行任务静默达到阈值时,Activity Protection 先登记保护记录,再并行启动通知提交和 3 秒宽限。通知处理返回或宽限到期后,monitor 重新校验候选,仍有效时才隐藏任务。通知失败也会继续完成保护。+非匿名运行任务静默达到阈值时,Activity Protection 先更新内存保护记录并安排异步保存,再并行启动通知提交和 3 秒宽限。通知处理返回或宽限到期后,monitor 重新校验候选,仍有效时才隐藏任务。隐藏不等待磁盘写入或通知成功。通知使用 `taskID + attemptID` 作为 identifier,提交前后校验 progress generation 和静默时长。新进展会使保护尝试失效,并撤回对应通知。@@ -221,12 +175,10 @@ app-server 连接重建后,同一窗口的 `resetsAt` 可能出现秒级修正## 防睡眠停止-低电量或最长时长导致防睡眠停止时,`KeepAliveController` 先撤销 CodexBarHelper 租约并等待 `SleepDisabled=0` 的回读确认。+低电量或最长时长导致防睡眠停止时,`KeepAliveController` 先撤销 CodexBarHelper 租约。只有回复确认来源为 `.codexBar` 且 `SleepDisabled=0` 时,才提交对应通知;其他结果会清除本轮待发通知。确认后才提交通知。App idle assertion 会保留到通知提交结束,避免合盖机器在通知交给系统前立即睡下。随后 controller 释放 assertion 并按需补发合盖睡眠。-这保证通知文字描述的是已经完成的系统级恢复,同时让异步提交有机会收口。-## 声音[`NotificationSoundOption.swift`](../../CodexBar/Services/Notifications/NotificationSoundOption.swift) 汇总 3 类选择:@@ -250,7 +202,7 @@ app-server 连接重建后,同一窗口的 `resetsAt` 可能出现秒级修正- 内置 ID 预先保留,防止本机同名文件在重启后改变已保存选项的含义- 已保存 ID 无法解析时回退 system default-system default 和静音不可试听。用系统 alert sound 冒充通知中心默认音会给用户错误预期,因此预览只支持有明确文件的系统音和内置音。+系统默认声音和静音不可试听,预览只支持有明确文件的系统音和内置音。## 触觉反馈@@ -264,7 +216,7 @@ system default 和静音不可试听。用系统 alert sound 冒充通知中心通知通过 `UNUserNotificationCenter` 提交:-- 单次提交失败最多重试 1 次+- 普通通知提交失败最多重试 1 次,异常会话保护通知不重试- 已发送 dedup key 保存到 UserDefaults- 最多保留 300 个 key- key 必须包含足够的账户或任务范围,避免不同对象相互压制@@ -272,7 +224,7 @@ system default 和静音不可试听。用系统 alert sound 冒充通知中心持久化去重避免 App 重启后立即重复发送同一事件,但不能替代上游任务 terminal 去重。-### 两层去重解决不同问题+### 提交中与已发送去重`submittingDedupKeys` 和 `sentDedupKeys` 不能合并:@@ -285,8 +237,6 @@ dedup 检查和 `submitting` 插入在创建 Task 前同步完成,因此正确只有 `UNUserNotificationCenter.add` 成功且事件在提交后仍相关时才写入 sent key。如果提前记录,一次系统提交失败会永久吃掉这条提醒。-300 条上限防止 UserDefaults 变成无界事件日志。这里接受很久以前的事件在 key 淘汰后理论上可能重现,因为上游周期身份和实时 transition 去重仍是第一道边界。-### 发送入口的统一语义所有通知内容最终经过同一个 `send` 和 `deliver`@@ -298,7 +248,7 @@ dedup 检查和 `submitting` 插入在创建 Task 前同步完成,因此正确-> 调用系统中心-> 提交后再次检查 relevance-> 成功后持久化 dedup- -> 失败时最多重试一次并执行分类清理+ -> 失败时按 retryCount 重试并执行分类清理(默认 1 次,异常会话保护为 0 次)```日志只记录 `kind` 和失败原因,不记录 title 或 body。通知正文可能包含项目名和任务信息,即使日志位于本机也不应复制这些内容。@@ -307,26 +257,11 @@ dedup 检查和 `submitting` 插入在创建 Task 前同步完成,因此正确App 是 `LSUIElement`,通知中心 delegate 明确允许 App 在前台时继续展示 banner 和声音。-用户点击通知后打开主面板。打开动作通过状态栏控制器执行,复用现有 popover 或 fallback panel 逻辑。--前台展示由 notification center delegate 显式返回 banner, list 和 sound。`LSUIElement` App 经常保持前台或处于特殊 activation 状态,依赖系统默认前台策略会让用户感觉通知随机消失。-点击处理不直接创建新窗口,而是调用 `openMenuSurface`。这保证锚点有效时复用 popover,锚点无效时使用 fallback panel,并继续遵守同一套焦点和 dismiss 规则。-## 新增通知类型的实现清单--1. 明确输入是快照、转场还是已确认副作用结果-2. 定义账户、窗口、task 或 attempt 作用域的身份-3. 决定是否需要会话去重、持久化去重和 relevance 检查-4. 明确 bootstrap、stale 数据和匿名任务是否允许触发-5. 选择声音和失败重试语义-6. 确认正文中的敏感字段不会进入日志-7. 为设置默认值和旧 UserDefaults 缺失值定义行为-8. 验证前台展示、点击激活和事件失效后的撤回-## Codex TUI 通知-设置页中的 Codex TUI 通知是 Codex 自身配置,通过 app-server 的 `config/batchWrite` 读写。+设置页中的 Codex TUI 通知是 Codex 自身配置,通过 app-server 的 `config/read` 读取,并通过 `config/batchWrite` 写入。它与 CodexBar 系统通知完全独立:diff --git a/Docs/DeveloperGuide/sleep-prevention.md b/Docs/DeveloperGuide/sleep-prevention.mdindex 73f4a2d..f009d8a 100644--- a/Docs/DeveloperGuide/sleep-prevention.md+++ b/Docs/DeveloperGuide/sleep-prevention.md@@ -2,13 +2,7 @@简体中文 | [English](../en/DeveloperGuide/sleep-prevention.md)-## 设计目标--防睡眠功能需要同时满足 3 个目标:--- 有符合条件的 Codex 任务时阻止 Mac 空闲睡眠-- App 退出、崩溃或失联后可靠恢复系统设置-- 不覆盖用户或其他应用已经设置的系统级防睡眠状态+## 控制链路普通 App 进程负责策略和用户界面,CodexBarHelper 只执行受限的系统睡眠与唤醒操作:@@ -27,9 +21,7 @@ AutoResetController-> IOPMSchedulePowerEvent```-## 为什么这不是一个 assertion 开关--防睡眠表面上像一个布尔设置,实际上同时跨越用户意图、实时任务、电源状态、App 生命周期和 root 系统状态。任何一层都可能先于其他层变化,因此实现不能把 `isEnabled` 直接等同于系统已经禁止睡眠。+## 状态分层系统把状态拆成 4 层:@@ -40,14 +32,12 @@ AutoResetController| 请求状态 | `appliedSleepPreventionRequested` 和 `requestInFlight` | App 最近向 helper 请求了什么 || 已确认效果 | `isPreventingSleep` 和 `sleepPreventionSource` | App 是否收到系统状态已经符合预期的证据 |-这种区分解决了两个容易被 UI 掩盖的问题:-- helper 暂时不可用时保留用户开关,修复依赖后可以自动恢复,不需要用户重新开启- XPC 请求发出但尚未确认时不提前显示成功,避免界面和系统实际状态相反-`sleepBlockReason` 是所有条件的唯一决策出口。UI 派生状态、条件日志和实际切换都读取同一个结果,新增条件时必须在一个有穷的 `switch` 中说明设置入口是否仍应可用。这是一处刻意的防遗漏设计。+`sleepBlockReason` 是所有条件的唯一决策出口。UI 派生状态、条件日志和实际切换都读取同一个结果,新增条件时必须在穷尽的 `switch` 中说明设置入口是否仍应可用。-## App assertion 与系统设置为什么并存+## 两层睡眠控制两套机制的作用域不同:@@ -56,13 +46,11 @@ AutoResetController| IOKit assertion | App 进程 | 阻止空闲系统睡眠,可选阻止显示器睡眠 | App 退出后由系统自动回收 || `pmset disablesleep` | 系统全局 | 覆盖 assertion 无法保证的系统睡眠路径 | 必须显式恢复,因此需要 ownership 和 watchdog |-只使用 assertion 的恢复成本低,但能力不完整。只使用 `pmset` 的能力更强,但 App 崩溃后可能留下全局状态。CodexBar 同时使用两者,并把高风险的全局状态交给最小权限 helper 管理。-App 侧 assertion 会在 XPC 获取流程开始前建立。这样 helper 切换期间不会出现短暂的空闲睡眠窗口。如果 helper 请求失败,统一清理路径会释放 assertion,避免形成只有 App 自己知道的半成功状态。-## 获取与释放是确认式事务+## 获取与释放事务-获取流程不是先改 UI 再异步补系统操作,而是一个带验证的事务:+获取流程在系统状态验证成功后更新已生效状态:```text条件求值为允许@@ -80,7 +68,7 @@ App 侧 assertion 会在 XPC 获取流程开始前建立。这样 helper 切换```text条件求值为阻断-> 请求 helper 撤销租约- -> helper 仅在 owned 且无其他租约时恢复系统值+ -> helper 仅在有恢复责任且无其他租约时恢复系统值-> App 收到实测结果-> 发布未防睡眠状态并释放 display assertion-> 停止时长累计@@ -89,11 +77,11 @@ App 侧 assertion 会在 XPC 获取流程开始前建立。这样 helper 切换-> 必要时补发合盖睡眠```-通知放在 helper 确认 `SleepDisabled=0` 之后,是为了保证用户看到的“已停止防睡眠”描述的是事实,而不是尚未完成的意图。+低电量和时长上限通知仅在 helper 回复来源为 `.codexBar` 且 `SleepDisabled=0` 后提交。-App idle assertion 会多保留到通知提交结束。合盖机器在全局设置恢复后可能立即睡下,如果先释放最后一条 assertion,通知请求可能来不及交给系统。提交完成后立即释放 assertion 并执行合盖边沿补偿,这段短暂顺序不会重新声明系统所有权。+App idle assertion 保留到通知提交结束,避免系统在提交前睡下。随后释放 assertion 并按需执行合盖睡眠补偿。-## `mayHaveHelperLease` 为什么不能在超时时清除+## 不确定的租约状态XPC 超时只证明 App 没收到回复,不证明 helper 没执行请求。请求可能已经把租约写入 helper,只是回复在连接断开时丢失。@@ -103,9 +91,7 @@ XPC 超时只证明 App 没收到回复,不证明 helper 没执行请求。请- 超时或连接失效时保持 `true`- 只有一次已确认的释放结果才能清为 `false`-这会让退出流程多做一次幂等释放,但能避免 App 误以为没有租约而直接退出。对全局系统状态而言,多释放一次的成本远低于遗留 `SleepDisabled=1`--## generation 解决什么竞态+## XPC 代际校验用户关闭开关、任务结束和重试可能在前一条 XPC 回复返回前连续发生。如果只按回复到达顺序更新状态,旧的“获取成功”可能覆盖新的“释放成功”。@@ -115,8 +101,6 @@ App 和 helper 都使用单调递增 generation:- helper 忽略比现有租约 generation 更旧的请求- 连接作废时 App 推进 generation,让在途回调自然失效-generation 不是用来给请求排序的日志编号,而是异步状态提交的资格证明。-## 生效条件[`KeepAliveController.swift`](../../CodexBar/Services/KeepAlive/KeepAliveController.swift) 只有在以下条件全部成立时才建立防睡眠:@@ -233,14 +217,14 @@ CodexBarHelper 先通过以下命令读取当前值:- 如果 CodexBarHelper 观察到初始值已经是 `1`,它把状态标记为 external- external 状态不会被 CodexBar 声明为自己拥有-- CodexBar 只在亲自完成 `0 -> 1` 切换后记录 owned-- 只有 owned 状态才允许在租约结束时恢复为 `0`+- CodexBar 读取到 `0` 后先持久化 owned,再执行并验证 `0 -> 1` 切换+- 最后一个租约结束后,owned 或 restoring 状态执行恢复为 `0`因此,用户或其他工具预先开启的 `SleepDisabled=1` 不会在 CodexBar 退出时被关闭。-### ownership 文件如何构成恢复事务+### Ownership 恢复事务-helper 的持久化顺序刻意偏向可恢复:+helper 按以下顺序写入恢复记录和系统值:```text获取: persist owned -> pmset 1 -> read back 1@@ -259,8 +243,6 @@ helper 的持久化顺序刻意偏向可恢复:- 外部来源消失而任务仍在时重新申请租约,由 helper 完成新的 `0 -> 1`- helper 已经因为其他有效客户端转为 owned 时更新来源展示,不重复创建计时周期-这项观察避免一个隐蔽空窗:用户先用其他工具开启防睡眠,CodexBar 因此判定为 external,随后其他工具关闭设置。如果 CodexBar 不重新观察,UI 会继续显示防睡眠,系统却已经可以睡眠。-## CodexBarHelper 状态持久化CodexBarHelper 把系统所有权记录保存在:@@ -276,7 +258,7 @@ CodexBarHelper 把系统所有权记录保存在:- 目录不能被 group 或 world 写入- 文件由 root 拥有,权限为 `0600`- 使用临时文件、full sync 和原子 rename 提交-- 启动时无法读取可信 owned 记录会执行恢复到 `disablesleep 0`+- 启动时记录缺失则写入 idle;记录为 owned 或 restoring 时恢复 `disablesleep 0`;记录无法读取或不可信时也尝试恢复为 `0`该文件记录 CodexBar 对系统睡眠设置的所有权。@@ -297,16 +279,16 @@ App 持有有效任务时保持带身份的 XPC lease。CodexBarHelper 不把一App 正常退出时先取消自动重置唤醒计划,再撤销租约和 IOKit assertion。如果 CodexBarHelper 尚未确认两类 root 状态都已清理,App 终止流程会等待,避免在不确定状态下直接离开。-### 正常退出为什么可以被取消+### 正常退出`applicationShouldTerminate` 不能在未确认释放时直接返回允许。`prepareForTermination()` 会先停止新重试,取消可能存在的自动重置唤醒计划,再请求释放可能存在的租约,然后等待 helper 回读结果:- 释放成功时继续终止- 释放失败时取消本次终止,恢复正常条件求值和重试-取消退出看似比直接关闭更强硬,但这是可恢复性的一部分。正常退出是 App 唯一能主动确认 root 全局状态的机会,不应主动放弃这次确认。强制退出仍由 helper 的 15 秒 watchdog 兜底。+强制退出时,helper 在 15 秒 watchdog 宽限结束后撤销失联客户端的租约。-### helper 自检不是只看进程存活+### Helper 自检helper 会分别检查 lease、ownership 记录和实测 `SleepDisabled`@@ -316,7 +298,7 @@ helper 会分别检查 lease、ownership 记录和实测 `SleepDisabled`- 持久化记录不可信时采取 fail-safe 恢复,不把损坏记录当成继续持有权限的依据- 自动重置唤醒事件取消失败且已经没有连接所有者时,每 5 秒继续回读并清理固定 owner-这里的周期检查不是替代事件驱动 XPC,而是修复系统设置被其他进程改写、回调丢失或进程重启造成的事实漂移。+周期检查修复系统值被其他进程改写、回调丢失或进程重启后的状态偏差。## 时长和电池策略@@ -351,7 +333,7 @@ helper 会分别检查 lease、ownership 记录和实测 `SleepDisabled`任务集合使用稳定 task ID 判断“新任务”和“等待后恢复”,而不是只比较数量。如果一个任务结束同时另一个任务开始,数量仍为 1,但新的任务应得到完整时长预算。-### 电池读取为何是三态+### 电池读取状态电池读取使用 `unavailable`, `unreadable` 和 `present` 三态,不能压成一个可选值:@@ -369,8 +351,6 @@ helper 会分别检查 lease、ownership 记录和实测 `SleepDisabled`阈值为 `T` 时,进入条件是电池供电且电量不高于 `T`,退出条件是电量至少达到 `T + 5`-这 5 个百分点不是展示层修饰,而是状态机滞回。没有它时,电量在阈值附近的测量抖动会反复执行 root 写入、assertion 切换和通知判断。-低电量通知还保留单轮锁存:- 只有此前确实由 CodexBar 防止睡眠时才排队通知@@ -400,8 +380,6 @@ CodexBar 在确认自己拥有的系统设置已恢复后读取 clamshell 状态- `SleepDisabled` 仍为 `1` 时不能请求- 无法读取合盖状态时不猜测-这是典型的边沿事件修复,不能用“最终值已经正确”替代。-## 失败与重试策略防睡眠采用有界重试,因为每次重试都会重新建立特权连接并可能启动 root 进程:diff --git a/Docs/DeveloperGuide/sync.md b/Docs/DeveloperGuide/sync.mdindex 26bb4bc..da7a3bf 100644--- a/Docs/DeveloperGuide/sync.md+++ b/Docs/DeveloperGuide/sync.md@@ -18,39 +18,17 @@ CloudKit 同步用于在同一 iCloud 账户的 Mac 之间合并 Hook 日级统账户、额度、token 总量、Reset Credits、自动重置设置与状态、实时任务和防睡眠状态不参与同步。-## 设计目标和非目标--同步的目标不是复制一台 Mac 的数据库,而是让多台设备对同一天的独立贡献可以安全相加。--因此设计优先级是:--1. 不上传原始工作内容和可直接关联硬件的身份-2. 本机统计永远不依赖 CloudKit 才能展示-3. 重扫和文件替换不能制造重复计数-4. 网络失败时保留最后一份可解释的远端快照-5. 重试必须幂等,不依赖请求恰好只执行一次--以下内容明确不属于同步协议:--- 实时任务状态,因为它变化快且需要本机低延迟判断-- 账户额度,因为它属于 Codex 账户而不是设备工作历史-- 自动重置,因为多设备收敛依赖相同 `creditId` 的确定性幂等键,不依赖 CloudKit 锁或任务记录-- 防睡眠状态,因为它是当前 Mac 的系统副作用-- 原始事件,因为跨设备统计只需要可合并的日级事实--把同步放在聚合层之后还有一个维护收益:原始 Hook 格式可以独立演进,CloudKit 只面对稳定的日级投影。--## 权威来源如何划分+## 数据来源同步展示同时使用 3 类值:| 数据 | 权威来源 | 断网时行为 || --- | --- | --- |-| 当前设备当天和历史贡献 | 本机 `daily.jsonl` | 继续实时更新 |+| 当前设备当天和历史贡献 | 本机 `daily.jsonl` 与同源云端缓存按完整性合并 | 本机聚合继续更新,保留云端缓存 || 其他设备贡献 | `cache.jsonl` 中最近成功拉取的记录 | 保留最后快照 || 上传确认和增量位置 | `state.json` 与 `cursor.data` | 下次继续或重建 |-当前设备始终 local-first。CloudKit 中的本机副本是传给其他设备的复制品,不是当前设备 UI 的真相来源。这个规则避免网络往返期间出现先增加一次,拉取后又重复增加一次的闪烁。+当前设备的本地聚合与云端副本按来源和完整性合并,同源贡献只计算一次。云端也可补充本地缺失的数据,或提供事件数更多的同源聚合。远端缓存是可重建投影,游标只是加速状态。任何游标错误都可以退化成全量读取 custom zone,不要求用户清理本地文件。@@ -69,7 +47,7 @@ private database 中的数据只属于当前 iCloud 账户,不写入 public dacustom zone 的意义不只是命名空间。它提供 zone change token 和删除事件,使设备可以增量同步新增、修改和删除,而不需要每轮扫描整个 private database。-zone 已确认状态和账户 salt 会在 actor 内跨同步轮次缓存,省去每轮两个固定网络往返。任意同步失败会使这两项缓存失效,因为 iCloud 账户切换也可能首先表现为一次请求失败。下一轮重新确认比继续使用错误账户上下文更安全。+zone 确认和账户 salt 在 actor 内跨轮次缓存;同步失败时使两者失效,下轮重新读取。## 启用条件@@ -80,7 +58,7 @@ zone 已确认状态和账户 salt 会在 actor 内跨同步轮次缓存,省- 当前 iCloud 账户可用- 本地聚合服务可用-首次启用会标记 backfill,上传本地保留期内需要同步的日期。同步调度有最短 8 秒冷却,合并短时间内的多次本地变化。+每轮同步都会检查本地保留期内的全部日期,通过 hash 筛选需要上传的数据,首次启用和后续补传使用同一流程。同步调度有最短 8 秒冷却,合并短时间内的多次本地变化。## 设备匿名化@@ -93,7 +71,7 @@ zone 已确认状态和账户 salt 会在 actor 内跨同步轮次缓存,省原始 `IOPlatformUUID` 不会上传。同一设备在同一 iCloud 账户中得到稳定 pseudonym,不同账户得到不同结果。-这里使用 HMAC 而不是普通 SHA-256。硬件 UUID 的输入空间有固定格式,单纯 hash 仍是跨账户稳定标识。账户私有 salt 让同一硬件在不同 iCloud 账户中产生不可关联的 pseudonym。+账户私有 salt 使同一设备在不同 iCloud 账户中得到不同 pseudonym。salt 存在同一个 private custom zone 中。多台设备先后创建时通过 CloudKit 冲突后回读现有记录收敛到同一份 salt,而不是让每台设备各自产生不兼容身份。@@ -156,9 +134,9 @@ salt 存在同一个 private custom zone 中。多台设备先后创建时通过上传循环在每批开始前检查 20 秒预算。已开始的批次继续等待结果;预算耗尽后,剩余日期留到后续同步处理。-每个日期的稳定 JSON 只编码并 hash 一次,同一结果同时用于筛选和成功确认。如果在不同阶段重新编码,字典顺序或可选字段差异可能让“是否改变”判断自行漂移。+每个日期的稳定 JSON 只编码并 hash 一次,同一结果用于待上传筛选和上传确认。-上传使用 `atomically: false`。单批部分成功时,每条 CloudKit 结果分别确认,失败日期移除本地 hash 以便重试。协议依赖单记录幂等身份,不要求 25 条全部成功才前进。+上传使用 `atomically: false`,远端允许单批部分成功。但只要该批出现错误,调用方就移除整批日期的本地确认 hash,下轮重新检查这一批。此前已完成批次的确认保留,远端已成功写入的记录不回滚。## 合并语义@@ -167,14 +145,14 @@ salt 存在同一个 private custom zone 中。多台设备先后创建时通过合并规则是:- 其他设备贡献按字段相加-- 当前设备使用最新本地聚合替换云端的同源贡献-- 同一 source generation 最多计算一份-- 已确认属于不同来源的 generation 可以累加-- 当前设备本地数据缺失时才使用云端缓存贡献+- 当前设备没有本地聚合时使用云端贡献+- 同源记录按 `sourceGeneration` 或旧记录的内容匹配,云端事件数较多时使用云端,否则使用本地+- 本地来源尚未确认完整且没有匹配云端记录时,优先展示已有云端贡献+- 未匹配的独立云端来源继续累加-用本地值替换当前设备云端值可以避免同步刚上传但本地 UI 已更新时发生双重计数。+`confirmedDates` 包括实际上传成功和上传决策为跳过的日期,不表示本地与云端内容必然逐字段相同。-### 同设备同日为什么可能有多条记录+### 同设备同日的多来源记录早期记录名只包含 `deviceId + date`。新鲜来源可额外使用 `deviceId + date + sourceGeneration`@@ -196,11 +174,11 @@ generation 记录用于表达某一份原始来源的身份。同源的本地和`sourceIsFresh` 是一次读取对原始来源完整性的判断,不是时间新旧。文件被替换、截断或仍在稳定边界确认中时,较新的时间戳也不代表更权威。-### missing 为什么不能转成 0+### 缺失计数字段CloudKit record schema 演进时,旧记录可能没有新计数字段。`nil` 表示该设备那天无法提供这项统计,`0` 表示明确观察到零次。-合并时保留可用性信息,UI 才能区分“所有设备合计为 0”和“部分历史来源不支持该指标”。把缺失解码成 0 会制造无法在以后修复的虚假事实。+CloudKit 解码及持久化模型保留可选计数字段。当前 `WorkflowDailyMetrics` 展示投影会把缺失的单项事件计数转换为 `0`;session 和 turn 计数先回退到对应的开始或停止事件计数,再回退为 `0`。UI 中整日统计不可用与单个计数字段缺失是不同情况。## 来源替换与重建@@ -213,7 +191,7 @@ CloudKit record schema 演进时,旧记录可能没有新计数字段。`nil`这种设计让重建只修正当前设备贡献。-### replacement 为什么是持久化事务+### Replacement 事务重建和 CloudKit 同步不一定在同一进程生命周期完成。`replacementDates` 因此保存在 `state.json`,不能只留在内存。@@ -239,7 +217,7 @@ replacement 进行中时,快照会临时过滤当前设备该日期的云端| 文件 | 作用 || --- | --- |-| `state.json` | 同步 schema、本地 hash、backfill 和替换状态 |+| `state.json` | 同步 schema、本地 hash 和替换状态 || `cache.jsonl` | 远端设备日聚合缓存 || `cursor.data` | CloudKit zone change token |@@ -259,7 +237,7 @@ replacement 进行中时,快照会临时过滤当前设备该日期的云端任何 record 字段、identity 或 schema 的变化都是兼容性决策。需要同时考虑旧 App 仍在写入、新 App 如何读取旧字段,以及降级后是否会覆盖新记录,不能只递增一个常量。-## 调度器为什么独立存在+## 同步调度器本地维护和 CloudKit 同步共享聚合输入,但触发频率不同。`WorkflowSyncScheduler` 把多处触发合并为单线程状态机。@@ -277,31 +255,19 @@ replacement 进行中时,快照会临时过滤当前设备该日期的云端- 同步在等待期间被关闭时清除 pending sync,但仍允许必要的本地维护继续- `@Published` 订阅发生在 `willSet`,从回调内读取属性仍是旧值,因此 activation 由新回调参数显式计算后传入-最后一点是 Combine 生命周期中很容易被“整理代码”破坏的小巧思。现场重新读取 settings 看起来更简洁,实际会用旧值决定是否同步。-## 失败和恢复语义-同步失败不回滚已经确认的独立 record,也不清空最后一份可用 cache。下轮通过 hash, record ID 和 CloudKit 幂等 API 继续收敛:+同步失败不回滚远端已经写入的记录,也不清空最后一份可用 cache。下轮通过 hash、record ID 和 CloudKit API 继续同步:| 失败点 | 已保留状态 | 下轮动作 || --- | --- | --- || zone 或账户确认 | 本地聚合和旧 cache | 重新确认 zone 和 salt || 增量拉取 | 旧 cache | 退化为全量重建 |-| 部分上传 | 已成功日期 hash | 仅重试未确认日期 |+| 部分上传 | 之前完整批次的 hash 和远端已成功记录 | 重新检查失败批次的所有日期 || replacement 删除 | replacement 标记 | 重新枚举并幂等删除 || prune | 有效期内数据和上传结果 | 后续再清理 |-账户级缓存会在失败后失效,但磁盘 cache 不会立刻作为新账户事实发布。availability 和 device identity 重新确认后才恢复同步快照。--## 修改同步协议时的检查顺序--1. 先定义字段语义,尤其是 missing、0 和空集合是否不同-2. 决定 record identity 是否仍然幂等-3. 评估旧 App 与新 App 并发写入的结果-4. 明确本地 state, cache 和 cursor 的升级或重建路径-5. 检查 replacement 是否能删除所有旧代际-6. 检查隐私边界和用户 opt-in 是否仍成立-7. 用两台设备和一次中途失败验证最终收敛+同步失败会使 actor 内缓存的 zone 确认和账户 salt 失效。下轮重新解析账户及设备身份;本地状态中的设备身份变化时重建远端缓存。## 保留与清理@@ -314,7 +280,7 @@ CloudKit 记录保留期与本地 Hook 历史一致,最长 210 天:## 错误分类-同步层区分以下状态,供设置页展示和通知:+同步层区分以下状态,供设置页和主面板显示:- 网络不可用- iCloud 账户不可用diff --git a/Docs/DeveloperGuide/ui-and-lifecycle.md b/Docs/DeveloperGuide/ui-and-lifecycle.mdindex 5637ee4..9b426f9 100644--- a/Docs/DeveloperGuide/ui-and-lifecycle.md+++ b/Docs/DeveloperGuide/ui-and-lifecycle.md@@ -8,20 +8,7 @@ CodexBar 在 [`Info.plist`](../../CodexBar/Resources/Info.plist) 中配置为 `L它没有 Dock 图标和普通主窗口生命周期。菜单栏、popover、浮动面板、设置窗口和通知点击都必须显式处理 App 激活与焦点。-普通 SwiftUI Window 的默认行为不足以覆盖这些场景,因此 UI 采用 SwiftUI 内容加 AppKit Controller 的组合。--## UI 架构的分工--SwiftUI 负责声明内容,AppKit 负责窗口和事件生命周期:--| 层 | 负责 | 不负责 |-| --- | --- | --- |-| SwiftUI View | 布局、数据展示、用户意图回调 | 创建长期服务、决定 key window、安装全局事件监听 |-| ViewModel 和 Settings | 发布稳定快照、保存用户设置 | 持有窗口或判断屏幕坐标 |-| AppKit Controller | popover, panel, window, focus, event monitor | 重新实现业务状态机 |-| AppDelegate | 组装和持有长期对象 | 承载具体视图布局 |--这个边界让同一份菜单内容可以装入 `NSPopover` 或 fallback `NSPanel`,同时避免 SwiftUI View 因 identity 变化而销毁 monitor、XPC 或通知服务。+UI 使用 SwiftUI 声明内容,由 AppKit Controller 管理窗口。## `LSUIElement` 下的 3 类焦点@@ -39,29 +26,18 @@ SwiftUI 负责声明内容,AppKit 负责窗口和事件生命周期:[`CodexBarAppDelegate.swift`](../../CodexBar/Controllers/CodexBarAppDelegate.swift) 是普通模式的 composition root,[`StatusItemController.swift`](../../CodexBar/Controllers/StatusItemController.swift) 只负责菜单栏和相关窗口编排。-AppDelegate 负责:--- 创建长期 service, ViewModel 和 settings-- 建立 monitor 与通知、防睡眠的观察关系,并装配自动重置状态机-- 启动状态刷新和 Hook 活动读取-- 创建状态栏控制器-- 安装全局快捷键-- 配置 Sparkle 更新-- 在 App 终止时协调自动重置唤醒计划取消和防睡眠释放--对象由 composition root 显式持有,避免 SwiftUI View 生命周期意外销毁长期服务。--### 启动顺序为什么重要+### 启动顺序普通模式的装配顺序体现依赖关系:```text-创建 settings 和数据服务- -> 建立 ViewModel- -> 创建 status item 和窗口 controller- -> 启动通知与自动重置副作用+创建 settings、数据服务、ViewModel 和更新服务+ -> 创建并安装 StatusItemController+ -> 装配菜单栏、观察者和快捷键+ -> 对账 Hook 并启动周期刷新+ -> 启动通知与自动重置+ -> 连接异常会话保护回调-> 启动 activity monitor 与 keep-alive 协调- -> 启动周期刷新与更新服务```通知和防睡眠只消费 monitor 已发布的快照或转场,不反向控制 reader。Controller 通过闭包连接这些服务,从而避免服务层依赖 AppKit 容器。@@ -75,10 +51,10 @@ AppDelegate 负责:任务状态点的优先级是:```text-等待批准 > 运行中 > 最近完成 > 最近中断 > 空闲+等待批准(橙色) > 运行中(蓝色) > 完成后 30 秒内(绿色)```-图标生成结果按输入状态缓存,避免每次定时刷新重复绘制。非激活或不可用状态通过 alpha 表达。+最近中断、空闲和完成高亮过期后均不显示任务状态点。图标生成结果按输入状态缓存,非激活或不可用状态通过 alpha 表达。### 图像状态与 tooltip 状态分离@@ -89,8 +65,6 @@ AppDelegate 负责:- 指示点或额度条显隐变化时才启动约 0.18 秒的 10 帧动画- 新渲染状态到达时取消旧动画,每帧再次确认目标状态仍是当前状态-如果直接对完整状态做 `NSImage` 重绘,每次计时文字变化都会打断动画并增加菜单栏绘制。将 render identity 显式建模是一个小而重要的性能边界。-无状态点和额度条时图标保持 template image,让系统根据浅色、深色和菜单栏状态自动着色。一旦加入自定义颜色或进度条就使用显式颜色绘制。tooltip 只在存在实时任务持续时间时启动 60 秒计时器,空闲时不保留永久 timer。App 还把 `NSInitialToolTipDelay` 调整为 500 ms,让菜单栏这种小点击目标的状态解释更容易被发现。@@ -110,7 +84,7 @@ CodexBar 自己管理 dismiss,原因包括:[`MenuSurfaceDismissMonitor.swift`](../../CodexBar/Controllers/MenuSurfaceDismissMonitor.swift) 监听全局和本地事件,[`MenuSurfaceFadeCoordinator.swift`](../../CodexBar/Controllers/MenuSurfaceFadeCoordinator.swift) 统一协调关闭动画。-### 为什么需要显式开合状态机+### 开合状态机`menuSurfaceState` 有 4 个状态:@@ -127,7 +101,7 @@ hidden -> opening -> shown -> closing -> hidden只检查 `popover.isShown` 不足以表示 opening 或 fade-out 中的逻辑状态,也无法同时覆盖 fallback panel。-### dismiss 规则为什么由一个监听器管理+### 关闭事件监听主面板的允许点击区域是一个集合:@@ -145,21 +119,17 @@ hidden -> opening -> shown -> closing -> hidden- 点击后重新固定 `NSVisualEffectView` 为 inactive,避免 AppKit 自动强调背景导致明暗跳变- 初次安装 observer 后 `Task.yield()` 再补一次窗口获取和聚焦,覆盖 popover window 尚未挂载的时机-这些规则应作为一个交互表面整体修改。只给某个侧边 panel 单独添加 event monitor 会制造监听顺序和重复关闭问题。+### 淡入淡出与完成任务-### 淡入淡出作用在内容而不是窗口+`MenuSurfaceFadeCoordinator` 同时调整活动容器的内容视图和窗口透明度,淡入为 0.24 秒,淡出为 0.18 秒。控制器只保存一个完成任务;新动画开始前取消旧任务,任务等待结束后检查取消状态,再标记已显示或完成关闭。-popover 的系统窗口由 AppKit 管理,直接动画窗口 alpha 容易与系统显示状态冲突。`MenuSurfaceFadeCoordinator` 对活动容器的 content view 做动画,完成后再调用统一 close。--关闭期间辅助窗口暂时拒绝 `makeKey()`。否则原本已打开的设置或日志窗口可能在菜单 fade-out 的几帧里突然跳到前面。+关闭期间设置和日志窗口暂时拒绝 `makeKey()`,关闭完成后约 120 ms 恢复。完成任务弱引用当次窗口,关闭后恢复内容视图和窗口透明度。## Fallback panel全局快捷键触发时,状态栏按钮的屏幕位置可能不可用或不可信。此时 [`FallbackPanelController.swift`](../../CodexBar/Controllers/FallbackPanelController.swift) 在鼠标所在屏幕显示浮动面板。-popover 和 fallback panel 承载同一份 SwiftUI 内容和状态。业务逻辑不能依赖具体容器类型。--### 锚点为何需要可信度检查+### 锚点校验全局快捷键可能在 status item 尚未完成布局、菜单栏位于另一块屏幕,或系统暂时不给出 button window 时触发。代码不会只检查 button 非 nil,还验证:@@ -184,8 +154,6 @@ fallback panel 在展示前根据 SwiftUI fitting size 和目标屏幕可见区所有详情面板实现 `MenuSideDetailPanel` 并登记在 `sideDetailPanels` 数组。互斥关闭、主表面关闭和 hit testing 都遍历同一份名册。-这比在每对面板之间写互相关闭更可扩展。新增第 4 个面板时只需要加入名册,不需要补齐 6 对互斥关系。-hover 类型的热力图面板在打开其他面板前可以渐隐,点击类型的面板通常立即关闭旧面板。这是为了避免同一屏幕位置出现两个反向滑动动画叠加。热力图详情面板以包含标题、日期范围和方格矩阵的完整热力图区域作为垂直锚点,因此主面板区域重排后仍优先保持两者顶边对齐。如果详情面板从该位置向下会超过主面板底边,则定位逻辑将它整体上移到与主面板底边对齐。@@ -201,9 +169,7 @@ hover 类型的热力图面板在打开其他面板前可以渐隐,点击类设置与日志由独立的 `HostingWindowController` 管理 `NSWindow`-`LSUIElement` App 打开普通窗口时需要暂时允许窗口成为 key、激活 App,再把焦点交给目标控件。关闭后恢复菜单栏 App 的非前台行为。--焦点恢复使用约 120 ms 延迟,给 AppKit 完成窗口和 activation 状态切换。这类延迟属于系统生命周期协调,不能简单删除为同步调用。+打开设置或日志窗口时,`HostingWindowController` 允许目标窗口成为 key 并激活 App。`AuxiliaryHostingWindow` 可以成为 key window,但不能成为 main window。上下文菜单 action 会延迟到 menu tracking 结束后执行,避免 AppKit 仍在菜单事件循环中时创建或激活窗口。@@ -237,17 +203,17 @@ hover 类型的热力图面板在打开其他面板前可以渐隐,点击类`MainPanelSettings` 使用稳定区域标识保存账户、任务中心、额度、Token 用量和底部状态的顺序与显隐。布局归一化会去重、忽略无效值、补齐缺失区域,并保证至少保留一个可见区域。`StatusItemController` 在读取到 Hook 关闭状态后调用 `updateHookEnabled(_:)`,持久化关闭任务中心;如果任务中心原本是唯一可见区域,则同时开启账户区域。设置面板只禁用任务中心开关,拖拽手柄仍保持可用。其他数据链路的临时可用性只影响当次渲染。-布局排序使用手柄上的自定义 `DragGesture`。拖动项通过悬浮副本跟随指针,其他行在跨过半行距离时按视图内预览顺序实时让位,松手后才调用 `setSectionOrder(_:)` 一次性持久化最终顺序。不要改回系统 `.draggable` 和 `.dropDestination`,它们只能在落点命中后换位,无法提供连续排序动画。+布局排序使用手柄上的自定义 `DragGesture`。拖动项通过悬浮副本跟随指针,其他行在跨过半行距离时按视图内预览顺序实时让位,松手后才调用 `setSectionOrder(_:)` 一次性持久化最终顺序。`SettingsWindowController` 持有这一窗口组唯一的 `UndoManager`。设置主窗口通过 `AuxiliaryHostingWindow` 暴露它,四个设置子面板展示时从父窗口取得同一实例,因此焦点位于设置主窗口或任一子面板时,`⌘Z` 和 `⌘⇧Z` 都作用于同一份布局历史。Hook 状态变化引起的任务中心自动关闭不进入用户撤销历史。-### 120 ms 焦点恢复不是业务延迟+### 代理配置对话框-菜单关闭时 `AuxiliaryHostingWindow` 暂时把 `allowsKeyFocus` 设为 false。关闭完成后等待约 120 ms 再恢复。+`CodexBarAppDelegate` 持有 `CodexProxySettings`,并经窗口控制器注入设置页。`AppSettingsView` 使用 SwiftUI `sheet` 展示 `ProxySettingsView`,打开前关闭侧边设置面板。-这段时间给 AppKit 完成 popover order-out, activation 和 key window 重算。删除延迟可能只在开发机上偶尔复现设置窗口闪前,因此应把它视为系统事件排序约束,而不是可以随意优化掉的等待。+未配置时点击整行或开关都会打开配置;已有配置时,行主体打开对话框,开关单独启停。对话框显示时从本机偏好加载草稿,关闭时取消测试并清空内存中的密码草稿。右上角清除菜单按保存记录是否存在显示,即使记录无法解码也可使用。-右键菜单 action 也要等 `menuDidClose` 后通过主队列执行。menu tracking 是嵌套事件循环,在其中同步创建窗口会得到不稳定的 activation 顺序。+关于页面的重连按钮紧邻 `Codex 版本` 标题,来源选择器位于行尾。重连及刷新期间两者禁用;没有可用来源时重连按钮禁用。## 全局快捷键@@ -269,38 +235,23 @@ Carbon API 适合无 Dock 菜单栏 App,不需要安装全局键盘事件 tap2. 注册成功后才释放当前 registration3. 注册失败时清理候选资源并恢复设置中的旧值-如果先注销旧快捷键,一次冲突会让用户同时失去新旧两组按键。`GlobalHotKeyRegistration` 在显式 invalidate 和 deinit 中都清理 Carbon 引用,避免重注册泄漏 handler。--至少两个修饰键降低误触概率。Command-Space 和 Command-Tab 被拒绝,因为它们属于核心系统导航,即使注册 API 某次允许也不应抢占。+`GlobalHotKeyRegistration` 在显式 invalidate 和 deinit 中清理 Carbon 引用。## 自动刷新与面板打开-app-server 状态默认每 60 秒刷新。面板打开时会安排约 160 ms 的延迟刷新,先完成动画和焦点切换,再更新数据。--主面板显示倒计时。手动刷新由双击触发,避免单击状态栏本身与按钮动作产生歧义。--刷新协调器合并并发触发,防止定时器、面板打开和用户操作重复创建相同请求。--面板打开时 Hook 统计立即从本地缓存刷新,app-server 请求延后约 160 ms。前者便宜且能快速填充内容,后者可能启动进程或发协议请求,放在开场动画之后可减少首帧卡顿。+app-server 状态默认每 60 秒检查刷新。主面板打开后约 160 ms 调用 `refreshIfNeeded`,倒计时起点为空或距上次刷新结果提交超过 60 秒时才发起请求。成功和失败的结果提交都会重置倒计时;该检查可能发生在淡入动画结束之前。-`refreshIfNeeded` 仍会执行 freshness 合并,160 ms 不是绕过协调器的第二套刷新路径。面板在等待期间关闭时 task 被取消,不再为不可见 UI 发请求。+主面板显示刷新倒计时,双击账户图标可立即手动刷新。-## 修改 UI 生命周期时的检查顺序+普通刷新在刷新或重连进行中被忽略。需要在当前请求后补刷的操作通过 `refreshAfterCurrent` 保存一个待执行触发,当前请求结束后再执行。-1. 确定变化属于 SwiftUI 内容还是 AppKit 容器生命周期-2. 检查 popover 和 fallback panel 是否共用相同行为-3. 检查 opening 和 closing 中间态,不只验证稳定状态-4. 检查点击区域是否需要加入 extra surface-5. 检查 App active、key window 和逻辑 presented 是否可能分离-6. 检查任务或 timer 在关闭和 uninstall 时是否取消-7. 在多显示器、多 Space 和无可信 status item anchor 下验证-8. 从通知点击、全局快捷键和右键菜单 3 个入口分别打开+面板打开时立即刷新本地 Hook 统计;延迟任务还会对账已安装的 Hook 配置。面板在等待期间关闭时会取消该任务。## 本地化和格式化简体中文和英文界面字符串位于 [`Localizable.xcstrings`](../../CodexBar/Resources/Localizable.xcstrings)-日期、数字和百分比使用系统自动更新 locale。不在业务模型中固定中文格式,也不把本地化后的字符串作为状态机输入。+百分比、时长和部分时间显示使用系统地区设置。`CodexDateFormat` 的日期键及日期范围固定为 `yyyy-MM-dd`,设置页最后上传时间和重置次数详情固定为本地时间 `yyyy-MM-dd HH:mm:ss`。本地化字符串不参与状态机判定。## 自动更新@@ -308,7 +259,7 @@ app-server 状态默认每 60 秒刷新。面板打开时会安排约 160 ms 的- appcast URL 来自 App 配置- 自动检查间隔为 3600 秒-- 更新 UI 由设置页和上下文菜单触发+- 更新 UI 由设置页和主面板的新版本提示触发- CodexBarHelper 变化在更新后单独执行 fingerprint 和注册状态检查发布脚本需要 Developer ID、签名和公证凭据,不属于日常本地构建流程。diff --git a/Docs/README.md b/Docs/README.mdindex acd04eb..eeb5b7e 100644--- a/Docs/README.md+++ b/Docs/README.md@@ -2,60 +2,27 @@简体中文 | [English](en/README.md)-CodexBar 文档按读者和职责分成两套,使用说明与实现细节保持独立:--| 文档 | 目标读者 | 解决的问题 |-| --- | --- | --- |-| [用户手册](UserGuide/README.md) | 使用 CodexBar 的普通用户 | 如何安装,使用功能,理解设置和排查常见问题 |-| [开发者指南](DeveloperGuide/README.md) | 贡献者和代码阅读者 | App 如何实现,数据如何流动,核心约束如何验证 |--## 推荐阅读路径--### 第一次使用 CodexBar--1. 阅读 [安装与快速开始](UserGuide/getting-started.md)-2. 了解 [主面板与菜单栏](UserGuide/main-panel.md)-3. 按需开启 [实时任务与 CodexBar Hook](UserGuide/activity-and-hook.md)-4. 在 [设置参考](UserGuide/settings.md) 中确认自动重置、防睡眠和其他选项的作用--### 排查使用问题--1. 先查看 [常见问题与排查](UserGuide/troubleshooting.md)-2. 再从 App 的日志窗口确认 app-server 请求状态-3. 涉及本机文件或网络边界时查看 [数据,同步与隐私](UserGuide/sync-data-privacy.md)--### 阅读或修改代码--1. 从 [整体架构](DeveloperGuide/architecture.md) 建立全局视图-2. 按改动范围进入对应的数据链路或服务文档-3. 在 [开发与验证](DeveloperGuide/development.md) 中查看构建,调试和验证方式-4. 在 [数据与隐私边界](DeveloperGuide/data-and-privacy.md) 中查看本地与云端数据范围--## 目录结构--```text-Docs-├── UserGuide-│ ├── README.md-│ ├── getting-started.md-│ ├── main-panel.md-│ ├── activity-and-hook.md-│ ├── notifications.md-│ ├── sleep-prevention.md-│ ├── sync-data-privacy.md-│ ├── settings.md-│ └── troubleshooting.md-└── DeveloperGuide- ├── README.md- ├── architecture.md- ├── design-decisions.md- ├── app-server.md- ├── hook-and-aggregation.md- ├── activity-monitor.md- ├── sleep-prevention.md- ├── sync.md- ├── notifications.md- ├── ui-and-lifecycle.md- ├── data-and-privacy.md- └── development.md-```+## 用户指南++- [安装与快速开始](UserGuide/getting-started.md)+- [主面板与菜单栏](UserGuide/main-panel.md)+- [实时任务与 CodexBar Hook](UserGuide/activity-and-hook.md)+- [通知与提醒](UserGuide/notifications.md)+- [防止系统睡眠](UserGuide/sleep-prevention.md)+- [数据、同步与隐私](UserGuide/sync-data-privacy.md)+- [设置参考](UserGuide/settings.md)+- [常见问题与排查](UserGuide/troubleshooting.md)++## 开发者指南++- [整体架构](DeveloperGuide/architecture.md)+- [设计原则与关键决策](DeveloperGuide/design-decisions.md)+- [app-server 数据链路](DeveloperGuide/app-server.md)+- [Hook 采集与历史聚合](DeveloperGuide/hook-and-aggregation.md)+- [实时任务监控](DeveloperGuide/activity-monitor.md)+- [防睡眠系统](DeveloperGuide/sleep-prevention.md)+- [CloudKit 同步](DeveloperGuide/sync.md)+- [通知系统](DeveloperGuide/notifications.md)+- [UI 与应用生命周期](DeveloperGuide/ui-and-lifecycle.md)+- [数据与隐私边界](DeveloperGuide/data-and-privacy.md)+- [开发与验证](DeveloperGuide/development.md)diff --git a/Docs/UserGuide/README.md b/Docs/UserGuide/README.mdindex 2fb4325..c194302 100644--- a/Docs/UserGuide/README.md+++ b/Docs/UserGuide/README.md@@ -1,4 +1,4 @@-# CodexBar 用户手册+# CodexBar 用户指南简体中文 | [English](../en/UserGuide/README.md)@@ -15,24 +15,9 @@| [设置参考](settings.md) | 通用、高级和关于页面中每一个设置的作用,包括自动重置 || [常见问题与排查](troubleshooting.md) | 登录、Hook、通知、自动重置、防睡眠、同步和日志问题 |-## 按目标快速查找+## 常用名称-- 只想查看账户和额度,从 [安装与快速开始](getting-started.md) 开始-- 想看正在运行或等待批准的任务,阅读 [实时任务与 CodexBar Hook](activity-and-hook.md)-- 想在留存重置到期前自动重置额度,阅读 [设置参考](settings.md#自动重置)-- 想在长任务期间阻止 Mac 睡眠,阅读 [防止系统睡眠](sleep-prevention.md)-- 想知道某个开关是否会上传数据,阅读 [数据、同步与隐私](sync-data-privacy.md)-- 已经遇到错误提示,直接进入 [常见问题与排查](troubleshooting.md)--## 术语约定--| 术语 | 含义 |-| --- | --- |-| Codex | Codex CLI, ChatGPT App 或 Codex App 中运行的 Codex 能力 |-| app-server | CodexBar 在本机启动并连接的 Codex 数据接口进程 |-| CodexBar Hook | CodexBar 安装到 Codex 配置中的事件处理器 |-| 实时任务 | CodexBar 根据 Hook 事件和本机会话状态判断出的运行中或等待批准任务 |-| Hook 聚合 | 从本机 Hook 原始事件计算出的每日会话、轮次和工具等统计 |-| CodexBarHelper | 负责系统级睡眠状态切换和固定自动重置唤醒计划的 CodexBar 后台服务 |+- CodexBar Hook:开启实时任务与每日活动统计的功能+- CodexBarHelper:随 App 安装的后台服务,用于防睡眠和自动重置唤醒返回 [CodexBar README](../../README.md)diff --git a/Docs/UserGuide/activity-and-hook.md b/Docs/UserGuide/activity-and-hook.mdindex 0735cd0..d63cbe3 100644--- a/Docs/UserGuide/activity-and-hook.md+++ b/Docs/UserGuide/activity-and-hook.md@@ -2,131 +2,43 @@简体中文 | [English](../en/UserGuide/activity-and-hook.md)-## Hook 解决什么问题--账户、额度和 Token 用量是周期性快照,无法说明一轮 Codex 任务正在运行、等待批准还是已经结束。--CodexBar Hook 会在 Codex 的关键事件发生时记录少量结构化字段,为 CodexBar 提供以下能力:--- 菜单栏任务状态点和任务提示-- 主面板活动卡片和并发任务中心-- 任务完成、等待批准和异常会话提醒-- 任务触觉反馈-- 每日会话、轮次、工具调用、权限请求、上下文压缩和子 Agent 统计-- 按实时任务自动防止系统睡眠-- 跨设备同步每日 Hook 聚合-- 从原始事件重建历史聚合--## 启用条件--开启 CodexBar Hook 前需要满足以下条件:--- CodexBar 能连接当前运行的 Codex app-server-- app-server 实际运行版本为 `0.145.0` 或更高版本-- Codex 配置中的 `features.hooks` 没有被全局关闭-- 当前 `hooks.json` 是有效 JSON--版本检查以当前已连接 app-server 的握手版本为准,不是磁盘上刚安装的版本。--更新 Codex 后如果仍提示版本过低,在“设置 > 关于”中点击“重新建立连接”。+CodexBar Hook 用于显示实时任务,并支持任务通知、触觉反馈、按任务防睡眠,以及每日会话、轮次和工具调用统计。开启后也可以同步或重建这些每日统计。## 开启方法-1. 右键或 Control 点击菜单栏图标-2. 选择 `设置`-3. 打开 `高级` 页面-4. 开启 `CodexBar Hook`-5. 等待开关完成配置和校验--CodexBar 会在启动、打开菜单、每次打开设置窗口、App 重新激活以及每轮额度刷新完成后检查已开启 Hook。额度自动刷新正常每 60 秒完成一轮,必要事件配置或信任项缺失时会自动修复。--## 配置文件会发生什么变化--CodexBar 使用 `$CODEX_HOME/hooks.json`,未设置 `CODEX_HOME` 时使用 `~/.codex/hooks.json`--开启时会完成以下操作:--1. 读取并保留已有配置-2. 为 CodexBar 追加独立的 command handler-3. 让 Codex 校验事件列表、来源和信任状态-4. 只更新与当前 CodexBar handler 匹配的信任项--关闭时只删除同时匹配当前 CodexBar 可执行路径和 `--hook-event` 参数的 handler。+1. 打开 `设置 > 高级`+2. 开启 `CodexBar Hook` 并等待校验完成+3. 开始一轮 Codex 任务,在主面板查看状态-用户自己的 handler、其他 App 的 handler、未识别字段和无关信任项都会保留。+Hook 要求当前使用的 Codex 为 `0.145.0` 或更高版本。更新后仍提示版本过低时,在 `设置 > 关于` 点击 `重新建立连接`。其他错误见 [常见问题与排查](troubleshooting.md#hook-无法开启或校验失败)-## 任务状态如何理解+CodexBar 会自动检查和修复已开启的 Hook 配置。开启或关闭时,会保留用户和其他 App 已有的 Hook。-| 状态 | 含义 | 是否算作活跃任务 |-| --- | --- | --- |-| 运行中 | 当前任务仍在产生进展 | 是 |-| 等待批准 | 当前任务正在等待用户批准下一步操作 | 是 |-| 最近完成 | 一轮任务已确认结束 | 否 |-| 最近终止 | 一轮任务被确认终止 | 否 |-| 已隐藏 | 运行中任务超过异常会话静默阈值 | 否 |+## 任务状态-完成只表示一轮任务结束,不代表执行结果一定成功。--等待批准只用于真正由用户处理的批准请求,自动审核不会被显示成用户等待状态。--子 Agent 事件会更新所属顶层任务,不会独立显示为另一条并发任务。--Codex Auto-review 使用独立 reviewer agent 处理权限审核。CodexBar 会识别并排除这个内部审核任务,因此它不会显示在菜单栏、活动卡片或任务中心,也不会触发通知、触觉反馈、异常会话保护或防睡眠。其他子 Agent 的现有行为不变。--Auto-review 来源优先根据 rollout 元数据识别;rollout 来源不可用时,精确匹配 `codex-auto-review` 的 model 作为后备判定。实时任务读取本机 Hook 记录时应用同一规则,不回填或重写原始记录。--Hook 事件缺少 session ID 时,CodexBar 会按项目显示匿名任务。匿名任务仍可出现在运行中、等待批准、最近完成和最近终止列表中,但不触发任务通知或触觉反馈,不参与防睡眠和异常会话保护。--活动卡片和任务中心使用橙色匿名图标标记这类任务,悬停时显示 `匿名任务不参与防睡眠`--## Hook 事件与用途--| 事件 | 主要用途 |-| --- | --- |-| `SessionStart` 和 `SessionEnd` | 会话生命周期和任务收尾 |-| `UserPromptSubmit` 和 `Stop` | 轮次生命周期、任务开始和完成候选 |-| `PreToolUse` 和 `PostToolUse` | 工具调用统计和任务进展 |-| `PermissionRequest` | 用户等待状态和权限请求统计 |-| `PreCompact` 和 `PostCompact` | 上下文压缩统计和任务进展 |-| `SubagentStart` 和 `SubagentStop` | 子 Agent 数量、状态和任务进展 |--## 每日统计如何计算--| 指标 | 含义 |+| 状态 | 含义 || --- | --- |-| 会话 | 除 `SessionEnd` 外,当天其他事件中不同 session 的数量 |-| 对话轮次 | 除 `Stop` 外,当天其他事件中不同 turn 的数量 |-| 工具调用 | `PreToolUse` 和 `PostToolUse` 两类计数中的较大值 |-| 权限请求 | `PermissionRequest` 事件数量 |-| 上下文压缩 | `PreCompact` 和 `PostCompact` 两类计数中的较大值 |-| 子 Agent | `SubagentStart` 和 `SubagentStop` 两类计数中的较大值 |-| 最常用模型 | 当天 Hook 事件中出现次数最多的模型 |--session 和 turn 只统计非空 ID,并分别在当天去重。跨天 session 或 turn 如果当天仍有其他事件会计入当天;当天只有 `SessionEnd` 的 session 和只有 `Stop` 的 turn 不计入。--使用较大值可以在成对事件缺少一端时保留已经观察到的操作数量。+| 运行中 | Codex 正在处理任务 |+| 等待批准 | 需要你批准下一步操作 |+| 最近完成 | 一轮任务已结束,不代表结果一定成功 |+| 最近终止 | 任务被中断,不发送完成通知 |-Auto-review 只从实时任务链路中排除,其 Hook 事件仍参与上述每日统计。+子 Agent 的活动合并到所属任务中。内部自动审核任务不显示为独立任务,也不触发任务提醒或防睡眠;它的活动仍计入每日统计。-## 关闭 Hook 的影响+无法识别会话的任务会带有橙色匿名图标。这类任务可以查看,但不触发通知或触觉反馈,也不参与防睡眠和异常会话保护。-关闭 Hook 后以下功能停止更新:+长时间没有进展的运行任务可能被 [异常会话保护](sleep-prevention.md#异常会话保护) 隐藏,恢复进展后重新显示。-- 实时任务和任务中心-- 菜单栏任务状态点-- 任务类通知和触觉反馈-- Hook 每日统计-- 防止系统睡眠-- 跨设备 Hook 聚合同步+## 每日统计-账户、额度、Token 热力图、更新检查和日志窗口仍然可以使用。+在主面板热力图上悬停日期,可查看当天的会话数、对话轮次、工具调用、权限请求、上下文压缩、子 Agent 和最常用模型。-## 数据边界+会话和轮次按天去重,跨天继续活动会计入新的一天。工具调用等成对记录可能不完整,因此统计反映 CodexBar 实际观察到的活动。-Hook 原始事件只保存时间、事件名、归一化来源 `origin`、模型、推理强度、权限模式、`reviewer`、`session`、`turn`、`agent`、工具名和工作目录等结构化字段。+## 关闭 Hook-CodexBar 不保存 rollout 路径、原始来源值、prompt 文本、Codex 回复、工具参数或工具输出。+关闭后,实时任务、任务通知、触觉反馈、防睡眠、Hook 统计及其跨设备同步停止更新。账户、额度和 Token 热力图仍可使用。-完整存储和同步边界见 [数据、同步与隐私](sync-data-privacy.md)+Hook 记录任务的时间、模型、工具名和项目等信息,不保存提问、回复或工具输入输出正文。保存期限与同步内容见 [数据、同步与隐私](sync-data-privacy.md)-返回 [用户手册](README.md)+返回 [用户指南](README.md)diff --git a/Docs/UserGuide/getting-started.md b/Docs/UserGuide/getting-started.mdindex b76bf48..2afeee1 100644--- a/Docs/UserGuide/getting-started.md+++ b/Docs/UserGuide/getting-started.md@@ -6,8 +6,8 @@- macOS 15.0 或更高版本- 已安装并登录 [Codex CLI](https://github.com/openai/codex),或安装了内置 Codex 的 ChatGPT App 或 Codex App-- 当前运行的 Codex app-server 版本需要为 `0.143.0` 或更高版本-- 使用 Hook 相关功能时,当前运行的 Codex app-server 版本需要为 `0.145.0` 或更高版本+- 当前使用的 Codex 版本需要为 `0.143.0` 或更高版本+- 使用 Hook 相关功能时,当前使用的 Codex 版本需要为 `0.145.0` 或更高版本- 使用跨设备同步时,Mac 需要登录可用的 iCloud 账户CodexBar 默认自动选择来源,优先使用全局安装的 Codex CLI,找不到时再尝试 ChatGPT App 和 Codex App 内置的 Codex。可在“设置 > 关于 > Codex 版本 > 来源”中手动选择。@@ -56,21 +56,13 @@ CodexBar 每 60 秒自动刷新一次账户、额度和 Token 用量,双击主全局快捷键优先在鼠标所在屏幕打开主面板,菜单栏锚点不可用时会使用独立浮动面板。-## 功能依赖+## 开启更多功能-| 功能 | CodexBar Hook | 其他条件 |-| --- | --- | --- |-| 账户、套餐和额度 | 不需要 | Codex 已登录,app-server 不低于 `0.143.0` |-| Token 汇总和热力图 | 不需要 | app-server 不低于 `0.143.0` |-| 实时任务和任务中心 | 需要 | Hook 已通过校验 |-| 每日 Hook 统计 | 需要 | 本机存在 Hook 原始事件 |-| 额度类通知 | 不需要 | 系统通知总开关和权限已开启 |-| 自动重置 | 不需要 | 每次开启需确认;系统睡眠期间按计划唤醒和显示临期选项需要 CodexBarHelper 获得批准;可选提前 15 分钟至 6 小时,默认提前 30 分钟 |-| 任务类通知 | 需要 | Hook 已通过校验且通知已开启 |-| 防止系统睡眠 | 需要 | 每次开启需确认;CodexBarHelper 已注册并获得系统批准 |-| 跨设备同步 | 需要 | iCloud 可用且用户主动开启同步 |--关闭 CodexBar Hook 不影响账户、额度、Token 热力图、更新检查或日志窗口。+- [CodexBar Hook](activity-and-hook.md):实时任务、每日活动统计和按任务防睡眠+- [系统通知](notifications.md):任务和额度提醒,需允许 macOS 通知权限+- [自动重置](settings.md#自动重置):提前使用即将过期的留存重置,可能短暂唤醒 Mac+- [防止系统睡眠](sleep-prevention.md):长任务期间保持 Mac 唤醒,需批准后台服务+- [跨设备同步](sync-data-privacy.md):合并多台 Mac 的 Hook 统计,需登录 iCloud## 语言与地区@@ -78,6 +70,4 @@ CodexBar 提供简体中文和英文界面,默认跟随 macOS 的 App 语言需要单独切换时,可在 macOS 系统设置的语言与地区页面为 CodexBar 指定 App 语言。-日期、时间、时长、百分比、月历和星期顺序始终跟随当前地区格式。-下一步可以阅读 [主面板与菜单栏](main-panel.md) 或 [设置参考](settings.md)diff --git a/Docs/UserGuide/main-panel.md b/Docs/UserGuide/main-panel.mdindex 804567e..d359418 100644--- a/Docs/UserGuide/main-panel.md+++ b/Docs/UserGuide/main-panel.md@@ -23,9 +23,7 @@ CodexBar 用图标、状态点和可选额度条同时表达账户、任务和## 自定义布局-在 `设置 > 通用 > 主面板布局` 中,可以拖动调整 `账户`、`任务`、`额度`、`用量` 和 `状态` 5 个区域的顺序,也可以分别控制是否显示。--主面板至少保留一个区域。Hook 未开启时,`任务` 区域自动关闭且开关置灰,但仍可拖动调整位置;如果该区域原本是唯一显示区域,`账户` 区域会自动开启。重新开启 Hook 后,可以再手动开启 `任务` 区域。拖拽排序或切换区域显隐后,可以使用 `⌘Z` 按操作顺序撤销,并使用 `⌘⇧Z` 重做。+在 `设置 > 通用 > 主面板布局` 中调整区域顺序和显隐,支持撤销与重做。具体操作见 [设置参考](settings.md#主面板布局)## 账户区域@@ -34,9 +32,10 @@ CodexBar 用图标、状态点和可选额度条同时表达账户、任务和- 双击账户图标会立即刷新账户、额度和用量- 双击邮箱会切换模糊显示- 未登录时显示 `未登录`-- app-server 无法初始化时显示 `初始化失败`+- 当前 Codex 版本低于要求时显示最低版本提示+- Codex 连接无法初始化时显示 `初始化失败`-主面板只展示适合用户判断的状态,具体请求错误保留在日志窗口。+具体连接失败原因可在设置的关于页面查看,完整请求和响应可在日志窗口查看。## 额度区域@@ -101,9 +100,9 @@ CodexBar Hook 开启且当天有数据时,日期详情还会显示以下统计防睡眠实际生效时,活动卡片右侧会显示咖啡杯标记。-Hook 事件缺少 session ID 时,任务仍会显示在活动卡片和任务中心,并带有橙色匿名图标。悬停图标会显示 `匿名任务不参与防睡眠`+无法识别会话的任务带有橙色匿名图标,悬停显示 `匿名任务不参与防睡眠`-活动卡片的 `+N` 只表示其他活跃任务总数,不拆分匿名任务数量。+活动卡片的 `+N` 表示其他活跃任务总数。点击有内容的活动卡片可以打开任务中心。@@ -116,13 +115,9 @@ Hook 事件缺少 session ID 时,任务仍会显示在活动卡片和任务中- 最近完成- 最近终止-最近完成和最近终止记录在任务中心保留 10 分钟,完成与终止是不同状态。--完成表示一轮任务已经结束,不代表执行结果一定成功。--终止不会触发任务完成通知。+最近完成和最近终止记录保留 10 分钟。完成表示一轮任务结束;终止表示被中断,不触发完成通知。-匿名任务在运行中、等待批准、最近完成和最近终止状态下都会显示同一个匿名图标。+完成不代表结果一定成功。## 底部状态@@ -135,4 +130,4 @@ Hook 事件缺少 session ID 时,任务仍会显示在活动卡片和任务中发现新版本时,双击更新提示可以开始更新。-返回 [用户手册](README.md)+返回 [用户指南](README.md)diff --git a/Docs/UserGuide/notifications.md b/Docs/UserGuide/notifications.mdindex c477a55..644a4de 100644--- a/Docs/UserGuide/notifications.md+++ b/Docs/UserGuide/notifications.md@@ -19,14 +19,14 @@| --- | --- | --- | --- || 任务完成 | 任务完成且运行时长达到所选阈值 | 开启,1 分钟 | CodexBar Hook || 任务等待 | 任务进入等待用户批准状态 | 开启 | CodexBar Hook |-| 额度预警 | 可信额度首次跌到阈值或以下 | 开启,10% | 无 |+| 额度预警 | 剩余额度达到预警阈值 | 开启,10% | 无 || 额度重置 | 已观察到消耗的额度窗口回到未消耗状态 | 开启 | 无 || 重置临期 | 留存重置进入过期前 7 天窗口 | 开启 | 存在可用留存重置 || 自动重置 | 自动重置明确返回成功或此前已成功 | 开启 | 自动重置开关、通知子开关和通知总开关 || 自动重置失败 | 认证失败导致暂停、协议错误导致停止,或本机明确观察到过期 | 与成功通知共用设置 | 自动重置开关、通知子开关和通知总开关 || 低电量保护 | 低电量保护成功恢复系统睡眠 | 开启 | 防睡眠和低电量保护 || 防睡眠上限 | 达到时长上限并成功恢复系统睡眠 | 开启 | 防睡眠和有限时长上限 |-| 异常会话保护 | 运行中任务超过静默阈值且候选仍有效 | 固定行为 | CodexBar Hook 和防睡眠主开关 |+| 异常会话保护 | 运行中任务持续无进展,达到保护阈值 | 固定行为 | CodexBar Hook 和防睡眠主开关 |异常会话保护没有独立通知开关,使用系统默认声音。@@ -41,26 +41,17 @@| 任务完成最短时长 | 30 秒, 1 分钟, 2 分钟, 5 分钟 || 低额度阈值 | 5%, 10%, 25% |-额度预警只在剩余比例从阈值上方跨到阈值或以下时触发,不会在每次 60 秒刷新时重复发送。--同一额度重置周期内,退出并重新启动 CodexBar 也不会重复发送额度预警。+剩余额度降到阈值或以下时触发预警,启动后首次读到低额度也会提醒。额度需要有明确的重置时间,同一重置周期只提醒一次。留存重置会在过期前 7, 6, 5, 4, 3, 2 和 1 天分别判断是否需要提醒。## 自动重置通知-“自动重置”和“额度已重置”来自两个独立事实:--- “自动重置”说明本机自动调用收到 `reset` 或 `alreadyRedeemed`-- “额度已重置”说明额度窗口从已消费状态回到未消费状态--因此一次自动重置可能产生两条通知。它们不互相替代,也分别遵守各自的触发条件。+自动重置成功或因登录、设置错误、过期而停止时,会按通知设置提醒。暂时的网络失败只在后台重试。-多台设备同时尝试时,明确收到成功结果的设备会发送自己的成功通知;只在刷新中看到凭证消失的设备不会通知,因为无法判断是手动使用、其他设备使用还是过期。+一次自动重置可能同时产生“自动重置”和“额度已重置”两条通知:前者是操作结果,后者是额度变化。成功和失败共用“自动重置通知”开关及音效。-网络、超时和暂时服务错误只会在后台重试,不会每次通知。认证仍失败时当前任务暂停,后续可信快照确认认证恢复后继续;确定的协议错误会停止当前任务;本机明确观察到凭证过期时停止并通知。如果凭证直接从服务端明细消失,因为无法判断是手动使用、其他设备使用还是过期,本机会静默停止。--同一凭证的同一失败原因最多通知一次,不同失败原因可能分别通知。成功和失败通知共用“自动重置通知”子开关及音效。自动重置功能关闭时该选项不可用,重新开启后恢复此前的通知和音效选择。+多台 Mac 同时尝试时,收到成功确认的设备会分别提醒;仅发现留存重置已消失的设备不提醒。同一留存重置的同一失败原因最多通知一次。## 通知音效@@ -77,21 +68,19 @@## 触觉反馈-开启 `任务触觉反馈` 后,任务完成或进入等待批准时会触发触摸板震动。+`任务触觉反馈` 默认关闭。开启后,任务完成或进入等待批准时会触发触摸板震动。触觉反馈不依赖 macOS 通知授权,但仍然服从 CodexBar 的系统通知总开关和 CodexBar Hook 状态。## Codex TUI 通知-`Codex TUI 通知` 修改的是 Codex 用户配置中的 `tui.notifications`--它与 CodexBar 本地通知相互独立,开启其中一个不会自动开启另一个。+此选项控制 Codex 自身的通知,与 CodexBar 通知相互独立。## 通知交互- CodexBar 位于前台时仍会显示通知横幅、通知列表项和声音- 点击任意 CodexBar 通知会打开主面板- 任务不再等待批准时,对应等待通知会从通知中心撤回-- 异常任务恢复进展或候选失效时,对应保护通知会从通知中心撤回+- 任务恢复进展或不再符合异常会话保护条件时,对应通知会从通知中心撤回-返回 [用户手册](README.md)+返回 [用户指南](README.md)diff --git a/Docs/UserGuide/settings.md b/Docs/UserGuide/settings.mdindex 6bf0011..3fc70d1 100644--- a/Docs/UserGuide/settings.md+++ b/Docs/UserGuide/settings.md@@ -4,188 +4,85 @@右键或 Control 点击菜单栏图标并选择 `设置`,或按 `⌘,` 打开设置窗口。-设置窗口包含 `通用`、`高级` 和 `关于` 三个页面。-## 通用设置| 设置 | 作用 | 默认或初始状态 || --- | --- | --- |-| 主面板布局 | 调整主面板 5 个区域的顺序和显隐 | 账户、任务、额度、用量、状态;Hook 未开启时任务关闭 |-| 动画效果 | 每次打开主面板时播放额度条填充和用量热力图波动动画 | 开启 |-| 开机自动启动 | 通过 macOS 登录项自动启动 CodexBar | 跟随当前系统登录项状态 |-| 自动检查更新 | 由 Sparkle 定期检查可用更新 | 跟随 Sparkle 当前设置 |-| 菜单栏额度指示 | 在菜单栏图标旁显示所选额度窗口剩余比例 | 主额度 |-| 全局快捷键 | 在任意 App 中打开或关闭 CodexBar 主面板 | `⌘⇧W` |--### 菜单栏额度指示--- 可在当前 Codex 返回的额度窗口之间选择-- 关闭前会记住最后选择的窗口-- 再次开启时恢复上次选择-- 缓存额度会降低显示透明度+| 主面板布局 | 调整账户、任务、额度、用量和状态的顺序与显隐 | 全部显示;Hook 关闭时任务区域关闭 |+| 动画效果 | 打开主面板时播放额度条和热力图动画 | 开启 |+| 开机自动启动 | 登录 Mac 后启动 CodexBar | 跟随系统登录项状态 |+| 自动检查更新 | 定期检查 CodexBar 更新 | 跟随当前更新设置 |+| 菜单栏额度指示 | 显示所选额度窗口的剩余比例 | 主额度 |+| 全局快捷键 | 在任意 App 中开关主面板 | `⌘⇧W` |### 主面板布局-点击设置行右侧的选项按钮,可以配置 `账户`、`任务`、`额度`、`用量` 和 `状态` 5 个区域:+点击右侧选项按钮后,可拖动排序或切换区域开关,至少保留一个区域。使用 `⌘Z` 撤销、`⌘⇧Z` 重做。隐藏区域不会停止相关功能。-- 拖动区域调整显示顺序-- 使用开关控制区域是否显示-- 至少需要保留一个区域-- 拖拽排序或切换显隐后,可以使用 `⌘Z` 按操作顺序撤销,并使用 `⌘⇧Z` 重做+Hook 关闭时任务区域自动关闭,重新开启 Hook 后需手动恢复;如果任务是唯一可见区域,账户区域会自动开启。-`任务` 区域与 CodexBar Hook 联动。Hook 未开启时,该区域自动关闭,其开关置灰且无法开启,但仍可拖动调整位置。重新开启 Hook 后,该区域保持关闭,可以再手动开启。+### 菜单栏额度指示-隐藏区域只影响主面板展示,不会停止额度刷新、Hook 统计、通知、防睡眠或同步。+选择要显示的额度窗口。关闭后再开启,会恢复上次选择;数据变淡表示显示的是缓存额度。### 全局快捷键-- 录制结果至少需要两个修饰键-- `Command-Space` 和 `Command-Tab` 等系统保留组合不可使用-- 已被其他 App 占用的组合会提示冲突-- 可以清除快捷键-- 可以恢复默认值 `⌘⇧W`+快捷键至少需要两个修饰键,不能使用 `Command-Space` 或 `Command-Tab`。组合已被占用时会提示冲突。可以清除快捷键或恢复默认值。## 高级设置| 设置 | 作用 | 默认状态 || --- | --- | --- |-| CodexBar Hook | 安装并校验 Codex 事件 handler | 未安装时关闭 |-| 系统通知 | 控制 CodexBar 本地通知和任务触觉反馈 | 关闭 |-| 自动重置 | 按所选提前量使用即将过期的留存重置 | 关闭,提前 30 分钟 |-| 防止系统睡眠 | 根据实时 Codex 任务自动切换系统睡眠 | 关闭 |-| 跨设备同步 | 通过 iCloud 同步每日 Hook 聚合 | 关闭 |-| 重建数据 | 从所选日期的本机原始事件重新生成聚合 | 手动操作 |+| 代理 | 配置 CodexBar 的 Codex 服务连接代理 | 关闭 |+| [CodexBar Hook](activity-and-hook.md) | 启用实时任务和每日活动统计 | 未安装时关闭 |+| [系统通知](notifications.md) | 配置通知类型、阈值、音效和触觉反馈 | 总开关关闭 |+| 自动重置 | 提前使用即将过期的留存重置 | 关闭,提前 30 分钟 |+| [防止系统睡眠](sleep-prevention.md) | 在符合条件的任务运行时保持 Mac 唤醒 | 关闭 |+| [跨设备同步](sync-data-privacy.md) | 通过 iCloud 合并每日 Hook 统计 | 关闭 |+| [重建数据](sync-data-privacy.md#重建数据) | 重新计算所选日期的 Hook 统计 | 手动操作 |-### CodexBar Hook+### 代理-开启后解锁实时任务、任务类通知、Hook 统计、防睡眠和跨设备同步。--开启和校验要求当前 app-server 为 `0.145.0` 或更高版本。--完整说明见 [实时任务与 CodexBar Hook](activity-and-hook.md)--### 系统通知子选项--| 选项 | 默认值 | 其他可选值或说明 |-| --- | --- | --- |-| 任务完成通知 | 开启,1 分钟 | 最短时长可选 30 秒, 1, 2, 5 分钟 |-| 任务等待通知 | 开启 | 需要 CodexBar Hook |-| 额度预警通知 | 开启,10% | 阈值可选 5%, 10%, 25% |-| 额度重置通知 | 开启 | 只在观察到消耗后识别重置 |-| 重置临期通知 | 开启 | 提醒 7 天内到期的留存重置 |-| 自动重置通知 | 开启 | 只有自动重置开启时可用,成功和失败共用音效 |-| 低电量保护通知 | 开启 | 只有低电量保护实际可用时生效 |-| 防睡眠上限通知 | 开启 | 只有最长时间不是无限制时生效 |-| 任务触觉反馈 | 关闭 | 任务完成或等待批准时触发触摸板震动 |-| Codex TUI 通知 | 跟随 Codex 配置 | 独立于 CodexBar 通知 |+点击设置行打开配置,填写服务器地址和端口。支持 HTTP、HTTPS、域名、IPv4 和 IPv6;端口范围为 `1~65535`。开启身份验证后用户名必填,密码可留空。-每类系统通知可以选择默认、静音、系统声音或 App 内置声音。+HTTP 代理也能转发 HTTPS 请求。只有代理端口本身支持 TLS 时才选择 HTTPS,证书需有效。-完整说明见 [通知与提醒](notifications.md)+- `测试连接` 检查尚未保存的配置,可取消,不会保存或启用代理+- `保存` 应用配置;首次保存后仍需打开设置行右侧开关+- `取消` 丢弃本次编辑+- `⋯ > 删除配置` 删除配置和密码并关闭代理,配置损坏时也可使用+- 关闭右侧开关会保留配置,便于下次启用-### 自动重置与防睡眠开启确认--`自动重置` 和 `防止系统睡眠` 每次从关闭切换为开启时都会显示确认框。确认框先按 CodexBarHelper 当前状态显示提示,再显示对应功能说明:--| CodexBarHelper 状态 | 确认提示 |-| --- | --- |-| 未注册或文件缺失 | `需要安装并授权 CodexBar Helper 后台运行` |-| 已安装但等待系统批准 | `已安装 CodexBar Helper 但需要授权允许后台运行` |-| 已安装并获得系统批准 | 只显示对应功能说明 |--对应功能说明为:--| 功能 | 确认标题 | 功能说明 |-| --- | --- | --- |-| 自动重置 | `开启自动重置?` | `开启后, CodexBar 在手动重置临近过期时, 按设置的临期时间提前自动使用重置; 并可能短暂唤醒 Mac` |-| 防止系统睡眠 | `开启防止系统睡眠?` | `开启后, CodexBar 会在 Codex 任务运行时防止系统睡眠, 任务结束后自动恢复` |--选择 `开启` 后保存开关状态并尝试注册 CodexBarHelper;选择 `取消` 时开关保持关闭。这两个功能的 Helper 授权系统设置只通过已开启设置行下方的 `打开系统设置` 按钮打开,该按钮在 CodexBarHelper 等待系统批准时显示。两个开关处于关闭状态时,设置行下方不显示状态说明。+密码默认隐藏,鼠标移入密码框时显示。代理只影响 CodexBar 的 Codex 服务连接,密码以明文保存在本机。详情见 [数据、同步与隐私](sync-data-privacy.md)### 自动重置-自动重置开关已开启且 CodexBarHelper 已安装并获得系统批准时,主开关行右侧显示选项按钮。点击后可在侧边面板的“临期时间”中选择到期前 `15 分钟`、`30 分钟`、`1 小时`、`2 小时`、`4 小时` 或 `6 小时` 开始尝试,默认是 `30 分钟`。Helper 状态不满足条件时入口隐藏,已展开的自动重置面板会关闭。--- 只处理 app-server 最新响应明确列出的可用留存重置-- 每次使用前重新确认账号、凭证状态和过期时间-- 同一时间只处理最早到期的一次-- 确认开启后会尝试注册 CodexBarHelper;即使“防止系统睡眠”关闭,也可能需要在“登录项与扩展”中批准 CodexBar 后台运行-- 自动重置设置行会显示 CodexBarHelper 待批准、未注册、注册失败或唤醒计划同步失败状态-- 有未来任务时,CodexBarHelper 只为最近一次阈值或重试注册一个系统唤醒事件;任务变化、功能关闭或 App 退出时会取消,异常中断遗留的事件会在 helper 下次启动时清理-- 定时触发后仅在重新读取和使用期间短暂阻止空闲睡眠,不唤醒显示器,也不会开启“防止系统睡眠”-- 系统自然唤醒或 App 下次启动时仍会立即补检;已经进入临期窗口且尚未过期时补试,否则按临期时间重新安排-- 只有已经读到具体凭证和过期时间时才会安排重试唤醒;每轮连续重试最多持续 5 分钟,后续普通额度刷新仍可重新尝试-- 当前没有可重置额度时不会消费次数,并会在本轮 5 分钟窗口内继续使用同一幂等键重试-- 服务端更新同一留存重置的过期时间后,会保留其幂等身份并按新时间重新安排-- 认证失效或确定的协议错误会暂停或停止当前任务,并在通知设置允许时通过系统通知说明--多台 Mac 同时开启时,每台设备独立调度,但会为相同 `creditId` 生成相同幂等键。最先成功的设备完成消费;其他设备收到已成功结果后停止,或者在刷新时发现凭证已经消失并静默停止。+自动重置会在留存重置即将过期时自动使用它。每次开启均需确认;如提示后台服务需要授权,点击设置行下方的 `打开系统设置` 并允许 CodexBar 后台运行。-成功后会发送“自动重置”通知。普通“额度已重置”通知来自额度窗口变化,因此两条通知可能同时出现。自动重置本身不依赖系统通知开关;通知关闭时仍会执行,只是不展示结果通知。+开启且 CodexBarHelper 获得批准后,点击右侧选项按钮设置临期时间:`15 分钟`、`30 分钟`、`1 小时`、`2 小时`、`4 小时` 或 `6 小时`,默认提前 `30 分钟`。-通知侧面板中的“自动重置通知”同时控制成功和失败通知,并为两者配置同一个音效。自动重置功能关闭时该项显示为关闭并置灰,保存的通知和音效选择不会被覆盖。+- 优先处理最早到期的可用留存重置,使用前重新检查登录和可用状态+- 可能短暂唤醒 Mac,但不点亮屏幕,也不会打开防睡眠开关+- 暂时失败时自动重试,每轮最多持续 5 分钟;后续刷新仍可再次尝试+- Mac 唤醒或 App 重新启动后,会补查尚未过期的留存重置+- 关闭功能或退出 App 会取消已安排的唤醒+- 多台 Mac 同时开启时,同一留存重置不会因重复尝试而多次消费-该设置只保存在当前 Mac,不通过 CloudKit 同步。--### 防止系统睡眠子选项--防止系统睡眠开关已开启且 CodexBar Hook 可用时,主开关行右侧可显示子选项按钮。没有符合条件的任务、CodexBarHelper 正在刷新、低电量保护生效或达到最长时间上限时,入口仍然保留;存在符合条件的任务但 CodexBarHelper 不可用时,入口会隐藏。--| 选项 | 默认值 | 可选值 |-| --- | --- | --- |-| 等待批准时保持防睡眠 | 关闭 | 开启或关闭 |-| 保持屏幕常亮 | 关闭 | 开启或关闭 |-| 最长防睡眠时间 | 12 小时 | 1, 2, 4, 8, 12, 24 小时或无限制 |-| 异常会话保护 | 1 小时 | 30 分钟, 1, 2, 4 小时 |-| 低电量保护 | 关闭 | 关闭或 5%, 10%, 15%, 20%, 25% |--没有内置电池的 Mac 不显示低电量保护。--完整说明见 [防止系统睡眠](sleep-prevention.md)--### 跨设备同步--- 只有 CodexBar Hook 已开启且 iCloud 可用时才能开启-- 首次开启会回填本机保留期内的每日 Hook 聚合-- 设置页显示同步状态和最近成功上传时间-- 关闭后停止网络同步,本机 Hook 数据仍然保留--完整说明见 [数据、同步与隐私](sync-data-privacy.md)--### 重建数据--- 日期选择器只允许选择原始 Hook 数据保留期内的日期-- 有原始事件的日期会显示数据标记-- 选择完整范围后才可执行重建-- 执行前会显示确认提示-- 完成后显示重建天数、事件数和跳过的无效行数-- 未完成的日期会在 Hook 可用时自动重试+自动重置不依赖通知开关。结果提醒可在 [通知选项](notifications.md#自动重置通知) 中配置。该功能的设置只保存在当前 Mac。## 关于页面-| 项目 | 作用 |+| 项目 | 操作或含义 || --- | --- |-| 来源 | 位于 Codex 版本标题右侧,保留自动选项,按检测结果展示已安装的 Codex CLI 或 Codex APP |-| 重新建立连接 | 点击来源选择器右侧的连接图标,按所选来源和磁盘上已安装的版本建立新连接 |-| Codex CLI | 展示全局 Codex CLI 的磁盘版本和路径 |-| Codex APP | 展示 ChatGPT App 或 Codex App 内置 CLI 的磁盘版本和路径 |-| 当前使用 | 标记当前 app-server 实际使用的 Codex 来源和运行版本 |-| 不可用 | 当前、已选或刷新失败的来源已无法检测到时,在原状态标签位置以橙色显示 |-| CodexBar 版本 | 展示当前版本、更新状态和可用更新 |-| GitHub 项目 | 打开 CodexBar 项目页面 |-| 检查更新 | 手动触发 Sparkle 更新检查 |-| 退出 CodexBar | 先完成必要清理再退出 App |--磁盘中的 Codex 已更新但当前 app-server 还没有重连时,关于页面会同时提示新安装版本。--更新提示与最低版本检查共用语义版本解析规则:同一版本的正式版高于预发布版,构建标记不影响版本优先级,无法识别的版本不显示更新提示。--来源默认为自动,优先使用 CLI,未安装 CLI 时使用 App 内置 Codex。来源选项只展示检测到的安装来源。版本行通常只展示已安装来源;当前、已选或刷新失败的来源被卸载后,保留该行并以“不可用”替换“当前使用”,不再在底部重复显示来源不可用提示。此标记表示无法从该来源建立新连接,不代表旧连接已经停止。切换来源后立即建立新连接,成功后保存选择,失败时保留原连接和原选择。之前手动指定的来源被卸载后,选择器显示“选择来源”,不会自动改用其他来源。--自动重连仍然保留:连接使用满 1 小时后,在下一次请求时按所选来源重建。也可以点击“重新建立连接”提前使用更新后的版本。旧版 CodexBar 会忽略来源选择,沿用原有自动规则。--悬停连接图标可查看“重新建立连接”提示,重连时显示“正在重新连接”。重连及后续刷新期间,图标持续播放动画,来源选择器和重连按钮暂时不可操作。成功后更新“当前使用”标记,来源缺失时显示“不可用”,其他失败在版本区域底部显示原因。--点击可执行文件路径可以复制完整路径。--返回 [用户手册](README.md)+| 来源 | 自动优先选择 Codex CLI,找不到时使用 ChatGPT App 或 Codex App 内置的 Codex,也可手动选择 |+| 重新建立连接 | 使用所选 Codex 来源重新连接,更新 Codex 后可用它立即切换到新版本 |+| Codex CLI / Codex APP | 查看检测到的版本,点击路径可复制 |+| 当前使用 | 当前连接所用的来源和版本 |+| 不可用 | 之前使用或选择的来源已无法找到 |+| CodexBar 版本 / 检查更新 | 查看版本并检查可用更新 |+| GitHub 项目 | 打开项目页面 |+| 退出 CodexBar | 退出 App |++连接期间暂时不能切换来源。连接失败原因显示在版本区域底部,可据此排查或重新选择来源。++返回 [用户指南](README.md)diff --git a/Docs/UserGuide/sleep-prevention.md b/Docs/UserGuide/sleep-prevention.mdindex 5ad92f0..54fdd9d 100644--- a/Docs/UserGuide/sleep-prevention.md+++ b/Docs/UserGuide/sleep-prevention.md@@ -2,127 +2,62 @@简体中文 | [English](../en/UserGuide/sleep-prevention.md)-## 功能目标+CodexBar 可以在任务运行时保持 Mac 唤醒,任务结束或保护条件触发后恢复睡眠。-macOS 进入系统睡眠后,正在本机运行的 Codex 任务可能被挂起。+## 开启与生效条件-CodexBar 会根据实时任务状态自动管理系统睡眠,让长任务在无人操作时继续运行,并在任务结束或保护条件触发后恢复系统原有行为。+1. 在 `设置 > 高级` 开启 CodexBar Hook+2. 开启 `防止系统睡眠` 并确认+3. 如需后台授权,点击 `打开系统设置` 并允许 CodexBar 后台运行-这个功能不是永久保持唤醒的通用开关。+防睡眠需要 CodexBar 正在运行、Hook 和后台服务可用,并有符合条件的任务。低电量或时长上限触发时会停止,条件恢复后按任务状态重新生效。主面板的咖啡杯表示当前防睡眠已生效。-开启设置只表示允许 CodexBar 自动管理睡眠,没有符合条件的任务时不会修改系统睡眠。--## 生效条件--以下条件同时满足时,CodexBar 才会实际阻止系统睡眠:--1. CodexBar 正在运行且没有进入退出流程-2. `防止系统睡眠` 主开关已打开-3. CodexBar Hook 已安装并通过最近一次明确校验-4. 至少有一个非匿名运行中任务,或已开启 `等待批准时保持防睡眠` 且存在非匿名等待任务-5. CodexBarHelper 已注册并获得系统批准-6. CodexBarHelper 当前不在更新过程中-7. 低电量保护当前没有生效-8. 本轮实际防睡眠时间没有达到上限--任一条件不满足时,CodexBar 会停止自己的防睡眠状态。--条件恢复后,仍有符合条件任务时会自动重新生效。--匿名任务即使显示为运行中或等待批准,也不会计入防睡眠的有效任务。+匿名任务和被异常会话保护隐藏的任务不参与防睡眠。## 设置选项+点击防睡眠行右侧的选项按钮调整:+| 选项 | 作用 | 默认值 | 可选值 || --- | --- | --- | --- |-| 等待批准时保持防睡眠 | 等待用户批准的任务也参与防睡眠 | 关闭 | 开启或关闭 |-| 保持屏幕常亮 | 同时阻止显示器睡眠、屏保和闲置锁屏 | 关闭 | 开启或关闭 |-| 最长防睡眠时间 | 限制一轮实际防睡眠的累计时长 | 12 小时 | 1, 2, 4, 8, 12, 24 小时或无限制 |-| 异常会话保护 | 长时间无进展时隐藏任务并停止其防睡眠贡献 | 1 小时 | 30 分钟, 1, 2, 4 小时 |-| 低电量保护 | 使用电池且电量过低时恢复系统睡眠 | 关闭 | 关闭或 5%, 10%, 15%, 20%, 25% |+| 等待批准时保持防睡眠 | 等待你批准时继续保持唤醒 | 关闭 | 开启或关闭 |+| 保持屏幕常亮 | 阻止显示器睡眠、屏保和闲置锁屏 | 关闭 | 开启或关闭 |+| 最长防睡眠时间 | 限制一轮累计防睡眠时长 | 12 小时 | 1, 2, 4, 8, 12, 24 小时或无限制 |+| 异常会话保护 | 隐藏长时间没有进展的运行任务 | 1 小时 | 30 分钟, 1, 2, 4 小时 |+| 低电量保护 | 电池供电且电量过低时恢复睡眠 | 关闭 | 关闭或 5%, 10%, 15%, 20%, 25% |没有内置电池的 Mac 不显示低电量保护。-## 等待批准时保持防睡眠--关闭时,任务从运行中进入等待批准后不再支撑防睡眠。+## 等待批准与屏幕常亮-开启时,等待批准期间继续防止系统睡眠。+默认只在任务运行期间防睡眠。开启等待批准选项后,无人处理批准请求时也会保持唤醒,直到达到时长上限或任务状态变化。-等待批准没有自然超时,无人值守时可能长时间保持唤醒,最长防睡眠时间仍然有效。--异常会话保护只判断运行中任务,不判断等待批准任务。--## 保持屏幕常亮--这个选项只在系统睡眠已经被 CodexBar 阻止时生效。--CodexBar 会同时阻止显示器睡眠,并定期声明用户活动以压住屏保和闲置锁屏。--任务结束、低电量保护生效、达到时长上限或防睡眠失败时会同步释放。--开启后可能让你离开电脑时仍保持解锁界面,因此默认关闭。+保持屏幕常亮只在防睡眠生效时工作,可能让离开电脑后的界面仍保持解锁状态。## 最长防睡眠时间-- 只累计真正阻止系统睡眠的时间-- 因低电量、CodexBarHelper 不可用或其他条件暂停的时间不计入上限-- 系统睡眠期间和系统时间调整不消耗上限-- 没有活跃任务时会重置计时-- 新运行任务出现或等待任务恢复运行时会开始新一轮计时-- 达到上限后恢复系统睡眠,直到下一轮任务开始+只累计实际防睡眠时间,暂停和系统睡眠期间不计时。新运行任务出现或等待任务恢复运行时会开始新一轮计时;没有活跃任务时重置。达到上限后恢复睡眠,等待下一轮任务。## 异常会话保护-异常会话保护用于处理任务已经没有真实进展,但缺少可靠终态而仍显示为运行中的情况:+运行任务超过所选时间没有进展时,会从活动卡片和任务中心隐藏,并停止支撑防睡眠。恢复进展后自动重新显示;调长阈值时,未超过新阈值的任务也会恢复。-- 跟随防睡眠主开关,没有独立开关-- 只判断非匿名运行中任务-- 最近进展来自 Hook 事件、子 Agent 事件和本机会话生命周期-- 达到阈值后保存保护记录,尝试通知并隐藏任务-- 被隐藏任务不显示在活动卡片和任务中心,也不参与防睡眠-- 后续出现新进展时自动恢复任务并撤回有效通知-- 修改为更长阈值后,未超过新阈值的隐藏任务会恢复-- Hook 历史回放、系统睡眠、唤醒对账和 Hook 数据源不可用期间暂停判断-- 保护记录最长保留到最后进展后的 24 小时+保护跟随防睡眠主开关,仅判断非匿名运行任务,不判断等待批准任务。启动恢复、系统睡眠和任务数据暂时不可用期间暂停判断。-保护记录只包含哈希任务标识和时间戳,不包含原始 `session`、`turn`、项目名或任务内容。+系统通知开启且获得授权时会尝试提醒,通知失败不影响保护生效。## 低电量保护-- 只在 Mac 使用电池供电时生效-- 电量首次小于或等于所选阈值时恢复系统睡眠-- 电量需要回升到阈值加 5 个百分点才解除保护-- 接通电源会立即解除当前低电量阻断-- 仍有任务时会自动恢复防睡眠-- 只有 CodexBar 确实停止自己的防睡眠状态后才发送低电量通知--5 个百分点的恢复差值用于避免电量在阈值附近反复切换。--## CodexBarHelper 授权+使用电池时,电量降到阈值或以下即停止防睡眠。回升到阈值加 5 个百分点,或接通电源后解除;仍有任务时自动恢复防睡眠。-防睡眠需要随 App 安装的 CodexBarHelper 修改系统级睡眠状态。自动重置也复用同一个后台服务注册和批准状态,用于设置固定的系统唤醒计划:+例如阈值为 10% 时,电量降到 10% 会停止,回升到 15% 才恢复。-- 每次从关闭切换为开启时显示 `开启防止系统睡眠?` 确认框-- CodexBarHelper 未注册或文件缺失时,确认框显示 `需要安装并授权 CodexBar Helper 后台运行`-- CodexBarHelper 已安装但等待系统批准时,确认框显示 `已安装 CodexBar Helper 但需要授权允许后台运行`-- CodexBarHelper 已获得系统批准时,确认框只显示 `开启后, CodexBar 会在 Codex 任务运行时防止系统睡眠, 任务结束后自动恢复`-- 选择 `开启` 后保存主开关并尝试注册后台服务,选择 `取消` 时保持关闭-- 系统要求批准后台项目时,已开启的设置行会显示 `打开系统设置`;点击该按钮进入 macOS 的“登录项与扩展”-- 主开关关闭时不显示状态说明;主开关与 Hook 可用时由当前阻断原因决定是否显示防睡眠子选项入口-- CodexBarHelper 缺失或注册失败时不会执行防睡眠-- App 更新导致 CodexBarHelper 变化时会刷新注册并校验睡眠状态-- App 正常退出前会先取消自动重置唤醒计划、释放 CodexBarHelper 租约并恢复由 CodexBar 修改的状态-- CodexBarHelper 连接意外中断后会在宽限期结束时释放失联客户端租约-- 自动重置使用独立连接;连接中断时会立即取消该连接拥有的唤醒计划+## 后台服务与其他 App-## 与其他防睡眠来源共存+CodexBarHelper 是随 App 安装的后台服务,负责系统睡眠控制。未获批准或服务异常时,设置页会提示处理方式,参见 [常见问题与排查](troubleshooting.md#codexbarhelper-无法注册)-如果任务开始前系统睡眠已经被其他 App 或用户关闭,CodexBar 会把来源标记为外部:+如果其他 App 已经关闭系统睡眠,设置页会显示外部来源,CodexBar 结束任务时会保留该设置。外部来源停止后,仍有任务时 CodexBar 会按需接管。-- CodexBar 不会把外部设置据为己有-- 任务结束时不会恢复或覆盖外部设置-- 外部设置恢复后任务仍在运行时,CodexBar 会重新检查并按需接管-- 主面板仍显示咖啡杯,设置页会说明系统睡眠由其他来源关闭+正常退出前,CodexBar 会恢复自己管理的睡眠状态并取消自动重置唤醒计划。退出未完成时,请查看设置页的后台服务错误。-返回 [用户手册](README.md)+返回 [用户指南](README.md)diff --git a/Docs/UserGuide/sync-data-privacy.md b/Docs/UserGuide/sync-data-privacy.mdindex 766b0e8..3f98b48 100644--- a/Docs/UserGuide/sync-data-privacy.md+++ b/Docs/UserGuide/sync-data-privacy.md@@ -2,136 +2,65 @@简体中文 | [English](../en/UserGuide/sync-data-privacy.md)-## 跨设备同步的内容+## 跨设备同步-跨设备同步用于合并多台 Mac 的每日 Hook 聚合,不同步账户、额度、Token 用量、留存重置或自动重置设置。+在 `设置 > 高级` 开启 `跨设备同步`,可以合并同一 iCloud 账户下多台 Mac 的每日 Hook 统计。需要先开启 CodexBar Hook,并登录可用的 iCloud 账户。-启用条件如下:--- CodexBar Hook 已开启-- 当前 iCloud 账户可用-- 用户主动打开 `跨设备同步`--开启后,CodexBar 会回填本机保留期内的每日 Hook 聚合,并在后续统计维护时上传变化的日期。--每台设备的同日数据独立保存,展示时会合并不同设备的贡献,同时避免重复叠加当前设备的本地副本和云端副本。--同步使用 `iCloud.app.zabrian.codexbar` 容器的 CloudKit private database。--## 同步状态--主面板底部和设置页会显示以下状态:+首次开启会上传本机保留期内的统计,之后自动同步变化。关闭同步会保留本机数据。| 状态 | 含义 || --- | --- |-| 同步未开启 | 用户没有开启同步或 CodexBar Hook 已关闭 |-| 正在同步 | 正在读取或写入 CloudKit |+| 同步未开启 | 同步开关或 CodexBar Hook 已关闭 |+| 正在同步 | 正在传输数据 || 已同步 | 最近一轮同步成功 |-| 同步失败 | 网络、iCloud 账户或服务暂时不可用 |--设置页还会显示最近一次成功上传时间。--## 重建数据--`设置 > 高级 > 重建数据` 用于从本机原始 Hook 事件重新生成所选日期的每日聚合。--适合以下场景:--- 旧聚合缺少新版本新增的统计字段-- 某些日期统计异常-- 本机原始事件发生过替换或截断-- 需要用本机结果替换当前设备同日的云端贡献--重建流程如下:--1. 日期选择器只允许选择原始 Hook 数据保留期内的日期-2. 有原始数据的日期会显示标记-3. 确认后重新解析所选日期的本机 JSONL-4. 无法解析的行会跳过并计入结果-5. 开启同步时,重建日期会在后续同步中替换当前设备对应日期的云端贡献+| 同步失败 | 网络、iCloud 账户或服务暂时不可用,稍后重试 |-重建不会修改 Codex 账户、额度或 Token 用量。+主面板底部和设置页显示同步状态,设置页还显示最近成功上传时间。-## 本机保存的数据+## 哪些数据会上传-| 数据 | 内容 | 位置或生命周期 |-| --- | --- | --- |-| Hook 原始事件 | 选定的结构化事件字段 | `~/Library/Application Support/CodexBar/HookEvents/events`,保留 210 天 |-| Hook 每日聚合 | 事件计数、会话与轮次、项目名计数和模型计数 | `~/Library/Application Support/CodexBar/HookEvents/daily.jsonl`,保留 210 天 |-| Hook 维护状态 | 文件 `offset`、`generation` 和待处理日期 | `~/Library/Application Support/CodexBar/HookEvents/maintenance.json` |-| 同步缓存 | CloudKit 缓存、游标和上传状态 | `~/Library/Application Support/CodexBar/HookEvents/Sync` |-| 异常会话保护 | 哈希任务标识和时间戳 | `~/Library/Application Support/CodexBar/ActivityProtection/state.json`,最长 24 小时 |-| CodexBarHelper 所有权 | 睡眠所有权状态和恢复事务 | `/Library/Application Support/CodexBar/helper-state.json` |-| 自动重置唤醒计划 | CodexBar 固定 owner、`wake` 类型和下一次时间 | macOS 系统电源管理,触发或取消后移除 |-| App 偏好 | 开关、阈值、快捷键、自动重置提前量和通知去重状态 | macOS UserDefaults |-| app-server 交互日志 | 最近 500 条请求和响应 | 只存在当前 App 进程内存 |+同步数据保存在你的 iCloud 私有数据库中,包括日期、每日事件和会话统计、项目显示名、模型名,以及用于区分设备和避免重复计数的标识。-每日聚合只在最近 3 天保留 session 和 turn ID 列表,更早日期转换为计数并删除列表。+以下内容不参与同步:-CodexBarHelper 所有权文件由 root 持有,用于 App 或 CodexBarHelper 异常退出后的睡眠状态恢复。+- 原始 Hook 事件、会话和任务标识、完整工作目录+- 提问、Codex 回复、工具参数和输出+- Codex 账户、额度、Token 用量和留存重置+- App 设置、代理配置和密码+- 日志、实时任务状态和异常会话保护记录-自动重置唤醒计划不包含账户、留存重置、`creditId` 或幂等键。CodexBarHelper 启动时会清理同一构建身份遗留的计划,App 也会在任务变化、功能关闭和正常退出时取消计划。+**项目显示名会上传** 如果项目名包含不希望存入 iCloud 的信息,请关闭跨设备同步。-匿名任务不参与异常会话保护,因此不会生成哈希任务标识或写入保护状态文件。+## 本机数据-## CloudKit 上传字段--每条每日聚合记录可能包含以下内容:--- iCloud 账户范围内的设备伪标识-- 日期-- 本机 Hook 数据来源 `generation`-- 各类 Hook 事件计数-- 会话数和对话轮次数-- 项目显示名计数-- 模型名计数-- 更新时间--设备伪标识由设备 UUID 和 iCloud private database 中的随机 salt 计算,不直接上传原始设备 UUID。--## CloudKit 不上传的内容--- 原始 Hook 事件文件-- session ID、turn ID 和 agent ID-- 完整工作目录路径-- prompt、Codex 回复、工具参数或工具输出-- Codex 账户、额度和 Token 用量-- 留存重置明细、自动重置设置和消费状态-- app-server 交互日志-- 异常会话保护记录-- Codex 认证 token--项目显示名和模型名属于同步内容,如果项目名本身包含敏感信息,不应开启跨设备同步。--## 数据读取边界--CodexBar 会读取以下本机数据:--- 通过本机 app-server 获取账户、额度、Token 用量、留存重置明细和 Codex 配置-- 读取 Hook 原始事件以生成统计和实时任务-- 读取 Hook model 字段和本机 Codex rollout 的首条来源及生命周期字段,以排除 Auto-review 实时任务、区分完成与终止并补充进展时间--来源判定优先使用 rollout 元数据;rollout 来源为 `unknown` 时,只有精确匹配 `codex-auto-review` 的 Hook model 才归类为 `autoReview`。rollout 来源读取最多 256 KiB,只保存 `main`, `autoReview`, `auxiliary` 或 `unknown` 四种归一化结果。CodexBar 不保存 rollout 路径或原始来源值;其他 rollout 读取也只提取生命周期、时间和推理强度等字段,不展示或保存会话正文和工具内容。+| 数据 | 内容与保留方式 |+| --- | --- |+| Hook 记录与每日统计 | 时间、事件、模型、工具、项目和任务标识等,保留 210 天;每日统计中的会话和轮次明细仅保留最近 3 天 |+| 异常会话保护 | 无法直接还原的任务标识和时间,最长保留到最后进展后的 24 小时 |+| App 设置 | 保存在当前 Mac,包括代理配置;代理密码以明文保存 |+| 交互日志 | 最近 500 条 Codex 请求和响应,只在本次运行期间保留 |+| 后台服务状态 | 用于恢复睡眠设置和清理自动重置唤醒计划 |-用户主动开启自动重置后,CodexBar 通过同一个本机 app-server 使用明确列出的临期留存重置。原始 `creditId` 和幂等键不写入磁盘或 CloudKit;`UserDefaults` 只保存功能开关、提前量、自动重置通知开关、音效选择和哈希后的通知去重键。+CodexBar 读取本机 Codex 的任务状态和活动记录,但不保存提问、回复或工具内容,也不复制 Codex 登录凭据。-CodexBar 不复制或持久化 Codex 认证 token。+关闭代理会保留配置和密码;保存关闭身份验证的配置或选择 `删除配置` 时会删除密码。-## 网络行为+## 重建数据-| 网络访问 | 目的 | 触发条件 |-| --- | --- | --- |-| Sparkle 更新源 | 检查并安装 CodexBar 更新 | 自动检查开启或用户手动检查时 |-| CloudKit private database | 同步多设备每日 Hook 聚合 | 用户开启跨设备同步时 |+统计异常时,可在 `设置 > 高级 > 重建数据` 选择日期范围并确认。可选范围为最近 210 天,有本机记录的日期会显示标记。-账户、额度、Token 用量、留存重置明细和用户开启的自动重置操作通过本机 app-server 的 stdio 通信完成。自动重置不会增加 CloudKit 请求;自动重置只向 CodexBarHelper 提交固定系统唤醒计划的时间,不提交账户或留存重置数据。+重建使用保留的本机记录重新计算 Hook 统计,完成后显示处理结果。开启同步时,重建结果会替换当前设备对应日期的云端统计,其他设备的贡献保留。账户、额度和 Token 用量不受影响。-## 日志隐私+## 网络与日志-系统日志只记录操作结果、状态分类、计数和错误阶段。+| 网络访问 | 用途 |+| --- | --- |+| Codex 服务 | 获取账户、额度和用量,执行自动重置 |+| 更新服务 | 检查并下载 CodexBar 更新 |+| iCloud | 开启同步后传输每日 Hook 统计 |-系统日志不应记录账户额度数值、Token 用量、项目名、任务内容、session ID、turn ID 或 OAuth token。+代理只用于 CodexBar 的 Codex 服务连接,不影响更新、iCloud 或其他 App。-App 内 app-server 交互日志可能包含请求和响应内容,但只存在当前进程内存,只有用户主动打开日志窗口时才显示。+交互日志可能包含账户和请求响应内容,退出 App 后清除。分享日志前,请检查其中是否有不希望公开的信息。-返回 [用户手册](README.md)+返回 [用户指南](README.md)diff --git a/Docs/UserGuide/troubleshooting.md b/Docs/UserGuide/troubleshooting.mdindex 9dc55e5..d7640bc 100644--- a/Docs/UserGuide/troubleshooting.md+++ b/Docs/UserGuide/troubleshooting.md@@ -20,38 +20,36 @@## 主面板显示初始化失败-常见原因如下:+到 `设置 > 关于` 查看连接错误,确认 Codex 已安装、路径可用,并检查代理配置。修正后点击 `重新建立连接`;持续失败时打开日志查看详情。-- 没有找到可执行的 Codex-- Codex app-server 启动失败-- app-server 没有在超时时间内响应-- app-server 返回了无法解析的响应+## 代理配置或连接失败-打开日志窗口查看最近失败的请求和错误详情,再到关于页面确认 Codex 路径和版本。+在 `设置 > 高级 > 代理` 中打开配置,使用 `测试连接` 检查。服务器地址和端口必填,开启身份验证后用户名必填;输入问题会标红并显示简短原因。++- 关于页面提示服务器或用户名无效时,修正后保存,或关闭代理开关+- 配置无法读取时,在配置窗口右上角 `⋯ > 删除配置` 删除损坏数据+- 地址和端口格式正确但代理不可达时,开关仍可保存为开启;使用测试连接检查网络+- 选择 HTTPS 时,代理端口本身必须支持 TLS,并提供有效证书## 额度或 Token 显示变淡变淡表示本轮读取失败后回退到了同一账户的缓存数据。-缓存用于保留上次可用信息,不代表数据已经成功刷新。--双击账户图标重试,如果持续变淡则查看日志窗口中的 `account/rateLimits/read` 和 `account/usage/read`+双击账户图标重试;持续变淡时,在关于页面查看连接错误或打开日志。## Hook 无法开启或校验失败-| 提示 | 含义 | 建议处理 |-| --- | --- | --- |-| 需要更高 Codex 版本 | 当前 app-server 版本不足 | 更新 Codex 后在关于页面点击“重新建立连接” |-| Codex Hook 已全局关闭 | `features.hooks` 已禁用 | 在 Codex 配置中重新启用 Hooks |-| CodexBar Hook 已不完整 | 至少一个必要事件缺少当前 handler | 重新打开设置触发自动补齐,仍未恢复时关闭后重新开启 Hook |-| CodexBar Hook 未被信任 | Codex 仍把 handler 判定为未信任或已修改 | 重新开启 Hook 并检查 Codex 配置 |-| CodexBar Hook 意外来源 | app-server 返回的来源不是当前配置文件 | 检查 `CODEX_HOME` 和当前 Codex 来源 |-| `hooks.json` 文件格式错误 | 顶层或 `hooks` 结构不是有效 JSON | 修复 JSON 后重新操作 |-| 无法验证 Codex Hook | app-server 暂时不可用或校验失败 | 查看日志并在 Codex 可用后重新打开设置 |--Hook 配置位于 `$CODEX_HOME/hooks.json`,未设置 `CODEX_HOME` 时位于 `~/.codex/hooks.json`+| 提示 | 处理方法 |+| --- | --- |+| 需要更高 Codex 版本 | 更新 Codex 后在关于页面点击 `重新建立连接` |+| Codex Hook 已全局关闭 | 在 Codex 配置中重新开启 `features.hooks` |+| CodexBar Hook 已不完整 | 重新打开设置等待自动修复,仍未恢复时关闭后重新开启 Hook |+| CodexBar Hook 未被信任 | 重新开启 Hook,并检查 Codex 的信任提示 |+| CodexBar Hook 意外来源 | 确认当前 Codex 来源和 `CODEX_HOME` 指向预期位置 |+| `hooks.json` 文件格式错误 | 修复该文件的 JSON 格式后重试 |+| 无法验证 Codex Hook | 等 Codex 连接恢复后重新打开设置 |-CodexBar 会在启动、打开菜单和每轮额度刷新完成后自动补齐已开启 Hook 所缺少的必要事件与信任数据。如果临时错误阻止了自动补齐,关闭并重新开启 Hook 仍会重建完整配置。+默认配置文件位于 `~/.codex/hooks.json`;设置过 `CODEX_HOME` 时,位于该目录下的 `hooks.json`## 实时任务没有出现@@ -60,7 +58,7 @@ CodexBar 会在启动、打开菜单和每轮额度刷新完成后自动补齐3. 新建一轮 Codex 任务以产生实时事件4. 打开设置窗口触发一次 Hook 重新校验-历史回放期间不会发送旧任务通知,数据源边界不稳定时会降级并跳过不可信历史。+重新启动 CodexBar 不会补发旧任务通知。## 收不到系统通知@@ -105,17 +103,11 @@ CodexBar 会在启动、打开菜单和每轮额度刷新完成后自动补齐1. `自动重置` 是否开启,提前量是否符合预期2. 自动重置设置行是否提示 CodexBarHelper 待批准、未注册或唤醒计划失败;临期选项按钮只在 Helper 已获得系统批准时显示-3. 当前 app-server 是否返回了具体的可用留存重置和过期时间+3. 主面板是否显示可用留存重置及其过期时间4. 计划时间到达后,网络与 Codex 登录状态是否可用5. “自动重置通知”是否开启;通知关闭不会阻止自动重置本身执行-自动重置只处理 app-server 最新响应明确列出的凭证。单轮网络或暂时服务故障最多连续重试 5 分钟,后续普通额度刷新仍会为仍然有效的凭证重新安排。--关闭自动重置或退出 CodexBar 会取消当前唤醒计划。需要核对系统计划时,可在 Terminal 中执行:--```bash-pmset -g sched-```+暂时故障每轮最多连续重试 5 分钟,后续刷新仍可再次尝试。关闭自动重置或退出 CodexBar 会取消唤醒计划。## 跨设备同步不可用@@ -129,9 +121,7 @@ pmset -g sched## 更新 Codex 后仍显示旧版本-当前版本来自已经运行的 app-server 握手,磁盘版本来自重新执行 Codex `--version`--如果关于页面显示新安装版本但 `当前使用` 仍是旧版本,点击“重新建立连接”。也可以等待当前连接满 1 小时后的下一次请求自动重建。+在关于页面点击 `重新建立连接`,让 CodexBar 使用更新后的 Codex。## 使用日志窗口@@ -140,22 +130,14 @@ pmset -g sched- 右键菜单栏图标并选择 `日志`- 主面板打开时按 `⌘L`-日志窗口保留当前进程最近 500 条 app-server 请求。+日志窗口保留本次运行期间最近 500 条 Codex 交互记录。每条记录包含请求时间、方法、状态和响应时间,展开后可以查看请求、响应或错误预览。完整内容可以在独立窗口中查看或复制,清空或退出 App 后不会恢复。-## 查看系统日志--在 Terminal 中执行以下命令:--```bash-/usr/bin/log stream --predicate 'subsystem == "app.zabrian.codexbar"' --style compact-```--Debug 版本的 `subsystem` 使用 `.debug` 后缀。+## 反馈问题-提交问题时请描述复现步骤和可见错误,分享日志前先检查 App 内交互日志是否包含不希望公开的请求内容。+提交问题时说明复现步骤、CodexBar 与 Codex 版本、可见错误。交互日志可能包含账户和请求内容,分享前请检查隐私信息。-返回 [用户手册](README.md)+返回 [用户指南](README.md)diff --git a/Docs/en/DeveloperGuide/README.md b/Docs/en/DeveloperGuide/README.mdindex de95a17..d72bab1 100644--- a/Docs/en/DeveloperGuide/README.md+++ b/Docs/en/DeveloperGuide/README.md@@ -2,56 +2,13 @@[简体中文](../../DeveloperGuide/README.md) | English-This guide is for developers who want to understand CodexBar's architecture, debug its data flows, or contribute to the project.--It describes not only what each module does, but also why responsibilities are divided this way, which failure paths are intentionally conservative, and which invariants must survive implementation changes.--For product features and instructions, see the [User Guide](../UserGuide/README.md).--## Goals--The Developer Guide should help readers with four kinds of work:--- Build a system model: understand where data originates, where it becomes state, and which component ultimately consumes it-- Find the right place to make a change: identify the sole owner of a behavior and the boundary of its side effects-- Understand design tradeoffs: avoid simplifying away seemingly redundant generations, stale markers, or recovery steps-- Validate changes: derive acceptance coverage from invariants and failure scenarios--Each topic follows roughly the same structure:--```text-Goals and constraints- -> Data or control flow- -> State ownership- -> Key design rationale- -> Failure and recovery- -> Change guide- -> Validation scenarios-```--## Reading Order--If you are new to the project, read these topics in order:--1. [Architecture](architecture.md)-2. [Design Principles and Key Decisions](design-decisions.md)-3. [app-server Data Flow](app-server.md)-4. [Hook Capture and Historical Aggregation](hook-and-aggregation.md)-5. [Live Task Monitoring](activity-monitor.md)-6. [Sleep Prevention System](sleep-prevention.md)-7. [CloudKit Sync](sync.md)-8. [Notification System](notifications.md)-9. [UI and App Lifecycle](ui-and-lifecycle.md)-10. [Data and Privacy Boundaries](data-and-privacy.md)-11. [Development and Validation](development.md)-## Find by Responsibility| Document | Contents || --- | --- || [Architecture](architecture.md) | Processes, modules, lifecycle, actor boundaries, and the three data flows |-| [Design Principles and Key Decisions](design-decisions.md) | Cross-module rationale, system invariants, failure priorities, and subtle implementation details |-| [app-server Data Flow](app-server.md) | CLI discovery, JSON-RPC sessions, account data, rate limits, usage refresh, and the Automatic Reset state machine |+| [Design Principles and Key Decisions](design-decisions.md) | State ownership, concurrent commits, data recovery, and privilege boundaries |+| [app-server Data Flow](app-server.md) | CLI discovery, proxy configuration and tests, JSON-RPC sessions, account data, rate limits, usage refresh, and Automatic Reset || [Hook Capture and Historical Aggregation](hook-and-aggregation.md) | Hook installation, event persistence, aggregation, retention, and schema evolution || [Live Task Monitoring](activity-monitor.md) | Incremental reading, rollout reconciliation, task state machine, and Stalled Task Protection || [Sleep Prevention System](sleep-prevention.md) | IOKit assertions, CodexBarHelper, XPC leases, Automatic Reset wake schedules, and recovery |@@ -61,32 +18,6 @@ If you are new to the project, read these topics in order:| [Data and Privacy Boundaries](data-and-privacy.md) | Local files, network access, cloud fields, and logging boundaries || [Development and Validation](development.md) | Project structure, build checks, debugging, and change acceptance |-## Find by Change--| Change | Read first | Also review |-| --- | --- | --- |-| Add an account or usage field | [app-server Data Flow](app-server.md) | [Data and Privacy Boundaries](data-and-privacy.md) |-| Add a Hook event or historical metric | [Hook Capture and Historical Aggregation](hook-and-aggregation.md) | [CloudKit Sync](sync.md) |-| Change task states or terminal-state detection | [Live Task Monitoring](activity-monitor.md) | [Notification System](notifications.md), [Sleep Prevention System](sleep-prevention.md) |-| Change a menu, window, or shortcut | [UI and App Lifecycle](ui-and-lifecycle.md) | [Development and Validation](development.md) |-| Change notification triggers or deduplication | [Notification System](notifications.md) | The guide for the corresponding data source |-| Change sleep-prevention policy or the helper | [Sleep Prevention System](sleep-prevention.md) | [Data and Privacy Boundaries](data-and-privacy.md) |-| Change Automatic Reset scheduling or wake plans | [app-server Data Flow](app-server.md) | [Sleep Prevention System](sleep-prevention.md), [Data and Privacy Boundaries](data-and-privacy.md) |-| Change sync fields or merge rules | [CloudKit Sync](sync.md) | [Hook Capture and Historical Aggregation](hook-and-aggregation.md) |-| Change persistence formats or defaults | [Development and Validation](development.md) | [Design Principles and Key Decisions](design-decisions.md) |--## Core Design Constraints--- Startup must handle `--hook-event` mode first; that mode must not initialize the UI-- app-server rate limits and usage, historical Hook aggregation, and live task monitoring are three independent data flows-- `CodexActivityMonitor` is the sole source of task state-- UI, controllers, view models, and settings run on `MainActor` by default-- Blocking I/O and shared mutable state must stay off the main actor-- CodexBarHelper is limited to fixed sleep controls and Automatic Reset wake schedules; it must not gain network access, arbitrary command execution, or additional file access-- Hook configuration changes must preserve handlers installed by the user and other applications-- Changes to aggregation semantics must increment the aggregation schema and fully rebuild from raw events-- A missing Hook count means the historical source is unavailable; it must not be interpreted as an explicit `0`-## Core Terminology| Term | Precise meaning in this project |@@ -98,26 +29,9 @@ If you are new to the project, read these topics in order:| unavailable | No trusted source is currently available; this is not equivalent to empty or `0` || generation | The generation of a data source or asynchronous operation, used to reject late results || source generation | The source identity of a day's raw Hook file; distinct from a code schema |-| owned | CodexBar changed the system state and is entitled to restore it |+| owned | CodexBar has persisted responsibility for restoring system sleep || external | A source outside CodexBar had already set the system state |-## How to Read the Source--Identify the state owner first, then read backward from its consumers.--For example, when changing approval-waiting behavior, use this order:--```text-CodexActivityTask- -> CodexActivityMonitor- -> CodexActivitySnapshot / transition- -> CodexNotificationService- -> KeepAliveController- -> SwiftUI View-```--Starting from a view usually reveals only the final display condition and makes it easy to miss bootstrap, deduplication, and recovery semantics.-## Main Entry Points- App startup: [`CodexBarApp.swift`](../../../CodexBar/App/CodexBarApp.swift)diff --git a/Docs/en/DeveloperGuide/activity-monitor.md b/Docs/en/DeveloperGuide/activity-monitor.mdindex c0fb012..22ac0c2 100644--- a/Docs/en/DeveloperGuide/activity-monitor.md+++ b/Docs/en/DeveloperGuide/activity-monitor.md@@ -2,19 +2,6 @@[简体中文](../../DeveloperGuide/activity-monitor.md) | English-## Design Motivation--A live task is not a direct mapping of Hook events.--One turn may have missing, late, or duplicate events; only a session ID; a new prompt replacing an old turn; `Stop` and rollout terminal arriving in either order; or an app launch after the task has already run for some time.--`CodexActivityMonitor` combines these incomplete observations into a conservative task state machine and produces two different outputs:--- A snapshot describes what can be displayed now-- A transition describes what just happened and may drive a one-time side effect--If every consumer inferred tasks from Hook lists independently, the menu bar, notifications, and sleep prevention would disagree at edge cases.-## GoalsThe live-task flow answers four questions:@@ -27,9 +14,9 @@ The live-task flow answers four questions:Hook events provide low-latency signals, and rollout files provide authoritative lifecycle context. [`CodexActivityMonitor.swift`](../../../CodexBar/Services/Workflow/CodexActivityMonitor.swift) merges both into the sole task snapshot:```text-Hook JSONL -> HookEventTailReader -----+- +-> CodexActivityMonitor -> ActivitySnapshot-rollout JSONL -> SessionLifecycleReader++Hook JSONL -> HookEventTailReader ---------++ +-> CodexActivityMonitor -> CodexActivitySnapshot+rollout JSONL -> CodexSessionLifecycleReader+```### Division Between Sources@@ -45,7 +32,7 @@ rollout JSONL -> SessionLifecycleReader+Hook prioritizes low latency; rollout prioritizes semantic accuracy. They do not simply overwrite by timestamp. Every field has its own trusted source.-### Why Snapshot and Transition Are Separate+### Snapshots and TransitionsA snapshot may be read repeatedly after view reconstruction, a new subscription, or a settings change. A transition may be emitted once from live data only.@@ -86,7 +73,7 @@ At `.bootstrapStart`, the monitor clears previous recovered state and pauses sidNeither UI nor notifications should observe a partially recovered intermediate batch.-### Why Stable Boundaries Retry Three Times+### Stable-Boundary RetriesAt the start of an attempt, the reader fixes inode and size for all relevant date files and validates them again after reading to those bounds:@@ -94,9 +81,9 @@ At the start of an attempt, the reader fixes inode and size for all relevant dat- The current date may append only beyond the fixed upper bound- The calendar day must not cross midnight during the read-If any condition fails, the reader retries from a new baseline. After three consecutive failures it moves to the current tail so bootstrap cannot block forever. Degraded health communicates the cost to Activity Protection instead of pretending success.+If any condition fails, the reader retries from a new baseline. After three consecutive failures, it moves to the current tail and publishes degraded health, pausing Activity Protection checks.-### Why Offset Advances Only Across Complete Lines+### Complete-Line CursorThe Hook recorder may be writing the final line. The reader includes only bytes before the last newline in `completeOffset`.@@ -110,7 +97,7 @@ When `UserPromptSubmit` predates the current incremental window, the reader can### `drainNow()` Read Barrier-`drainNow()` is not an ordinary immediate-refresh hint. Every caller must wait for a read that begins after its request:+Every caller of `drainNow()` must wait for a read that begins after its request:```textCall drainNow@@ -158,7 +145,7 @@ A resume can continue a session created long ago. If the fast path misses, eachIf a file moves to the archive, a missing cached URL clears its cursor and allows full discovery again.-### Why the Rollout Cursor Starts at the Last 512 KB+### Rollout Read BudgetLive tasks need lifecycle near an active turn, not a full read of a long-running session. Starting from the last 512 KB reduces resident I/O and discards the first potentially partial line.@@ -166,7 +153,7 @@ If effort remains missing, a targeted lookup for that turn can read up to 8 MB.Effort backfill applies only to nonterminal tasks that have run for at least 2 seconds and still lack effort, with a 10-second retry interval per turn. This avoids a large search immediately after every task creation.-### Why Only Structural Events Are Parsed+### Rollout FieldsThe shared `CodexRolloutLineEnvelope` extracts only fields needed for turn context, lifecycle, and progress. Prompt, response, and tool content never enters the activity model.@@ -184,7 +171,7 @@ A new prompt replaces the old turn in the same session. The old turn enters termSubagent events update activity under their parent task and do not create separate top-level cards.-### Why Identity Degrades by Precision+### Identity Precision and Fallback`session ID + turn ID` precisely distinguishes sequential turns in one session and is preferred.@@ -207,11 +194,11 @@ When an exact Auto-review event arrives, the monitor:If an explicit `main` or `auxiliary` event later matches the same key, source truth wins and clears that ignored-key inference. An Auto-review event without a turn ID is ignored only for that event and never creates a session-wide blacklist.-Other subagents normalize to `auxiliary` and retain their existing behavior; Memories does not change under this rule. Raw Hook events still enter historical aggregation, so live-task filtering does not change metrics or CloudKit data.+Other subagents, including Memories, are classified as `auxiliary` and participate in auxiliary-task association. Raw Hook events still enter historical aggregation; live Auto-review filtering does not change statistics or CloudKit data.-When JSONL omits `origin` or contains an unrecognized origin value, the origin field first decodes as `unknown`. If that record's model exactly equals `codex-auto-review`, the event model normalizes `origin` to `.autoReview`; other records remain `.unknown`. The monitor replays only the most recent 24 hours, does not scan historical rollouts, and does not rewrite raw Hook records.+A missing or unrecognized JSONL `origin` first decodes as `unknown`. An exact `codex-auto-review` model match normalizes it to `.autoReview`; other records remain `.unknown`. This step uses existing record fields, performs no additional historical rollout scan for origin classification, and does not rewrite raw Hook records.-### Why a New Prompt Does Not Immediately Terminate the Old Turn+### New Prompts and Terminal GraceTurns in one session run sequentially. When a new prompt arrives, the old turn must leave the active list immediately or the UI briefly shows two top-level tasks.@@ -248,19 +235,6 @@ Anonymous running tasks do not show precise elapsed time, and anonymous completiThey publish no waiting or completion transitions to notification consumers, trigger no task haptics, enter neither the running nor waiting sets for KeepAlive, and do not participate in Stalled Task Protection. `activityProtectionIdentifier` returns `nil` for an anonymous key, so protection state never persists an anonymous task.-### Why Anonymous Tasks Still Appear in the UI--A missing session ID does not mean the task does not exist. Dropping it entirely would show Codex working while CodexBar appears idle.--Keeping visibility while forbidding high-impact side effects is a layered response to uncertain identity:--- Later events can correct a visibility error-- A false notification interrupts the user-- Incorrect sleep prevention may last for hours-- Persisting an anonymous project key might suppress a different real task later--The orange dashed-person icon therefore communicates limited capability instead of presenting an anonymous task as precise.-## State MachineActive tasks mainly use these internal states:@@ -294,7 +268,7 @@ Terminal signals reconcile by reliability:| running | Silence exceeds threshold | suppressed | Hide and remove sleep-prevention contribution || suppressed | New progress | running | Clear persisted protection and old notification |-### Why Waiting for Approval Uses Two-Phase Confirmation+### Two-Stage Approval Confirmation`PermissionRequest` indicates an approval flow, but reviewer may be user, policy, or automatic review.@@ -302,13 +276,11 @@ If the Hook event includes reviewer, the task can confirm immediately. If reviewOnly an explicit user reviewer emits a waiting transition. Remaining running while uncertain is more truthful than falsely telling the user Codex is waiting for them.-### Why Effort Can Become `mixed`+### Effort MergingSeveral context events in one turn may report different reasoning efforts. The task does not silently let the last overwrite the first. It marks `mixed` after observing conflict.-This tells the UI that several values genuinely appeared over the task lifecycle rather than displaying a precise-looking value from only the final observation.--### Why Subagent Count Can Be Unknown+### Subagent Count ReliabilityA subagent turn ID belongs to the subagent, so its parent can be associated only by shared session.@@ -334,21 +306,15 @@ The snapshot feeds:- Notification system- Sleep-prevention controller-### Why Recent Completion and Termination Have Different Weight--Completion produces a 30-second green menu bar highlight as short positive feedback. Termination appears only in recent records, emits no completion transition, and has no green state.--Task Center retains terminal items for 10 minutes, while keys preventing duplicate completion from late events remain for 24 hours. Display retention and deduplication retention solve different problems and must not be combined into one cache.--### Why Publish Only When the Snapshot Changes+### Snapshot PublicationThe monitor polls rollout each second and also updates itself at several deadlines. Assigning the same value to `@Published` on every cycle would make SwiftUI and all Combine consumers recalculate unnecessarily.A candidate snapshot is compared with the current value and published only after structural change. Views format elapsed time from the current clock and do not require per-second mutation of task objects.-### Stable Sorting Tie-Breaker+### Stable Ordering-Several tasks in one batch can share timestamps, and Swift sorting is unstable.+Several tasks in one batch can share a timestamp; comparing timestamps alone does not determine their relative order.All lists sort by most recent time first and then display UUID string. Stable order keeps SwiftUI diffing from jumping when equivalent tasks randomly exchange positions.@@ -372,11 +338,11 @@ Stalled Task Protection pauses when the system is about to sleep. Wake follows aIf the new read fails, the reader is replaced, or the source is unavailable, evaluation must not continue from the pre-sleep snapshot.-### Why Silence Timing Pauses During System Sleep+### Evaluation Pauses During System Sleep-Neither Hook nor rollout produces normal progress during system sleep. Comparing wall time alone would classify every running task as stalled immediately after a two-hour sleep.+Silence evaluation stops during system sleep. On recovery, the monitor silently reconciles progress from newly read Hook and rollout data before resuming normal evaluation.-Protection schedules its next check with `SuspendingClock`, but system-time changes and data-source recovery still require explicit recalculation. `will-sleep` enters recovery first; `did-wake` restores evaluation only through a new data read barrier.+The check task waits with `SuspendingClock`, but silence duration is calculated from `Date` and `lastProgressAt` without subtracting time spent asleep. `will-sleep` enters recovery; `did-wake` reevaluates after a new data read barrier.### Why Wake Order Cannot Be Reversed@@ -401,7 +367,7 @@ Threshold options are:At the threshold:-1. Persist a protection record first+1. Update the in-memory protection record and enqueue its serial persistence2. Start notification submission and a 3-second grace period together3. Revalidate the candidate after notification completes or grace expires4. If still valid, hide it from the activity snapshot@@ -417,14 +383,6 @@ Evaluation pauses during:- Hook data-source unavailability- Reader replacement-### Failure Model Addressed by Protection--After Hook or Codex exits abnormally, `Stop`, `SessionEnd`, and rollout terminal may all be missing. A task can remain running indefinitely and keep sleep prevention active forever.--Protection does not decide whether Codex is “truly stuck.” It handles one observable fact: a non-anonymous running task made no Hook or rollout progress beyond the threshold while sources were trusted.--Waiting tasks are excluded because waiting for the user is legitimate silence. Anonymous tasks are excluded because a project key cannot prove which specific task a persisted record belongs to.-### Purpose of Progress GenerationTimestamps alone cannot protect an asynchronous attempt. Two progress events may share the same second, and the threshold setting may change while notification submission is in flight.@@ -438,22 +396,11 @@ Every valid progress event increments `progressGeneration`. A protection candidaAll four must still match when notification returns or grace expires. Any new progress or threshold change invalidates the old attempt.-### Why Persist Before Hiding+### Protection Record Save Ordering-After a task disappears from the snapshot, the app may immediately exit or the system may sleep. Without a queued persistence write, restart bootstrap could show it again and let it support sleep prevention.+An attempt updates the in-memory record synchronously, then a task calls `ActivityProtectionStateStore.apply` in sequence. A disk-write failure is logged and does not prevent hiding the task.-The attempt therefore writes the record first, waits for notification submission, then hides. Failed notification permission or service does not block suppression because releasing erroneous sleep prevention is the protection's core purpose.--### Meaning of the 3-Second Notification Grace--The protection notification is useful explanation but cannot block sleep restoration indefinitely:--- Suppress immediately when notification submission succeeds-- Suppress after 3 seconds if it has not finished-- If notification succeeds later but the attempt is invalid, withdraw it immediately-- New progress within grace cancels the attempt and persisted record--This window constrains the notification side effect only; it does not alter the silence threshold.+Saved records restore protection during the next bootstrap. Hiding does not wait for disk commit, so recovery across restarts depends on the write succeeding.### Reconciling Threshold Changes@@ -461,7 +408,7 @@ Shortening the threshold immediately reevaluates running tasks already past it.Lengthening it silently restores suppressed tasks that no longer exceed the new threshold and clears their records and notifications. Tasks still beyond the new threshold remain suppressed without duplicate alerts.-Turning off Prevent System Sleep disables Activity Protection and restores all suppressed tasks because protection exists to prevent incorrect sleep blocking, not to hide tasks permanently.+Turning off the sleep-prevention switch disables Activity Protection and restores all suppressed tasks in the current process.## Protection-State Persistence@@ -485,9 +432,7 @@ Turn and session keys first become canonical strings with type prefixes and NULTypes and separators prevent boundary ambiguity between concatenated fields. The domain separator prevents directly correlating the same raw ID hashed for another use.-This does not resist brute force when the session ID is already known. It prevents readable identity from appearing directly in the state file and limits cross-purpose correlation.--### Why Debug and Release Share a Locked File+### Cross-Process State MergeBoth app bundle IDs can run together and observe the same Codex Hook data. With separate protection state, a stalled task hidden by one build might still drive sleep prevention in the other.@@ -517,18 +462,6 @@ These constraints prevent false completion alerts and incorrect release during sEach answers a different “is this current?” question and cannot become one global counter. A task making progress without a reader change should invalidate only its protection attempt, not the entire reader.-## Steps to Extend the Task State Machine--1. Classify new input as fact, metadata, progress, or terminal-2. Define whether bootstrap and live input produce the same snapshot and whether either may emit a transition-3. Define degradation when turn or session ID is missing-4. Define how timestamp, terminal memory, or generation rejects late and duplicate input-5. If reading a new rollout field, extend the minimal envelope rather than reading content-6. Keep per-task domain state in `CodexActivityTask` and cross-task association in the monitor-7. Before changing the snapshot, decide whether notifications and sleep prevention should consume the new state-8. Define recovery for system sleep, reader replacement, and unhealthy sources-9. By default, anonymous tasks gain no new high-impact side effect unless identity reliability changes fundamentally-## Suggested Failure-Scenario Tests- Starting the app while a task is running shows it through bootstrap without replaying notificationsdiff --git a/Docs/en/DeveloperGuide/app-server.md b/Docs/en/DeveloperGuide/app-server.mdindex 4efe9ab..9889e5e 100644--- a/Docs/en/DeveloperGuide/app-server.md+++ b/Docs/en/DeveloperGuide/app-server.md@@ -2,25 +2,12 @@[简体中文](../../DeveloperGuide/app-server.md) | English-## Design Motivation--CodexBar does not reimplement Codex sign-in, token refresh, or account protocols. It treats local `codex app-server` as the account-capability boundary.--This design means:--- Codex owns authentication and server protocols, so CodexBar does not duplicate a client that can drift-- The app communicates with a local subprocess over stdio, avoiding another direct network implementation in the primary account flow-- The version of Codex actually running comes from the handshake and can gate global and Hook capabilities-- A global CLI and an app-bundled CLI share one upper-level data model--The cost is that a menu bar app must handle missing shell environments, subprocess lifecycle, pipe backpressure, mixed stdout, timeouts, and connection rotation after upgrades.-## ResponsibilitiesThe app-server flow reads Codex account and server state:- Current account and plan-- 5-hour and weekly rate limits+- Rate-limit groups and windows returned by Codex- Token usage and usage history- Reset Credits state- Hook feature flags, handler lists, and configuration-write capabilities@@ -69,7 +56,7 @@ A menu bar app launched from Finder may lack the complete `PATH` of an interactiThe data directory uses `CODEX_HOME` when set and otherwise uses `~/.codex` under the real user's home directory.-### Why the Process Environment Is Not Trusted Directly+### Process Environment NormalizationAn `LSUIElement` app launched from Finder or Login Items usually lacks the complete `PATH` injected by an interactive shell. Calling only `/usr/bin/env codex` would make Homebrew, Volta, or global npm installations work in Terminal but disappear from CodexBar.@@ -81,12 +68,35 @@ The resolver normalizes in three layers:`CodexCLISourceSelection.automatic` prefers the global CLI and falls back to the bundled CLI when none is found. Selecting `global` or `bundled` uses only that source and returns `sourceUnavailable` if it is missing. `CodexStatusService` saves the selection and reuses it when rebuilding the connection.-### Why On-Disk and Running Versions Are Separate+### Disk and Running VersionsSettings may read versions from both CLI candidates on disk, but minimum-version checks for the primary flow and Hook use only the app-server `userAgent` returned by `initialize`.A connection may be reused for up to 1 hour. If the user upgrades the on-disk binary while it remains alive, the current process is still the old version. Checking the disk value would let the UI claim a capability is available while the running app-server does not support its method.+## In-App Proxy++The proxy is implemented by four types:++| Type | Responsibility |+| --- | --- |+| [`CodexProxyConfiguration`](../../../CodexBar/Models/CodexProxyConfiguration.swift) | HTTP/HTTPS settings, input validation, and child-process environment |+| [`CodexProxyStore`](../../../CodexBar/Services/Settings/CodexProxyStore.swift) | Settings and password stored under `CodexProxy.configuration` in UserDefaults |+| [`CodexProxySettings`](../../../CodexBar/Services/Settings/CodexProxySettings.swift) | Saved configuration, editing draft, toggle commits, and test state |+| [`CodexProxyConnectionTester`](../../../CodexBar/Services/CodexStatus/CodexProxyConnectionTester.swift) | Independent test process using the draft |++Without an enabled configuration, the regular connection uses `CodexCLIResolver.environment`. Enabling a proxy sets `HTTP_PROXY`, `HTTPS_PROXY`, `ALL_PROXY`, `WS_PROXY`, `WSS_PROXY`, and their lowercase forms. `NO_PROXY` and `no_proxy` become `localhost,127.0.0.1,::1`. Only custom-proxy processes append `-c features.respect_system_proxy=false`; the configuration is not written to global Codex files.++Loading preserves decodable raw input. Enabling the proxy and saving an edited form validate the server, port, and authentication username; disabling it permits invalid fields to remain stored. Undecodable records still have a clear action.++The toggle updates its displayed state and sets `isSaving` before creating the asynchronous task; repeated toggles are ignored while it runs. `CodexStatusService.applyProxy` serially saves settings, closes the old connection, and clears supplemental caches. Completion restores interaction and triggers a refresh; failure restores the previous toggle state. The dialog edits a separate draft, committed only by Save or Clear.++### Connection Tests++Testing temporarily enables the draft, resolves the selected Codex source, and calls `AppServerSession.initializeAccount()` for the same handshake and account checks used by regular connections. It then calls `account/rateLimits/read`. Regular connections continue with rate limits and usage after the handshake.++Test requests share an eight-second deadline, do not retry server business errors, and do not record interaction logs. The temporary process is closed on exit using the session’s shutdown wait budget. Editing fields, canceling a test, or closing the dialog cancels both the outer task and its worker; canceled results cannot update the UI.+## Process and ProtocolCodexBar launches this command and communicates over stdio:@@ -126,7 +136,7 @@ Resolve executableA connection enters service state only after the actual version passes the global threshold and both handshake and first account read succeed. A version below `0.143.0` or an unparseable version is treated as unsupported; the half-initialized session closes without further account requests.-### Why the stdout Reader Exposes Complete Lines Only+### Stdout Framing and Response Matchingapp-server frames one JSON message per line. A `Data` block delivered to the pipe callback may:@@ -135,25 +145,25 @@ app-server frames one JSON message per line. A `Data` block delivered to the pip- Mix ordinary logs between JSON lines- End with an unterminated final line when the process exits-`PipeReadBuffer` therefore maintains its own byte buffer and publishes only complete, nonempty lines terminated by a newline. The session first decodes only the response ID and fully decodes a result or error only when the ID matches.+`PipeReadBuffer` maintains a byte buffer, emits nonempty newline-delimited lines during reading, and flushes a nonempty trailing fragment at EOF or when stopped. The session first decodes the response ID and fully decodes the result or error only for a matching ID.This avoids treating logs as protocol errors and fully decodes a large response only once.-### Why stderr Must Also Be Drained+### Stderr DrainingEven though CodexBar does not display stderr content, it must drain the pipe. A subprocess pipe buffer is finite; if the parent never reads stderr, app-server eventually blocks while writing and no later stdout response can arrive.-`PipeDrain` does not parse content. It only removes backpressure. This is required for process correctness, not a logging feature.+`PipeDrain` does not parse content; it continuously drains stderr.### Shutdown StrategyA session shuts down in this order:1. Stop stdout and stderr readers-2. Close the stdin writer so app-server can observe EOF normally-3. Wait up to 1 second for a graceful exit-4. If still running, force termination and wait another 0.5 seconds-5. If it remains alive, record a diagnostic error+2. Close the stdin writer+3. Send `SIGTERM` if the process is still running and wait up to 1 second+4. If still running, send `SIGKILL` and wait another 0.5 seconds+5. Record a diagnostic error if it remains aliveWriting after an early process exit may raise `SIGPIPE`. The service ignores that signal during initialization so the write returns a Swift error and follows the transport-rebuild path instead of terminating the entire menu bar app.@@ -171,28 +181,22 @@ Writing after an early process exit may raise `SIGPIPE`. The service ignores thaEach session caches unsupported methods. After app-server explicitly returns method unsupported, that connection does not request the method again.-### Why Unsupported State Is Cached Per Session+### Session Capability CacheMethod unsupported usually means the running app-server lacks a capability. Calling it again every minute only adds logs and latency.The conclusion must not persist to UserDefaults, however, because a new connection may come from an upgraded binary. The unsupported set belongs only to `AppServerSession` and is probed again after reconstruction.-### Why Configuration Reuses the Same Connection--`config/read`, `hooks/list`, and `config/batchWrite` must use the same actual app-server source as account refresh.--A separate resolver or process for Settings could connect the main panel to the global CLI while Hook validation connects to a bundled CLI. One service keeps capability checks, configuration source, and running version tied to the same process choice.-## Session Lifecycle[`CodexStatusService.swift`](../../../CodexBar/Services/CodexStatus/CodexStatusService.swift) is an actor that owns the connection and refresh state:- One request times out after 20 seconds-- A connection is reused for at most 1 hour+- Connection age is checked on requests; a connection aged 1 hour is rebuilt- A business error retries at most once in the same session- A transport failure rebuilds the connection at most once- When authentication requires refresh, `account/read` retries with `refreshToken = true` at most once-- Closing the service or exiting the process terminates the subprocess and completes all pending requests+- Closing or releasing a connection terminates its subprocess; a request that encounters a closed reader reports a connection errorBusiness and transport errors are separate. The former may be a temporary failure of one method; the latter makes the current stdio session untrustworthy.@@ -212,7 +216,9 @@ ready-> account missing after refresh: close and notLoggedIn```-One hour is the maximum connection lifetime, not the data-refresh interval. Periodic reconstruction ensures an upgraded Codex binary takes effect within one connection cycle.+One hour is the reuse limit checked at request time. The next request after that limit rebuilds the connection using the Codex binary then on disk; no independent timer destroys the connection.++Manual reconnection, source changes, and expired-connection rebuilding all close the old connection first; a failed replacement leaves the app disconnected. Source selection is saved only after successful manual reconnection. Automatic refresh and manual reconnect errors both update `CodexStatusViewModel.connectionErrorMessage`, which About displays.### Error Classification Matrix@@ -226,7 +232,7 @@ One hour is the maximum connection lifetime, not the data-refresh interval. PeriLimiting reconstructions prevents a fault from repeatedly launching subprocesses. The next normal timed refresh still gets a new attempt after the current cycle ends.-### Why Authentication Refresh Happens Only Once per Cycle+### Authentication Refresh BudgetOne refresh reads account, rate limits, and usage; Reset Credits details are included in the rate-limit response. Several interfaces may detect an expired token in the same cycle.@@ -236,7 +242,7 @@ This avoids repeatedly refreshing the same credential during one UI refresh.## Refresh Model-The status view model refreshes every 60 seconds by default. The user can also double-click in the main panel for an immediate refresh.+The status view model refreshes every 60 seconds by default. Users can double-click the account icon in the main panel to request an immediate refresh.Each refresh resolves the account first, then reads rate limits and usage. Supplemental caches are strictly bound to account identity:@@ -245,7 +251,7 @@ Each refresh resolves the account first, then reads rate limits and usage. Suppl- An explicitly unsupported method appears as a missing source- A missing source must not become the business value `0`-A coordinator coalesces refresh tasks so the timer, panel opening, and manual refresh do not issue duplicate concurrent requests.+Ordinary refresh triggers are ignored during a refresh or reconnect. Operations requiring a follow-up use `refreshAfterCurrent` to retain one pending trigger until the current request ends; the coordinator handles cancellation and stale-result checks.### Building One Snapshot@@ -284,7 +290,7 @@ Method unsupported does not use old cache because it is an explicit capability rStale is part of data confidence. A new presentation must not copy the value while dropping the marker.-### Why the Refresh Coordinator Still Needs a Generation+### Refresh Generation ChecksAn `isRefreshing` guard prevents ordinary duplicate triggers, but cancellation and object lifecycle may still let an old `Task` return.@@ -292,7 +298,7 @@ An `isRefreshing` guard prevents ordinary duplicate triggers, but cancellation aAutomatic refresh waits for the remaining interval since the last completion. After a manual refresh, the countdown realigns naturally rather than letting the old timer refresh again a few seconds later.-### Small Model-Layer Optimizations+### Data Models and Display Projection`CodexUsageSnapshot` aggregates potentially repeated daily buckets into `tokensByDate` during initialization.@@ -352,7 +358,7 @@ Results have these semantics:| `nothingToReset` | No rate-limit window can currently be reset | Credit remains unredeemed; retry with the same idempotency key || `noCredit` | The account currently has no available credit | Force refresh; stop silently if the target disappears, otherwise retry as temporary inconsistency |-`alreadyRedeemed` is neither failure nor a second redemption. It confirms that the same logical request already succeeded, so a device receiving it stops retries and sends its local “Automatic Reset” notification.+`alreadyRedeemed` confirms that the same logical request previously succeeded. It stops retries and sends a local success notification according to notification settings.### Cross-Device Idempotency Contract@@ -430,7 +436,9 @@ This is a capability-safety boundary. A future feature depending on an app-serveIt helps inspect process startup, JSON-RPC methods, retries, and error classifications. It must not contain access tokens or Hook prompt content.-### Why There Are Two Logging Channels+`CodexProxyError` configuration failures go to the `settings` category in system logs without creating app-server request-log entries. Before RPC responses and errors enter the interaction log, JSON escapes are decoded and string values are traversed to redact HTTP/HTTPS URL credentials. Non-JSON messages use text redaction.++### Request and System LogsUnified system logs retain only control-flow classifications and support long-term diagnosis of whether refresh ran and which stage failed.@@ -438,17 +446,6 @@ The in-app `RequestLog` keeps previews of at most 500 request interactions in cuReset Credits details include opaque credit IDs. Unified logs must not record IDs or raw responses; the in-app request log remains current-process-only under its existing rules. Before logging a new RPC, check whether its payload can contain credentials or content fields.-## Steps to Extend app-server Data--1. Model protocol optionality in the external DTO without filling display defaults first-2. Decide in `CodexStatusService` whether the method is account-critical or supplemental-3. Define degradation separately for ordinary failure, unsupported, and authentication failure-4. If cached, bind the value to account identity and carry stale semantics-5. Convert timestamps, percentages, ordering, and other stable rules in the domain snapshot-6. Let UI consume only the snapshot, never the raw response-7. Let notifications and other side effects use only trusted snapshots-8. Check whether requests or logging broaden privacy boundaries-## Suggested Failure-Scenario Tests- A Finder launch still finds Codex installed by Homebrew, npm, or Volta@@ -481,6 +478,8 @@ Reset Credits details include opaque credit IDs. Unified logs must not record ID- A full rate-limit refresh after redemption is not dropped behind a concurrent ordinary refresh- The 60-second countdown realigns after manual refresh+Proxy checks also cover disabling invalid settings, clearing corrupt records, isolating canceled test results, submitting only once during rapid toggles, rolling back failed commits, and redacting credentials in plain and JSON-escaped URLs.+## Key Source Files- [`CodexCLIResolver.swift`](../../../CodexBar/Services/CodexCLI/CodexCLIResolver.swift)diff --git a/Docs/en/DeveloperGuide/architecture.md b/Docs/en/DeveloperGuide/architecture.mdindex c0889b3..9ec69e2 100644--- a/Docs/en/DeveloperGuide/architecture.md+++ b/Docs/en/DeveloperGuide/architecture.md@@ -2,23 +2,6 @@[简体中文](../../DeveloperGuide/architecture.md) | English-## What This Architecture Solves--CodexBar's central challenge is not drawing a menu bar interface. It is coordinating short-lived Hook subprocesses, a local app-server, append-only files, CloudKit, system notifications, and a root helper inside a long-running `LSUIElement` app.--See the [interactive runtime architecture diagram](https://codexbar.zabrian.app/architecture) for the full component relationships, data flows, and source references.--The architecture must continuously satisfy these goals:--- A failure in one data flow must not disable unrelated features-- Short-lived Hook mode and normal app mode share an executable but have completely isolated lifecycles-- The UI observes explainable snapshots and does not own I/O, deduplication, or recovery logic-- Privileged operations expose the smallest possible interface while business policy remains in the unprivileged app process-- Every asynchronous result can prove that it still belongs to the current configuration and data-source generation-- Rebuildable data remains separate from side effects that cannot be replayed--For the broader rationale, see [Design Principles and Key Decisions](design-decisions.md).-## Technical BaselineCodexBar is a menu bar app for macOS 15 and later, built with Swift 6, SwiftUI, AppKit, and MVVM.@@ -64,7 +47,7 @@ Two points define these boundaries:| --- | --- | --- | --- || Hook subprocess | One event, at most a few seconds | Read stdin, extract minimal fields, append local JSONL | Initialize UI, open network connections, or wait for long-running services || Main app | Long-running within the user login session | Orchestrate UI, data flows, and side effects | Change system settings directly as root |-| app-server | Reused for up to 1 hour | Expose account and configuration capabilities through JSON-RPC | Substitute for Hook history or live task state |+| app-server | Rebuilt on the next request after reaching 1 hour | Expose account and configuration capabilities through JSON-RPC | Substitute for Hook history or live task state || CodexBarHelper | LaunchDaemon | Run fixed `pmset` operations, manage a `wake` event for a fixed owner, and restore system state | Access accounts, Hook data, rollout files, the network, or arbitrary commands |## Directory Responsibilities@@ -85,7 +68,7 @@ Scripts/ Build, DMG, appcast, and CodexBarHelper cleanup scripts## Startup Order-The initialization order in [`CodexBarApp.swift`](../../../CodexBar/App/CodexBarApp.swift) is an architectural constraint, not an implementation detail:+[`CodexBarApp.swift`](../../../CodexBar/App/CodexBarApp.swift) branches startup in this order:```textProcess starts@@ -103,6 +86,7 @@ Process startsIn normal mode, `CodexBarAppDelegate` creates and owns long-lived objects, including:- `CodexStatusService` and `CodexStatusViewModel`+- `CodexProxySettings`- `WorkflowService` and its view model- `CodexHookSettings`- `CodexActivityMonitor`@@ -114,7 +98,7 @@ In normal mode, `CodexBarAppDelegate` creates and owns long-lived objects, incluBefore quitting, the app must cancel the Automatic Reset wake schedule and release sleep prevention. If CodexBarHelper has not confirmed that both categories of system state were restored, termination waits or is canceled. Before accepting a new connection at startup, the helper also removes stale wake events for its fixed owner, converging state left by sudden power loss or forced termination.-### Why Hook Detection Must Run in `App.init`+### Hook Startup Branch`@NSApplicationDelegateAdaptor` connects the AppKit lifecycle to the SwiftUI app. Once the normal lifecycle begins, it may create menu bar objects, register a notification delegate, or access CloudKit.@@ -122,20 +106,7 @@ The Hook handler runs on Codex's critical path and must behave like a command-liThis order also prevents Hook capture failures from contaminating normal-exit diagnostics. `AppProcessDiagnostics.install()` runs only in `applicationDidFinishLaunching`, so a Hook subprocess is not misclassified as a complete app that exited abnormally.-### Why AppDelegate Owns Long-Lived Objects--SwiftUI may recreate views because of layout, conditional branches, or window reconstruction. If a view owned a service, an ordinary UI change could terminate a reader, app-server, or XPC connection.--`CodexBarAppDelegate` therefore acts as the composition root:--- It is the only place that creates long-lived services, settings, and view models-- It wires callbacks among monitoring, notifications, and keep-alive coordination-- Views receive references that already exist-- Shutdown stops services in reverse order from the same owner--This does not place all logic in AppDelegate. It owns assembly and lifecycle only; business rules remain in their services or controllers.--### Why Termination Can Be Canceled+### Termination Coordination`applicationShouldTerminate` first calls `KeepAliveController.prepareForTermination()` and returns `.terminateLater`.@@ -153,13 +124,6 @@ CodexBar does not use a single aggregation service for all state. The three flow| Hook history | Hook JSONL | Daily event, session, turn, tool, and model aggregations | Activity heatmap, historical metrics, CloudKit || Live tasks | Incremental Hook events plus rollout lifecycle | Running, waiting for approval, completed, terminated | Menu bar status, Task Center, notifications, sleep prevention |-The flows may share infrastructure and models, but they cannot replace one another:--- app-server does not provide complete live task state-- Historical aggregation may be delayed or rebuilt; live tasks cannot wait for aggregation-- Live task snapshots cannot be a persistent source for historical metrics-- If one flow becomes unavailable, the others must remain available-### Dependency Direction```text@@ -180,9 +144,7 @@ Hook + rollout --------> CodexActivityMonitor --------> UIArrows show the direction in which data or read-only state is consumed. A downstream component must not become an upstream source of truth.-For example, the menu bar may draw rate-limit progress and task state in one icon, but whether that icon exists must not decide whether the task monitor runs. The sync scheduler may reuse a historical-maintenance trigger, but CloudKit availability must not decide whether local aggregation runs.--### A Shared Trigger Is Not a Data Dependency+### Shared Refresh TriggersHistorical maintenance normally runs after the 60-second rate-limit refresh to reduce resident timers and log noise. The flows share scheduling, not facts.@@ -219,7 +181,7 @@ These objects own observable state and UI coordination. They must not perform blDTOs crossing actor boundaries must be immutable value types and declare `Sendable` or `nonisolated` where appropriate.-### Why the Monitor Still Runs on MainActor+### Monitor MainActor BoundaryActors read inputs for `CodexActivityMonitor`, but the state machine itself is closely connected to several Combine consumers.@@ -231,23 +193,6 @@ Keeping the monitor on `MainActor` provides:The monitor must not perform blocking file reads directly. `HookEventTailReader`, `CodexSessionLifecycleReader`, and `ActivityProtectionStateStore` own those I/O boundaries.-### Why the Nonisolated Pipe Reader Uses a Lock--app-server communicates over stdio, requiring a combination of `FileHandle`, `DispatchSourceRead`, and semaphores. These types are not naturally `Sendable`, and crossing a Swift actor hop for every line is unsuitable.--`PipeReadBuffer` confines the unsafe boundary to one `@unchecked Sendable` type. An `NSLock` protects all mutable state, read events stay on a dedicated queue, and the caller sees only complete lines and closed state.--Here, `@unchecked` is a localized promise backed by encapsulation, not a way to disable concurrency checks for the whole module.--### Why Cross-Process Files Need More Than an Actor--The Hook recorder runs in another process, so the `WorkflowService` actor cannot protect it. `stats.lock` uses `flock` to provide a process-wide exclusive transaction over joint changes to event files and maintenance state.--The same flow therefore uses both an actor and `flock`:--- The actor prevents maintenance operations inside the main app from changing state concurrently-- `flock` prevents the main app and short-lived Hook subprocesses from committing conflicting file changes at the same time-## Model LayersThe project does not reuse one large object directly across app-server DTOs, persistence, and views:@@ -258,7 +203,7 @@ The project does not reuse one large object directly across app-server DTOs, per| Persistence model | Store recoverable state and schema | Remain compatible with old values and express missing semantics || Domain snapshot | Express current trusted state to consumers | Immutable, comparable, and safe across actors || Transition | Represent one live state change | Never inferred from historical snapshots; deduplicated upstream |-| Presentation format | Dates, percentages, copy, and colors | Follow the locale and never feed back into business decisions |+| Presentation format | Dates, percentages, copy, and colors | Use regional settings or a fixed format for each field; never feed back into business decisions |For example, `CodexQuotaSnapshot` can carry both a current value and a stale marker. `CodexActivitySnapshot` contains only task fields needed for presentation; raw session IDs do not enter views.@@ -268,7 +213,7 @@ Different states have different lifetimes and cannot share one cache duration:| State | Lifetime | Reason || --- | --- | --- |-| app-server connection | Up to 1 hour | Reuse reduces startup cost; periodic reconstruction picks up on-disk upgrades |+| app-server connection | A 1-hour reuse limit checked on requests | Later requests rebuild with the binary on disk || app-server supplemental cache | Current account only | Prevents values from leaking across accounts || Hook live bootstrap window | 24 hours | Covers long-running tasks that may still be active || Completion highlight | 30 seconds | Short menu bar feedback |@@ -282,23 +227,10 @@ Before changing one time window, check for paired invariants. For example, the t## State Ownership-Live task state has one authoritative source: [`CodexActivityMonitor.swift`](../../../CodexBar/Services/Workflow/CodexActivityMonitor.swift).--Its snapshot is consumed by:--- The menu bar icon and main-panel task card-- Task Center-- Completion and approval-request notifications-- Sleep-prevention eligibility-- Stalled Task Protection--Consumers may present the snapshot or perform side effects from it, but must not rebuild separate task state machines.--### State Ownership Table-| State | Sole owner | Permissions of other modules || --- | --- | --- |-| app-server connection and same-account cache | `CodexStatusService` | Request read-only results |+| app-server connection and same-account cache | `CodexStatusService` | Read data, change configuration, or reconnect through service methods |+| Proxy draft, tests, and toggle interaction | `CodexProxySettings` | Settings submits through methods; `CodexStatusService` applies the active connection configuration || Main-panel account loading state | `CodexStatusViewModel` | Observe published values || Automatic Reset target, deadline, and retries | `AutoResetController` | Settings changes only the switch and lead time || Automatic Reset wake-time synchronization | `AutoResetWakeScheduler` | `AutoResetController` submits only the next time; `KeepAliveController` submits only helper readiness |@@ -322,7 +254,7 @@ When adding a consumer, subscribe to an existing snapshot first. If it lacks a f- Recovery must complete a new read barrier before evaluation continues- Persistent writes require atomic replacement or file locking to avoid corruption from concurrent Debug and Release processes-### Error Classification Matters More Than Uniform Retries+### Error Classification| Error class | Typical handling | Incorrect handling || --- | --- | --- |@@ -334,45 +266,6 @@ When adding a consumer, subscribe to an existing snapshot first. If it lacks a f| Uncertain privileged state | Retain the possible lease or wake event and actively confirm cleanup | Assume the helper did nothing || Hook recorder failure | Drop this capture and exit successfully | Block Codex or present UI |-### Why Logs Record Stages Instead of User Data--System logs explain control flow with `trigger`, `stage`, `reason`, `counts`, and `elapsed`, without recording rate-limit values, project paths, or task identities.--This structure can distinguish whether:--- Sync failed during zone, device, fetch, upload, or prune-- app-server created or reused a connection-- Aggregation was a no-op, incremental write, or dirty rebuild-- A particular condition blocked sleep prevention--Diagnostics need control-flow evidence, not copies of user data.--## Where to Make a Core-Flow Change--### Adding a Data Source--1. Decide whether it belongs to one of the existing three flows-2. Define source-missing, stale, and failure semantics-3. Perform I/O and caching inside an actor service-4. Cross into MainActor through an immutable snapshot-5. Review network and privacy boundaries separately--### Adding a One-Time Side Effect--1. Find a live transition that proves the event just occurred-2. Do not infer it from a current snapshot or historical list-3. Define in-process and cross-restart deduplication scopes-4. Check immediately before submission that the event is still relevant-5. Define whether side-effect failure may affect primary state--### Adding Persistent State--1. Explain why in-memory state is insufficient-2. Define the schema, atomicity, and concurrent-access boundary-3. Define how old versions read new files and new versions read old files-4. Limit stored fields and retention-5. Confirm the compatibility strategy before changing the format-## System Integration| Capability | System interface |diff --git a/Docs/en/DeveloperGuide/data-and-privacy.md b/Docs/en/DeveloperGuide/data-and-privacy.mdindex 2a62af0..618dd83 100644--- a/Docs/en/DeveloperGuide/data-and-privacy.md+++ b/Docs/en/DeveloperGuide/data-and-privacy.md@@ -2,17 +2,6 @@[简体中文](../../DeveloperGuide/data-and-privacy.md) | English-## Principles--CodexBar reads only the data required for account display, Automatic Reset, Hook metrics, live tasks, and sleep prevention:--- Do not upload raw data when it can remain local-- Store aggregates instead of content when possible-- Store hashed identities instead of raw identities when possible-- Mark missing data explicitly when a source is unavailable--Privacy boundaries are architectural constraints on every data flow, not a static blacklist of fields. Even if a new field is technically easy to read, first ask whether it is necessary to achieve a product goal.-## Data Classification ModelClassifying data during development helps determine its storage and propagation scope:@@ -23,8 +12,6 @@ Classifying data during development helps determine its storage and propagation| Identity and context | Session IDs, full paths, project names | Minimize use to necessary flows; redact or remove before upload || Aggregated metrics | Daily event counts, model counts | May persist locally; upload only specified fields after explicit opt-in |-“Stored only on this Mac” does not mean zero privacy cost. Local logs, crash reports, backups, and other processes on the same machine can expand exposure, so unnecessary data should be discarded at the parsing boundary.-## Trust Boundaries```text@@ -49,8 +36,6 @@ These boundaries mean:## Minimize at the Capture Boundary-Removing sensitive fields only during upload is insufficient because raw values may already have entered local JSONL, in-memory logs, or error messages.-CodexBar narrows data in this order:1. The Hook recorder extracts only allowlisted structural fields from stdin@@ -59,8 +44,6 @@ CodexBar narrows data in this order:4. The sync model projects again into CloudKit-allowed fields5. Logging records only stages, classifications, and nonsensitive counts-Every layer narrows the data shape, so adding a downstream field does not automatically expose all upstream source text.-## Data-Flow Overview| Source | Use in CodexBar | Persisted? | Uploaded to CloudKit? |@@ -73,17 +56,6 @@ Every layer narrows the data shape, so adding a downstream field does not automa| CodexBarHelper ownership | System-sleep recovery | Root-owned state file | No || Automatic Reset wake schedule | Fixed owner, `wake` type, and next time | System power management | No |-### Why the Three Business Flows Remain Independent--app-server, Hook history, and live activity read different facts with different freshness and failure modes:--- app-server failure must not erase local history-- Hook aggregation maintenance failure must not freeze live tasks-- Temporary rollout unavailability must not mark rate limits as erroneous-- CloudKit failure must not block current-device aggregation--Collapsing them into one “globally loaded” state would let a lower-sensitivity or lower-priority flow expand the data access and availability impact of another.-## Local Reads### Codex app-server@@ -118,8 +90,6 @@ These reads parse only structural fields such as origin classification, lifecyclThe rollout reader scans backward from file tails under a budget. This reduces I/O and limits how much unrelated historical content enters process memory. Parsing DTOs declare only required fields, and `JSONDecoder` ignores everything else.-This is not complete privacy isolation from rollout files because the reader must still open them. A future full-text search or prompt display would be a new privacy capability, not a natural extension of the current reader.-### Reset Credits Details`account/rateLimits/read` returns the Reset Credits count and optional details in the app-server response.@@ -161,14 +131,6 @@ A rate-limit response from stale cache may remain visible but cannot trigger a nDaily aggregations for the latest 3 days may retain session and turn ID details for exact deduplication. Older data retains counts only.-Three days of identity detail balances exact deduplication against long-term minimization:--- Recent Hook files may still receive late or duplicate writes and require identity sets for correct merging-- Distant history rarely changes, and retaining only totals substantially reduces long-term identity exposure-- Counts cannot restore identities after compaction, so algorithm changes rebuild from raw JSONL still inside the 210-day retention period--Raw events and daily aggregations share the same 210-day limit, preventing more sensitive raw data from remaining indefinitely after derived data is gone.-Anonymous tasks do not create Stalled Task Protection identifiers and therefore never write to `ActivityProtection/state.json`.### UserDefaults@@ -178,14 +140,20 @@ UserDefaults stores:- Feature switches and options- Notification thresholds and sound names- Global shortcut+- Proxy enabled state, protocol, server, port, authentication username, and password- Menu bar display selection- Automatic Reset switch and lead time- Bounded notification deduplication keys- Runtime configuration such as the CodexBarHelper fingerprint-Renaming a persistence key, changing its structure, or changing a default requires consideration of upgrades from older versions.+Changes to persistence keys, data structures, enum raw values, or defaults for missing values require an agreed migration and downgrade strategy before implementation.++The `CodexProxy.configuration` key stores one JSON data value containing `configuration` and `password`. Passwords are stored in plain text in local UserDefaults and removed when settings are saved with authentication disabled or the configuration is cleared. Debug and Release use separate preference domains:++- Debug: `~/Library/Preferences/app.zabrian.codexbar.debug.plist`+- Release: `~/Library/Preferences/app.zabrian.codexbar.plist`-UserDefaults is not schemaless. Renaming an existing key, changing an enum raw value, or changing the default for a missing value changes behavior for upgrading users. These are compatibility issues and require an agreed migration and degradation strategy first.+`CodexProxyStore` distinguishes a missing record from a decoding failure. A failed record remains available for the configuration dialog’s clear action.### CodexBarHelper Directory@@ -205,8 +173,6 @@ The in-app [`RequestLog.swift`](../../../CodexBar/Services/CodexStatus/RequestLoIt diagnoses the app-server protocol. Even in memory, it must not contain OAuth tokens or Hook content.-The 500-entry cap limits memory and rendering cost when the Logs window opens. It is not an audit log and cannot track problems across launches. Cross-launch diagnosis uses unified system logging under the same field boundaries.-The unified logging subsystem is `app.zabrian.codexbar`, with a `.debug` suffix in Debug builds.System logs may contain only:@@ -224,17 +190,22 @@ System logs must not contain:- Full project paths or sensitive project names- Account rate-limit or token-usage details+Fixed `CodexProxyError` messages go to the `settings` system-log category without configuration values. Before app-server responses enter the app interaction log, JSON escapes are decoded and HTTP/HTTPS URL credentials in string values are redacted. Other account and protocol fields retain the existing request-log behavior.+## Network Access| Destination | Purpose | Trigger || --- | --- | --- || CloudKit private database | Sync daily Hook aggregations | User explicitly enables sync |+| Codex service, through the app-server subprocess | Authentication, rate limits, usage, and Reset Credit consumption | Regular refreshes, proxy tests, or Automatic Reset || Sparkle appcast and update resources | Check for or install updates | Automatic check or manual user request |Account data, rate limits, token usage, Reset Credits details, and explicitly enabled Reset Credit redemption use local app-server stdio. CodexBar does not add a separate HTTP client for Automatic Reset.CodexBarHelper performs no network access.+When a proxy is enabled, its address and optional credentials are passed through environment variables to app-server processes started by CodexBar. This does not configure system networking, Sparkle, CloudKit, or other Codex processes. Connection tests use a temporary app-server, close it afterward, and do not write app interaction logs.+## CloudKit BoundaryCloudKit uploads only daily aggregate fields:@@ -258,11 +229,10 @@ CloudKit does not upload:- Access tokens- App request logs- Activity Protection state+- Proxy settings and passwordsA project display name may derive from a directory name and still contain sensitive information. Sync must remain an explicit user choice.-An HMAC device pseudonym reduces linkability of hardware identity but does not anonymize project names. A private database also does not mean that data remains on the device. Settings copy and developer documentation must therefore continue to explain synced content rather than enabling it by default simply because CloudKit belongs to the user's account.-## Root Helper Data IsolationCodexBarHelper needs only four kinds of state:@@ -274,7 +244,7 @@ CodexBarHelper needs only four kinds of state:It does not need task IDs, project names, Hook paths, account state, `creditId`, or complete user settings. XPC carries only Boolean requests, client session ID, generation, update identifier, and a bounded Unix timestamp.-This capability minimization means future network or data features in the regular app do not automatically reach the root process. Business services must not be linked into the helper merely to reuse file or network code.+The helper target contains restricted power operations and the shared XPC protocol; it does not link the app’s business services.The helper ownership file is a crash-recovery transaction record, not a user preference. It must be root-owned, reject group- or world-writable directories, and use full sync plus atomic rename so a restart can decide whether restoration is required.@@ -287,20 +257,6 @@ The helper ownership file is a crash-recovery transaction record, not a user pre- CodexBarHelper state commits with root ownership, permission checks, full sync, and atomic rename- Data shared by Debug and Release uses locking and compatible schemas-## Privacy Meaning of Missing, Stale, and Unavailable--Do not hide unavailable data behind friendly-looking defaults:--| State | Correct representation | Incorrect behavior |-| --- | --- | --- |-| Field missing from an older source | `nil` or unavailable | Decode as an explicit zero |-| app-server cache expired | Stale snapshot | Continue triggering notifications |-| Rollout supplemental read unavailable | Retain existing Hook task state and continue polling for lifecycle updates | Treat a missing rollout result as a task ending |-| CloudKit offline | Preserve old cache with source attribution | Treat it as new data for the current account |-| Battery read failed | Preserve prior decision and mark unreadable | Treat as no battery |--Explicit degradation improves correctness and avoids reading extra fallback sources or storing additional data simply to fill the UI.-## Checklist Before Adding a Data Field1. State the product goal and the behavior that is impossible without the fielddiff --git a/Docs/en/DeveloperGuide/design-decisions.md b/Docs/en/DeveloperGuide/design-decisions.mdindex 74fae4e..beec1b9 100644--- a/Docs/en/DeveloperGuide/design-decisions.md+++ b/Docs/en/DeveloperGuide/design-decisions.md@@ -2,316 +2,58 @@[简体中文](../../DeveloperGuide/design-decisions.md) | English-This document explains why CodexBar has its current structure and which problems that structure solves.+## State Ownership-It is neither a source-tree index nor a feature list. Its purpose is to establish decision criteria: when implementation must change, which mechanisms are replaceable and which system invariants must remain true.+Each data flow has one service owning its facts; consumers read snapshots or transitions:-## Deriving the Architecture from Product Goals--CodexBar may look like a simple menu bar app, but it crosses four fundamentally different boundaries:--- Codex's local protocol and configuration-- Continuously changing Hook and rollout files-- macOS windows, notifications, and power management-- Root-privileged control of system sleep and scheduled wake--These boundaries cannot share one failure strategy.--For example, preserving the previous value is usually more useful than clearing it when a rate-limit refresh fails. A failed Hook capture must be abandoned immediately because statistics must never block Codex. A failed sleep-state release, however, must not be ignored during exit because CodexBar may still own system state.--The project therefore avoids one global service that does everything. It separates components first by input source and failure semantics, then combines read-only snapshots at the UI and side-effect layers.--## Decision Priorities--Resolve implementation tradeoffs in this order:--1. Do not block the Codex task the user is running-2. Do not leave behind or incorrectly change system-level state-3. Do not present old, missing, or uncertain data as a current fact-4. Do not let a late asynchronous result overwrite newer user intent-5. Do not broaden the boundaries of privileged processes, network access, or persisted data-6. Only then optimize latency, file size, and UI animation--This order explains several intentionally asymmetric behaviors:--- A Hook recorder drops the current statistic after a lock timeout instead of waiting longer-- App termination may be delayed until the helper confirms release of CodexBar-owned sleep state and cancellation of the Automatic Reset wake schedule-- A failed supplemental app-server request may show stale cached data, but an unsupported method must show that the source is unavailable-- Stalled Task Protection remains paused if wake recovery has not passed a new Hook read barrier--## Facts, Snapshots, and Side Effects--Project state has three layers:--| Layer | Meaning | Examples |+| Flow | Source of state | Output use || --- | --- | --- |-| Fact | An input that has occurred in an external system or local log | Hook event, rollout terminal, app-server response |-| Snapshot | Displayable state derived from facts under current rules | `CodexQuotaSnapshot`, `WorkflowSnapshot`, `CodexActivitySnapshot` |-| Side effect | A one-time action caused by a trusted state change | Notification, haptic feedback, XPC lease, CloudKit upload |--Views intentionally do not execute side effects from raw facts.--For example, the notification service does not scan Task Center and guess which task just completed; it consumes transitions published by the monitor. The sleep-prevention controller does not parse Hook data; it consumes running and waiting tasks in the activity snapshot.--This has two benefits:--- A snapshot may be read repeatedly, while a transition must be consumed at most once-- One state machine handles bootstrap, deduplication, late events, and rollout reconciliation consistently, so consumers do not implement similar but divergent rules--## Why the Three Data Flows Must Remain Independent--### app-server Flow--app-server provides periodic snapshots of account, rate-limit, and token usage data. Minute-level refreshes are appropriate, and transient failures may fall back to a same-account cache.--### Historical Hook Flow--The historical flow converts append-only raw events into daily aggregations. It may be delayed and rebuilt from raw JSONL; long-term consistency is its primary goal.--### Live Task Flow--The live flow tracks task states and one-time transitions on a seconds-level timescale. It combines Hook and rollout data, cannot wait for daily aggregation, and must not treat a terminal state from ten minutes ago as a new notification.--Combining the three produces incorrect coupling:--- A transient app-server failure would erase local task state that remains readable-- An aggregation rebuild would block live task updates-- Terminal deduplication designed for notifications would contaminate historical counts-- CloudKit or network failures would affect local Hook presentation--The UI may combine the flows, but they must never become sources of fact for one another. This is one of CodexBar's most important architectural boundaries.--## User Intent, Dependency Availability, and Actual Effect--Settings-driven features usually have three distinct states:--```text-User intent -> Dependency availability -> Actual effect-```--Sleep prevention is the clearest example:--- `isEnabled` means the user allows CodexBar to manage sleep-- Hook, helper, battery, and duration state determine whether execution is currently possible-- `isPreventingSleep` means the app and helper have confirmed the actual effect--A temporarily unavailable dependency must not write `false` back to `isEnabled`. Otherwise, one RPC failure would permanently change a user preference and prevent automatic recovery.--Hook settings make a similar distinction:--- `isEnabled` means the handler is installed in the configuration file-- `isVerified` means app-server most recently returned an explicit usable result-- `isOperable` is the state downstream dependencies should consume--This three-layer model has more states than one Boolean but avoids merging configuration, diagnostics, and effect into an unexplained switch.--## Uncertainty Must Appear in Types and UI--Several parts of the project preserve `nil`, stale, or degraded state instead of converting everything to zero or an empty array.--### Missing Is Not Zero--When old Hook data lacks a count field, `nil` means the capture capability did not exist at that time. Only `0` means the source explicitly confirms that nothing occurred.--Merging them would draw unknown history as real zeroes and make the interpretation impossible to repair later.--### Stale Is Not Failure--If a supplemental app-server method fails temporarily for the same account, old rate-limit or usage values remain useful. The snapshot marks them with `isRateLimitsStale` and `isUsageStale`; the UI uses opacity to show reduced confidence, while notifications skip stale rate limits entirely.--### Degraded Bootstrap Is Not Idle--If the live reader cannot obtain a stable file boundary, it moves to the end of the file while also publishing degraded state and an unhealthy data source. This means “existing tasks cannot be recovered reliably,” not “there are definitely no tasks.”--## Why Generations Are Used Extensively--Most CodexBar I/O shares this race:--1. Request A begins-2. The user changes a setting or the reader is replaced-3. Request B begins and finishes first-4. Request A returns last--Canceling a `Task` is not enough. Some system APIs and synchronous bridges cannot truly cancel, so old callbacks may still arrive.--Critical asynchronous paths therefore maintain monotonically increasing generations:--- The refresh coordinator allows only the current generation to commit-- Hook settings allow only the latest operation to update UI-- Replacing a tail reader invalidates batches from the old reader-- Wake recovery validates both reader and recovery generations-- XPC lease requests use generations so a late acquire cannot overwrite a release-- Helper-state requests and CloudKit availability checks also discard old results by generation--The value of a generation is not easier cancellation. It turns permission to commit into an explicit, verifiable condition.--## Why the Project Uses Actors, MainActor, and Locks--Each mechanism covers a different boundary:--| Mechanism | Scope | Typical objects |-| --- | --- | --- |-| `MainActor` | UI-observable state and AppKit lifecycle | Controllers, view models, settings, monitor |-| Swift actor | Asynchronous mutable state within one process | app-server, aggregation, readers, CloudKit service |-| `flock` | Transactions over files shared across processes | Hook recorder and main-app statistics files |--An actor cannot protect another CodexBar Hook subprocess. `flock` is unsuitable for UI state. Choose the concurrency tool based on where contention occurs rather than forcing every synchronization problem into actors because the project already uses them.--Default `MainActor` isolation makes UI types safer, but every blocking file or pipe wait must explicitly move off the main actor. `AppServerSession` and its pipe reader use locked nonisolated boundaries, while the higher-level `CodexStatusService` actor serializes connection management.--## Why Raw Logs and Derived Caches Are Separate--Raw Hook JSONL is an auditable fact source; `daily.jsonl` is a cache generated by the current algorithm.--This structure provides three long-term benefits:--- Historical data can be rebuilt after an aggregation fix without designing a migration for every old field-- The write-critical path appends one line instead of reading and rewriting all statistics during the few seconds Codex is waiting-- CloudKit sync can upload only aggregations, leaving raw identities and paths on the Mac--The cost is explicit management of schemas, offsets, and source replacement. Maintenance state therefore stores `sourceGeneration`, inode, size, boundary hash, and dirty/pending state.--## `sourceGeneration` Is Not a Version Number--An event file for a given day may be replaced, truncated, or rebuilt by the user. The same date does not prove that it is the same fact source.--`sourceGeneration` gives “which generation of raw file produced this day's data” a stable identity:--- Normal appends preserve the generation-- An inode change, file shrink, or rewrite before the consumed boundary creates a new generation-- CloudKit record names can distinguish generations-- The presentation layer adds clearly independent contributions and treats same-source results as replacements--If date alone were the identity, a rebuilt value would be added to the old cloud value and create permanent double counting.--## Why Live Tasks Read Both Hook and Rollout Data--Each source solves only half of the problem:--| Source | Strength | Gap |-| --- | --- | --- |-| Hook | Low latency, clear event types, suitable for live UI | `Stop` cannot always distinguish completion from interruption; some context fields may be missing |-| rollout | More authoritative terminal, effort, and reviewer fields | Slower file discovery and parsing; unsuitable as the only low-latency signal |--The monitor first establishes active state from Hook data, then fills in lifecycle details from rollout files. `Stop` creates a completion candidate. `SessionEnd` or a new prompt moves the task into a short terminal-confirmation window, and rollout provides accurate classification during the grace period.--This is not a simple two-source merge. Conflicts require semantic authority rules, and late events must not revive a task that already completed.--## Why the Privileged Helper Accepts Only Constrained Power Operations--The app needs root privileges to change `pmset disablesleep` and schedule system `wake` events. Task identification, Automatic Reset policy, network access, and file parsing do not require root.--Putting policy in the helper would greatly expand its attack surface and recovery scope. The current boundary keeps it a small executor:--- Inputs are limited to sleep leases, generations, state queries, update-recovery markers, and bounded Unix wake timestamps-- Sleep commands are fixed argument combinations for `/usr/bin/pmset`; wake schedules use a fixed CodexBar owner and `wake` type-- Clients are validated through code-signing requirements-- The helper does not read Codex files, access the network, or accept arbitrary paths or commands--The app decides what should happen; the helper executes and verifies it with constrained privileges.--## Why Leases Still Need Ownership Records--A lease answers whether an active app still requests the effect. Ownership answers whether CodexBar changed the current system value.--Neither can replace the other:--- When no lease remains, the helper should revoke its own effect-- If `SleepDisabled=1` was originally set by the user or another app, CodexBar has no right to restore it to `0`-- If CodexBar completed `0 -> 1`, the helper must persist owned state first so it can recover after a crash--The release condition is therefore “the last lease ended and ownership is owned,” not simply “there are no clients, so write `0`.”--## Why CloudKit Syncs Aggregations Instead of Raw Events--Cross-device presentation needs only daily metrics. Uploading raw events would expose more identity data, increase volume, and complicate deduplication without enabling a current product capability.--Benefits of syncing aggregations include:--- Session, turn, and agent IDs remain local-- Network and CloudKit operations scale with days rather than events-- Each Mac can still rebuild independently, while the cloud stores only per-device contributions-- Cross-device merge rules can be defined around `deviceId + date + sourceGeneration`--Project display names may still be sensitive, so sync must be explicitly enabled. Signing in to iCloud must never upload them by default.--## Subtle but Important Details--### `@Published` Callback Arguments Are More Reliable Than Immediate Reads--Combine publishes during `willSet`. When a subscriber closure runs, the property itself may still contain the old value.--Subscriptions for Hook availability, sync activation, and sleep-prevention dependencies therefore calculate from closure arguments instead of immediately reading the object property again. This explains several seemingly redundant state mirrors.--### The Boundary Hash Covers Only the Consumed Tail--Historical aggregation does not hash every file in full on every cycle. It stores a boundary hash for the 4 KB before the offset and uses mtime to decide whether to recompute it.--Normal appends occur after the offset and do not change this boundary. This detects in-place rewrites of consumed content without holding `stats.lock` for long, letting Hook subprocesses persist events quickly.--### State Sorting Uses UUID as a Tie-Breaker--Several tasks may share a timestamp, and Swift sorting is unstable. Snapshots break timestamp ties with the UUID string so SwiftUI diffing does not repeatedly refresh because of meaningless order changes.--### Notifications Recheck Relevance Before Submission--An asynchronous window exists between deciding to notify about an approval request or stalled task and the system actually accepting it. The task may already have resumed.--Before every submission or retry, the notification service calls `isStillRelevant`. If it is false, pending and delivered notifications are withdrawn. This is more reliable than attempting removal only when state changes.+| app-server | Account, quota, and usage responses | Periodic display with same-account stale-cache fallback |+| Hook history | Raw JSONL | Rebuildable daily statistics and cross-device sync |+| Live tasks | Incremental Hook events and rollout lifecycle | Activity snapshots, task alerts, and sleep prevention |-### An XPC Timeout Cannot Clear a “Possible Lease”+Snapshots can be read repeatedly. Notifications use live transitions; bootstrap establishes a baseline without replaying historical alerts. Historical aggregation shares some refresh triggers with quota, but reads and failure handling remain independent. See [Architecture](architecture.md) for component relationships.-A timeout proves only that the reply did not arrive; it does not prove that the helper failed to acquire the lease. `mayHaveHelperLease` therefore remains true until an explicitly successful release.+## User Intent and Actual Effects-Clearing it on timeout could make app termination skip release and leave the helper waiting for its watchdog before restoring system state.+A saved switch expresses intent, dependencies determine whether execution is possible, and result state expresses a confirmed effect. Temporary dependency failures preserve the user’s switch and reconcile again on recovery.-### External Sleep Sources Need Continuous Observation+Sleep prevention represents these layers with `isEnabled`, `sleepBlockReason`, and `isPreventingSleep`. Hook combines `isEnabled` and `isVerified` into `isOperable`; live tasks require operability, while historical aggregation can still process recorded data.-If the system already has `SleepDisabled=1` when a task starts, the helper marks the source external. That source may remove its setting while the task is still running.+## Missing, Stale, and Untrusted Data-The helper periodically reads the actual value. If the external effect disappears while a lease remains valid, CodexBar can safely perform its own `0 -> 1` transition, take ownership, and keep sleep prevention from silently ending.+| State | Current handling |+| --- | --- |+| Temporary app-server supplemental failure | Use same-account stale cache with reduced UI opacity; do not trigger quota alerts or automatic redemption |+| Unsupported method | Cache missing capability for the session and probe again after rebuilding the connection |+| Missing historical Hook count | Retain `nil` in persisted and sync models; current display projection still falls back to counts |+| Live reader cannot obtain a stable boundary | Publish degraded health and pause Activity Protection |-### Menu Bar Anchors Must Be Validated+The source layer supplies these states; consumers determine whether to display data or perform effects. See [Hook Aggregation](hook-and-aggregation.md) for count projection and [app-server](app-server.md) for account caches.-When a global shortcut fires, the `NSStatusBarButton` may temporarily lack a valid window or be on another display. Showing a popover directly may position it incorrectly or not display it at all.+## Concurrency and Stale Results-The controller first validates the anchor size and screen intersection. If it is untrusted, it uses a fallback panel on the screen under the pointer. Both containers share the same SwiftUI content, so the business layer does not need to know which one is active.+| Mechanism | Protected scope |+| --- | --- |+| `MainActor` | UI, controllers, and observable-state commit ordering |+| Actors | Shared service state and I/O coordination within a process |+| `NSLock` and similar locks | Mutable state behind synchronous interfaces such as nonisolated pipe readers |+| `flock` | Shared-file transactions across Hook subprocesses, the main app, Debug, and Release |-### Schedule Only the Nearest Real Deadline+Configuration or readers may change while an asynchronous call runs. Noncancelable system callbacks validate their generation before committing. Cancellation controls task lifetime; generation checks establish result ownership.-Task expiration, completion highlighting, terminal grace, and stalled-task silence are not scanned by a high-frequency UI timer. The monitor gathers all deadlines, creates one `Task` for the nearest, then recalculates and schedules the next deadline when it fires.+Menu fade completion commits synchronously after checking cancellation, so it keeps one cancelable task. XPC, reader replacement, and wake recovery still require generations; their fields are documented in the corresponding topics.-This reduces meaningless wakeups while the menu bar app is resident and gives every retention period an explicit source in code.+Combine’s `@Published` emits during `willSet`. Combined-setting decisions use the new value delivered to the subscription instead of rereading a property that has not changed yet.-## How to Review a Design Change+## Rebuildable Data and Recovery Records-Before adding a feature or changing core semantics, answer these questions in order:+Raw Hook JSONL is the source for rebuilding history; daily aggregates are derived output. Aggregation-semantic changes increment the schema and rebuild retained history. `sourceGeneration` distinguishes file replacements: same-day, same-source data replaces a contribution, while independent sources add together.-1. Which flow supplies the new data, and what is its authoritative source?-2. Are missing data, old values, explicit zeroes, and failures distinct?-3. Is this repeatable state or a transition that may execute at most once?-4. When an asynchronous result returns, how does it prove that it still belongs to the current generation?-5. Does the change broaden network, persistence, CloudKit, or root-helper boundaries?-6. Does it affect old UserDefaults, local schemas, CloudKit records, or Debug and Release coexistence?-7. How does it recover from crashes, forced exits, system sleep, and file replacement?-8. Which logs distinguish expected degradation from real failure without exposing user data?-9. Which manual scenarios validate design invariants, not only the ideal path?+Activity Protection and helper ownership records recover state changes that have already occurred. Protection saves asynchronously and does not wait for disk before hiding a task. The helper persists recovery responsibility before changing system sleep state. See [Live Task Monitoring](activity-monitor.md) and [Sleep Prevention](sleep-prevention.md) for ordering.-If any answer remains unclear, the implementation does not yet have a complete lifecycle design.+## Privileged Operations and Upload Scope-## Invariants That Should Not Change Lightly+Task identification, Automatic Reset policy, and networking run in the main app. The root helper accepts only fixed sleep-lease and wake operations, validates client signatures, and reads back system results.-- Hook subprocess failure must not block Codex-- The three data flows remain independent-- `CodexActivityMonitor` is the sole source of live task state-- Bootstrap does not publish historical transitions-- `drainNow()` guarantees a new read barrier after the request-- Missing count fields are not interpreted as `0`-- Raw events are the rebuild source for aggregation caches-- Changes to aggregation semantics increment the schema and trigger a full rebuild-- The root helper gains no network access, arbitrary command execution, or additional file-read capability-- CodexBar may restore only sleep state it acquired itself-- Automatic Reset replaces or cancels only the `wake` event for CodexBar's fixed owner; it does not change other scheduled events-- Notifications that describe a system effect are sent only after the effect is confirmed-- Anonymous tasks do not participate in notifications, sleep prevention, or Stalled Task Protection-- Compatibility changes require a migration and degradation strategy before implementation+CloudKit syncs only daily aggregates. Raw events, session identifiers, account data, and proxy passwords remain local. Project display names are uploaded only after the user enables sync. See [Data and Privacy Boundaries](data-and-privacy.md) for fields and storage scope.diff --git a/Docs/en/DeveloperGuide/development.md b/Docs/en/DeveloperGuide/development.mdindex b0c772e..bc26262 100644--- a/Docs/en/DeveloperGuide/development.md+++ b/Docs/en/DeveloperGuide/development.md@@ -2,494 +2,115 @@[简体中文](../../DeveloperGuide/development.md) | English-## Requirements+## Environment and Build-- macOS 15 or later-- Xcode and the macOS SDK-- Swift 6 toolchain-- `swiftformat`-- `swiftlint`-- A working local Codex CLI or an app with bundled Codex--The project uses the `CodexBar` scheme. Routine builds do not require a Developer ID or notarization credentials.--## Project Structure--| Directory | Responsibility |-| --- | --- |-| `CodexBar/App` | App startup entry points |-| `CodexBar/Controllers` | AppKit lifecycle, menu bar, and window control |-| `CodexBar/Models` | Business DTOs, snapshots, and presentation models |-| `CodexBar/Services` | app-server, Hook, task, sync, notification, and system services |-| `CodexBar/Views` | SwiftUI interface |-| `CodexBar/Resources` | Plists, entitlements, localization, and resources |-| `CodexBarHelper` | Root LaunchDaemon |-| `Shared` | Shared XPC interface |-| `Config` | Version configuration |-| `Scripts` | Release and maintenance scripts |--## Recommended Order for Reading the Code--Do not infer business state backward from a view. Follow the facts:--1. Start in [`CodexBarApp.swift`](../../../CodexBar/App/CodexBarApp.swift) to see Hook subprocess branching-2. Read [`CodexBarAppDelegate.swift`](../../../CodexBar/Controllers/CodexBarAppDelegate.swift) for the normal-mode composition root-3. Read [`StatusItemController.swift`](../../../CodexBar/Controllers/StatusItemController.swift) for menu bar and window orchestration-4. Choose one flow and follow its source, service, snapshot, and view model-5. Then see how notifications or sleep prevention subscribe to upstream results-6. Finally, inspect how SwiftUI presents state and reports user intent--For live tasks:--```text-WorkflowHookEventRecorder- -> HookEventTailReader- -> CodexActivityMonitor- -> CodexActivitySnapshot / CodexActivityTransition- -> StatusItemController assembly- -> UI- -> CodexNotificationService- -> KeepAliveController-```--Finding authoritative state first prevents mistaking a UI cache, notification deduplication set, or controller intermediate state for a business fact.--## Define Five Things Before a Change--Before implementing anything beyond a purely visual change, answer at least these questions in design or development notes:--| Question | Example |-| --- | --- |-| Target fact | “The task is waiting for user approval,” not “show an orange dot” |-| Authoritative source | Hook event after reviewer confirmation |-| Derived consumers | Activity card, notifications, sleep prevention |-| Failure semantics | Pause evaluation while the reader is unavailable |-| Acceptance evidence | One transition, no bootstrap replay, reconciliation after recovery |--This step is not process for its own sake. It reveals when three side-effect consumers have assigned different meanings to one field.--## Where Common Changes Belong--| Change | Preferred location | Avoid |-| --- | --- | --- |-| app-server protocol method | `CodexStatus/` service and DTO | SwiftUI view |-| Raw Hook field | Recorder model and aggregation projection | Reading stdin directly into a CloudKit record |-| Live task transition | `CodexActivityMonitor` | Notification service inferring from history |-| Daily metrics presentation | `WorkflowViewModel` projection | View remerging raw events |-| System notification | `CodexNotificationService` | Button action or view lifecycle |-| Sleep-prevention condition | `KeepAliveController.sleepBlockReason` | Several UI computed properties |-| Window behavior | AppKit controller | Service or model |-| User default | Corresponding settings type | Scattered `UserDefaults.standard` calls |--Prefer extending an existing responsibility for a small change. Create a service only when a capability has its own lifecycle, state ownership, or failure boundary.--## Routine Checks--### Build--```bash-xcodebuild \- -project CodexBar.xcodeproj \- -scheme CodexBar \- -destination 'generic/platform=macOS' \- build-```--### Format+Requires macOS 15+, Xcode, Swift 6, `swiftformat`, and `swiftlint`. The only scheme is `CodexBar`, containing the app and `CodexBarHelper` targets. There is no XCTest target.```bash+xcodebuild -project CodexBar.xcodeproj -scheme CodexBar -destination 'generic/platform=macOS' buildswiftformat .-```--The project uses Swift 6 and four-space indentation configured in `.swiftformat`.--### Static Analysis--```bashswiftlint```-Rules are in `.swiftlint.yml`.+`.swiftformat` configures Swift 6 and 4-space indentation. `swiftlint` checks only `CodexBar/`, excluding `Shared/`, `CodexBarHelper/`, and `Scripts/`.-The repository currently has no XCTest target or coverage gate. Build, formatting, and lint do not replace manual validation of affected workflows.--### Recommended Check Order--```text-Inspect worktree scope- -> Complete the smallest implementation- -> swiftformat- -> Review formatting diff- -> swiftlint- -> xcodebuild- -> Targeted manual validation- -> git diff --check-```+Check `git status --short` before editing. With existing uncommitted work, format only Swift files touched by the change, or check with `swiftformat --lint . --cache ignore`. `swiftlint --no-cache` avoids cache writes.-Formatting before build ensures final validation covers the actual code intended for submission. If the repository already contains uncommitted user changes, do not format everything indiscriminately. Check scope first with `git status --short` and `git diff --name-only`, and format only touched Swift files when necessary.+Daily builds do not need Developer ID or notarization credentials. See [AGENTS.md](../../../AGENTS.md) for writing, Git, and compatibility rules.-`xcodebuild` checks Swift 6 concurrency, target membership, entitlements, and resource references. `swiftlint` checks style and some static rules. Neither validates AppKit focus, XPC crash recovery, or notification relevance.+## Implementation Entry Points-Even documentation-only changes follow the repository convention of formatting, linting, and building. Those checks do not validate documentation, so also check Markdown relative links, `git diff --check`, and the repository's Chinese-punctuation rules.--### Reading Build Failures--Find the first real `error:` rather than the final `BUILD FAILED`.--- An actor-isolation error usually indicates unclear state ownership; do not first suppress it with `nonisolated(unsafe)`-- For a missing file or resource, check target membership and Xcode project references-- A helper protocol error requires checking the app target, helper target, and `Shared` interface together-- For entitlement or signing errors, confirm whether the current identity is Debug or Release--Fix the first root cause and rebuild. Many later generic or module errors are cascading failures.--## Logging+| Feature | Main location | Implementation guide |+| --- | --- | --- |+| app-server, proxy, Automatic Reset | `Services/CodexStatus` and corresponding Settings | [app-server Data Flow](app-server.md) |+| Hook installation and statistics | `CodexHookSettings`, `WorkflowService`, aggregate models | [Hook Collection and Aggregation](hook-and-aggregation.md) |+| Live tasks and protection | `CodexActivityMonitor` and readers | [Live Task Monitoring](activity-monitor.md) |+| Sleep prevention and system wakes | `KeepAliveController`, `AutoResetWakeScheduler`, helper | [Sleep Prevention](sleep-prevention.md) |+| Notifications and sound | `CodexNotificationService`, notification Settings | [Notifications](notifications.md) |+| Sync | `WorkflowSyncService` and scheduler | [CloudKit Sync](sync.md) |+| Menus, windows, hot keys | `Controllers` and corresponding views | [UI and Lifecycle](ui-and-lifecycle.md) |-View Release system logs with:+`CodexBarAppDelegate` assembles long-lived objects. Add state to its existing owner where possible; views consume snapshots and emit action intents. See [Architecture](architecture.md) for source entry points.-```bash-/usr/bin/log stream \- --predicate 'subsystem == "app.zabrian.codexbar"' \- --style compact-```+## Change Review-The Debug subsystem has a `.debug` suffix.+Changes to persisted keys, schemas, identity computation, minimum OS versions, or version coexistence require explaining the impact and compatibility options, then waiting for the user’s choice. Review [Data and Privacy Boundaries](data-and-privacy.md) before adding networking, log fields, or CloudKit fields.-The in-app Logs window shows the latest 500 app-server interactions in the current process and helps diagnose CLI discovery, handshake, method unsupported, and retries.+Changes to aggregation algorithms, output semantics, or deduplication increment `WorkflowMaintenanceState.currentAggregationSchema` and rebuild from retained raw JSONL instead of adding field-level historical migrations.-### What a Log Should Answer+For asynchronous changes, check cancellation, commit eligibility, and generation. Cross-process files still need `flock`; actors protect only one process. `@Published` subscriptions use the closure’s new value rather than rereading old state during `willSet`.-A useful state-machine log should identify:+## Validation Workflow-- What triggered the operation-- Which state it intended to reach-- Which stage failed-- Which degradation or retry action followed-- Duration and processing scale+1. Review the change scope and preserve existing work+2. Format and run `swiftlint`+3. Build the app and helper+4. Manually verify affected normal, failure, and recovery flows+5. Review documentation and run `git diff --check`-The repository uses `LogTrigger`, `LogDuration`, and `LogFields.joined` for consistent fields. High-frequency polling logs only state transitions or result changes so no-op messages do not obscure real faults.+For build failures, find the first actual `error:`. Check Debug/Release identity for signing or entitlement errors, and both targets plus `Shared` for helper protocol changes. Compilation and static checks do not cover window focus, system authorization, or hardware power behavior.-Prefer stable English keys with controlled values, for example:+Documentation-only changes run format checks, lint, and build, plus relative-link and bilingual-content checks.-```text-trigger=wake want=0 reason=lowBattery elapsed=0.183s-```+### Manual Scenarios-Do not log notification bodies, full paths, identities, or tokens. If an error's `localizedDescription` may contain sensitive request data, classify the error before logging it.+| Change area | Key scenarios |+| --- | --- |+| Menus and windows | Rapid toggles, reopen during fade-out, popover/fallback, displays and Spaces, settings/log focus, notification clicks and hot keys |+| Hook and aggregation | Preserve handlers, minimum version, concurrent append, partial/corrupt lines, replacement/truncation, full rebuild |+| Live tasks | Bootstrap without replayed alerts, approval waits, late terminals, anonymous tasks, wake read-barrier failure and recovery |+| Notifications | Authorization denial/recovery, threshold crossing, cycle deduplication, withdrawal after progress, missing sounds |+| Proxy | First configuration, enable/disable, disable invalid data, delete corrupt records, cancel tests, rapid actions and failure rollback |+| Sync | First upload, multiple devices, offline recovery, partial upload failure, rebuild replacement, iCloud account changes |+| Power and helper | First approval, running/waiting transitions, low battery, duration limit, external sleep sources, abnormal exit and restart |+| Automatic Reset wakes | Replace schedules, disable/exit cleanup, connection loss, helper restart, clear before unregistering, fresh reads when due |-### Troubleshooting by Subsystem and Stage+Helper changes also require checking executable and plist placement inside the app, signatures, and registration fingerprints. Each feature guide lists more detailed state-transition scenarios.-| Symptom | First logs and state to inspect |-| --- | --- |-| Rate limits do not refresh | app-server handshake, method, retry, stale |-| Hook has no metrics | Hook configuration, recorder timeout, maintenance counts |-| Live task is stuck | Tail-reader generation, rollout reconciliation, data-source availability |-| Sync data is missing | Sync stage, local and confirmed counts, replacement dates |-| Notification does not appear | Authorization, kind, duplicate, or obsolete |-| Sleep prevention does not engage | Block reason, helper registration, XPC generation, source |-| Automatic Reset did not run | Target, threshold, retry window, helper registration, wake schedule |+Record the build, initial settings, action sequence, actual results, and relevant logs so validation can be reproduced.## Debug and Release-The configurations use separate identities:--| Configuration | App bundle ID | CodexBarHelper bundle ID |+| Configuration | App bundle ID | Helper bundle ID || --- | --- | --- |-| Release | `app.zabrian.codexbar` | `app.zabrian.codexbar.helper` || Debug | `app.zabrian.codexbar.debug` | `app.zabrian.codexbar.debug.helper` |+| Release | `app.zabrian.codexbar` | `app.zabrian.codexbar.helper` |-Do not mix configurations while diagnosing CodexBarHelper installation, LaunchDaemon state, or system approval.--The Hook handler binds to the current app executable path. When switching between Debug and Release, confirm that the installed handler points to the intended build.--### Why the Builds Still Share Some State--Separating bundle IDs prevents app, helper registration, and system approval from overwriting one another. Raw Hook data and Activity Protection must observe the same Codex work facts, however, and deliberately share files.--Shared state means:--- Writes require `flock`; actors protect only one process-- Schemas must remain interpretable while two versions coexist-- A changed identity-hash algorithm affects both builds-- Diagnosis must record which app writes and which helper controls the system--Do not temporarily isolate Debug by renaming its directory. That changes the product definition of its data source and hides real coexistence problems.--## Architecture Rules--### Startup Entry--`WorkflowHookEventRecorder.handleIfRequested()` must be the first work in app initialization.--`--hook-event` mode reads stdin, writes JSONL under a lock, and exits immediately. It initializes no UI, notifications, CloudKit, or long-lived services.--### MainActor--UI, controllers, view models, and settings use default isolation. Blocking file, subprocess, and network I/O belongs in actors or asynchronous services.--Shared mutable state belongs in an actor. Add concurrency declarations to DTOs and cross-actor value types where needed rather than disabling Swift 6 checks.--#### MainActor Is Not an I/O Queue--Default isolation clarifies UI state mutation; it does not permit synchronous file and subprocess work on the main thread.--Use this pattern:--```text-MainActor captures immutable input- -> Actor or async API performs I/O- -> Return a Sendable result- -> MainActor validates generation- -> Commit snapshot-```--Do not pass a mutable controller or non-Sendable AppKit object into a background closure. A cross-actor DTO should generally be a small value type. Use `nonisolated` to express that the type itself does not depend on an actor, not to bypass one access error.--#### Actors and `flock` Solve Different Problems--- An actor serializes tasks within one process-- `flock` coordinates the app, Hook subprocesses, Debug, Release, and other processes--An actor-safe read-modify-write can still be interrupted by another process. Conversely, `flock` alone does not protect in-memory state across actor reentrancy before and after `await`.--#### `@Published` Uses `willSet`--When a Combine sink receives a new value, the property on its publisher may still be old. For decisions based on the combined post-change state:--- Use the sink argument for the changing value-- Read other unchanged dependencies from the object-- Or publish one snapshot containing the complete new state--Sync activation and low-rate-limit threshold reevaluation depend on this rule. Replacing callback arguments with immediate property reads creates a one-frame inverted decision.--### Data Flows--Keep these flows independent:--- app-server account, rate limits, and usage-- Historical Hook aggregation-- Live tasks from `CodexActivityMonitor`--New UI may combine snapshots from all three, but one flow must not become an implicit prerequisite of another.--Combination belongs only in presentation or explicit business policy. A menu bar icon may show both a rate-limit bar and activity dot, but app-server failure must not stop activity monitoring, and Hook maintenance must not wait for CloudKit before publishing local metrics.--Write a truth table for any new cross-flow behavior. Sleep prevention is a legitimate example: it explicitly requires an operational Hook and a non-anonymous live task rather than acquiring the dependency simply because both objects happen to share a controller.--### Hook--- Preserve existing user and third-party configuration when changing handlers-- Enabling and validation require actual app-server version `0.145.0` or later-- Hook subprocess failure must not block Codex-- `SessionEnd` times out after 3 seconds; other events after 5 seconds-- `drainNow()` must preserve read-barrier semantics-- An unavailable source must not reuse an old snapshot for evaluation--When adding a Hook event, review:--1. Handler group and timeout in Codex configuration-2. Recorder allowlist fields and fail-open path-3. Forward and backward compatibility of raw JSONL decoding-4. Aggregation counts and missing semantics-5. Whether the live monitor consumes it-6. Whether CloudKit projection needs a field-7. Privacy documentation and logging fields--Not every event belongs in every layer. An explicit “not consumed” is easier to maintain than reliance on default decoder behavior.--### Aggregation--When the raw-event-to-aggregate algorithm, output fields, meanings, or deduplication rules change:--1. Increment `WorkflowMaintenanceState.currentAggregationSchema`-2. Fully rebuild from raw JSONL inside retention-3. Do not add field-level historical migration-4. Preserve the difference between missing and `0`-5. Mark current-device replacement dates in CloudKit--Increment schema when the same raw event produces semantically different output, not only when Codable can no longer decode. Even a deduplication fix requires rebuilding because old daily files already contain the incorrect result.--Full rebuild is preferable because raw JSONL is the fact source. Field-level migration must guess information lost by old algorithms and accumulates historical branches that cannot compose.--### System Power Control--- CodexBarHelper controls only fixed sleep state and Automatic Reset `wake` events-- CodexBarHelper gains no network or arbitrary-command capability-- CodexBar must neither claim nor restore external `SleepDisabled=1`-- Leases, watchdog, and owned persistence must all remain in place-- The Automatic Reset wake interface accepts only bounded timestamps; owner and event type are fixed by the helper-- Before exit, the app confirms sleep restoration and Automatic Reset wake-schedule cancellation--Before changing sleep prevention, write five sequences: acquire, release, timeout, crash, and external owner. Testing only normal toggling does not prove global system state is recoverable.--Before changing Automatic Reset wake scheduling, write six sequences: schedule, replace, cancel, connection loss, helper startup, and unregister. System read-back must prove that the fixed owner has exactly one matching event or none.--Every new helper method requires proof that root execution is necessary. Reads, network operations, and file work possible in the regular app must not enter the helper merely for reuse.--### Compatibility--Compatibility concerns include:--- Renamed or restructured persistence keys-- Local schema changes-- CloudKit record or field changes-- CodexBarHelper ownership format changes-- Automatic Reset wake-event owner or type changes-- Debug/Release shared identity-calculation changes-- Minimum system-version or API-availability changes--These affect old data, old apps, or Debug/Release coexistence and require migration and degradation design.--By repository policy, an implementer must not choose a compatibility outcome silently. Before changing anything, explain to the user:--- Affected versions and data scope-- Options to preserve old format, migrate once, rebuild fully, or discard explicitly-- Failure modes and future maintenance costs of each choice-- Whether old and new apps may run together-- How upgrade and, if necessary, downgrade will be validated--Implement only after the user chooses. Documentation should record the resulting invariant, not merely the migration steps.--## Common Change Recipes--### Adding a Setting--1. Define one key and its missing-value default in the corresponding settings type or controller-2. Define the value for upgrading users instead of relying on a coincidentally matching Swift property default-3. Connect changes to one reconciliation entry point-4. Do not let views write `UserDefaults` directly-5. Test first install, existing install, and immediate effect after toggling--### Adding a State Field--1. Classify it as fact, derived state, or presentation format-2. Put it in the model nearest the authoritative source-3. Define `nil`, empty, zero, and stale-4. Decide whether it changes Equatable snapshots-5. Check whether notifications, sleep prevention, and UI consume it-6. If persistence or sync is required, perform compatibility and privacy review first--### Adding an Asynchronous Refresh--1. Define trigger and freshness rules-2. Coalesce identical requests with single-flight or a coordinator-3. Add a generation for connection or source replacement-4. Revalidate current eligibility after every `await`-5. Define cancellation, timeout, and last-usable-snapshot behavior-6. Log only state change or final result--### Adding a Window or Side Panel--1. Decide whether it belongs to the menu interaction surface or is an independent auxiliary window-2. Reuse `HostingWindowController` or `MenuSideDetailPanel`-3. Add it to mutual-exclusion registration and extra hit regions-4. Handle multi-display visible frames and Spaces-5. Validate key focus, activation, and closing-animation intermediate states--## Validation by Change Type--### Menus and Windows--- Left-click, right-click, and Control-click behavior-- Dismissal after clicking outside the popover-- Side-panel hit regions and mutual exclusion-- Settings and Logs window focus-- Global shortcut and fallback panel-- Multiple displays and menu bar locations--### Hook and Aggregation--- Preserve existing handlers-- Reject enable when the version is insufficient-- Persist every event within its timeout-- File replacement, truncation, and cross-day reads-- Full rebuild after schema upgrade-- Missing fields do not display as `0`+Preferences and system approval are isolated by identity; Hook data and Activity Protection files are shared. Identify the running app, helper, and installed Hook executable path when debugging.-### Live Tasks+## Logs-- Running, waiting, completion, and termination transitions-- Automatic review does not enter waiting state-- Subagents belong to parent tasks-- Bootstrap sends no notifications-- Wake reconciles only after a new successful read-- Reader replacement discards old results--### Sync+Release system logs:-- Initial backfill-- Multi-device merge without duplicating current-device contribution-- Rebuild replaces only dates for the current device-- iCloud offline, account switching, and recovery-- Retention pruning--### Notifications--- System permission allowed and denied-- Threshold crossing and persistent deduplication-- Foreground presentation and click activation-- Missing custom sound fallback-- TUI and app notifications remain independent--### System Power and Helper--- CodexBarHelper and plist locations inside the app bundle-- App and CodexBarHelper signatures-- First-time system approval-- Running and waiting-for-approval transitions-- Low-battery and maximum-duration stops-- Coexistence with external `SleepDisabled`-- Recovery after normal and abnormal exit-- Confirmation every time Automatic Reset or sleep prevention is enabled, and remaining off after cancellation-- Confirmation copy for unregistered, awaiting-approval, and approved Helper states-- Automatic Reset options appear only while enabled and the Helper is approved-- Helper registration and system approval with Automatic Reset enabled-- Automatic Reset threshold and retry retain only the nearest `wake` event for the fixed owner-- Wake-event cleanup after Automatic Reset disable, target change, normal exit, disconnect, and helper restart-- The fixed-owner wake event is confirmed empty before helper unregister-- Debug and Release remain separated--## Recording Reviewable Manual Evidence--For every affected workflow, record at least:--- Whether the build is Debug or Release-- Initial settings and data state-- Action sequence-- Expected and actual UI-- Relevant log fields-- Whether restart, failure, and recovery paths were checked--For example, Hook wake recovery can record:--```text-Precondition: 1 non-anonymous running task, sleep prevention enabled-Action: Put the Mac to sleep and wake it after rollout writes terminal during sleep-Expected: Task ends after a new drainNow cycle succeeds, no bootstrap notification, helper lease released-Logs: trigger=wake, reader generation advanced, rollout reconciliation completed+```bash+/usr/bin/log stream --predicate 'subsystem == "app.zabrian.codexbar"' --style compact```-This is easier to reproduce during a future regression than “manual test passed.”+Debug uses `app.zabrian.codexbar.debug`; the helper subsystem uses its corresponding bundle ID.-## Definition of Done+The app’s Logs window retains the latest 500 app-server interactions. Proxy configuration errors use the system-log `settings` category; temporary proxy tests do not write interaction logs.-A change is complete only when:+| Problem | Inspect |+| --- | --- |+| Quota did not refresh | Handshake, method, retry, stale |+| Hook not working | Configuration, version, trust, completeness |+| Task did not finish | Reader generation, rollout reconciliation, source health |+| Missing sync data | Zone, fetch, upload, replacement, prune stages |+| Missing notification | Authorization, kind, duplicate, obsolete |+| Sleep prevention inactive | Block reason, helper registration, XPC generation, source |+| Automatic Reset did not run | Target, threshold, retry window, wake schedule |-- Code lives in the correct state owner without duplicating a second rule-- Normal, missing, stale, failure, and recovery semantics are explicit-- Concurrent requests have cancellation or generation boundaries-- Compatibility and privacy impact are confirmed-- Formatting, lint, and build pass for the change scope-- Affected workflows receive manual validation-- DeveloperGuide matches actual constants, schemas, and behavior-- `git diff` contains no unrelated user changes or accidental formatting+Logs use `LogTrigger`, `LogDuration`, and `LogFields.joined` for stages, classifications, counts, and elapsed time. See [Data and Privacy Boundaries](data-and-privacy.md) for request-content and identity restrictions.-## Release Scripts+## Release and Cleanup Scripts-These scripts require Developer ID, signing, notarization, or appcast credentials and are not for routine validation:+| Script | Purpose |+| --- | --- |+| `Scripts/build.sh` | Release archive, Developer ID export, notarization, stapling, and Gatekeeper checks |+| `Scripts/dmg.sh` | Package a DMG |+| `Scripts/appcast.sh` | Sign updates and generate the appcast |+| `Scripts/cleanup.swift` | Unregister helpers after all CodexBar instances exit; `--check` checks only, and `--debug` or `--release` limits scope |-- `Scripts/build.sh`-- `Scripts/dmg.sh`-- `Scripts/appcast.sh`+Release scripts require signing and notarization credentials and are not daily validation tools. The version comes from [`Version.xcconfig`](../../../Config/Version.xcconfig).-The version comes from [`Version.xcconfig`](../../../Config/Version.xcconfig).+Helper cleanup cancels and verifies an empty system wake schedule before unregistering; failure stops cleanup. See [Sleep Prevention](sleep-prevention.md).diff --git a/Docs/en/DeveloperGuide/hook-and-aggregation.md b/Docs/en/DeveloperGuide/hook-and-aggregation.mdindex bf65ee1..76a0732 100644--- a/Docs/en/DeveloperGuide/hook-and-aggregation.md+++ b/Docs/en/DeveloperGuide/hook-and-aggregation.md@@ -2,17 +2,6 @@[简体中文](../../DeveloperGuide/hook-and-aggregation.md) | English-## Design Motivation--The Hook flow serves two similar-looking goals with opposite requirements:--- Record facts as quickly as possible on Codex's critical path-- Maintain reliable long-term statistics in the main app--Capture must be small, bounded, and allowed to fail. Aggregation can run asynchronously and must detect file changes, repair damaged caches, and support full rebuilds.--The implementation therefore uses append-only raw JSONL plus rebuildable daily aggregations instead of making Hook subprocesses update a complex statistics object directly.-## Flow ResponsibilitiesThe Hook flow turns Codex lifecycle events into rebuildable local history:@@ -28,31 +17,11 @@ Codex HookRaw events are the fact source; daily aggregation is a rebuildable cache. A change to the aggregation algorithm or field semantics requires a full rebuild from raw events within retention.-### Why Hook Subprocesses Do Not Aggregate Directly--Reading and rewriting `daily.jsonl` appears to remove a file layer but creates four problems:--- Every Hook invocation decodes and rewrites history, so latency grows with event volume-- The subprocess runs within Codex's timeout budget, turning aggregation failure into task delay-- Algorithm upgrades lack raw facts for recalculation-- Concurrent Codex sessions can lose updates between read and rewrite--The current design reduces the critical path to one append. The main app aggregates in batches on its own schedule, and a failure leaves raw events for a later repair.--### Raw Facts and Cache Responsibilities--| File | Authoritative? | Recovery |-| --- | --- | --- |-| `events/YYYY-MM-DD.jsonl` | Yes | Append only; prune after retention |-| `daily.jsonl` | No | Fully rebuild from raw events |-| `maintenance.json` | No | Reconcile when missing or after schema change |-| `stats.lock` | Stores no business data | Coordinates cross-process transactions only |-## Installation and Validation-[`CodexHookSettings.swift`](../../../CodexBar/Services/Settings/CodexHookSettings.swift) reads and changes Hook configuration through app-server.+[`CodexHookSettings.swift`](../../../CodexBar/Services/Settings/CodexHookSettings.swift) reads and writes local `hooks.json` directly, reads or updates related configuration through app-server, and calls `hooks/list` after writing to validate installation.-Enabling requires:+The enable flow checks the following conditions, validating source, trust, and event completeness after writing:- A resolvable current executable path- Actual app-server version `0.145.0` or later@@ -72,21 +41,9 @@ Installation adds the CodexBar handler as a separate command within the existing`isEnabled` is the Hook's enabled state for the current process and is initially restored from an existing CodexBar handler. `isVerified` means the most recent app-server validation passed. The UI treats Hook as a working source only when `isOperable` is true.-### Why Installation and Validation Are Separate--A command in `hooks.json` proves only that configuration exists on disk, not that Codex will run it.--Execution may still be blocked when:--- The current app-server version is too old-- `features.hooks` is globally disabled-- The handler event set is incomplete-- app-server resolves another source file-- The handler is untrusted or modified+### Validation State-`isEnabled` is therefore the switch state for the current process, while `isVerified` is Codex's most recent explicit conclusion for the current source. Sleep prevention and task notifications depend only on their combined `isOperable` state.--A transient RPC failure means validation could not run this cycle, not that the handler became invalid. CodexBar preserves the last explicit conclusion while exposing the operation error for diagnosis.+A handler in `hooks.json` does not prove Codex will execute it. `isOperable` combines the enabled state with the last explicit validation result. Temporary RPC failures preserve the previous result and expose the operation error; unsupported versions, disabled global hooks, incorrect sources, trust failures, or incomplete events fail validation.### Reconciliation of an Enabled Hook@@ -115,11 +72,9 @@ Confirm running app-server >= 0.145.0-> Run hooks/list again for full validation```-Preflight checks happen before file changes. A failed version or global-feature check leaves the user's file byte-for-byte unchanged.-Trust matching requires both command and `sourcePath`. Command-only matching might trust the same command from another configuration; source-only matching might select the user's own handler.-### Why Disable Queries Trust Keys First+### Disable and Trust CleanupAn app-server Hook key comes from the handler it currently parsed. Removing the command from `hooks.json` first would make a later `hooks/list` unable to recover the corresponding key.@@ -127,11 +82,11 @@ Disable therefore saves keys for exact matches, removes handlers, then removes tA failed trust cleanup does not reinstall the handler. The UI reports that Hook is off but cleanup is incomplete because the user's intent to stop capture succeeded.-### Why Every Event Uses a Separate Group+### Event GroupsCodexBar does not insert commands into an existing user group. Separate groups make uninstall remove only its own handler without interpreting the composition of user matchers and other handlers.-Removal skips structurally malformed sibling entries instead of failing the entire switch. CodexBar recognizes its own command; it is not a global validator for the user's Hook configuration.+Removal skips malformed sibling entries and processes only precisely identified CodexBar commands.### Generations for Asynchronous Settings Operations@@ -189,13 +144,13 @@ The lock-wait budget is the handler timeout minus 2 seconds. Lock acquisition stInvalid stdin, lock timeout, or write failure is swallowed. A statistics failure in the Hook subprocess must never block Codex.-### Why It Still Returns Success+### Failure ExitHook metrics are supplemental to CodexBar and not required for Codex to finish a task. Returning a nonzero exit code after a parsing or disk error could turn one statistics failure into a user's Codex failure.After explicitly entering `--hook-event` mode, the process therefore reports handled and exits successfully regardless of input validity. Failure loses one statistic but never escalates into an upstream task failure.-### Why Event and Maintenance State Commit in One Lock Transaction+### Locked Event and Maintenance TransactionOne capture performs under the same `stats.lock`:@@ -211,7 +166,7 @@ If append and pending were separate lock transactions, the app could finish mainThe joint commit keeps “the file grew” consistent with “maintenance knows it must read.”-### Why Lock Waiting Uses Only Part of the Timeout+### Lock-Wait BudgetCodex waits at most 3 seconds for `SessionEnd` and 5 seconds for other events. The recorder caps lock waiting at total budget minus 2 seconds.@@ -219,7 +174,7 @@ The reserve covers encoding, append, saving maintenance state, and process exit.Waiting backs off exponentially from 1 ms to 20 ms. Normal app critical sections are short, so a small start resumes quickly after release, while the cap avoids busy looping under contention.-### Why the Lock File Uses One `open(O_CREAT)`+### Lock File CreationCode must not check for absence, create, then reopen. Two processes could create different inodes; after one replaces the directory entry, both would lock separate files and each believe it has exclusivity.@@ -235,7 +190,7 @@ Raw records retain only information required for statistics and live state:- Model and reasoning effort- Permission and approval reviewer- Session and turn IDs-- Agent and parent relationships+- Agent ID- Normalized `origin`For `UserPromptSubmit` and `PermissionRequest`, input may omit reviewer or effort. When needed, the recorder looks for a matching `turn_context` near the end of the rollout transcript.@@ -316,31 +271,17 @@ HookEvents/Raw events and daily aggregations are retained for up to 210 days. Detailed session and turn ID lists remain only for 3 days; older dates compact them to counts to reduce file size and identity retention.-### Why JSONL--JSONL matches this write pattern:--- The recorder appends one complete record to the tail-- One damaged line can be isolated instead of failing the whole file-- Files can rotate by day and be pruned by retention-- Individual structures remain inspectable during manual diagnosis-- Aggregation and remote caches can use the same line-level recovery strategy--A regular JSON array would rewrite tail structure on every append. A database would add schema, locking, and deployment complexity, while current queries only scan chronologically by date and gain too little from it.-### A Complete Line Is the Commit UnitThe reader advances only to the offset of the final newline. If a partial line is being written at the tail, the current cycle keeps its old offset and processes the line after a future cycle sees it complete.`JSONLines.decodeWithFailures` decodes per line. One malformed line increments the corrupt count without discarding valid events from the same read block.-### Why Identity Details Remain for Only 3 Days+### Identity CompactionSession and turn IDs support recent exact deduplication, while long-term presentation needs counts only.-Compacting identifiers to counts after 3 days reduces file size and identity retention. The aggregation model must record whether a field is retained or compacted; otherwise it cannot know whether later events can still use IDs for exact deduplication.--Raw events remain for 210 days and support a full algorithm rebuild. CloudKit never uploads these raw identities.+After 3 days, identifiers are compacted into counts. The accumulator chooses ID lists or counts in `finalized(identifierStorage:)`; `retained` and `compacted` select the output form and are not separately persisted mode fields.## Incremental Reading and Source Generations@@ -377,7 +318,7 @@ Maintenance combines four kinds of evidence:Inode and size detect replacement and truncation; the boundary hash detects an in-place rewrite at the same length.-### Why Boundary Hash Also Uses mtime+### Boundary Hash and mtimeRehashing every file across 210 days each cycle would hold `stats.lock` for too long and directly increase Hook recorder wait probability.@@ -385,7 +326,7 @@ Maintenance records nanosecond mtime from the last boundary validation. If inodeA normal append changes bytes only after offset, so the boundary continues to match and maintenance can aggregate incrementally. A changed boundary creates a new generation and marks it dirty.-### Why Build and Commit Are Separate+### Build and Commit ValidationThe aggregator cannot hold `stats.lock` while reading a full day because Hook subprocesses could time out repeatedly.@@ -434,9 +375,9 @@ A missing field differs from numeric `0`:- Missing means the historical source cannot provide this metric for the date- `0` means the source is available and explicitly observed none-Decoding and UI must preserve the distinction.+Decoding and persistence retain optional values. The `WorkflowDailyMetrics` display projection converts missing individual event counts to `0`; session and turn counts use deduplicated IDs or compacted counts first, then fall back to corresponding event counts.-### Why Paired Events Use `max`+### Paired Event Counts`PreToolUse` and `PostToolUse` describe the two sides of one tool call. Since the recorder may fail, either side may be absent:@@ -447,18 +388,13 @@ Decoding and UI must preserve the distinction.Compaction and subagent pairs follow the same rule.-If a future Hook protocol provides stable operation IDs, the algorithm can move to set deduplication, but that changes aggregation semantics and requires a schema increment and full rebuild.-### Carrying Availability Through Old DataOlder aggregations may not have a newer Hook count. Rebuild cannot assume that an old source captured an event merely because current code understands it.`WorkflowHookCountAvailability` records source availability for each count. Rebuild inherits an existing date's availability for old fields, while a fresh source can declare all current fields available.-The UI can therefore distinguish:--- Explicitly zero occurrences-- Historical capture for the date did not provide the metric+This availability is retained in aggregate and sync fields; the current UI does not display missing historical fields individually.## Schema Evolution and Rebuild@@ -487,18 +423,9 @@ A schema change usually marks all event dates in retention dirty. A source-generNeither can be replaced with the app version. One app version may not change aggregation, while development builds may iterate schemas without changing a version number.-### Why There Is No Field-Level Migration--`daily.jsonl` is a derived cache and raw JSONL remains available during retention. Migrating every historical field would retain both old and new algorithms and make mixed semantics more likely.--A full rebuild has a bounded one-time cost and guarantees:+### Rebuild Source-- Every date under one schema uses the same code-- Removed or redefined fields leave no residual values-- Damaged aggregate lines are repaired at the same time-- CloudKit replacement follows source generation consistently--Only when the raw source itself lacks a field does missing preserve the historical capability difference.+Aggregation-semantic changes rebuild from raw JSONL. Filling fields cannot recover identities or event relationships already lost in old aggregates. Missing semantics are retained when the raw source itself lacks the field.### Commit Semantics for a User Rebuild@@ -514,7 +441,7 @@ The operation fails as a whole only if every date fails. Partial success returnsMaintenance coordinates with the rate-limit refresh cycle but has no data dependency on it. The Workflow view model refreshes UI no more often than every 5 seconds to avoid rerendering for frequent file changes.-### Why No-Op Maintenance Does Not Emit Normal Logs+### Maintenance LogsMaintenance normally follows the 60-second refresh. An idle machine would otherwise emit more than a thousand no-change checks per day.@@ -532,19 +459,6 @@ After sync completes, an 8-second cooldown combines incoming requests and retainOpening the UI reads the current local snapshot and does not bypass the scheduler to start an unconditional CloudKit request.-## Steps to Add a Hook Event or Metric--1. Register the protocol name, configuration name, and handler timeout in `CodexHookEvent`-2. Ensure the recorder persists only minimal fields required for calculation-3. Update Hook-installation completeness validation-4. Define count and deduplication semantics in the accumulator-5. Update aggregate Codable and JSONL encoding while preserving missing semantics for old fields-6. Increment `WorkflowMaintenanceState.currentAggregationSchema`-7. Update CloudKit record schema and upload/download mapping-8. Decide coexistence with old apps and new records before changing compatibility formats-9. Update UI and privacy boundaries-10. Manually test normal append, a missing side of a pair, file replacement, and full rebuild-## Suggested Failure-Scenario Tests- Concurrent Codex sessions write complete lines without overwriting one another@@ -555,7 +469,7 @@ Opening the UI reads the current local snapshot and does not bypass the schedule- Inode change, file shrink, and boundary rewrite each create a new generation- Appends during build commit only to the fixed upper bound and leave the tail pending- A schema change rebuilds every in-retention date with the current algorithm-- Missing fields on old dates remain unavailable instead of becoming `0`+- Missing historical fields remain optional in decoding and persistence; display counts follow the current fallback rules- Disabling CodexBar Hook preserves user handlers and trust entries- During rapid Hook toggling, old RPC results cannot overwrite the final operationdiff --git a/Docs/en/DeveloperGuide/notifications.md b/Docs/en/DeveloperGuide/notifications.mdindex f25b305..1e6947e 100644--- a/Docs/en/DeveloperGuide/notifications.md+++ b/Docs/en/DeveloperGuide/notifications.md@@ -6,50 +6,14 @@[`CodexNotificationService.swift`](../../../CodexBar/Services/Notifications/CodexNotificationService.swift) is the single entry point for notification side effects.-It consumes three kinds of state:+It consumes four kinds of state:-- app-server account, rate-limit, and Reset Credits snapshots-- Task transitions and sleep-restoration events from `CodexActivityMonitor`-- Confirmed redemption results or user-facing failures from `AutoResetController`+- App-server account and quota snapshots+- `CodexActivityMonitor` task transitions and Activity Protection candidates+- `KeepAliveController` sleep-prevention restoration results+- `AutoResetController` confirmed redemption results or reportable failures-Views and other services do not create system notifications directly. They publish state changes; the notification service handles eligibility, deduplication, sound, and click behavior.--## Design Principles--A notification is not state. It is an external side effect triggered by a state change. A reliable notification requires all four conditions:--```text-The event occurred- + The user allows this category- + The event is still relevant- + It has not been sent in this lifecycle or persistence cycle-```--Centralizing these checks serves two purposes:--- Upstream components publish facts and transitions without knowing about system permission, sounds, or deduplication storage-- Every submission follows the same relevance checks, retry rules, and privacy-preserving logging--Direct notification delivery from a view could repeat after SwiftUI reconstruction, repeated panel openings, or snapshot republication. Views may change settings or display state, but cannot own notification side effects.--## Snapshots and Transitions Are Not Interchangeable--Different notifications require different evidence:--| Notification | Input | Reason |-| --- | --- | --- |-| Low rate limit | Consecutive trusted snapshots | Must compare values on both sides of a threshold |-| Rate-limit reset | Consecutive trusted snapshots | Must observe consumption before observing a return to zero |-| Reset Credits expiration | Current snapshot plus time scheduling | A future deadline triggers the reminder |-| Automatic Reset | app-server mutation result | Only an explicit result proves that this Mac performed the automatic action |-| Task completion | Monitor transition | Historical terminal snapshots must not replay |-| Waiting for approval | Monitor transition plus current snapshot | Notify on new waiting state, then withdraw stale notifications |-| Stalled Task Protection | A relevant candidate that has reached the silence threshold | Revalidate before notification submission and before hiding |-| Sleep prevention stopped | Confirmed system-restoration result | Must not announce success before restoration |--Inferring task completion from a current snapshot looks simpler, but every app launch would treat historical completed tasks as new events. Conversely, one transition alone cannot identify a low-rate-limit case when the app starts after the threshold was crossed.--## App Settings and System Authorization Are Separate Gates+## Settings and System Authorization`NotificationSettings` stores in-app intent separately from macOS authorization:@@ -59,7 +23,7 @@ Inferring task completion from a current snapshot looks simpler, but every app l| `authorizationStatus` | Whether macOS permits notifications || `canDeliver` | Effective eligibility when both allow delivery |-The master switch is off by default, so first launch does not present an unexplained permission request. CodexBar invokes the authorization API only after the user enables it.+The main switch defaults to off; system authorization is requested when the user enables it.The app rereads system state on app activation, when the settings window regains focus, and when settings are explicitly opened. A `denied` result preserves the in-app switch and displays a secondary-color permission message with an Open System Settings button. An actual `notDetermined` result turns the in-app switch off; enabling it again requests authorization. The initial placeholder status does not modify the saved switch.@@ -67,7 +31,7 @@ While an authorization request is pending, duplicate requests are suppressed andAfter the authorization request finishes, permission reads use the normal refresh flow. If another focus refresh arrives during a query, the new query replaces the old one so stale results cannot overwrite the latest permission state.-Haptic feedback does not depend on `UNUserNotificationCenter` authorization but still follows the in-app master switch. This is a capability boundary, not a way around user intent.+Haptic feedback does not depend on `UNUserNotificationCenter` authorization but still follows the in-app master switch.## Notification Switches@@ -93,15 +57,11 @@ Stalled Task Protection follows Prevent System Sleep. Its notifications requireA rate-limit reset notification requires observing a consumed window first and then a new window restored to an unconsumed state.-This prevents a notification merely because the first value seen after launch is 100%.-Observation state is isolated by account and rate-limit window. An account change does not carry the previous account's consumption state into the new account.Each window also has an in-session lifecycle token. A window that disappears from trusted snapshots and later returns receives a new token. If a failed submission callback for the old window arrives late, it restores `hasObservedConsumption` only if the token still matches.-This prevents a race in which app-server switches account or window while an old notification is submitting, then the late failure callback incorrectly marks the new window as previously consumed.--Reset observation is not persisted. After launch, the app must observe consumption again before notifying. It deliberately accepts missing an offline reset in exchange for never misreporting 0% usage as a reset at startup.+Reset state is not persisted. After each launch, the app observes consumption and a return to zero again; it does not replay resets that occurred while offline.## Automatic Reset@@ -110,7 +70,7 @@ An automatic reset operation and a rate-limit-window reset are separate events,- “Automatic Reset” means CodexBar's automatic action returned `reset` or `alreadyRedeemed`- “Rate Limit Reset” means a normal rate-limit snapshot first showed consumption and later returned to zero-One automatic reset may satisfy both, so the same Mac can receive both notifications. Similar wording is not a reason to merge them: one proves an automation action, the other represents the rate-limit lifecycle, and their sources and settings differ.+One automatic reset can satisfy both conditions, so one device may receive both notifications, each controlled by its own switch.The success body prefers a fresh post-redemption read of remaining reset credits, including an explicit `0`. If that read fails, the explicit success still stands and CodexBar sends a title-only notification.@@ -130,15 +90,11 @@ Success and failure share the Automatic Reset Notifications switch and sound, enAvailable thresholds are 5%, 10%, and 25%; the default is 10%.-A notification is sent only when remaining allowance moves from above the threshold to the threshold or below. Remaining in the low region does not repeat on each refresh.--The first trusted snapshot being below the threshold also counts as a downward crossing, covering app startup after the actual crossing.-The persisted deduplication key contains the second-level reset time returned by app-server. For the same account and rate-limit window, a reset time within 60 seconds of the recorded value belongs to the same cycle; only a difference greater than 60 seconds creates a new cycle.Returning above the threshold rearms crossing detection, but one reset cycle still notifies only once. After a new reset cycle begins, the next downward crossing may notify again.-### Why Detection Uses a Downward Crossing+### Threshold Crossing“Currently below 10%” is a persistent state. “Just dropped below 10%” is the notification event. For each `account + limit + window`, the service stores the previous remaining percentage:@@ -151,7 +107,7 @@ The settings subscription uses the new value passed to its callback. Combine pubA stale app-server snapshot neither advances the previous value nor triggers low-rate-limit or reset notifications. Old cache data supports display continuity but cannot prove a new side effect.-### Why Reset Time Allows 60 Seconds of Drift+### Reset Cycle MatchingAfter rebuilding an app-server connection, the same window's `resetsAt` may receive a seconds-level correction. Absolute equality would treat it as a new cycle and notify twice.@@ -163,7 +119,7 @@ When the number of Reset Credits is greater than `0` and an expiration date is aThe deduplication key includes account, expiration date, and days remaining. Multiple refreshes on one day do not repeat the notification.-The service does not create seven long-lived system pending requests. It schedules only the nearest future checkpoint, then recalculates from the current snapshot and schedules the next one when that point arrives.+The service schedules only the nearest future checkpoint, then recalculates from the current snapshot and schedules the next one.This handles:@@ -187,8 +143,6 @@ Anonymous tasks are not published to task-notification consumers. The notificatiMinimum completion duration is 30, 60, 120, or 300 seconds; the default is 60 seconds. A shorter completed task does not notify but may still appear briefly in the UI.-Filtering anonymous tasks again is defense in depth at the side-effect boundary, even though the monitor already omits their transitions. If a future upstream refactor or new transition type changes that guarantee, a task without a session ID still cannot produce a system notification or haptic effect accidentally.-Haptics start for every task transition. A new transition cancels the previous sequence of 10 pulses and begins again. Settings are rechecked before each pulse, so disabling haptics stops an old sequence immediately.## Waiting for Approval@@ -213,7 +167,7 @@ Relevance checks both before and after submission cover the asynchronous window.## Stalled Task Protection-When a non-anonymous running task reaches its silence threshold, Activity Protection records the candidate and starts notification submission alongside a 3-second grace period. When notification handling returns or the grace period expires, the monitor revalidates the candidate and hides the task if it remains relevant. Protection proceeds even if notification submission fails.+When a non-anonymous running task reaches its silence threshold, Activity Protection updates its in-memory record and schedules an asynchronous save, then starts notification submission and a 3-second grace period together. After notification handling returns or grace expires, the monitor revalidates the candidate before hiding it. Hiding waits for neither disk commit nor notification success.The notification identifier uses `taskID + attemptID`. Checks before and after submission compare progress generation and silence duration. New progress invalidates the protection attempt and withdraws its notification.@@ -221,12 +175,10 @@ Protection notifications use the system default sound and a `retryCount` of `0`## Sleep Prevention Stopped-When low battery or the duration limit stops sleep prevention, `KeepAliveController` first revokes the CodexBarHelper lease and waits for a read-back confirmation of `SleepDisabled=0`.+When low battery or the duration limit stops sleep prevention, `KeepAliveController` first releases its helper lease. It submits the notification only if the reply reports source `.codexBar` and `SleepDisabled=0`; other results clear the pending notice for that cycle.It submits the notification only after confirmation. The app idle assertion remains until notification submission completes, preventing a closed-lid Mac from sleeping before the notification reaches the system. The controller then releases the assertion and, if needed, issues a compensating lid-close sleep.-This ensures the copy describes a completed system-level restoration while giving asynchronous submission time to converge.-## Sounds[`NotificationSoundOption.swift`](../../../CodexBar/Services/Notifications/NotificationSoundOption.swift) combines three option groups:@@ -250,7 +202,7 @@ Sound options persist stable IDs rather than absolute file paths:- Bundled IDs are reserved in advance so a same-named local file cannot change the meaning of a saved choice after restart- An unresolvable saved ID falls back to system default-System default and silent choices cannot be previewed. Playing a system alert as a substitute for Notification Center's default sound creates a false expectation, so previews support only system and bundled sounds backed by explicit files.+System default and silent choices cannot be previewed. Preview is available for system and built-in sounds with a concrete audio file.## Haptic Feedback@@ -264,7 +216,7 @@ This separation lets a user disable banners while keeping consistent task hapticNotifications are submitted through `UNUserNotificationCenter`:-- One failed submission retries at most once+- Ordinary failed submissions retry at most once; Activity Protection notifications do not retry- Sent deduplication keys persist in UserDefaults- No more than 300 keys are retained- Keys include enough account or task scope to avoid suppressing different objects@@ -272,7 +224,7 @@ Notifications are submitted through `UNUserNotificationCenter`:Persistent deduplication prevents immediate repeats after restart but does not replace upstream terminal deduplication.-### Two Deduplication Layers Solve Different Problems+### In-Flight and Sent Deduplication`submittingDedupKeys` and `sentDedupKeys` cannot be merged:@@ -285,8 +237,6 @@ The deduplication check and `submitting` insertion happen synchronously before cA key enters the sent set only after `UNUserNotificationCenter.add` succeeds and the event is still relevant afterward. Recording it earlier would permanently consume an alert after one system submission failure.-The 300-entry cap prevents UserDefaults from becoming an unbounded event log. An old event could theoretically recur after eviction; that is accepted because upstream cycle identity and live-transition deduplication remain the first boundary.-### Shared Delivery SemanticsAll notification content eventually passes through the same `send` and `deliver` flow:@@ -298,7 +248,7 @@ Synchronously check deduplication-> Call the system notification center-> Check relevance again after submission-> Persist deduplication after success- -> On failure, retry at most once and run category cleanup+ -> Retry failures according to retryCount and perform classified cleanup (default 1, Activity Protection 0)```Logs record only `kind` and the failure reason, never title or body. Notification bodies may contain project names or task information and must not be copied into logs even when those logs remain local.@@ -307,26 +257,11 @@ Logs record only `kind` and the failure reason, never title or body. NotificatioCodexBar is an `LSUIElement`, so its notification-center delegate explicitly allows banners and sounds while the app is in the foreground.-Clicking a notification opens the main panel. The status-bar controller performs the action and reuses existing popover or fallback-panel logic.--The delegate explicitly returns banner, list, and sound for foreground presentation. An `LSUIElement` app often remains foregrounded or in unusual activation states; relying on default foreground policy would make notifications appear to disappear unpredictably.-Click handling calls `openMenuSurface` instead of constructing a new window. This reuses the popover when its anchor is valid, uses the fallback panel otherwise, and preserves the same focus and dismissal rules.-## Checklist for a New Notification Type--1. Identify whether its input is a snapshot, transition, or confirmed side-effect result-2. Define identity scoped to account, window, task, or attempt-3. Decide whether it needs session deduplication, persistent deduplication, and relevance checks-4. Define whether bootstrap, stale data, and anonymous tasks may trigger it-5. Choose sound and failure-retry semantics-6. Ensure sensitive fields from the body cannot enter logs-7. Define defaults and behavior for missing old UserDefaults values-8. Validate foreground display, click activation, and withdrawal after invalidation-## Codex TUI Notifications-The Codex TUI Notifications setting belongs to Codex itself and is read and written through app-server `config/batchWrite`.+Codex TUI notifications are Codex settings, read through app-server `config/read` and written through `config/batchWrite`.It is completely independent of CodexBar system notifications:diff --git a/Docs/en/DeveloperGuide/sleep-prevention.md b/Docs/en/DeveloperGuide/sleep-prevention.mdindex b9df5a7..7d0b2a5 100644--- a/Docs/en/DeveloperGuide/sleep-prevention.md+++ b/Docs/en/DeveloperGuide/sleep-prevention.md@@ -2,13 +2,7 @@[简体中文](../../DeveloperGuide/sleep-prevention.md) | English-## Design Goals--Sleep prevention must satisfy three goals at once:--- Prevent idle sleep while an eligible Codex task exists-- Restore system settings reliably after app exit, crash, or disconnection-- Never overwrite a system sleep setting already owned by the user or another app+## Control FlowThe regular app process owns policy and UI. CodexBarHelper executes only constrained system sleep and wake operations:@@ -27,9 +21,7 @@ AutoResetController-> IOPMSchedulePowerEvent```-## Why This Is Not an Assertion Switch--Sleep prevention looks like one Boolean setting but spans user intent, live tasks, power state, app lifecycle, and root system state. Any layer can change before another, so `isEnabled` cannot mean that system sleep is already disabled.+## State LayersState is split into four layers:@@ -40,14 +32,12 @@ State is split into four layers:| Request state | `appliedSleepPreventionRequested` and `requestInFlight` | What did the app most recently request from the helper? || Confirmed effect | `isPreventingSleep` and `sleepPreventionSource` | Has the app received evidence that system state matches? |-This distinction resolves two issues often hidden by UI:-- Temporary helper unavailability preserves the user's switch, allowing automatic recovery without requiring them to enable it again- UI does not claim success after an XPC request but before confirmation, avoiding disagreement with actual system state-`sleepBlockReason` is the sole decision output for all conditions. Derived UI state, condition logging, and actual switching read the same result. Every new condition must use a finite `switch` to state whether the settings entry remains available. This intentionally prevents omissions.+`sleepBlockReason` is the sole decision output for all conditions. Derived UI state, condition logging, and actual switching read the same result. Every new condition must state whether the settings entry remains available in an exhaustive `switch`.-## Why App Assertions and System Settings Coexist+## Two Layers of Sleep ControlThe mechanisms have different scopes:@@ -56,13 +46,11 @@ The mechanisms have different scopes:| IOKit assertion | App process | Prevents idle system sleep and optionally display sleep | Reclaimed automatically after app exit || `pmset disablesleep` | System-wide | Covers system-sleep paths not guaranteed by assertions | Requires explicit restoration, ownership, and a watchdog |-Assertions are cheap to recover but incomplete. `pmset` is stronger but can leave global state after a crash. CodexBar uses both and delegates high-risk global state to a least-privileged helper.-The app assertion is established before XPC acquisition begins so there is no idle-sleep gap while the helper switches state. A shared cleanup path releases it after helper failure, preventing a half-success known only to the app.-## Acquisition and Release Are Confirmed Transactions+## Acquire and Release Transactions-Acquisition does not optimistically change UI and patch system state later. It is verified:+Acquisition updates the effective state after system verification succeeds:```textConditions allow activation@@ -80,7 +68,7 @@ Release converges in the opposite direction:```textConditions block activation-> Ask helper to revoke lease- -> Helper restores system value only when owned and no leases remain+ -> Helper restores system value only when it has restoration responsibility and no leases remain-> App receives measured result-> Publish inactive state and release display assertion-> Stop duration accumulation@@ -89,11 +77,11 @@ Conditions block activation-> Compensate for lid-close sleep if needed```-Notifications come after the helper confirms `SleepDisabled=0`, ensuring that “sleep prevention stopped” describes fact rather than pending intent.+Low-battery and duration-limit notices are submitted only when the helper replies with source `.codexBar` and `SleepDisabled=0`.-The app idle assertion remains until notification submission ends. A closed-lid Mac may sleep immediately after global restoration; releasing the last assertion first could prevent the request from reaching the notification system. CodexBar then releases it immediately and compensates for the lid edge without reclaiming system ownership.+The app retains its idle assertion until notification submission finishes so the system does not sleep before submission. It then releases the assertion and applies lid-close sleep compensation if needed.-## Why `mayHaveHelperLease` Survives a Timeout+## Uncertain Lease StateAn XPC timeout proves only that the app received no reply, not that the helper did not execute the request. The helper may hold the lease while its reply was lost during disconnect.@@ -103,9 +91,7 @@ An XPC timeout proves only that the app received no reply, not that the helper d- Remain `true` after timeout or connection invalidation- Change to `false` only after an explicitly confirmed release-This may add one idempotent release during exit, but that is far cheaper than leaving global `SleepDisabled=1`.--## The Race Solved by Generation+## XPC Generation ChecksThe user may turn off the switch, a task may finish, and retry may start before an earlier XPC reply returns. Applying replies by arrival order could let old acquisition success overwrite newer release success.@@ -115,8 +101,6 @@ Both app and helper use monotonically increasing generations:- The helper ignores requests older than a lease's current generation- Invalidating a connection advances app generation so in-flight callbacks become stale-Generation is not a logging sequence number. It proves eligibility to commit asynchronous state.-## Activation Conditions[`KeepAliveController.swift`](../../../CodexBar/Services/KeepAlive/KeepAliveController.swift) establishes sleep prevention only when all conditions hold:@@ -233,14 +217,14 @@ Ownership rules prevent damage to external state:- If the initial observed value is already `1`, the helper marks it external- CodexBar does not claim external state-- CodexBar records owned only after personally completing `0 -> 1`-- Only owned state may restore to `0` when leases end+- After observing `0`, CodexBar persists owned before performing and verifying its own `0 -> 1` transition+- When the final lease ends, owned or restoring state restores to `0`Thus, `SleepDisabled=1` set earlier by a user or another tool remains on after CodexBar exits.-### How the Ownership File Forms a Recovery Transaction+### Ownership Recovery Transaction-Persistence deliberately favors recoverability:+The helper writes recovery records and system state in this order:```textAcquire: persist owned -> pmset 1 -> read back 1@@ -259,8 +243,6 @@ Release persists restoring first. A crash before `pmset 0` or final idle commit- If it disappears while a task remains, reacquire a lease and let the helper perform a new `0 -> 1`- If another valid client already made helper state owned, update source presentation without restarting the duration period-This avoids a subtle gap: another tool disables sleep first, so CodexBar reports external; that tool later restores sleep while the task still runs. Without observation, the UI would continue claiming prevention while the system could sleep.-## CodexBarHelper State PersistenceCodexBarHelper stores ownership at:@@ -276,7 +258,7 @@ Security and reliability requirements are:- Directory is not group- or world-writable- File is root-owned with `0600` permissions- Commits use a temporary file, full sync, and atomic rename-- If a trusted owned record cannot be read at startup, recover to `disablesleep 0`+- At startup, a missing record creates idle state; owned or restoring records restore `disablesleep 0`; unreadable or untrusted records also trigger restoration to `0`The file records CodexBar's ownership of system sleep settings.@@ -297,16 +279,16 @@ After abnormal exit, connection invalidation, the watchdog, and persisted ownersNormal app exit first cancels the Automatic Reset wake schedule, then revokes the lease and IOKit assertion. If the helper has not confirmed both root-state categories clean, app termination waits instead of leaving under uncertainty.-### Why Normal Exit Can Be Canceled+### Normal Exit`applicationShouldTerminate` cannot approve exit before confirmed release. `prepareForTermination()` stops new retries, cancels a possible Automatic Reset wake schedule, requests release of a possible lease, and waits for helper read-back:- Continue termination after successful release- Cancel this termination and resume normal condition evaluation and retries after failure-Canceling exit is stricter than simply closing, but it is part of recoverability. Normal exit is the app's only opportunity to confirm root global state actively and should not discard it. Forced exit still falls back to the helper's 15-second watchdog.+On forced exit, the helper revokes the disconnected client’s lease after the 15-second watchdog grace period.-### Helper Self-Check Is More Than Process Liveness+### Helper Self-ChecksThe helper checks leases, ownership records, and measured `SleepDisabled` independently:@@ -316,7 +298,7 @@ The helper checks leases, ownership records, and measured `SleepDisabled` indepe- On an untrusted persistence record, fail safe by restoring rather than treating corruption as permission to remain active- If Automatic Reset cancellation failed and no connection owner remains, reread and clean the fixed owner every 5 seconds-Periodic checks supplement event-driven XPC by repairing drift after another process changes settings, a callback is lost, or a process restarts.+Periodic checks repair state divergence after external writes, lost callbacks, or process restarts.## Duration and Battery Policy@@ -351,7 +333,7 @@ When low battery or duration limit stops prevention, notification must follow coThe task set uses stable task IDs to detect “new task” and “resumed from waiting,” not count alone. If one task ends as another starts, count remains one, but the new task deserves a full budget.-### Why Battery Reading Has Three States+### Battery Read StatesBattery reads use `unavailable`, `unreadable`, and `present` rather than one optional value:@@ -369,8 +351,6 @@ Battery use comes from power-source state, not `isCharging`. A connected Mac thaFor threshold `T`, protection enters while on battery at or below `T` and exits only at or above `T + 5`.-The five points are state-machine hysteresis, not a display adjustment. Without it, measurement noise near the threshold would repeatedly cause root writes, assertion switches, and notification checks.-Low-battery notification has a per-period latch:- Queue it only if CodexBar previously prevented sleep@@ -400,8 +380,6 @@ Compensation applies only to `.codexBar` source:- It must not request sleep while `SleepDisabled` remains `1`- It does not guess when clamshell state is unreadable-This repairs an edge event and cannot be replaced by merely reaching the correct final value.-## Failure and RetrySleep prevention uses bounded retries because each attempt reconstructs a privileged connection and may launch a root process:diff --git a/Docs/en/DeveloperGuide/sync.md b/Docs/en/DeveloperGuide/sync.mdindex 74b3149..72ac82b 100644--- a/Docs/en/DeveloperGuide/sync.md+++ b/Docs/en/DeveloperGuide/sync.md@@ -18,39 +18,17 @@ Local raw Hook JSONLAccount data, rate limits, total tokens, Reset Credits, Automatic Reset settings and state, live tasks, and sleep-prevention state do not sync.-## Goals and Non-Goals--Sync does not replicate one Mac's database. It safely adds independent contributions from multiple devices for the same day.--Its priorities are:--1. Do not upload raw work content or identities directly tied to hardware-2. Local metrics must remain displayable without CloudKit-3. Rescans and file replacement must not create duplicate counts-4. Preserve the last explainable remote snapshot during network failure-5. Retries must be idempotent rather than depending on exactly-once requests--The sync protocol explicitly excludes:--- Live task state, which changes quickly and requires low-latency local evaluation-- Account rate limits, which belong to the Codex account rather than device work history-- Automatic Reset, whose multi-device convergence uses a deterministic idempotency key for the same `creditId`, not CloudKit locks or task records-- Sleep-prevention state, which is a system side effect on the current Mac-- Raw events, because cross-device statistics need only mergeable daily facts--Placing sync after aggregation also improves maintenance: the raw Hook format can evolve independently while CloudKit sees a stable daily projection.--## Sources of Authority+## Data SourcesSynced presentation combines three kinds of values:| Data | Authoritative source | Offline behavior || --- | --- | --- |-| Current-device contributions for today and history | Local `daily.jsonl` | Continues updating live |+| Current-device contributions for today and history | Local `daily.jsonl` merged with same-source cloud cache by completeness | Local aggregation continues; cloud cache is retained || Contributions from other devices | Last successfully fetched records in `cache.jsonl` | Preserves the last snapshot || Upload confirmation and incremental position | `state.json` and `cursor.data` | Continues or rebuilds next time |-The current device is always local-first. Its CloudKit copy exists for other devices, not as truth for its own UI. This rule avoids a value appearing once locally and then doubling after a round trip to the cloud.+Current-device local aggregates and cloud copies are merged by source and completeness, counting each source once. The cloud can supply missing local data or a same-source aggregate with more events.The remote cache is a rebuildable projection, and the cursor is only an optimization. Any cursor failure can fall back to a full custom-zone read without requiring the user to delete local files.@@ -69,7 +47,7 @@ Private-database content belongs only to the current iCloud account and is neverThe custom zone is more than a namespace. It provides zone change tokens and deletion events so devices can sync additions, modifications, and deletions incrementally instead of scanning the entire private database each cycle.-Confirmed zone state and the account salt are cached in the actor across sync cycles, avoiding two fixed network round trips each time. Any sync failure invalidates both because an iCloud account switch may first appear as a request failure. Reconfirming next cycle is safer than continuing with the wrong account context.+Zone confirmation and account salt are cached in the actor across cycles. Sync failure invalidates both for the next cycle to reread.## Activation Conditions@@ -80,7 +58,7 @@ Sync runs only when all conditions hold:- The current iCloud account is available- The local aggregation service is available-First enable marks a backfill and uploads dates within local retention that need synchronization. Scheduling has a minimum 8-second cooldown to coalesce several local changes.+Each sync checks all dates within local retention and uses hashes to select data that needs uploading, so initial sync and subsequent backfill use the same flow. Scheduling has a minimum 8-second cooldown to coalesce several local changes.## Device Pseudonymization@@ -93,7 +71,7 @@ Sync must distinguish device contributions without uploading a raw hardware idenThe raw `IOPlatformUUID` is never uploaded. One device receives a stable pseudonym within one iCloud account and a different value in another account.-HMAC is used instead of plain SHA-256. Hardware UUIDs have a fixed input format, so a simple hash would remain stable across accounts. A private per-account salt makes the same hardware unlinkable across accounts.+The private account salt gives the same device a different pseudonym in each iCloud account.The salt lives in the same private custom zone. If several devices attempt initial creation, they converge on the existing record by reading it after a CloudKit conflict instead of keeping incompatible salts.@@ -156,9 +134,9 @@ Every stage writes a `stage` field to logs, so an error identifies zone, device,The upload loop checks its 20-second budget before each batch. A batch already in progress continues waiting for its result. Once the budget is exhausted, remaining dates wait for a later sync.-Stable JSON for each date is encoded and hashed once, and the same result drives filtering and success confirmation. Re-encoding in different phases could let dictionary order or optional fields make change detection drift.+Each date’s stable JSON is encoded and hashed once, reusing the result for pending-upload filtering and upload confirmation.-Uploads use `atomically: false`. On partial batch success, each CloudKit result is confirmed separately, while failed dates lose their local hash so they retry. The protocol relies on idempotent single-record identity rather than requiring all 25 records to succeed together.+Uploads use `atomically: false`, allowing partial success remotely. If any error occurs in a batch, the caller removes local confirmation hashes for every date in that batch and rechecks it next cycle. Confirmations from earlier completed batches remain, and successful remote writes are not rolled back.## Merge Semantics@@ -166,15 +144,15 @@ One day may have records from several devices plus a newer local result that theMerge rules are:-- Add contributions from other devices by field-- Replace the current device's same-source cloud contribution with its latest local aggregation-- Count a source generation at most once-- Add generations confirmed to represent independent sources-- Use a current-device cloud contribution only when local data is missing+- Add other-device contributions by field+- Use cloud contributions when the current device has no local aggregate+- Match sources by `sourceGeneration` or legacy-record content; use the cloud aggregate if it has more events, otherwise use local data+- If local source completeness is unconfirmed and no cloud record matches it, prefer existing cloud contributions+- Continue adding unmatched independent cloud sources-Replacing the current device's cloud value with its local value prevents double counting when sync just uploaded but the local UI was already updated.+`confirmedDates` includes both successful uploads and dates skipped by the upload decision; it does not guarantee field-for-field equality between local and cloud content.-### Why One Device Can Have Multiple Records for One Day+### Multiple Sources for One Device and DateLegacy record names contain only `deviceId + date`. New source records may use `deviceId + date + sourceGeneration`.@@ -196,11 +174,11 @@ Upload targets follow these rules:`sourceIsFresh` describes the completeness of the raw source for one read, not its timestamp. A newer timestamp is not more authoritative while a file is replaced, truncated, or awaiting stable-boundary confirmation.-### Why Missing Cannot Become Zero+### Missing Count FieldsAs the CloudKit record schema evolves, an old record may lack a new count field. `nil` means that device cannot provide the metric for that day; `0` means it explicitly observed zero occurrences.-Preserving availability during merge lets the UI distinguish “all devices total zero” from “some historical sources do not support this metric.” Decoding missing as zero creates a false fact that cannot be repaired later.+CloudKit decoding and persisted models preserve optional counts. The current `WorkflowDailyMetrics` display projection converts missing individual event counts to `0`; session and turn counts first fall back to their start or stop event counts, then to `0`. Unavailable daily statistics and a missing individual count are different UI cases.## Source Replacement and Rebuild@@ -213,7 +191,7 @@ When the user requests a rescan:This design limits a rebuild to correcting the current device's contribution.-### Why Replacement Is a Persistent Transaction+### Replacement TransactionRebuild and CloudKit synchronization may not finish in one process lifetime, so `replacementDates` persists in `state.json` instead of memory only.@@ -239,7 +217,7 @@ Sync state lives at:| File | Purpose || --- | --- |-| `state.json` | Sync schema, local hashes, backfill, and replacement state |+| `state.json` | Sync schema, local hashes, and replacement state || `cache.jsonl` | Cached daily aggregates from remote devices || `cursor.data` | CloudKit zone change token |@@ -259,7 +237,7 @@ The local `3 -> 4` read path rebuilds the remote cache before committing new staAny change to record fields, identity, or schema is a compatibility decision. It must account for old apps still writing, new apps reading old fields, and whether downgrade can overwrite new records—not merely increment a constant.-## Why the Scheduler Is Separate+## Sync SchedulerLocal maintenance and CloudKit sync share aggregation input but require different trigger rates. `WorkflowSyncScheduler` coalesces triggers into a single-threaded state machine.@@ -277,31 +255,19 @@ Important details include:- Disabling sync during a wait clears pending sync but still allows required local maintenance- `@Published` subscriptions run during `willSet`, when rereading the property returns the old value, so activation is calculated explicitly from the new callback argument-The last detail is easy to break while “cleaning up” Combine lifecycle code. Rereading settings appears simpler but would decide synchronization using the old value.-## Failure and Recovery Semantics-A sync failure neither rolls back independently confirmed records nor clears the last usable cache. The next cycle converges through hashes, record IDs, and idempotent CloudKit APIs:+A sync failure does not roll back remote writes or clear the last usable cache. The next cycle continues through hashes, record IDs, and CloudKit APIs:| Failure point | Preserved state | Next cycle || --- | --- | --- || Zone or account confirmation | Local aggregation and old cache | Reconfirm zone and salt || Incremental fetch | Old cache | Fall back to a full rebuild |-| Partial upload | Hashes for successful dates | Retry only unconfirmed dates |+| Partial upload | Hashes from earlier completed batches and successful remote writes | Recheck all dates in the failed batch || Replacement deletion | Replacement marker | Re-enumerate and delete idempotently || Prune | In-retention data and upload results | Prune later |-Account-level caches are invalidated after failure, but the disk cache is not immediately published as fact for a new account. The sync snapshot returns only after availability and device identity are confirmed again.--## Checklist for Sync Protocol Changes--1. Define field semantics first, especially whether missing, zero, and empty collections differ-2. Decide whether record identity remains idempotent-3. Evaluate concurrent writes by old and new app versions-4. Define upgrade or rebuild paths for local state, cache, and cursor-5. Confirm replacement can delete every old generation-6. Recheck privacy boundaries and explicit opt-in-7. Validate eventual convergence with two devices and an interrupted cycle+A sync failure invalidates the actor’s cached zone confirmation and account salt. The next cycle resolves account and device identity again; a change from the device identity stored locally rebuilds the remote cache.## Retention and Pruning@@ -314,7 +280,7 @@ CloudKit records share the local Hook-history retention period of up to 210 days## Error Classification-The sync layer distinguishes these states for Settings and notifications:+The sync layer distinguishes the following states for Settings and the main panel:- Network unavailable- iCloud account unavailablediff --git a/Docs/en/DeveloperGuide/ui-and-lifecycle.md b/Docs/en/DeveloperGuide/ui-and-lifecycle.mdindex bca8e28..916da22 100644--- a/Docs/en/DeveloperGuide/ui-and-lifecycle.md+++ b/Docs/en/DeveloperGuide/ui-and-lifecycle.md@@ -8,20 +8,7 @@ CodexBar is configured as an `LSUIElement` in [`Info.plist`](../../../CodexBar/RIt has no Dock icon or conventional main-window lifecycle. The menu bar, popover, floating panel, Settings window, and notification clicks must all manage app activation and focus explicitly.-Default SwiftUI `Window` behavior does not cover these cases, so the UI combines SwiftUI content with AppKit controllers.--## UI Responsibilities--SwiftUI declares content; AppKit owns window and event lifecycles:--| Layer | Responsible for | Not responsible for |-| --- | --- | --- |-| SwiftUI view | Layout, data presentation, callbacks for user intent | Creating long-lived services, choosing the key window, installing global event monitors |-| View model and settings | Publishing stable snapshots, saving user settings | Owning windows or evaluating screen coordinates |-| AppKit controller | Popovers, panels, windows, focus, event monitoring | Reimplementing business state machines |-| AppDelegate | Assembling and retaining long-lived objects | Specific view layout |--This boundary allows the same menu content to run in an `NSPopover` or fallback `NSPanel`, while preventing SwiftUI identity changes from destroying monitors, XPC connections, or notification services.+The UI declares content in SwiftUI and manages windows through AppKit controllers.## Three Kinds of Focus Under `LSUIElement`@@ -39,29 +26,18 @@ The code therefore does not treat `NSApp.isActive` as the sole truth for the men[`CodexBarAppDelegate.swift`](../../../CodexBar/Controllers/CodexBarAppDelegate.swift) is the composition root for normal mode. [`StatusItemController.swift`](../../../CodexBar/Controllers/StatusItemController.swift) is responsible only for the menu bar and related window orchestration.-AppDelegate:--- Creates long-lived services, view models, and settings-- Connects the monitor to notifications and sleep prevention, and assembles the Automatic Reset state machine-- Starts status refresh and Hook activity reading-- Creates the status-item controller-- Installs the global shortcut-- Configures Sparkle updates-- Coordinates Automatic Reset wake-schedule cancellation and sleep-prevention release during termination--The composition root retains these objects explicitly so SwiftUI view lifecycle cannot destroy long-running services accidentally.--### Why Startup Order Matters+### Startup OrderingNormal-mode assembly reflects dependency direction:```text-Create settings and data services- -> Build view models- -> Create status item and window controllers- -> Start notification and Automatic Reset side effects- -> Start activity monitoring and keep-alive coordination- -> Start periodic refresh and update services+Create settings, data services, view models, and updater+ -> Create and install StatusItemController+ -> Set up the status item, observers, and hot key+ -> Reconcile Hook and start periodic refresh+ -> Start notifications and automatic reset+ -> Connect Activity Protection callbacks+ -> Start the activity monitor and keep-alive coordination```Notifications and sleep prevention consume only snapshots or transitions already published by the monitor; they do not control readers upstream. Controllers connect these services through closures, keeping AppKit containers out of the service layer.@@ -75,10 +51,10 @@ The status icon combines app-server loading state, the menu bar rate-limit settiTask-status priority is:```text-Waiting for approval > Running > Recently completed > Recently terminated > Idle+Waiting for approval (orange) > Running (blue) > Within 30 seconds of completion (green)```-Rendered icons are cached by input state to avoid redrawing on every timed refresh. Inactive or unavailable state is expressed through alpha.+Recent termination, idle state, and expired completion highlights show no task dot. Icon output is cached by input state; inactive or unavailable states use reduced alpha.### Separating Image State from Tooltip State@@ -89,8 +65,6 @@ Rendered icons are cached by input state to avoid redrawing on every timed refre- A roughly 0.18-second, 10-frame animation starts only when the indicator dot or rate-limit bar appears or disappears- A new render state cancels the previous animation; every frame confirms that its target is still current-Redrawing `NSImage` from the complete state would interrupt animations and add menu bar work whenever timer text changes. Explicit render identity is a small but important performance boundary.-With no status dot or rate-limit bar, the icon remains a template image so the system colors it for light mode, dark mode, and menu bar state. Adding custom colors or a progress bar switches to explicit color rendering.The tooltip starts a 60-second timer only when a live task duration exists; it does not retain a permanent timer while idle. The app also sets `NSInitialToolTipDelay` to 500 ms so the status explanation for this small click target is easier to discover.@@ -110,7 +84,7 @@ CodexBar manages dismissal because:[`MenuSurfaceDismissMonitor.swift`](../../../CodexBar/Controllers/MenuSurfaceDismissMonitor.swift) observes global and local events. [`MenuSurfaceFadeCoordinator.swift`](../../../CodexBar/Controllers/MenuSurfaceFadeCoordinator.swift) coordinates closing animation.-### Why Opening and Closing Need an Explicit State Machine+### Open and Close State Machine`menuSurfaceState` has four states:@@ -127,7 +101,7 @@ They resolve intermediate states from rapid repeated clicks:Checking only `popover.isShown` cannot represent logical opening or fade-out state and cannot cover the fallback panel.-### Why One Monitor Owns Dismissal Rules+### Dismiss Event MonitoringThe allowed click region for the main panel is a set:@@ -145,21 +119,17 @@ Special rules include:- After a click, the code pins `NSVisualEffectView` back to inactive so AppKit background emphasis does not cause a brightness jump- After first installing observers, `Task.yield()` performs a second window acquisition and focus pass in case the popover window was not attached yet-Change these rules as a single interaction surface. Adding a separate event monitor to one side panel creates monitor-order and duplicate-dismissal problems.+### Fades and Completion Tasks-### Fade Content, Not the Window+`MenuSurfaceFadeCoordinator` animates both the active container’s content view and window opacity, with a 0.24-second fade-in and a 0.18-second fade-out. It stores one completion task, cancels it before starting a new animation, and checks cancellation after waiting before marking the surface shown or completing the close.-AppKit owns the popover's system window, so animating its alpha directly can conflict with system presentation state. `MenuSurfaceFadeCoordinator` animates the active container's content view, then calls the shared close operation.--Auxiliary windows temporarily reject `makeKey()` while closing. Otherwise, an already-open Settings or Logs window can jump to the front for a few frames during menu fade-out.+Settings and log windows temporarily reject `makeKey()` during closing and regain that ability about 120 ms after completion. The completion task holds a weak reference to that window and restores content and window opacity after closing.## Fallback PanelThe status-bar button's screen position may be unavailable or untrusted when a global shortcut fires. [`FallbackPanelController.swift`](../../../CodexBar/Controllers/FallbackPanelController.swift) then presents a floating panel on the screen under the pointer.-The popover and fallback panel host identical SwiftUI content and state. Business logic must not depend on the container type.--### Why the Anchor Needs a Trust Check+### Anchor ValidationA global shortcut may fire before status-item layout completes, while the menu bar is on another display, or when the system temporarily provides no button window. The code validates more than a non-`nil` button:@@ -184,8 +154,6 @@ These panels are mutually exclusive. Opening one closes the others. Each adds itAll detail panels implement `MenuSideDetailPanel` and register in the `sideDetailPanels` array. Mutual exclusion, main-surface closing, and hit testing all iterate over this one registry.-This scales better than encoding every pairwise close relationship. Adding a fourth panel requires one registry entry rather than six new mutual-exclusion pairs.-The hover-driven heatmap panel may fade before another panel opens; click-driven panels normally close the old panel immediately. This avoids two opposing slide animations at the same screen location.The heatmap detail panel uses the complete heatmap area, including its heading, date range, and square grid, as its vertical anchor. Reordering main-panel sections therefore still keeps their top edges aligned whenever possible. If the detail panel would extend below the main panel from that position, placement shifts it upward until their bottom edges align.@@ -201,9 +169,7 @@ Related controllers include:Separate `HostingWindowController` instances manage `NSWindow` for Settings and Logs.-When an `LSUIElement` app opens a normal window, it must temporarily allow that window to become key, activate the app, and transfer focus to the target control. Closing restores menu-bar-app foreground behavior.--Focus recovery waits about 120 ms for AppKit to finish window and activation transitions. This delay coordinates system lifecycle and cannot simply become a synchronous call.+When opening settings or logs, `HostingWindowController` allows the target window to become key and activates the app. `AuxiliaryHostingWindow` can become key but cannot become the main window.Context-menu actions wait until menu tracking finishes before running, avoiding window creation or activation inside AppKit's menu event loop.@@ -237,17 +203,17 @@ When a condition becomes false, Settings sends the corresponding `close` action`MainPanelSettings` stores the order and visibility of Account, Task Center, Quota, Token Usage, and Footer Status with stable section identifiers. Layout normalization removes duplicates, ignores invalid values, appends missing sections, and keeps at least one section visible. After reading a disabled Hook state, `StatusItemController` calls `updateHookEnabled(_:)` to persist Task Center as hidden. If Task Center was the only visible section, Account is enabled at the same time. The settings panel disables only the Task Center switch, so its drag handle remains available. Temporary availability of other data sources affects only the current rendering.-Layout sorting uses a custom `DragGesture` on each handle. A floating copy follows the pointer, while the other rows make room using a view-local preview order whenever the drag crosses half a row. Only after release does the view call `setSectionOrder(_:)` once to persist the final order. Do not replace this with system `.draggable` and `.dropDestination`, which reorder only after a drop target is hit and cannot provide continuous sorting animation.+Layout sorting uses a custom `DragGesture` on the handle. A floating copy follows the pointer, other rows move when it crosses half a row, and releasing calls `setSectionOrder(_:)` once to persist the final order.`SettingsWindowController` owns the only `UndoManager` for this window group. The Settings window exposes it through `AuxiliaryHostingWindow`, and each of the four settings child panels obtains the same instance from its parent when shown. `Command-Z` and `Command-Shift-Z` therefore operate on one layout history while focus is in either the Settings window or any child panel. Automatic Task Center changes caused by Hook state do not enter the user's undo history.-### The 120 ms Focus Recovery Is Not Business Delay+### Proxy Configuration Dialog-While the menu closes, `AuxiliaryHostingWindow` temporarily sets `allowsKeyFocus` to false. It waits about 120 ms after closing before restoring it.+`CodexBarAppDelegate` owns `CodexProxySettings` and injects it into Settings through the window controllers. `AppSettingsView` presents `ProxySettingsView` in a SwiftUI `sheet`, closing side settings panels first.-This gives AppKit time to complete popover order-out, activation, and key-window recalculation. Removing it may produce an intermittent Settings-window flash only on some machines; treat it as a system event-ordering constraint, not arbitrary wait time.+Without a configuration, clicking the row or toggle opens the dialog. With one saved, the row opens the dialog and the toggle independently enables or disables it. Presentation loads the draft from local preferences; dismissal cancels tests and clears the in-memory password draft. The top-right clear menu depends on whether a saved record exists and remains available when decoding fails.-Right-click menu actions also dispatch on the main queue after `menuDidClose`. Menu tracking is a nested event loop, and creating a window synchronously inside it produces unstable activation order.+In About, the reconnect button sits immediately after the Codex Versions title, with the source picker at the end of the row. Both are disabled during reconnection and refresh; Reconnect is also disabled when no source is available.## Global Shortcut@@ -269,38 +235,23 @@ Registration uses try-before-swap:2. Release the current registration only after the candidate succeeds3. On failure, clean up candidate resources and restore the previous setting-Unregistering first would leave the user without either shortcut after one conflict. `GlobalHotKeyRegistration` releases Carbon references in both explicit invalidation and `deinit` to avoid leaking handlers during reregistration.--At least two modifiers reduce accidental activation. Command-Space and Command-Tab are rejected because they are core system navigation shortcuts and should not be captured even if the registration API occasionally permits it.+`GlobalHotKeyRegistration` clears Carbon references on explicit invalidation and deinitialization.## Automatic Refresh and Panel Opening-app-server state refreshes every 60 seconds by default. Opening the panel schedules a refresh after about 160 ms so animation and focus transitions finish before data updates.--The main panel displays a countdown. A double-click triggers manual refresh, avoiding ambiguity between clicking the status item and invoking a button action.--The refresh coordinator merges concurrent triggers so the timer, panel opening, and user action do not issue duplicate requests.--When the panel opens, Hook metrics refresh immediately from local cache, while the app-server request waits about 160 ms. The former is cheap and fills content quickly; the latter may launch a process or make protocol requests, so deferring it reduces first-frame stalls.+App-server state is checked for refresh every 60 seconds by default. About 160 ms after the main panel opens, `refreshIfNeeded` requests data if no countdown origin exists or more than 60 seconds have passed since the last refresh result was committed. Both successful and failed results reset the countdown; this check can occur before fade-in finishes.-`refreshIfNeeded` still performs freshness coalescing; the 160 ms delay is not a second refresh path that bypasses coordination. If the panel closes while waiting, the task is canceled and no request runs for hidden UI.+The main panel shows a refresh countdown. Double-clicking the account icon requests an immediate manual refresh.-## Checklist for UI Lifecycle Changes+Ordinary refreshes are ignored while a refresh or reconnect is in progress. Operations requiring a follow-up use `refreshAfterCurrent` to retain one pending trigger and run it after the current request finishes.-1. Decide whether the change belongs to SwiftUI content or AppKit container lifecycle-2. Confirm that the popover and fallback panel behave identically-3. Test intermediate `opening` and `closing` states, not only stable states-4. Determine whether a click region belongs to the extra surface-5. Check whether app-active, key-window, and logical-presentation states can diverge-6. Ensure tasks and timers are canceled on close and uninstall-7. Test multiple displays, multiple Spaces, and an untrusted status-item anchor-8. Open the UI separately from a notification click, global shortcut, and right-click menu+Opening the panel immediately refreshes local Hook statistics. The delayed task also reconciles installed Hook configuration and is canceled if the panel closes while it waits.## Localization and FormattingSimplified Chinese and English interface strings are in [`Localizable.xcstrings`](../../../CodexBar/Resources/Localizable.xcstrings).-Dates, numbers, and percentages follow the system's automatically updating locale. Business models must not hard-code Chinese formatting or consume localized strings as state-machine inputs.+Percentages, durations, and some time displays use system regional settings. `CodexDateFormat` fixes date keys and ranges to `yyyy-MM-dd`; the settings page’s last-upload time and reset-credit details use local time in `yyyy-MM-dd HH:mm:ss`. Localized strings do not drive state-machine decisions.## Automatic Updates@@ -308,7 +259,7 @@ Dates, numbers, and percentages follow the system's automatically updating local- The appcast URL comes from app configuration- Automatic checks run every 3,600 seconds-- Settings and the context menu trigger update UI+- Update UI is triggered from settings and the main panel’s new-version notice- After an update, CodexBar checks CodexBarHelper fingerprint and registration state separately if the helper changedRelease scripts require Developer ID, signing, and notarization credentials and are not part of routine local builds.diff --git a/Docs/en/README.md b/Docs/en/README.mdindex 9ce7ccc..63537df 100644--- a/Docs/en/README.md+++ b/Docs/en/README.md@@ -2,60 +2,27 @@[简体中文](../README.md) | English-CodexBar documentation is split into two sets by audience and responsibility, keeping product instructions separate from implementation details:--| Document | Audience | What it covers |-| --- | --- | --- |-| [User Guide](UserGuide/README.md) | CodexBar users | Installing and using features, understanding settings, and resolving common issues |-| [Developer Guide](DeveloperGuide/README.md) | Contributors and code readers | How the app works, how data flows, and how to validate core constraints |--## Recommended Reading Paths--### Using CodexBar for the first time--1. Read [Installation and Quick Start](UserGuide/getting-started.md)-2. Learn about the [Main Panel and Menu Bar](UserGuide/main-panel.md)-3. Enable [Live Tasks and CodexBar Hook](UserGuide/activity-and-hook.md) if needed-4. Review automatic reset, sleep prevention, and other options in the [Settings Reference](UserGuide/settings.md)--### Troubleshooting--1. Start with [Troubleshooting](UserGuide/troubleshooting.md)-2. Check app-server request status in the app's Logs window-3. For local files or network boundaries, see [Data, Sync, and Privacy](UserGuide/sync-data-privacy.md)--### Reading or modifying the code--1. Start with [Architecture](DeveloperGuide/architecture.md) for a system-wide view-2. Continue to the data-flow or service guide relevant to your change-3. See [Development and Validation](DeveloperGuide/development.md) for build, debugging, and verification workflows-4. See [Data and Privacy Boundaries](DeveloperGuide/data-and-privacy.md) for local and cloud data scopes--## Directory Structure--```text-Docs/en-├── UserGuide-│ ├── README.md-│ ├── getting-started.md-│ ├── main-panel.md-│ ├── activity-and-hook.md-│ ├── notifications.md-│ ├── sleep-prevention.md-│ ├── sync-data-privacy.md-│ ├── settings.md-│ └── troubleshooting.md-└── DeveloperGuide- ├── README.md- ├── architecture.md- ├── design-decisions.md- ├── app-server.md- ├── hook-and-aggregation.md- ├── activity-monitor.md- ├── sleep-prevention.md- ├── sync.md- ├── notifications.md- ├── ui-and-lifecycle.md- ├── data-and-privacy.md- └── development.md-```+## User Guide++- [Installation and Quick Start](UserGuide/getting-started.md)+- [Main Panel and Menu Bar](UserGuide/main-panel.md)+- [Live Tasks and CodexBar Hook](UserGuide/activity-and-hook.md)+- [Notifications and Alerts](UserGuide/notifications.md)+- [Prevent System Sleep](UserGuide/sleep-prevention.md)+- [Data, Sync, and Privacy](UserGuide/sync-data-privacy.md)+- [Settings Reference](UserGuide/settings.md)+- [Troubleshooting](UserGuide/troubleshooting.md)++## Developer Guide++- [Architecture](DeveloperGuide/architecture.md)+- [Design Principles and Key Decisions](DeveloperGuide/design-decisions.md)+- [app-server Data Flow](DeveloperGuide/app-server.md)+- [Hook Collection and Historical Aggregation](DeveloperGuide/hook-and-aggregation.md)+- [Live Task Monitoring](DeveloperGuide/activity-monitor.md)+- [Sleep Prevention](DeveloperGuide/sleep-prevention.md)+- [CloudKit Sync](DeveloperGuide/sync.md)+- [Notifications](DeveloperGuide/notifications.md)+- [UI and Lifecycle](DeveloperGuide/ui-and-lifecycle.md)+- [Data and Privacy Boundaries](DeveloperGuide/data-and-privacy.md)+- [Development and Validation](DeveloperGuide/development.md)diff --git a/Docs/en/UserGuide/README.md b/Docs/en/UserGuide/README.mdindex f613b93..b0e9aed 100644--- a/Docs/en/UserGuide/README.md+++ b/Docs/en/UserGuide/README.md@@ -15,24 +15,9 @@| [Settings Reference](settings.md) | Every setting on the General, Advanced, and About pages, including Automatic Reset || [Troubleshooting](troubleshooting.md) | Sign-in, Hook, notifications, Automatic Reset, sleep prevention, sync, and logging issues |-## Find What You Need+## Common Names-- To view only your account and rate limits, start with [Installation and Quick Start](getting-started.md)-- To follow running tasks or tasks waiting for approval, read [Live Tasks and CodexBar Hook](activity-and-hook.md)-- To reset your rate limit automatically before banked resets expire, see [Automatic Reset](settings.md#automatic-reset)-- To keep your Mac awake during long tasks, read [Preventing System Sleep](sleep-prevention.md)-- To find out whether a setting uploads data, read [Data, Sync, and Privacy](sync-data-privacy.md)-- If you already see an error, go directly to [Troubleshooting](troubleshooting.md)+- CodexBar Hook: enables live tasks and daily activity statistics+- CodexBarHelper: the included background service for sleep prevention and Automatic Reset wakes-## Terminology--| Term | Meaning |-| --- | --- |-| Codex | Codex capabilities running through Codex CLI, ChatGPT App, or Codex App |-| app-server | The local Codex data-interface process that CodexBar launches and connects to |-| CodexBar Hook | The event handler that CodexBar installs in your Codex configuration |-| Live task | A running task or task waiting for approval, inferred from Hook events and local session state |-| Hook aggregation | Daily session, turn, tool, and other metrics calculated from local raw Hook events |-| CodexBarHelper | CodexBar's background service for system-level sleep-state changes and a fixed Automatic Reset wake schedule |--Back to the [CodexBar README](../../../README.en.md)+Back to the [CodexBar README](../../../README.en.md).diff --git a/Docs/en/UserGuide/activity-and-hook.md b/Docs/en/UserGuide/activity-and-hook.mdindex 723d98f..2ad4d64 100644--- a/Docs/en/UserGuide/activity-and-hook.md+++ b/Docs/en/UserGuide/activity-and-hook.md@@ -2,131 +2,43 @@[简体中文](../../UserGuide/activity-and-hook.md) | English-## What the Hook Provides+CodexBar Hook provides live task status, task notifications, haptics, task-based sleep prevention, and daily session, turn, and tool-call statistics. It also enables syncing and rebuilding those daily statistics.-Account, rate-limit, and token usage data are periodic snapshots. They cannot tell you whether a Codex task is running, waiting for approval, or finished.+## Enable Hook-CodexBar Hook records a small set of structured fields when key Codex events occur, enabling:+1. Open `Settings > Advanced`+2. Enable `CodexBar Hook` and wait for validation+3. Start a Codex task and check its status in the main panel-- Menu bar task-status dots and task details-- The main-panel activity card and Task Center for concurrent tasks-- Alerts for task completion, approval requests, and stalled tasks-- Haptic feedback for task events-- Daily metrics for sessions, turns, tool calls, permission requests, context compactions, and subagents-- Automatic sleep prevention based on live tasks-- Cross-device sync of daily Hook aggregations-- Rebuilding historical aggregations from raw events+Hook requires the Codex currently in use to be `0.145.0` or later. If the version warning remains after upgrading, click `Reconnect` in `Settings > About`. For other errors, see [Troubleshooting](troubleshooting.md#codexbar-hook-cannot-be-enabled-or-validated).-## Requirements+CodexBar automatically checks and repairs enabled Hook configuration. Enabling or disabling it preserves Hooks belonging to you and other apps.-Before enabling CodexBar Hook, make sure that:+## Task States-- CodexBar can connect to the currently running Codex app-server-- The running app-server version is `0.145.0` or later-- `features.hooks` is not disabled globally in the Codex configuration-- The current `hooks.json` is valid JSON--The version check uses the handshake version from the connected app-server, not a newly installed version on disk.--If CodexBar still reports an older version after you update Codex, click Reconnect under Settings > About.--## Enabling the Hook--1. Right-click or Control-click the menu bar icon-2. Select `Settings`-3. Open the `Advanced` page-4. Enable `CodexBar Hook`-5. Wait for configuration and validation to finish--CodexBar checks an enabled Hook at launch, when you open the menu or Settings, when the app becomes active again, and after each quota refresh. Automatic quota refresh normally completes every 60 seconds, and missing required event configuration or trust entries are repaired automatically.--## Configuration Changes--CodexBar uses `$CODEX_HOME/hooks.json`, or `~/.codex/hooks.json` when `CODEX_HOME` is unset.--When enabled, CodexBar:--1. Reads and preserves the existing configuration-2. Appends a separate command handler for CodexBar-3. Asks Codex to validate the event list, source, and trust status-4. Updates only trust entries that match the current CodexBar handler--When disabled, it removes only handlers that match both the current CodexBar executable path and the `--hook-event` argument.--Your own handlers, handlers from other apps, unrecognized fields, and unrelated trust entries are preserved.--## Understanding Task States--| State | Meaning | Active task? |-| --- | --- | --- |-| Running | The task is still making progress | Yes |-| Waiting for Approval | The task is waiting for you to approve its next action | Yes |-| Recently Completed | A task turn has been confirmed as finished | No |-| Recently Terminated | A task turn has been confirmed as terminated | No |-| Hidden | A running task exceeded the stalled-task silence threshold | No |--Completion means that a task turn ended; it does not necessarily mean that the result was successful.--Waiting for Approval applies only to approval requests that require user action. Automatically reviewed requests are not shown as waiting for you.--Subagent events update their parent top-level task instead of appearing as separate concurrent tasks.--Codex Auto-review uses a separate reviewer agent for permission review. CodexBar recognizes and excludes that internal review task, so it does not appear in the menu bar, activity card, or Task Center and cannot trigger notifications, haptics, Stalled Task Protection, or sleep prevention. Existing behavior for other subagents is unchanged.--Auto-review origin is identified from rollout metadata first. When rollout origin is unavailable, an exact `codex-auto-review` model match serves as the fallback. Live activity applies the same rule while reading local Hook records without backfilling or rewriting the raw records.--When a Hook event has no session ID, CodexBar shows an anonymous task for its project. Anonymous tasks can still appear in Running, Waiting for Approval, Recently Completed, and Recently Terminated lists, but they do not trigger task notifications or haptic feedback and do not participate in sleep prevention or stalled task protection.--The activity card and Task Center mark these tasks with an orange anonymous icon. Hovering over it shows `Anonymous tasks do not prevent sleep`.--## Hook Events and Their Uses--| Event | Primary use |-| --- | --- |-| `SessionStart` and `SessionEnd` | Session lifecycle and task finalization |-| `UserPromptSubmit` and `Stop` | Turn lifecycle, task start, and completion candidates |-| `PreToolUse` and `PostToolUse` | Tool-call metrics and task progress |-| `PermissionRequest` | User-waiting state and permission-request metrics |-| `PreCompact` and `PostCompact` | Context-compaction metrics and task progress |-| `SubagentStart` and `SubagentStop` | Subagent count, state, and task progress |--## How Daily Metrics Are Calculated--| Metric | Meaning |+| State | Meaning || --- | --- |-| Sessions | Distinct sessions in the day's events other than `SessionEnd` |-| Turns | Distinct turns in the day's events other than `Stop` |-| Tool calls | The larger of the `PreToolUse` and `PostToolUse` counts |-| Permission requests | Number of `PermissionRequest` events |-| Context compactions | The larger of the `PreCompact` and `PostCompact` counts |-| Subagents | The larger of the `SubagentStart` and `SubagentStop` counts |-| Most-used model | The model that appears most often in Hook events for that day |--Only nonempty session and turn IDs are counted and deduplicated within each day. A session or turn spanning multiple days contributes when that day contains another event; a session observed only through `SessionEnd` and a turn observed only through `Stop` do not contribute.--Using the larger count preserves observed operations when one side of an event pair is missing.+| Running | Codex is processing the task |+| Waiting for Approval | You need to approve the next action |+| Recently Completed | A turn ended; its result is not necessarily successful |+| Recently Terminated | The task was interrupted; no completion notification is sent |-Auto-review is excluded only from the live-task pipeline; its Hook events still contribute to these daily metrics.+Subagent activity is combined with its parent task. Internal automatic-review tasks do not appear separately or trigger task alerts or sleep prevention; their activity still contributes to daily statistics.-## Effects of Disabling the Hook+Tasks whose session cannot be identified show an orange anonymous icon. You can view them, but they do not trigger notifications or haptics, prevent sleep, or participate in Stalled Task Protection.-Disabling CodexBar Hook stops updates to:+[Stalled Task Protection](sleep-prevention.md#stalled-task-protection) may hide running tasks that stop making progress. They reappear when progress resumes.-- Live tasks and Task Center-- Menu bar task-status dots-- Task notifications and haptic feedback-- Daily Hook metrics-- Sleep prevention-- Cross-device sync of Hook aggregations+## Daily Statistics-Account data, rate limits, the token heatmap, update checks, and the Logs window remain available.+Hover over a day in the main panel heatmap to view sessions, turns, tool calls, permission requests, context compactions, subagents, and the most-used model.-## Data Boundaries+Sessions and turns are deduplicated within each day; activity continuing into another day counts toward that day. Paired records such as tool-call events may be incomplete, so statistics reflect the activity CodexBar actually observed.-Raw Hook events contain only structured fields such as time, event name, normalized `origin`, model, reasoning effort, approval mode, `reviewer`, `session`, `turn`, `agent`, tool name, and working directory.+## Disable Hook-CodexBar does not store rollout paths, raw source values, prompt text, Codex responses, tool arguments, or tool output.+Disabling Hook stops updates to live tasks, task notifications, haptics, sleep prevention, Hook statistics, and their cross-device sync. Account, quota, and token heatmap features remain available.-See [Data, Sync, and Privacy](sync-data-privacy.md) for complete storage and sync boundaries.+Hook records task information such as time, model, tool name, and project, without saving prompt, reply, or tool input/output content. See [Data, Sync, and Privacy](sync-data-privacy.md) for retention and sync details.-Back to the [User Guide](README.md)+Back to the [User Guide](README.md).diff --git a/Docs/en/UserGuide/getting-started.md b/Docs/en/UserGuide/getting-started.mdindex b21387c..d1d13f8 100644--- a/Docs/en/UserGuide/getting-started.md+++ b/Docs/en/UserGuide/getting-started.md@@ -6,8 +6,8 @@- macOS 15.0 or later- [Codex CLI](https://github.com/openai/codex) installed and signed in, or ChatGPT App or Codex App with bundled Codex installed-- The running Codex app-server must be `0.143.0` or later-- Hook features require the running Codex app-server to be `0.145.0` or later+- The Codex currently in use must be `0.143.0` or later+- Hook features require the Codex currently in use to be `0.145.0` or later- Cross-device sync requires an available iCloud account on the MacBy default, CodexBar automatically prefers a globally installed Codex CLI. If it cannot find one, it tries the Codex bundled with ChatGPT App and Codex App. You can select a source under Settings > About > Codex Versions > Source.@@ -56,21 +56,13 @@ CodexBar refreshes account, rate-limit, and token usage data every 60 seconds. DThe global shortcut opens the main panel on the screen under the pointer when possible. If the menu bar anchor is unavailable, CodexBar uses a standalone floating panel.-## Feature Dependencies+## Enable More Features-| Feature | CodexBar Hook | Other requirements |-| --- | --- | --- |-| Account, plan, and rate limits | Not required | Signed in to Codex; app-server `0.143.0` or later |-| Token totals and heatmap | Not required | app-server `0.143.0` or later |-| Live tasks and Task Center | Required | Hook validation has passed |-| Daily Hook metrics | Required | Local raw Hook events are available |-| Rate-limit notifications | Not required | System Notifications and macOS permission are enabled |-| Automatic Reset | Not required | Confirmation is required each time it is enabled; waking from system sleep and showing the lead-time options require approved CodexBarHelper access; lead time ranges from 15 minutes to 6 hours and defaults to 30 minutes |-| Task notifications | Required | Hook validation has passed and notifications are enabled |-| Prevent System Sleep | Required | Confirmation is required each time it is enabled; CodexBarHelper is registered and approved by macOS |-| Cross-device sync | Required | iCloud is available and sync is explicitly enabled |--Disabling CodexBar Hook does not affect account data, rate limits, the token heatmap, update checks, or the Logs window.+- [CodexBar Hook](activity-and-hook.md): live tasks, daily activity statistics, and task-based sleep prevention+- [System Notifications](notifications.md): task and quota alerts, requiring macOS notification permission+- [Automatic Reset](settings.md#automatic-reset): use banked resets shortly before expiration; may briefly wake your Mac+- [Prevent System Sleep](sleep-prevention.md): keep your Mac awake during long tasks, requiring background-service approval+- [Cross-Device Sync](sync-data-privacy.md): combine Hook statistics across Macs, requiring iCloud sign-in## Language and Region@@ -78,6 +70,4 @@ CodexBar provides Simplified Chinese and English interfaces. By default, it follTo choose a language specifically for CodexBar, use Language & Region in macOS System Settings.-Dates, times, durations, percentages, calendar layout, and the first day of the week always follow the current regional format.-Next, read [Main Panel and Menu Bar](main-panel.md) or the [Settings Reference](settings.md).diff --git a/Docs/en/UserGuide/main-panel.md b/Docs/en/UserGuide/main-panel.mdindex 2fc3839..4fb0cb7 100644--- a/Docs/en/UserGuide/main-panel.md+++ b/Docs/en/UserGuide/main-panel.md@@ -23,9 +23,7 @@ When rate-limit data comes from cache, the icon and progress bar become transluc## Layout Customization-In `Settings > General > Main Panel Layout`, you can drag the `Account`, `Tasks`, `Quota`, `Usage`, and `Status` sections into a different order and control each section's visibility.--The main panel always keeps at least one section visible. When Hook is disabled, the `Tasks` section turns off automatically and its switch is disabled, but the row remains draggable. If it was the only visible section, `Account` is enabled automatically. After Hook is enabled again, you can turn `Tasks` on manually. After reordering sections or changing their visibility, press `Command-Z` to undo changes in order and `Command-Shift-Z` to redo them.+Reorder and show or hide sections in `Settings > General > Main Panel Layout`, with undo and redo support. See [Settings Reference](settings.md#main-panel-layout).## Account@@ -34,9 +32,10 @@ The main panel always keeps at least one section visible. When Hook is disabled,- Double-clicking the account icon refreshes account, rate-limit, and usage data immediately- Double-clicking the email toggles blurring- Shows `Not signed in` when no account is signed in-- Shows `Initialization failed` when app-server cannot initialize+- Shows the minimum-version requirement when the Codex currently in use is too old+- Shows `Initialization failed` when the Codex connection cannot initialize-The main panel presents only states that help you decide what to do. Detailed request errors remain available in the Logs window.+The About page in Settings shows the connection failure reason; the Logs window provides complete requests and responses.## Rate Limits@@ -101,9 +100,9 @@ The card shows the following fields when available:When sleep prevention is actively engaged, a coffee-cup indicator appears on the right side of the activity card.-If a Hook event has no session ID, the task still appears in the activity card and Task Center with an orange anonymous icon. Hovering over the icon shows `Anonymous tasks do not prevent sleep`.+Tasks whose session cannot be identified show an orange anonymous icon with the tooltip `Anonymous tasks do not prevent sleep`.-The activity card's `+N` shows only the total number of other active tasks; it does not break out anonymous tasks separately.+The activity card’s `+N` shows the total number of other active tasks.Click a populated activity card to open Task Center.@@ -116,13 +115,9 @@ Task Center groups tasks into:- Recently Completed- Recently Terminated-Recently completed and recently terminated tasks remain in Task Center for 10 minutes. Completion and termination are distinct states.--Completion means that a task turn ended; it does not necessarily mean that the result was successful.--Terminated tasks do not trigger task-completion notifications.+Recently completed and terminated records remain for 10 minutes. Completion means a turn ended; termination means it was interrupted and does not trigger a completion notification.-Anonymous tasks use the same anonymous icon while running, waiting for approval, recently completed, or recently terminated.+Completion does not guarantee a successful result.## Footer Statusdiff --git a/Docs/en/UserGuide/notifications.md b/Docs/en/UserGuide/notifications.mdindex 3ec6efc..617670c 100644--- a/Docs/en/UserGuide/notifications.md+++ b/Docs/en/UserGuide/notifications.md@@ -19,14 +19,14 @@ System Notifications is off by default. Turning it off disables all CodexBar sys| --- | --- | --- | --- || Task completed | A task finishes after running for at least the selected duration | On, 1 minute | CodexBar Hook || Waiting for approval | A task starts waiting for user approval | On | CodexBar Hook |-| Low rate limit | A trusted rate limit reaches or crosses the threshold for the first time | On, 10% | None |+| Low rate limit | Remaining quota reaches the alert threshold | On, 10% | None || Rate limit reset | A rate-limit window previously observed as consumed returns to an unconsumed state | On | None || Banked resets expiring | Banked resets enter the 7-day expiration window | On | Available banked resets || Automatic Reset | An automatic reset explicitly returns success or reports that it already succeeded | On | Automatic Reset, its notification option, and System Notifications || Automatic Reset failed | Authentication failure pauses the task, a protocol error stops it, or this Mac explicitly observes expiration | Shares the success-notification setting | Automatic Reset, its notification option, and System Notifications || Low Battery Protection | Low Battery Protection successfully restores system sleep | On | Sleep prevention and Low Battery Protection || Keep-awake limit | The time limit is reached and system sleep is successfully restored | On | Sleep prevention and a finite time limit |-| Stalled Task Protection | A running task exceeds the silence threshold and the candidate is still valid | Fixed behavior | CodexBar Hook and Prevent System Sleep |+| Stalled Task Protection | A running task makes no progress for the selected protection interval | Fixed behavior | CodexBar Hook and Prevent System Sleep |Stalled Task Protection has no separate notification option and uses the default system sound.@@ -41,26 +41,17 @@ Anonymous tasks do not trigger completion, approval, or Stalled Task Protection| Minimum duration for completed tasks | 30 seconds, 1 minute, 2 minutes, 5 minutes || Low rate-limit threshold | 5%, 10%, 25% |-A low-rate-limit alert fires only when the remaining percentage moves from above the threshold to the threshold or below. It does not repeat on every 60-second refresh.--Restarting CodexBar does not repeat the alert within the same rate-limit reset cycle.+A low-quota alert fires when remaining quota drops to or below the threshold, including when the first reading after startup is already low. A known reset time is required, and each reset cycle is notified only once.Banked resets are checked for reminders at 7, 6, 5, 4, 3, 2, and 1 day before expiration.## Automatic Reset Notifications-“Automatic Reset” and “Rate Limit Reset” represent two independent facts:--- “Automatic Reset” means this Mac's automatic call returned `reset` or `alreadyRedeemed`-- “Rate Limit Reset” means a rate-limit window changed from consumed to unconsumed--One automatic reset can therefore produce both notifications. Neither replaces the other, and each follows its own trigger rules.+Automatic Reset sends alerts, subject to notification settings, when it succeeds or stops because of sign-in, configuration, or expiration issues. Temporary network failures retry in the background.-When several devices try at the same time, each device that receives an explicit success result sends its own success notification. A device that only sees the credit disappear during refresh does not notify because it cannot tell whether the credit was used manually, used by another device, or expired.+One reset may produce both “Automatic Reset” and “Quota Reset” notifications: one reports the operation result, the other the quota change. Success and failure share the Automatic Reset Notifications switch and sound.-Network errors, timeouts, and temporary service errors retry silently in the background. If authentication still fails, the current task pauses and resumes after a later trusted snapshot confirms recovery. A definitive protocol error stops the current task. If this Mac explicitly observes expiration, the task stops and notifies. If the credit simply disappears from server details, the task stops silently because the cause is unknown.--The same failure reason is reported at most once for a given credit; different reasons may be reported separately. Success and failure notifications share the `Automatic Reset Notification` option and sound. When Automatic Reset is off, this option is unavailable. Re-enabling the feature restores the previous notification and sound choices.+When multiple Macs try a reset, each device receiving success confirmation may notify. Devices that only discover the reset has disappeared do not notify. Each failure reason is reported at most once per banked reset.## Notification Sounds@@ -77,21 +68,19 @@ If a saved sound is unavailable on the current Mac, CodexBar falls back to the d## Haptic Feedback-When `Task Haptic Feedback` is enabled, the trackpad provides haptic feedback when a task finishes or starts waiting for approval.+`Task Haptic Feedback` is off by default. When enabled, the trackpad vibrates when a task finishes or starts waiting for approval.Haptic feedback does not require macOS notification permission, but it still follows CodexBar's System Notifications switch and CodexBar Hook status.## Codex TUI Notifications-`Codex TUI Notifications` changes `tui.notifications` in the Codex user configuration.--It is independent of CodexBar's local notifications. Enabling one does not enable the other.+This option controls Codex’s own notifications independently of CodexBar notifications.## Notification Interaction- Banners, Notification Center entries, and sounds still appear while CodexBar is in the foreground- Clicking any CodexBar notification opens the main panel- When a task is no longer waiting for approval, its waiting notification is removed from Notification Center-- When a stalled task resumes progress or its candidate becomes invalid, its protection notification is removed from Notification Center+- When a task resumes progress or no longer meets the Stalled Task Protection conditions, its notification is removed from Notification CenterBack to the [User Guide](README.md)diff --git a/Docs/en/UserGuide/settings.md b/Docs/en/UserGuide/settings.mdindex a33f496..4a2ae01 100644--- a/Docs/en/UserGuide/settings.md+++ b/Docs/en/UserGuide/settings.md@@ -2,190 +2,87 @@[简体中文](../../UserGuide/settings.md) | English-Right-click or Control-click the menu bar icon and select `Settings`, or press `⌘,` to open the Settings window.--Settings contains three pages: `General`, `Advanced`, and `About`.+Right-click or Control-click the menu bar icon and choose `Settings`, or press `⌘,`.## General Settings-| Setting | Effect | Default or initial state |+| Setting | Purpose | Default or initial state || --- | --- | --- |-| Main Panel Layout | Reorders and shows or hides the five main-panel sections | Account, Tasks, Quota, Usage, and Status; the Tasks section is off while Hook is disabled |-| Animation Effects | Animates the rate-limit bars and usage heatmap whenever the main panel opens | On |-| Launch at Login | Starts CodexBar automatically through macOS Login Items | Follows the current system Login Item state |-| Automatically Check for Updates | Lets Sparkle check periodically for updates | Follows the current Sparkle setting |-| Menu Bar Quota Indicator | Shows the remaining percentage for a selected rate-limit window beside the menu bar icon | Primary rate limit |-| Global Shortcut | Opens or closes the CodexBar main panel from any app | `⌘⇧W` |--### Menu Bar Quota Indicator--- Choose from the rate-limit windows returned by the current Codex installation-- CodexBar remembers the last selected window when you turn the indicator off-- Turning it on again restores the previous selection-- Cached rate-limit data is shown with reduced opacity+| Main Panel Layout | Reorder and show or hide Account, Tasks, Quota, Usage, and Status | All visible; Tasks is off when Hook is disabled |+| Animation Effects | Animate quota bars and the heatmap when opening the panel | On |+| Launch at Login | Start CodexBar when you sign in to your Mac | Follows the system login-item state |+| Automatically Check for Updates | Periodically check for CodexBar updates | Follows the current update setting |+| Menu Bar Quota Indicator | Show the remaining allowance in a selected window | Primary quota |+| Global Shortcut | Toggle the main panel from any app | `⌘⇧W` |### Main Panel Layout-Click the options button on the settings row to configure the `Account`, `Tasks`, `Quota`, `Usage`, and `Status` sections:+Click the options button to drag sections into order or toggle visibility, keeping at least one section visible. Use `⌘Z` to undo and `⌘⇧Z` to redo. Hiding a section does not stop its features.-- Drag sections to change their display order-- Use each switch to show or hide a section-- Keep at least one section visible-- Press `Command-Z` to undo section reordering or visibility changes in order, and `Command-Shift-Z` to redo them+Disabling Hook turns off Tasks; enable it manually after re-enabling Hook. If Tasks was the only visible section, Account is enabled automatically.-The `Tasks` section follows CodexBar Hook. When Hook is disabled, this section turns off automatically and its switch is disabled, but the row remains draggable. After Hook is enabled again, the section remains off until you turn it on manually.+### Menu Bar Quota Indicator-Hiding a section affects only the main-panel presentation. It does not stop rate-limit refreshes, Hook metrics, notifications, sleep prevention, or sync.+Choose the quota window to display. Turning the indicator off and back on restores the last choice. Faded data indicates cached quota.### Global Shortcut-- A recorded shortcut must contain at least two modifier keys-- System-reserved combinations such as `Command-Space` and `Command-Tab` cannot be used-- CodexBar reports combinations already used by another app as conflicts-- You can clear the shortcut-- You can restore the default `⌘⇧W`+A shortcut needs at least two modifier keys and cannot use `Command-Space` or `Command-Tab`. Conflicting combinations produce a warning. You can clear the shortcut or restore the default.## Advanced Settings-| Setting | Effect | Default |+| Setting | Purpose | Default || --- | --- | --- |-| CodexBar Hook | Installs and validates the Codex event handler | Off when not installed |-| System Notifications | Controls CodexBar local notifications and task haptic feedback | Off |-| Automatic Reset | Uses banked resets at the selected lead time before expiration | Off; 30 minutes early |-| Prevent System Sleep | Manages system sleep automatically based on live Codex tasks | Off |-| Sync Across Devices | Syncs daily Hook aggregations through iCloud | Off |-| Rebuild Data | Regenerates aggregations from local raw events for selected dates | Manual action |+| Proxy | Configure the proxy for CodexBar’s Codex service connection | Off |+| [CodexBar Hook](activity-and-hook.md) | Enable live tasks and daily activity statistics | Off if not installed |+| [System Notifications](notifications.md) | Configure notification types, thresholds, sounds, and haptics | Main switch off |+| Automatic Reset | Use banked resets shortly before expiration | Off, 30-minute lead time |+| [Prevent System Sleep](sleep-prevention.md) | Keep your Mac awake while eligible tasks run | Off |+| [Cross-Device Sync](sync-data-privacy.md) | Combine daily Hook statistics through iCloud | Off |+| [Rebuild Data](sync-data-privacy.md#rebuild-data) | Recalculate Hook statistics for selected dates | Manual |-### CodexBar Hook+### Proxy-Enabling the Hook unlocks live tasks, task notifications, Hook metrics, sleep prevention, and cross-device sync.--Enabling and validating it requires the current app-server to be `0.145.0` or later.--See [Live Tasks and CodexBar Hook](activity-and-hook.md) for details.--### System Notification Options--| Option | Default | Other choices or notes |-| --- | --- | --- |-| Task Completion | On, 1 minute | Minimum duration: 30 seconds or 1, 2, or 5 minutes |-| Approval Requests | On | Requires CodexBar Hook |-| Low Quota | On, 10% | Threshold: 5%, 10%, or 25% |-| Quota Reset | On | Recognized only after consumption has been observed |-| Reset Expiration | On | Alerts for banked resets expiring within 7 days |-| Automatic Reset Notifications | On | Available only while Automatic Reset is enabled; success and failure share one sound |-| Low Battery Alert | On | Applies only when Low Battery Protection is available |-| Keep-Awake Limit | On | Applies only when the maximum duration is not unlimited |-| Task Haptics | Off | Provides trackpad feedback when a task finishes or waits for approval |-| Codex TUI Notifications | Follows the Codex configuration | Independent of CodexBar notifications |+Click the setting row and enter a server address and port. HTTP, HTTPS, hostnames, IPv4, and IPv6 are supported; ports must be within `1–65535`. Authentication requires a username; the password may be empty.-Each system notification can use the default sound, no sound, a system sound, or a built-in app sound.+An HTTP proxy can forward HTTPS requests. Select HTTPS only if the proxy port itself supports TLS with a valid certificate.-See [Notifications and Alerts](notifications.md) for details.+- `Test Connection` checks unsaved settings and can be canceled; it does not save or enable the proxy+- `Save` applies the configuration; after the first save, enable the switch on the setting row+- `Cancel` discards this edit+- `⋯ > Delete Configuration` removes the configuration and password and disables the proxy, even if the saved configuration is damaged+- Turning off the row’s switch retains the configuration for later use-### Confirmation for Automatic Reset and Sleep Prevention--Every transition of `Automatic Reset` or `Prevent System Sleep` from off to on shows a confirmation dialog. The dialog first shows guidance based on the current CodexBarHelper state, then explains the selected feature:--| CodexBarHelper state | Confirmation message |-| --- | --- |-| Not registered or file missing | `CodexBar Helper must be installed and authorized to run in the background` |-| Installed but awaiting macOS approval | `CodexBar Helper is installed but still needs authorization to run in the background` |-| Installed and approved | Shows only the feature description |--Feature descriptions are:--| Feature | Confirmation title | Description |-| --- | --- | --- |-| Automatic Reset | `Enable Automatic Reset?` | `When enabled, CodexBar automatically uses a manual reset credit at the configured time before it expires and may briefly wake your Mac.` |-| Prevent System Sleep | `Enable System Sleep Prevention?` | `When enabled, CodexBar prevents system sleep while Codex tasks are running and restores normal sleep afterward.` |--Selecting `Enable` saves your intent and attempts to register CodexBarHelper. Selecting `Cancel` leaves the switch off. System Settings for Helper approval opens only through the `Open System Settings` button below an enabled settings row; the button appears while CodexBarHelper is awaiting approval. No status explanation appears below either row while its switch is off.+Passwords are hidden until you hover over the field. The proxy affects only CodexBar’s Codex service connection, and its password is stored locally in plain text. See [Data, Sync, and Privacy](sync-data-privacy.md).### Automatic Reset-When Automatic Reset is enabled and CodexBarHelper is installed and approved, an options button appears on the right side of the main row. Open it to choose a `Time Before Expiration` of `15 Minutes`, `30 Minutes`, `1 Hour`, `2 Hours`, `4 Hours`, or `6 Hours`; the default is `30 Minutes`. The entry is hidden if the Helper state no longer qualifies, and any open Automatic Reset side panel closes.--- Processes only available banked resets explicitly listed in the latest app-server response-- Revalidates the account, credit state, and expiration time before every use-- Processes only the earliest-expiring credit at a time-- Attempts to register CodexBarHelper after confirmation; even if Prevent System Sleep is off, CodexBar may need approval to run in the background under Login Items & Extensions-- Shows CodexBarHelper approval, registration, registration-failure, or wake-schedule synchronization status on the Automatic Reset row-- If a future task exists, CodexBarHelper registers one system wake event for the nearest threshold or retry; the schedule is canceled when the task changes, the feature is disabled, or the app exits, and a schedule left by an abnormal exit is removed the next time the helper starts-- At the scheduled time, prevents idle system sleep only while it rereads and uses the credit; it does not wake the display or enable Prevent System Sleep-- Rechecks immediately after a natural system wake or the next app launch; it retries if the credit is still inside its lead-time window and has not expired, otherwise it reschedules for that window-- Schedules a retry wake only after reading a specific credit and expiration time; continuous retries last no more than 5 minutes per round, while later normal rate-limit refreshes can try again-- Does not consume anything when no reset is currently available, and reuses the same idempotency key throughout that 5-minute round-- Preserves the credit's idempotent identity and reschedules when the server changes its expiration time-- Pauses or stops the current task on authentication failure or a definitive protocol error, with a system notification when notification settings permit--When several Macs enable Automatic Reset, each schedules independently but derives the same idempotency key for the same `creditId`. The first device to succeed consumes the credit. Other devices stop after receiving an already-successful result, or stop silently after a refresh shows that the credit disappeared.+Automatic Reset uses banked resets shortly before expiration. Every enable action requires confirmation. If the background service needs approval, click `Open System Settings` below the row and allow CodexBar to run in the background.-After success, CodexBar sends an “Automatic Reset” notification. A regular “Quota Reset” notification comes from a change in the rate-limit window, so both may appear. Automatic Reset itself does not depend on System Notifications; it still runs when notifications are off but does not show a result notification.+Once enabled and CodexBarHelper is approved, use the options button to choose a lead time of `15 Minutes`, `30 Minutes`, `1 Hour`, `2 Hours`, `4 Hours`, or `6 Hours`. The default is `30 Minutes`.-The `Automatic Reset Notifications` side-panel option controls both success and failure notifications and configures one sound for both. When Automatic Reset is off, the option appears off and disabled without overwriting your saved notification and sound choices.+- Processes the earliest-expiring available reset first, rechecking sign-in and availability before use+- May briefly wake your Mac without lighting the display or enabling Prevent System Sleep+- Retries temporary failures for up to 5 minutes per round; later refreshes may try again+- Rechecks unexpired resets when the Mac wakes or the app restarts+- Cancels scheduled wakes when disabled or when the app quits+- Multiple Macs trying the same banked reset do not consume it multiple times-This setting is stored only on the current Mac and is not synced through CloudKit.--### Prevent System Sleep Options--When Prevent System Sleep is enabled and CodexBar Hook is available, an options button can appear on the right side of the main row. The entry remains visible when there is no eligible task, CodexBarHelper is refreshing, Low Battery Protection is active, or the maximum duration has been reached. It is hidden when an eligible task exists but CodexBarHelper is unavailable.--| Option | Default | Choices |-| --- | --- | --- |-| Keep Awake While Waiting | Off | On or off |-| Keep Display Awake | Off | On or off |-| Keep-Awake Limit | 12 hours | 1, 2, 4, 8, 12, or 24 hours; unlimited |-| Stalled Task Protection | 1 hour | 30 minutes; 1, 2, or 4 hours |-| Low Battery Protection | Off | Off; 5%, 10%, 15%, 20%, or 25% |--Low Battery Protection does not appear on Macs without a built-in battery.--See [Preventing System Sleep](sleep-prevention.md) for details.--### Sync Across Devices--- Can be enabled only when CodexBar Hook is on and iCloud is available-- On first enable, uploads daily local Hook aggregations within the retention period-- Settings shows sync status and the most recent successful upload time-- Turning it off stops network sync but keeps local Hook data--See [Data, Sync, and Privacy](sync-data-privacy.md) for details.--### Rebuild Data--- The date picker allows only dates within the raw Hook-data retention period-- Dates with raw events are marked-- Rebuild becomes available only after a complete range is selected-- A confirmation appears before rebuilding-- The result shows the number of rebuilt days, parsed events, and skipped invalid lines-- Incomplete dates retry automatically when the Hook is available+Automatic Reset runs independently of notifications. Configure result alerts in [Notification Options](notifications.md#automatic-reset-notifications). Its settings apply only to the current Mac.## About-| Item | Purpose |+| Item | Action or meaning || --- | --- |-| Source | Located beside the Codex Versions heading; Automatic is always available, while Codex CLI and Codex APP appear only when detected as installed |-| Reconnect | The connector icon next to the source selector establishes a new connection using the selected source and its installed version |-| Codex CLI | Shows the on-disk version and path of the global Codex CLI |-| Codex APP | Shows the on-disk version and path of the CLI bundled with ChatGPT App or Codex App |-| In Use | Identifies the Codex source and running app-server version currently in use |-| Unavailable | An orange badge in the status position when the current, selected, or failed refresh source can no longer be detected |-| CodexBar Version | Shows the current version, update status, and any available update |-| GitHub Project | Opens the CodexBar project page |-| Check for Updates | Runs a manual Sparkle update check |-| Quit CodexBar | Completes required cleanup before quitting the app |--If Codex has been updated on disk but the current app-server has not reconnected, About shows the newly installed version as well.--Update hints share the semantic version parser used by minimum-version checks: a stable release takes precedence over its prereleases, build metadata does not affect precedence, and unrecognized versions do not produce an update hint.--The default source is Automatic, which prefers CLI and uses the app's bundled Codex when CLI is not installed. Source options only show detected installations. Version rows normally show installed sources; if the current, selected, or failed refresh source is uninstalled, its row remains with Unavailable replacing In Use, without a duplicate source-unavailable message below. This badge means a new connection cannot be opened from that source, not that the old connection has stopped. Changing the source connects immediately and saves the choice only after success. Failure preserves the previous connection and choice. If a previously selected source is uninstalled, the picker shows “Select Source” without falling back to another source.--Automatic reconnection remains enabled: once a connection is one hour old, the next request rebuilds it using the selected source. Reconnect applies an installed update sooner. Older CodexBar versions ignore the source preference and retain their original automatic selection behavior.--Hover over the connector icon to see “Reconnect”; the tooltip changes to “Reconnecting” while connecting. The icon keeps animating through reconnection and the following refresh, while both controls remain disabled. Success updates In Use; a missing source shows Unavailable, while other failures display a reason below the version rows.--Click an executable path to copy the full path.--Back to the [User Guide](README.md)+| Source | Automatic selection prefers Codex CLI, then Codex bundled with ChatGPT App or Codex App; manual selection is also available |+| Reconnect | Reconnect using the selected source; use after upgrading Codex to switch immediately to the new version |+| Codex CLI / Codex APP | View detected versions; click a path to copy it |+| Currently Using | Source and version used by the current connection |+| Unavailable | A previously used or selected source can no longer be found |+| CodexBar Version / Check for Updates | View the version and check for updates |+| GitHub Project | Open the project page |+| Quit CodexBar | Exit the app |++Source selection is temporarily disabled while connecting. Connection failure reasons appear below the version area to help you troubleshoot or choose another source.++Back to the [User Guide](README.md).diff --git a/Docs/en/UserGuide/sleep-prevention.md b/Docs/en/UserGuide/sleep-prevention.mdindex 9aed702..a4750a5 100644--- a/Docs/en/UserGuide/sleep-prevention.md+++ b/Docs/en/UserGuide/sleep-prevention.md@@ -1,128 +1,63 @@-# Preventing System Sleep+# Prevent System Sleep[简体中文](../../UserGuide/sleep-prevention.md) | English-## Purpose+CodexBar can keep your Mac awake while tasks run and restore sleep when tasks finish or a protection condition takes effect.-When macOS enters system sleep, Codex tasks running on that Mac may be suspended.+## Enable and Activate-CodexBar manages system sleep automatically based on live task state, allowing long tasks to continue unattended and restoring normal system behavior when tasks finish or a protection rule is triggered.+1. Enable CodexBar Hook in `Settings > Advanced`+2. Enable `Prevent System Sleep` and confirm+3. If background approval is required, click `Open System Settings` and allow CodexBar to run in the background-This feature is not a general-purpose switch that keeps your Mac awake indefinitely.+Sleep prevention requires CodexBar to be running, Hook and its background service to be available, and an eligible task to exist. Low battery or the duration limit stops it; when conditions recover, task state determines whether it resumes. The coffee cup in the main panel indicates that sleep prevention is active.-Enabling it only allows CodexBar to manage sleep automatically. CodexBar does not change system sleep when no eligible task exists.--## Activation Conditions--CodexBar prevents system sleep only when all of the following are true:--1. CodexBar is running and is not quitting-2. `Prevent System Sleep` is enabled-3. CodexBar Hook is installed and passed the latest explicit validation-4. At least one non-anonymous task is running, or `Keep Awake While Waiting` is enabled and a non-anonymous task is waiting-5. CodexBarHelper is registered and approved by macOS-6. CodexBarHelper is not being updated-7. Low Battery Protection is not active-8. The current keep-awake period has not reached its limit--If any condition becomes false, CodexBar stops its own sleep prevention.--If the conditions recover while an eligible task still exists, sleep prevention resumes automatically.--Anonymous tasks do not count as eligible, even when shown as running or waiting for approval.+Anonymous tasks and tasks hidden by Stalled Task Protection do not prevent sleep.## Options-| Option | Effect | Default | Choices |-| --- | --- | --- | --- |-| Keep Awake While Waiting | Tasks waiting for your approval continue to prevent sleep | Off | On or off |-| Keep Display Awake | Also prevents display sleep, the screen saver, and idle screen locking | Off | On or off |-| Keep-Awake Limit | Limits accumulated time that sleep is actively prevented in one period | 12 hours | 1, 2, 4, 8, 12, or 24 hours; unlimited |-| Stalled Task Protection | Hides tasks with no progress for an extended period and removes their contribution to sleep prevention | 1 hour | 30 minutes; 1, 2, or 4 hours |-| Low Battery Protection | Restores system sleep when running on low battery | Off | Off; 5%, 10%, 15%, 20%, or 25% |--Low Battery Protection does not appear on Macs without a built-in battery.+Click the options button beside the sleep-prevention setting:-## Keep Awake While Waiting--When this option is off, a task stops supporting sleep prevention after it moves from Running to Waiting for Approval.--When it is on, sleep prevention continues while the task waits for approval.--Approval requests have no natural timeout, so an unattended Mac may stay awake for a long time. The Keep-Awake Limit still applies.--Stalled Task Protection evaluates only running tasks, not tasks waiting for approval.--## Keep Display Awake+| Option | Purpose | Default | Choices |+| --- | --- | --- | --- |+| Keep Awake While Waiting | Remain awake while waiting for your approval | Off | On or off |+| Keep Display Awake | Prevent display sleep, screen saver, and idle locking | Off | On or off |+| Keep-Awake Limit | Limit cumulative sleep prevention in one cycle | 12 hours | 1, 2, 4, 8, 12, or 24 hours; unlimited |+| Stalled Task Protection | Hide running tasks that stop making progress | 1 hour | 30 minutes; 1, 2, or 4 hours |+| Low Battery Protection | Restore sleep at low charge while on battery | Off | Off; 5%, 10%, 15%, 20%, or 25% |-This option takes effect only while CodexBar is already preventing system sleep.+Low Battery Protection is hidden on Macs without a built-in battery.-CodexBar also prevents display sleep and periodically declares user activity to suppress the screen saver and idle screen locking.+## Waiting and Display Wake-It releases these effects when tasks finish, Low Battery Protection activates, the time limit is reached, or sleep prevention fails.+By default, only running tasks prevent sleep. Enabling the waiting option keeps the Mac awake while approval requests are unattended, until the duration limit is reached or task state changes.-Because this may leave the screen unlocked while you are away, the option is off by default.+Keep Display Awake works only while sleep prevention is active and may leave the screen unlocked after you step away.## Keep-Awake Limit-- Counts only time during which system sleep is actively prevented-- Excludes time paused because of low battery, unavailable CodexBarHelper, or another condition-- Does not count time spent in system sleep or changes to the system clock-- Resets when there are no active tasks-- Starts a new period when a new running task appears or a waiting task resumes running-- Restores system sleep when the limit is reached, until the next task period begins+Only time actually preventing sleep is counted; pauses and system sleep are excluded. A new running task or a waiting task returning to running starts a new cycle. No active tasks resets the timer. Reaching the limit restores sleep until the next task cycle.## Stalled Task Protection-Stalled Task Protection handles tasks that have stopped making real progress but still appear as running because no reliable terminal state is available:+A running task with no progress for the selected duration is hidden from the activity card and Task Center and stops preventing sleep. New progress restores it. Increasing the threshold also restores tasks that no longer exceed it.-- Follows the Prevent System Sleep switch and has no separate on/off switch-- Evaluates only non-anonymous running tasks-- Uses Hook events, subagent events, and local session lifecycle as progress signals-- Saves a protection record, attempts a notification, and hides the task when the threshold is reached-- Removes hidden tasks from the activity card and Task Center and excludes them from sleep prevention-- Restores a task automatically and withdraws any active notification when new progress appears-- Restores hidden tasks that no longer exceed the threshold after you select a longer threshold-- Pauses evaluation during Hook history replay, system sleep, wake reconciliation, or Hook data-source outages-- Keeps protection records for no more than 24 hours after the last progress+Protection follows the main sleep-prevention switch and evaluates only non-anonymous running tasks, not tasks waiting for approval. Evaluation pauses during startup recovery, system sleep, and temporary task-data unavailability.-Protection records contain only hashed task identifiers and timestamps. They do not contain raw `session` or `turn` IDs, project names, or task content.+If notifications are enabled and authorized, CodexBar attempts an alert. Notification failure does not block protection.## Low Battery Protection-- Applies only while the Mac is running on battery power-- Restores system sleep when the battery first reaches or falls below the selected threshold-- Remains active until the battery rises 5 percentage points above the threshold-- Clears immediately when the Mac is connected to power-- Resumes sleep prevention automatically if an eligible task remains-- Sends a low-battery notification only after CodexBar successfully stops its own sleep prevention--The 5-point recovery margin prevents repeated toggling near the selected threshold.--## Authorizing CodexBarHelper+On battery power, sleep prevention stops when charge reaches the threshold or lower. It resumes with eligible tasks after charge rises 5 percentage points above the threshold or power is connected.-Sleep prevention requires the bundled CodexBarHelper to change system-level sleep settings. Automatic Reset shares the same background-service registration and approval state to install a fixed system wake schedule:+For example, a 10% threshold stops sleep prevention at 10% and resumes it at 15%.-- Every transition from off to on shows an `Enable System Sleep Prevention?` confirmation dialog-- If CodexBarHelper is unregistered or missing, the dialog says `CodexBar Helper must be installed and authorized to run in the background`-- If CodexBarHelper is installed but awaiting approval, the dialog says `CodexBar Helper is installed but still needs authorization to run in the background`-- If CodexBarHelper is approved, the dialog shows only `When enabled, CodexBar prevents system sleep while Codex tasks are running and restores normal sleep afterward.`-- Selecting `Enable` saves the switch state and attempts to register the background service; selecting `Cancel` leaves it off-- When macOS requires approval for the background item, the enabled settings row shows `Open System Settings`; use it to open Login Items & Extensions-- No status explanation appears while the main switch is off; when the switch and Hook are available, the current blocking reason determines whether the sleep-prevention options are shown-- Sleep prevention does not run if CodexBarHelper is missing or registration fails-- If an app update changes CodexBarHelper, CodexBar refreshes its registration and validates the sleep state-- Before a normal app exit, CodexBar cancels the Automatic Reset wake schedule, releases the CodexBarHelper lease, and restores any state it changed-- If a CodexBarHelper connection ends unexpectedly, the helper releases that client's lease after a grace period-- Automatic Reset uses a separate connection; if it disconnects, the helper immediately cancels the wake schedule owned by that connection+## Background Service and Other Apps-## Coexisting with Other Sleep-Prevention Sources+CodexBarHelper is the background service included with the app that controls system sleep. Settings provides guidance when approval is missing or the service fails; see [Troubleshooting](troubleshooting.md#codexbarhelper-cannot-be-registered).-If system sleep was already disabled by another app or by the user before a task started, CodexBar marks the source as external:+If another app has already disabled system sleep, Settings identifies an external source. CodexBar preserves that setting when its tasks finish. If the external source stops while tasks remain, CodexBar takes over as needed.-- CodexBar does not claim ownership of the external setting-- It does not restore or overwrite that setting when the task finishes-- If the external setting is restored while the task is still running, CodexBar checks again and takes over when needed-- The main panel still shows the coffee cup, while Settings explains that system sleep is disabled by another source+Before a normal exit, CodexBar restores sleep state it manages and cancels Automatic Reset wake schedules. If exit does not complete, check Settings for background-service errors.-Back to the [User Guide](README.md)+Back to the [User Guide](README.md).diff --git a/Docs/en/UserGuide/sync-data-privacy.md b/Docs/en/UserGuide/sync-data-privacy.mdindex 6f7629a..ca7f05a 100644--- a/Docs/en/UserGuide/sync-data-privacy.md+++ b/Docs/en/UserGuide/sync-data-privacy.md@@ -2,136 +2,65 @@[简体中文](../../UserGuide/sync-data-privacy.md) | English-## What Cross-Device Sync Includes+## Cross-Device Sync-Cross-device sync merges daily Hook aggregations from multiple Macs. It does not sync account data, rate limits, token usage, banked resets, or Automatic Reset settings.+Enable `Cross-Device Sync` in `Settings > Advanced` to combine daily Hook statistics from Macs using the same iCloud account. CodexBar Hook must be enabled and an available iCloud account signed in.-It requires:+The first sync uploads statistics within local retention; later changes sync automatically. Turning sync off keeps local data.-- CodexBar Hook to be enabled-- An available iCloud account-- `Sync Across Devices` to be explicitly enabled--After you enable it, CodexBar uploads daily Hook aggregations within the local retention period, then uploads changed dates during later statistics maintenance.--Each device stores its contribution for a date separately. CodexBar merges contributions from different devices for display while avoiding double-counting the current device's local and cloud copies.--Sync uses the CloudKit private database in the `iCloud.app.zabrian.codexbar` container.--## Sync Status--The bottom of the main panel and the Settings page show these states:--| Status | Meaning |+| State | Meaning || --- | --- |-| Sync is off | You have not enabled sync, or CodexBar Hook is off |-| Syncing | CodexBar is reading from or writing to CloudKit |-| Synced | The most recent sync completed successfully |-| Sync failed | The network, iCloud account, or service is temporarily unavailable |--Settings also shows the time of the most recent successful upload.--## Rebuilding Data--Use `Settings > Advanced > Rebuild Data` to regenerate daily aggregations for selected dates from local raw Hook events.--This is useful when:--- Older aggregations lack metrics added by a newer version-- Metrics for certain dates look incorrect-- Local raw events were replaced or truncated-- You need to replace the current device's cloud contribution for those dates with a local result--The rebuild process works as follows:--1. The date picker allows only dates within the raw Hook-event retention period-2. Dates with raw data are marked-3. After confirmation, CodexBar reparses the selected local JSONL files-4. Unparseable lines are skipped and included in the result count-5. If sync is enabled, the rebuilt dates replace this device's cloud contribution during a later sync+| Sync Off | Sync or CodexBar Hook is disabled |+| Syncing | Data is being transferred |+| Synced | The latest sync cycle succeeded |+| Sync Failed | The network, iCloud account, or service is temporarily unavailable; CodexBar will retry |-Rebuilding does not change your Codex account, rate limits, or token usage.+The main panel footer and Settings show sync status. Settings also shows the last successful upload time.-## Data Stored Locally+## Uploaded Data-| Data | Contents | Location or lifetime |-| --- | --- | --- |-| Raw Hook events | Selected structured event fields | `~/Library/Application Support/CodexBar/HookEvents/events`, retained for 210 days |-| Daily Hook aggregations | Event counts, sessions and turns, project-name counts, and model counts | `~/Library/Application Support/CodexBar/HookEvents/daily.jsonl`, retained for 210 days |-| Hook maintenance state | File `offset`, `generation`, and pending dates | `~/Library/Application Support/CodexBar/HookEvents/maintenance.json` |-| Sync cache | CloudKit cache, cursors, and upload state | `~/Library/Application Support/CodexBar/HookEvents/Sync` |-| Stalled Task Protection | Hashed task identifiers and timestamps | `~/Library/Application Support/CodexBar/ActivityProtection/state.json`, up to 24 hours |-| CodexBarHelper ownership | Sleep-state ownership and recovery transactions | `/Library/Application Support/CodexBar/helper-state.json` |-| Automatic Reset wake schedule | CodexBar's fixed owner, `wake` type, and next time | macOS power management; removed after firing or cancellation |-| App preferences | Switches, thresholds, shortcut, Automatic Reset lead time, and notification deduplication state | macOS UserDefaults |-| app-server interaction log | The latest 500 requests and responses | Current app process memory only |+Synced data is stored in your private iCloud database. It includes dates, daily event and session statistics, project display names, model names, and identifiers used to distinguish devices and avoid duplicate counts.-Daily aggregations retain lists of session and turn IDs only for the latest 3 days. Older dates are reduced to counts and the lists are removed.+The following are not synced:-The CodexBarHelper ownership file is owned by root and is used to recover sleep state after an unexpected CodexBar or CodexBarHelper exit.+- Raw Hook events, session and task identifiers, and full working-directory paths+- Prompts, Codex replies, and tool parameters or output+- Codex account data, quota, token usage, and banked resets+- App settings, proxy configuration, and passwords+- Logs, live task state, and Stalled Task Protection records-The Automatic Reset wake schedule contains no account data, banked resets, `creditId`, or idempotency key. CodexBarHelper removes schedules left by the same build identity when it starts. The app also cancels schedules when tasks change, the feature is disabled, or the app exits normally.+**Project display names are uploaded.** Disable cross-device sync if a project name contains information you do not want stored in iCloud.-Anonymous tasks do not participate in Stalled Task Protection, so they do not create hashed task identifiers or write to the protection-state file.+## Local Data-## Fields Uploaded to CloudKit--Each daily aggregation record may contain:--- A pseudonymous device identifier scoped to the iCloud account-- Date-- The local Hook data source `generation`-- Counts for each Hook event type-- Session and turn counts-- Project display-name counts-- Model-name counts-- Update time--The pseudonymous device identifier is derived from the device UUID and a random salt in the iCloud private database. The raw device UUID is not uploaded.--## Data Not Uploaded to CloudKit--- Raw Hook event files-- Session IDs, turn IDs, and agent IDs-- Full working-directory paths-- Prompts, Codex responses, tool arguments, or tool output-- Codex account, rate-limit, or token usage data-- Banked reset details, Automatic Reset settings, or redemption state-- app-server interaction logs-- Stalled Task Protection records-- Codex authentication tokens--Project display names and model names are synced. Do not enable cross-device sync if a project name itself contains sensitive information.--## Local Data Access--CodexBar reads the following local data:--- Account, rate-limit, token usage, banked reset details, and Codex configuration through the local app-server-- Raw Hook events to generate metrics and live tasks-- Hook model fields and the first origin and lifecycle fields from local Codex rollout files to exclude Auto-review live tasks, distinguish completion from termination, and supplement progress timestamps--Origin classification prefers rollout metadata. When rollout origin is `unknown`, only an exact `codex-auto-review` Hook model match classifies the event as `autoReview`. Origin reading is limited to 256 KiB and stores only the normalized result `main`, `autoReview`, `auxiliary`, or `unknown`. CodexBar does not store rollout paths or raw source values; other rollout reads likewise extract only lifecycle, time, reasoning-effort, and similar fields and never display or store conversation text or tool content.+| Data | Contents and retention |+| --- | --- |+| Hook records and daily statistics | Times, events, models, tools, projects, and task identifiers, retained for 210 days; session and turn details in daily statistics are retained for only the latest 3 days |+| Stalled Task Protection | Irreversible task identifiers and times, retained for up to 24 hours after the last progress |+| App settings | Stored on the current Mac, including proxy configuration; proxy passwords are stored in plain text |+| Interaction logs | The latest 500 Codex requests and responses, retained only during the current run |+| Background-service state | Used to restore sleep settings and clean up Automatic Reset wake schedules |-After you explicitly enable Automatic Reset, CodexBar uses banked resets that the same local app-server explicitly reports as near expiration. Raw `creditId` and idempotency keys are not written to disk or CloudKit. `UserDefaults` stores only the feature switch, lead time, notification switch, sound choice, and hashed notification-deduplication keys.+CodexBar reads local Codex task state and activity records without saving prompts, replies, or tool content, or copying Codex sign-in credentials.-CodexBar does not copy or persist Codex authentication tokens.+Turning the proxy off retains its configuration and password. Saving with authentication disabled or choosing `Delete Configuration` removes the password.-## Network Activity+## Rebuild Data-| Network access | Purpose | Trigger |-| --- | --- | --- |-| Sparkle update feed | Check for and install CodexBar updates | Automatic checking is enabled or you check manually |-| CloudKit private database | Sync daily Hook aggregations across devices | You enable cross-device sync |+If statistics look incorrect, choose a date range in `Settings > Advanced > Rebuild Data` and confirm. You can select from the last 210 days; dates with local records are marked.-Account data, rate limits, token usage, banked reset details, and user-enabled Automatic Reset actions all use stdio communication with the local app-server. Automatic Reset does not add CloudKit requests. It sends CodexBarHelper only the time for a fixed system wake schedule, never account or banked reset data.+Rebuilding recalculates Hook statistics from retained local records and displays the result. With sync enabled, the result replaces this device’s cloud statistics for those dates while preserving other devices’ contributions. Account, quota, and token usage are unaffected.-## Log Privacy+## Network and Logs-System logs contain only operation results, state classifications, counts, and error stages.+| Network access | Purpose |+| --- | --- |+| Codex service | Read account, quota, and usage data; perform Automatic Reset |+| Update service | Check for and download CodexBar updates |+| iCloud | Transfer daily Hook statistics when sync is enabled |-They must not record account rate-limit values, token usage, project names, task content, session IDs, turn IDs, or OAuth tokens.+The proxy applies only to CodexBar’s Codex service connection, not updates, iCloud, or other apps.-The in-app app-server interaction log may contain request and response data, but it exists only in current-process memory and is shown only when you explicitly open the Logs window.+Interaction logs may contain account data and request or response content and are cleared when the app quits. Check for private information before sharing them.-Back to the [User Guide](README.md)+Back to the [User Guide](README.md).diff --git a/Docs/en/UserGuide/troubleshooting.md b/Docs/en/UserGuide/troubleshooting.mdindex d6dd37a..0370d8b 100644--- a/Docs/en/UserGuide/troubleshooting.md+++ b/Docs/en/UserGuide/troubleshooting.md@@ -20,38 +20,36 @@ Automatic mode prefers the global Codex CLI. The `In Use` indicator on the About## The Main Panel Says “Initialization Failed”-Common causes include:+Check the connection error in `Settings > About`, confirm Codex is installed at an available path, and review proxy settings. Click `Reconnect` after fixing the issue. If it persists, open Logs for details.-- No executable Codex installation was found-- Codex app-server failed to start-- app-server did not respond before the timeout-- app-server returned a response that could not be parsed+## Proxy Configuration or Connection Failures-Open the Logs window for the latest failed request and error details, then check the Codex path and version on the About page.+Open `Settings > Advanced > Proxy` and use `Test Connection` to check the draft. Server and port are required; authentication also requires a username. Invalid fields are outlined in red with a short reason beside the test button.++- If About reports an invalid server or username, correct and save the settings, or turn the proxy off+- If the configuration cannot be read, use `⋯ > Delete Configuration` at the top right of the dialog+- A correctly formatted but unreachable proxy can still be saved and enabled; use Test Connection to check connectivity+- HTTPS requires the proxy endpoint itself to support TLS and present a valid certificate## Rate Limits or Tokens Appear DimmedA dimmed value means that the current read failed and CodexBar fell back to cached data for the same account.-The cache preserves the last available information; it does not mean that the data refreshed successfully.--Double-click the account icon to retry. If the values remain dimmed, check `account/rateLimits/read` and `account/usage/read` in the Logs window.+Double-click the account icon to retry. If data remains faded, check the connection error in About or open Logs.## CodexBar Hook Cannot Be Enabled or Validated-| Message | Meaning | Recommended action |-| --- | --- | --- |-| A newer Codex version is required | The current app-server version is too old | Update Codex, then click Reconnect on the About page |-| Codex Hook is disabled globally | `features.hooks` is disabled | Re-enable Hooks in the Codex configuration |-| CodexBar Hook is incomplete | At least one required event is missing the current handler | Reopen Settings to trigger automatic repair; if it still fails, turn Hook off and on again |-| CodexBar Hook is not trusted | Codex still considers the handler untrusted or modified | Re-enable the Hook and inspect the Codex configuration |-| Unexpected CodexBar Hook source | app-server reported a source other than the active configuration file | Check `CODEX_HOME` and the active Codex source |-| Invalid `hooks.json` format | The top-level value or `hooks` structure is not valid JSON | Repair the JSON, then try again |-| Unable to validate Codex Hook | app-server is temporarily unavailable or validation failed | Check the logs and reopen Settings after Codex becomes available |--The Hook configuration is at `$CODEX_HOME/hooks.json`, or `~/.codex/hooks.json` when `CODEX_HOME` is unset.+| Message | Action |+| --- | --- |+| A newer Codex version is required | Update Codex, then click `Reconnect` in About |+| Codex Hook is globally disabled | Re-enable `features.hooks` in Codex configuration |+| CodexBar Hook is incomplete | Reopen Settings for automatic repair; if needed, turn Hook off and back on |+| CodexBar Hook is untrusted | Re-enable Hook and review Codex’s trust prompts |+| Unexpected CodexBar Hook source | Verify the selected Codex source and the location of `CODEX_HOME` |+| Invalid `hooks.json` format | Repair the file’s JSON format and retry |+| Cannot validate Codex Hook | Reopen Settings after the Codex connection recovers |-CodexBar automatically restores required events and trust data missing from an enabled Hook at launch, when the menu opens, and after each quota refresh. If a transient error prevents automatic repair, turning Hook off and on still rebuilds the complete configuration.+The default configuration file is `~/.codex/hooks.json`. If `CODEX_HOME` is set, use `hooks.json` in that directory.## Live Tasks Do Not Appear@@ -60,7 +58,7 @@ CodexBar automatically restores required events and trust data missing from an e3. Start a new Codex task to generate live events4. Open Settings to trigger Hook validation again-CodexBar does not send notifications for old tasks during history replay. When data-source boundaries are unstable, it falls back safely and skips untrusted history.+Restarting CodexBar does not replay old task notifications.## System Notifications Do Not Arrive@@ -105,17 +103,11 @@ Check in this order:1. `Automatic Reset` is enabled and its lead time is what you expect2. The Automatic Reset row does not report pending CodexBarHelper approval, missing registration, or wake-schedule failure; the lead-time options appear only after the Helper is approved-3. The current app-server response includes a specific available banked reset and expiration time+3. The main panel shows an available banked reset and its expiration time4. Network access and Codex sign-in were available at the scheduled time5. `Automatic Reset Notifications` is enabled if you expected a notification; disabling notifications does not stop Automatic Reset itself-Automatic Reset processes only credits explicitly listed in the latest app-server response. A single round retries network or temporary service failures continuously for no more than 5 minutes. Later normal rate-limit refreshes can schedule another attempt for a credit that remains valid.--Disabling Automatic Reset or quitting CodexBar cancels the current wake schedule. To inspect system schedules, run this command in Terminal:--```bash-pmset -g sched-```+Temporary failures retry for up to 5 minutes per round; later refreshes may try again. Disabling Automatic Reset or quitting CodexBar cancels its wake schedule.## Cross-Device Sync Is Unavailable@@ -129,9 +121,7 @@ A sync failure does not delete local Hook data. A later maintenance run retries## CodexBar Still Shows the Old Version After Updating Codex-The current version comes from the running app-server handshake. The on-disk version comes from running Codex `--version` again.--If About shows the new installed version but `In Use` still shows the old one, click Reconnect. Alternatively, the next request after the connection is one hour old rebuilds it automatically.+Click `Reconnect` in About to use the updated Codex.## Using the Logs Window@@ -140,22 +130,14 @@ Open it by either:- Right-clicking the menu bar icon and selecting `Log`- Pressing `⌘L` while the main panel is open-The Logs window keeps the latest 500 app-server requests from the current process.+The Logs window retains the latest 500 Codex interactions from the current run.Each entry includes request time, method, status, and response time. Expand it to inspect a request, response, or error preview.You can view or copy the full content in a separate window. It cannot be recovered after you clear the log or quit the app.-## Viewing System Logs--Run this command in Terminal:--```bash-/usr/bin/log stream --predicate 'subsystem == "app.zabrian.codexbar"' --style compact-```--Debug builds use a `subsystem` with a `.debug` suffix.+## Report a Problem-When reporting an issue, describe the reproduction steps and visible error. Before sharing logs, check whether the in-app interaction log contains request data that you do not want to disclose.+Include reproduction steps, CodexBar and Codex versions, and visible errors. Interaction logs may contain account and request content; review private information before sharing.-Back to the [User Guide](README.md)+Back to the [User Guide](README.md).diff --git a/README.en.md b/README.en.mdindex af52678..8a31527 100644--- a/README.en.md+++ b/README.en.md@@ -61,6 +61,7 @@ It can notify you when a task finishes, needs approval, or when your rate limits- Runs as a menu bar app without taking up space in the Dock- Supports a global keyboard shortcut, launch at login, and automatic updates- Provides Simplified Chinese and English interfaces+- Configurable HTTP/HTTPS proxy for the Codex service- Optionally merges daily Hook metrics across Macs through iCloud## Installation@@ -102,7 +103,7 @@ The default global shortcut is `⌘⇧W`. You can record a different shortcut or## Privacy-CodexBar processes all data locally. It uploads aggregated data to your private iCloud database only when you enable cross-device sync.+Raw Hook events and live tasks are processed locally. Enabling cross-device sync uploads daily Hook aggregates to your private iCloud database. Account and usage data come through the local Codex app-server, which connects to the service; update checks use Sparkle.See [Data, Sync, and Privacy](Docs/en/UserGuide/sync-data-privacy.md) for complete details about data access, local storage, and network boundaries.diff --git a/README.md b/README.mdindex 24087f7..60717f8 100644--- a/README.md+++ b/README.md@@ -21,46 +21,47 @@----CodexBar 是面向 macOS 15 及更高版本的菜单栏 App, 用于集中展示 Codex 账户, 额度, Token 用量和实时任务状态+CodexBar 是面向 macOS 15 及更高版本的菜单栏 App,用于集中展示 Codex 账户、额度、Token 用量和实时任务状态。-它可以在任务完成, 等待批准或额度变化时提醒你, 也能只在 Codex 任务运行期间自动防止系统睡眠+它可以在任务完成、等待批准或额度变化时提醒你,也能只在 Codex 任务运行期间自动防止系统睡眠。## 功能### 账户与额度一目了然- 展示当前 Codex 账户和套餐-- 展示全部额度窗口, 剩余比例和重置时间+- 展示全部额度窗口、剩余比例和重置时间- 展示可用积分和留存重置- 支持自动重置,可设置在留存重置过期前 15 分钟到 6 小时执行,默认提前 30 分钟;计划到点时可唤醒 Mac,并在执行前重新确认可用状态- 可在菜单栏图标旁直接显示所选额度窗口### 看见自己的 Codex 使用节奏-- 展示累计 Token, 单日峰值和连续使用天数+- 展示累计 Token、单日峰值和连续使用天数- 展示最长任务时长- 通过 30 周热力图回顾每日 Token 用量-- 开启 CodexBar Hook 后可查看会话, 对话轮次, 工具调用和子 Agent 等每日统计+- 开启 CodexBar Hook 后可查看会话、对话轮次、工具调用和子 Agent 等每日统计### 不错过正在发生的任务-- 菜单栏状态点区分运行中, 等待批准和刚完成任务-- 主面板展示当前任务, 项目, 模型, 推理强度和持续时间-- 任务中心集中查看并发任务, 最近完成和最近终止记录-- 支持任务完成, 等待批准和异常会话提醒+- 菜单栏状态点区分运行中、等待批准和刚完成任务+- 主面板展示当前任务、项目、模型、推理强度和持续时间+- 任务中心集中查看并发任务、最近完成和最近终止记录+- 支持任务完成、等待批准和异常会话提醒### 让长任务安心运行- 只在符合条件的 Codex 任务存在时防止系统睡眠-- 可选择等待批准期间继续保持, 或同时保持屏幕常亮-- 支持最长防睡眠时间, 低电量保护和异常会话保护+- 可选择等待批准期间继续保持,或同时保持屏幕常亮+- 支持最长防睡眠时间、低电量保护和异常会话保护- 任务结束或保护条件触发后自动恢复系统睡眠### 融入 macOS 工作流-- 作为菜单栏 App 运行, 不占用 Dock-- 支持全局快捷键, 开机启动和自动更新+- 作为菜单栏 App 运行,不占用 Dock+- 支持全局快捷键、开机启动和自动更新- 支持简体中文和英文界面+- 支持为 Codex 服务配置 HTTP/HTTPS 代理- 可选通过 iCloud 合并多台 Mac 的每日 Hook 统计## 安装@@ -73,42 +74,42 @@ brew install --cask bob-zebedy/tap/codexbar### DMG-从 [GitHub Releases](https://github.com/bob-zebedy/CodexBar/releases) 下载最新版本并拖入 Applications+从 [GitHub Releases](https://github.com/bob-zebedy/CodexBar/releases) 下载最新版本并拖入 Applications。## 运行要求- macOS 15.0 或更高版本- 已安装并登录 [Codex CLI](https://github.com/openai/codex) 或安装了内置 Codex 的 ChatGPT App 或 Codex App- 当前运行的 Codex 版本需要为 `0.143.0` 或更高版本-- 使用实时任务等 Hook 功能时, 当前运行的 Codex 版本需要为 `0.145.0` 或更高版本-- 使用跨设备同步时, Mac 需要登录可用的 iCloud 账户+- 使用实时任务等 Hook 功能时,当前运行的 Codex 版本需要为 `0.145.0` 或更高版本+- 使用跨设备同步时,Mac 需要登录可用的 iCloud 账户## 快速开始-1. 启动 CodexBar, 在菜单栏找到 CodexBar 图标-2. 左键点击图标查看账户, 额度和 Token 用量-3. 右键或按住 Control 点击图标打开设置, 日志或退出菜单-4. 在 `设置 > 高级` 中启用 CodexBar Hook, 解锁实时任务, 任务类通知, 防睡眠和 Hook 统计+1. 启动 CodexBar,在菜单栏找到 CodexBar 图标+2. 左键点击图标查看账户、额度和 Token 用量+3. 右键或按住 Control 点击图标打开设置、日志或退出菜单+4. 在 `设置 > 高级` 中启用 CodexBar Hook,解锁实时任务、任务类通知、防睡眠和 Hook 统计-默认全局快捷键为 `⌘⇧W`, 可在设置中重新录制或关闭+默认全局快捷键为 `⌘⇧W`,可在设置中重新录制或关闭。## 使用文档| 文档 | 内容 || --- | --- |-| [用户手册](Docs/UserGuide/README.md) | 安装, 主面板, Hook, 通知, 防睡眠, 同步, 全部设置和问题排查 |-| [开发者指南](Docs/DeveloperGuide/README.md) | 架构, 数据链路, 核心状态机, 存储, 隐私边界和开发验证 |+| [用户指南](Docs/UserGuide/README.md) | 安装、主面板、Hook、通知、防睡眠、同步、全部设置和问题排查 |+| [开发者指南](Docs/DeveloperGuide/README.md) | 架构、数据链路、核心状态机、存储、隐私边界和开发验证 || [文档导航](Docs/README.md) | 文档导航 |## 隐私-CodexBar 所有数据都在本地处理, 只有在开启跨设备同步功能后才会将各种汇总的数据上传到 iCloud private database+Hook 原始事件和实时任务在本机处理。开启跨设备同步后,日级 Hook 聚合会上传到 iCloud private database。账户和用量通过本机 Codex app-server 获取,由 Codex 连接服务端;更新检查使用 Sparkle。-完整的数据访问, 本机存储和网络边界见 [数据, 同步与隐私](Docs/UserGuide/sync-data-privacy.md)+完整的数据访问、本机存储和网络边界见 [数据、同步与隐私](Docs/UserGuide/sync-data-privacy.md)## 反馈-Bug, 功能建议或使用问题欢迎通过 [GitHub Issues](https://github.com/bob-zebedy/CodexBar/issues) 反馈+Bug、功能建议或使用问题欢迎通过 [GitHub Issues](https://github.com/bob-zebedy/CodexBar/issues) 反馈。## 许可证diff --git a/appcast.xml b/appcast.xmlindex 54130ad..9f68dbd 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.7.0</title>+ <sparkle:version>84</sparkle:version>+ <sparkle:shortVersionString>3.7.0</sparkle:shortVersionString>+ <sparkle:minimumSystemVersion>15.0</sparkle:minimumSystemVersion>+ <sparkle:releaseNotesLink>https://codexbar.zabrian.app/notes#3.7.0</sparkle:releaseNotesLink>+ <pubDate>Mon, 07 Sep 2026 23:05:04 +0800</pubDate>+ <enclosure url="https://codexbar.zabrian.app/download/CodexBar-v3.7.0.dmg" sparkle:edSignature="7916h2Cdb90MLizxKzu+QDVoIg+r7vqiOXrJKzew0Af5oOI161b+MTwmpG1rxqskOXD8sgJq3XaXKZelHPlNBQ==" length="7892139" type="application/octet-stream"/>+ </item><item><title>CodexBar.app 3.6.16</title><sparkle:version>83</sparkle:version>