CodexBar 是一个 macOS 菜单栏应用,用于查看本机 Codex 账号状态、额度、Token 用量、详细统计信息
Swift appkitcodexcodex-clideveloper-toolsmacosmacos-appmenu-bar-appopenai-codexproductivityswiftswiftuiusage-tracker
fix: 同步活动卡片与主面板的尺寸过渡
Bobe1bc423a7a75
diff --git a/AGENTS.md b/AGENTS.mdindex 70b4239..1758141 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -82,7 +82,10 @@ CodexBar 是面向 macOS 15+ 的 `LSUIElement` 菜单栏应用,使用 Swift 6,- 行末禁止使用标点- 行内标点后如果还有文字,间隔一个英文空格- 注释中引用类型、成员、参数或命令后尽量不要紧跟标点,需要断句时补一个词或者使用空格再断-- 一个注释段只解释一件事,需要说明多个独立主题时拆成多个注释段+- 注释清晰简洁、通俗易懂,优先说明代码中不明显的原因和约束,避免复述实现+- 一个注释段只解释一件事,长注释按主题分段;需要列出独立条件或步骤时使用简短列表+- 按职责边界适当使用 `// MARK: - 名称`,帮助浏览较长文件;不为每个属性或短函数单独添加标记+- 不在注释中重复容易变化的展示数量、尺寸或动画参数;涉及数据处理时直接说明字段和操作,避免使用各种笼统表述### 项目文档diff --git a/CodexBar/Controllers/FallbackPanelController.swift b/CodexBar/Controllers/FallbackPanelController.swiftindex a3a00ad..a353b50 100644--- a/CodexBar/Controllers/FallbackPanelController.swift+++ b/CodexBar/Controllers/FallbackPanelController.swift@@ -41,18 +41,15 @@ final class FallbackPanelController {panel?.orderOut(nil)}- func resizeIfVisible(animated: Bool) {- guard let panel, panel.isVisible else { return }- let size = contentSize(for: panel)- guard panel.frame.size != size else { return }+ func resizeIfVisible(contentHeight: CGFloat) {+ guard let panel, panel.isVisible,+ contentHeight.isFinite, contentHeight > 0,+ panel.frame.height != contentHeight else { return }var frame = panel.frame- frame.origin.y = frame.maxY - size.height- frame.size = size- NSAnimationContext.runAnimationGroup { context in- context.duration = animated ? 0.20 : 0- context.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)- panel.animator().setFrame(frame, display: true)- }+ frame.origin.y = frame.maxY - contentHeight+ frame.size.height = contentHeight+ // 高度已由 SwiftUI 逐帧插值, 再启动窗口动画会让宿主滞后于内容+ panel.setFrame(frame, display: true)}private func makePanelIfNeeded() -> KeyableBorderlessPanel {diff --git a/CodexBar/Controllers/SettingsWindowController.swift b/CodexBar/Controllers/SettingsWindowController.swiftindex 6fe133e..4c454b7 100644--- a/CodexBar/Controllers/SettingsWindowController.swift+++ b/CodexBar/Controllers/SettingsWindowController.swift@@ -218,9 +218,8 @@ final class SettingsWindowController: HostingWindowController {keepAliveController: keepAliveController)},- // 音效子行随各开关增删, 自动重置 低电量与上限三行还跟着各自的依赖置灰- // 置灰会连带收起音效子行, 所以三个依赖的派生值都要订上- // 防睡眠只订这两个派生值: 订整个控制器会让任务每起停一次都白重算一次高度+ // 通知选项的可用性会影响音效子行显隐, 需要订阅各项依赖的派生状态+ // 防睡眠只订阅相关派生值, 避免每次任务起停都触发面板高度重算contentChanges: Publishers.MergeMany([notificationSettings.objectWillChange.eraseToAnyPublisher(),codexHookSettings.objectWillChange.eraseToAnyPublisher(),diff --git a/CodexBar/Controllers/SidePanelSupport.swift b/CodexBar/Controllers/SidePanelSupport.swiftindex d2ddb80..8f9df37 100644--- a/CodexBar/Controllers/SidePanelSupport.swift+++ b/CodexBar/Controllers/SidePanelSupport.swift@@ -172,7 +172,7 @@ final class SidePanelDrawerAnimator {// MARK: - 展开与收起-/// 重置次数 设置子选项和并发任务中心三类一次性展开抽屉面板共用的显隐状态机+/// 抽屉面板共用的显隐状态机, 用于重置次数 设置子选项和任务中心/// 负责 generation 竞态防护 入退场动画和 child window 挂载与卸载/// 热力图详情面板带切边与延迟隐藏 状态机不同 因此不走这里@MainActordiff --git a/CodexBar/Controllers/StatusItemController.swift b/CodexBar/Controllers/StatusItemController.swiftindex 1958c48..042ef61 100644--- a/CodexBar/Controllers/StatusItemController.swift+++ b/CodexBar/Controllers/StatusItemController.swift@@ -111,7 +111,6 @@ final class StatusItemController: NSObject, NSMenuDelegate {private var statusIconHostingView: StatusItemIconHostingView?private var statusIconExpirationTask: Task<Void, Never>?private var statusToolTipTask: Task<Void, Never>?- private var popoverResizeAnimationTask: Task<Void, Never>?private var registeredHotKeyShortcut: GlobalHotKeyShortcut?private var auxiliaryWindowFocusRestoreTask: Task<Void, Never>?private var activeStatusItemMenu: NSMenu?@@ -374,6 +373,13 @@ final class StatusItemController: NSObject, NSMenuDelegate {).environmentObject(appUpdater).frame(width: CodexStatusMenuView.menuWidth)+ .fixedSize(horizontal: false, vertical: true)+ .onGeometryChange(for: CGFloat.self) { geometry in+ geometry.size.height+ } action: { [weak self] height in+ guard !usesPreferredContentSize else { return }+ self?.fallbackPanelController.resizeIfVisible(contentHeight: height)+ }let hostingController = NSHostingController(rootView: AnyView(rootView))if usesPreferredContentSize {@@ -393,8 +399,6 @@ final class StatusItemController: NSObject, NSMenuDelegate {.map(\.hasTaskCenterContent).removeDuplicates()- observeActivityCardSize()-let isTaskCenterVisible = Publishers.CombineLatest(codexHookSettings.$isEnabled,mainPanelSettings.$layout@@ -475,37 +479,6 @@ final class StatusItemController: NSObject, NSMenuDelegate {.store(in: &cancellables)}- private func observeActivityCardSize() {- Publishers.CombineLatest(viewModel.$snapshot.map { $0 != nil }, activityMonitor.$snapshot)- .map { hasQuota, activity in hasQuota && activity.primaryActivity.tokenUsage != nil }- .removeDuplicates()- .handleEvents(receiveOutput: { [weak self] _ in- self?.animatePopoverContentResize()- })- // 用量补齐会改变卡片高度, 等 @Published 完成赋值后再测量备用面板- .receive(on: DispatchQueue.main)- .sink { [weak self] _ in- guard let self else { return }- fallbackPanelController.resizeIfVisible(- animated: fallbackPanelAnimationState.allowsAnimations- )- }- .store(in: &cancellables)- }-- private func animatePopoverContentResize() {- guard menuSurfaceState == .shown, popover.isShown, popoverAnimationState.allowsAnimations else { return }- popoverResizeAnimationTask?.cancel()- // preferredContentSize 更新前启用 AppKit 尺寸动画, 显隐仍由统一淡入淡出管理- popover.animates = true- popoverResizeAnimationTask = Task { @MainActor [weak self] in- try? await Task.sleep(for: .milliseconds(250))- guard !Task.isCancelled else { return }- self?.popover.animates = false- self?.popoverResizeAnimationTask = nil- }- }-private func observeWorkflowSyncState() {codexHookSettings.$isEnabled.removeDuplicates()@@ -930,9 +903,6 @@ final class StatusItemController: NSObject, NSMenuDelegate {return}- popoverResizeAnimationTask?.cancel()- popoverResizeAnimationTask = nil- popover.animates = falsemenuSurfaceFadeCoordinator.cancel()hideSideDetailPanels()menuSurfaceDismissMonitor.remove()@@ -1152,7 +1122,6 @@ final class StatusItemController: NSObject, NSMenuDelegate {private func closeActiveMenuSurface() {// 主动关闭先清除宿主身份, 避免同步的关闭回调重入清理流程activeMenuSurface = .none- popover.animates = falseif popover.isShown {popover.performClose(nil)}diff --git a/CodexBar/Models/CodexWorkflowModels.swift b/CodexBar/Models/CodexWorkflowModels.swiftindex ebe32fc..8f7fb8e 100644--- a/CodexBar/Models/CodexWorkflowModels.swift+++ b/CodexBar/Models/CodexWorkflowModels.swift@@ -840,7 +840,7 @@ nonisolated struct WorkflowDailyAggregate: Codable, Equatable {}}-/// 同步存储中保存的脱敏每日聚合行: 对应 daily.jsonl 但不包含 sessionIds / turnIds+/// 同步用的每日聚合行, 保留 daily.jsonl 中的计数, 不包含 sessionIds 和 turnIdsnonisolated struct WorkflowSyncedDailyAggregate: Codable, Equatable {let date: Stringvar sourceGeneration: String?diff --git a/CodexBar/Services/CodexStatus/AppServerSession.swift b/CodexBar/Services/CodexStatus/AppServerSession.swiftindex c80f438..9da1d1f 100644--- a/CodexBar/Services/CodexStatus/AppServerSession.swift+++ b/CodexBar/Services/CodexStatus/AppServerSession.swift@@ -93,7 +93,7 @@ final nonisolated class AppServerSession {}}- // 先解码 JSON 转义, 避免 URL 中的斜杠或 Unicode 转义绕过脱敏+ // 先解码 JSON 转义, 才能匹配 URL 中的用户名和密码并替换为 <redacted>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) {diff --git a/CodexBar/Services/KeepAlive/KeepAliveController.swift b/CodexBar/Services/KeepAlive/KeepAliveController.swiftindex 58617e2..34ab098 100644--- a/CodexBar/Services/KeepAlive/KeepAliveController.swift+++ b/CodexBar/Services/KeepAlive/KeepAliveController.swift@@ -26,7 +26,7 @@ final class KeepAliveController: ObservableObject {@Published private(set) var isLowBatteryProtectionEnabled = false/// 时长上限是不是真的会到点: 防睡眠本身可用, 且没选无限制/// 与 isLowBatteryProtectionEnabled 同一个用法, 视图只读结论, 不各自再判一次 unlimited- /// 只在跨越边界时发信号, 1 小时改 2 小时不必让通知面板白排一轮高度重算+ /// 只在功能可用性变化时发信号, 单纯调整时长不需要通知面板重算高度@Published private(set) var isMaximumDurationEnabled = false/// 低电量是不是当下唯一拦住防睡眠的那一项@@ -438,7 +438,7 @@ final class KeepAliveController: ObservableObject {return}- // 百分比只在这里记一次; 放进 SleepConditions 会让每掉 1% 刷一条+ // 百分比只在这里记录, 避免电量每次变化都触发 SleepConditions 日志// 本来就没在挡睡眠时这一跌不改变任何事, 但仍要记: 这是排查"为什么在这个电量断的"的唯一依据let wasPreventingSleep = isActivelyPreventingSleep&& sleepPreventionSource == .codexBar@@ -772,19 +772,16 @@ final class KeepAliveController: ObservableObject {pendingKeepAliveLimit = maximumDuration}- /// UI 关心的两个布尔都从 blockReason 派生, 且只在这里写- /// 这么做是因为 sleepBlockReason 里的输入 (任务, helper 刷新中) 变化远比结论频繁,- /// 让它们各自 @Published 会把整个设置页拖着一起重算- /// 新增阻断条件时 allowsOptions 那个 switch 必须表态, 于是不会出现"入口亮着却点不动"+ /// 从阻断原因计算 UI 状态, 只在结论变化时发布+ /// 避免任务或 helper 状态频繁变化时重复刷新设置页private func publishDerivedState(blockReason: SleepBlockReason?) {assign(blockReason == .lowBattery, to: \.isLowBatteryBlocking)assign(Self.allowsOptions(blockReason), to: \.canShowOptions)publishNotificationDependencies()}- /// 通知面板那两行的置灰依据- /// 输入分散在三条路径上 (用户开关与 Hook 走 reconcileSleepState, 电量与阈值走 updateBatteryState,- /// 上限走 setMaximumDuration), 所以规则只写这一份, 三处都调它+ /// 通知选项是否可用取决于用户开关, Hook, 电量和时长上限+ /// 各输入的更新路径统一调用此方法, 避免各自维护判定规则private func publishNotificationDependencies() {let isKeepAliveUsable = isEnabled && isHookEnabledassign(@@ -797,7 +794,8 @@ final class KeepAliveController: ObservableObject {)}- /// 缺依赖时收起入口, 只是没在防睡眠 (没任务, 低电量, 已达上限) 时仍然要能改设置+ /// 缺少必要依赖时隐藏设置入口+ /// 因任务, 电量或时长暂停防睡眠时, 仍允许修改设置private static func allowsOptions(_ blockReason: SleepBlockReason?) -> Bool {switch blockReason {case .notStarted, .userOff, .hookDisabled, .helperUnavailable, .terminating:@@ -807,8 +805,7 @@ final class KeepAliveController: ObservableObject {}}- /// 任何一项变了才记一条, 逐次求值不记- /// want 为 0 时这条是唯一能看出「是哪一项把它拉下来」的依据+ /// 只在判定条件变化时记录日志, 用于定位防睡眠未生效的原因private func logSleepConditionsIfChanged(blockReason: SleepBlockReason?,trigger: LogTrigger@@ -1383,7 +1380,7 @@ final class KeepAliveController: ObservableObject {}// 每次重试都会重建特权连接并以 root 拉起 pmset- // 固定 2 秒无上限重试会让持续失败的 helper 变成无限循环+ // 限制重试次数, 避免 helper 持续失败时反复拉起特权进程guard retryAttempt < KeepAliveHelperConfiguration.sleepToggleRetryDelays.count else {AppLog.keepAlive.error("KeepAlive 切换重试已放弃: attempts=\(KeepAliveHelperConfiguration.sleepToggleRetryDelays.count)"diff --git a/CodexBar/Services/KeepAlive/KeepAliveModels.swift b/CodexBar/Services/KeepAlive/KeepAliveModels.swiftindex abcb560..4c4f6cb 100644--- a/CodexBar/Services/KeepAlive/KeepAliveModels.swift+++ b/CodexBar/Services/KeepAlive/KeepAliveModels.swift@@ -53,7 +53,7 @@ extension KeepAliveController {}/// 日志用的小时数, 与 LowBatteryThreshold 的百分比同一种可读形式, 无限制同样记 -1- /// rawValue 是秒数, 直接记会得到 14400 这种不好读的值+ /// rawValue 使用秒数, 日志转换为小时便于阅读var loggedHours: Int {self == .unlimited ? -1 : rawValue / 3600}@@ -127,7 +127,7 @@ extension KeepAliveController {/// shouldDisableSleep 的求值结果与它依赖的各项, 只用于变化检测与日志/// blockReason 与 shouldDisableSleep 同源, 不会出现"字段都满足却报某项缺失"- /// battery 只放布尔: 放电量百分比会让每掉 1% 都记一条+ /// battery 只保存布尔状态, 避免电量每次变化都触发日志struct SleepConditions: Equatable {let blockReason: SleepBlockReason?let enabled: Booldiff --git a/CodexBar/Services/KeepAlive/PowerSourceMonitor.swift b/CodexBar/Services/KeepAlive/PowerSourceMonitor.swiftindex b44b26b..ac789c6 100644--- a/CodexBar/Services/KeepAlive/PowerSourceMonitor.swift+++ b/CodexBar/Services/KeepAlive/PowerSourceMonitor.swift@@ -57,7 +57,7 @@ final class PowerSourceMonitor {private var hasSeenBattery = false/// 回调里持有的是 unretained 指针, 停止监听必须显式做, 由持有者在 stop 时调用- /// 不放 deinit: Swift 6 的 nonisolated deinit 碰不了这两个非 Sendable 属性+ /// 在此释放资源, 因为 Swift 6 的 nonisolated deinit 无法访问这些非 Sendable 属性func stop() {isMonitoring = falsepollTask?.cancel()diff --git a/CodexBar/Services/KeepAlive/SystemSleepService.swift b/CodexBar/Services/KeepAlive/SystemSleepService.swiftindex 48433d8..9299128 100644--- a/CodexBar/Services/KeepAlive/SystemSleepService.swift+++ b/CodexBar/Services/KeepAlive/SystemSleepService.swift@@ -123,7 +123,7 @@ final class SystemSleepService {}}- /// 逐次声明不记日志, 只在成败翻转时记一条: 这是 30 秒一拍的高频路径, 持续失败会把日志刷满+ /// 定期声明用户活动时只记录成败变化, 避免持续失败产生重复日志private func declareUserActivity() {let result = IOPMAssertionDeclareUserActivity(displayAssertion.name,diff --git a/CodexBar/Services/Notifications/CodexNotificationService.swift b/CodexBar/Services/Notifications/CodexNotificationService.swiftindex 0680ebf..75d0f3d 100644--- a/CodexBar/Services/Notifications/CodexNotificationService.swift+++ b/CodexBar/Services/Notifications/CodexNotificationService.swift@@ -590,10 +590,12 @@ final class CodexNotificationService: NSObject {// MARK: - 发送与文案- /// 通知的 title 与 body 含项目名和任务信息, 一律不进日志, 只记 kind- /// 返回提交任务, 需要等通知真的发出去再做下一步的调用方 await 它的 value- /// 只有这一个入口: 另开一条 async 通道会让它悄悄少掉去重 时效判定和失败回调三项能力- /// 去重判定留在同步段, 这样连续两次 send 的第二次一定被挡下, 不依赖 Task 的调度顺序+ /// 统一提交通知, 处理去重, 时效判定和失败回调+ /// 去重在创建异步任务前完成, 避免连续调用重复提交+ ///+ /// 日志只记录 kind, 不记录包含项目名和任务信息的 title 与 body+ ///+ /// - Returns: 提交任务, 调用方可 await 其 value 获取提交结果@discardableResultprivate func send(_ notification: CodexNotificationContent,diff --git a/CodexBar/Services/Settings/NotificationSettings.swift b/CodexBar/Services/Settings/NotificationSettings.swiftindex b9980b8..7ae7871 100644--- a/CodexBar/Services/Settings/NotificationSettings.swift+++ b/CodexBar/Services/Settings/NotificationSettings.swift@@ -4,8 +4,8 @@ import Foundationimport osimport UserNotifications-/// 通知偏好: 总开关; 八类通知子开关及声音; 任务触觉开关; 两个阈值和系统授权状态镜像-/// 授权请求/查询集中在这里, 通知与触觉反馈判定在 CodexNotificationService+/// 管理通知偏好和系统授权状态+/// 具体的通知发送与触觉反馈由 CodexNotificationService 处理@MainActorfinal class NotificationSettings: ObservableObject {@Published private(set) var isEnabled: Bool@@ -118,6 +118,8 @@ final class NotificationSettings: ObservableObject {authorizationTask?.cancel()}+ // MARK: - 偏好设置+func setEnabled(_ enabled: Bool) {guard enabled != isEnabled else {return@@ -219,6 +221,8 @@ final class NotificationSettings: ObservableObject {setSound(sound, current: &keepAliveLimitSound, key: Self.keepAliveLimitSoundKey)}+ // MARK: - 系统授权+/// 用户可能在系统设置里改过权限, 回到 App 时需要重新读取func refreshAuthorizationStatus() {// 系统授权弹窗也会改变 App 与窗口焦点, 查询不能取消正在等待用户回应的请求@@ -290,12 +294,14 @@ final class NotificationSettings: ObservableObject {}}+ // MARK: - 偏好读写+private func setBool(_ value: Bool, current: inout Bool, key: String) {guard value != current else {return}- // 八个通知细项都走这里, 用持久化 key 区分是哪一项, 不必逐个 setter 铺日志+ // 分类通知统一在这里记录日志, 用持久化 key 区分设置项let details = LogFields.joined("key=\(key)","enabled=\(value ? 1 : 0)"diff --git a/CodexBar/Services/Workflow/CodexActivityMonitor.swift b/CodexBar/Services/Workflow/CodexActivityMonitor.swiftindex 38559e8..3f7432b 100644--- a/CodexBar/Services/Workflow/CodexActivityMonitor.swift+++ b/CodexBar/Services/Workflow/CodexActivityMonitor.swift@@ -1071,7 +1071,7 @@ final class CodexActivityMonitor: ObservableObject {}/// SessionEnd 没有 turn_id, 以 session 为边界把活跃任务移入终态确认窗口- /// 任务会立即退出活跃列表, rollout 仍有 5 秒补回准确的完成或终止分类+ /// 任务立即退出活跃列表, 后续继续从 rollout 确认完成或终止分类private func terminateSession(from event: WorkflowHookEvent) {guard let sessionId = event.sessionId else {returndiff --git a/CodexBar/Services/Workflow/WorkflowHookEventRecorder.swift b/CodexBar/Services/Workflow/WorkflowHookEventRecorder.swiftindex 2ced919..76436e1 100644--- a/CodexBar/Services/Workflow/WorkflowHookEventRecorder.swift+++ b/CodexBar/Services/Workflow/WorkflowHookEventRecorder.swift@@ -92,7 +92,7 @@ nonisolated enum WorkflowHookEventRecorder {)}- /// 留出 2 秒在 Codex 杀掉子进程前主动收工, 避免写入中途留下半截坏行+ /// 为事件写入预留时间, 避免等待锁耗尽超时预算后被 Codex 中途终止private static func lockWaitLimitSeconds(for event: CodexHookEvent?) -> TimeInterval {let timeout = event.map(hookTimeoutSeconds(for:)) ?? defaultHookTimeoutSecondsreturn max(0, Double(timeout) - 2)diff --git a/CodexBar/Services/Workflow/WorkflowService.swift b/CodexBar/Services/Workflow/WorkflowService.swiftindex 7cc7cd3..4227595 100644--- a/CodexBar/Services/Workflow/WorkflowService.swift+++ b/CodexBar/Services/Workflow/WorkflowService.swift@@ -12,7 +12,7 @@ private nonisolated enum MaintenanceStage: String {}/// 一轮汇总的计数, 成功路径压进 WorkflowSyncScheduler 的收尾那一条日志, 不为每天单独记一行-/// dates 由三个分支相加得出, 不额外存一份+/// dates 从各处理结果的计数求和得出, 不额外保存nonisolated struct WorkflowMaintenanceCounts {var events = 0var written = 0@@ -304,7 +304,7 @@ actor WorkflowService {}/// 空转的一轮返回 nil- /// 它跟着每 60 秒的额度刷新跑, 无条件记会让空闲机器每天多出上千条没有信息的日志+ /// 维护跟随额度刷新执行, 只记录有实际工作的轮次, 避免空闲时持续产生重复日志/// 收尾日志由 WorkflowSyncScheduler 统一记, 这里只负责判断有没有值得记的东西private func performMaintenanceIfNeeded() -> WorkflowMaintenanceCounts? {let duration = LogDuration()@@ -497,11 +497,10 @@ actor WorkflowService {return changed}- /// boundaryHash 覆盖的是 [offset-4KB, offset), 而追加只写在 offset 之后,- /// 所以文件没被写过时那段字节不可能变化, 无需重算哈希.- /// 保留期内可能有上百个历史文件, 每轮全量重算会显著拉长持锁时间,- /// 而 Hook 子进程要等这把锁才能记录事件.- /// 返回边界是否变化, 以及重算确认无变化时应记下的 mtime (无需记录时为 nil)+ /// boundaryHash 覆盖 offset 之前的边界片段, 追加只写在 offset 之后+ /// 文件未修改时复用已有哈希, 减少持锁时间和 Hook 子进程的等待+ ///+ /// - Returns: 边界是否变化, 以及确认边界未变时的文件修改时间. 无需记录时, 时间为 nilprivate func boundaryStatus(dateKey: String,day: WorkflowDayMaintenanceState,@@ -1110,8 +1109,7 @@ nonisolated enum WorkflowStorage {}}- /// 轮询间隔从 1ms 起翻倍: 维护流程每次持锁都只有几毫秒,- /// 固定长间隔会让 Hook 子进程为一次已经释放的锁白等一整个间隔+ /// 锁轮询从短间隔开始逐步退避, 兼顾短期争用的响应速度和持续争用时的开销private static let lockMinimumRetryIntervalMicroseconds: UInt32 = 1000private static let lockMaximumRetryIntervalMicroseconds: UInt32 = 20000@@ -1140,7 +1138,7 @@ nonisolated enum WorkflowStorage {}/// 单次 stat 同时返回大小与 inode 标识, 文件缺失或不可读时为 nil- /// 维护流程每轮要 stat 上百个事件文件, 用裸 stat(2) 而非 attributesOfItem 避免逐个构造属性字典+ /// 维护流程需要批量读取文件状态, 直接使用 stat(2) 避免逐个构造属性字典/// mtime 记整数纳秒: 落盘状态用 JSON 编码, Date 会退化成浮点而无法精确比较/// 沿用 attributesOfItem 的语义跟随符号链接, 因此用 stat 而非 lstatstatic func fileStat(at url: URL) -> WorkflowFileStat? {@@ -1214,7 +1212,7 @@ nonisolated enum WorkflowStorage {}/// 记录单日事件文件已处理到的 offset, 支持后续增量维护-/// stat(2) 里维护流程需要的三个字段+/// 维护流程使用的文件状态字段nonisolated struct WorkflowFileStat {let size: UInt64let identifier: UInt64diff --git a/CodexBar/Services/Workflow/WorkflowSyncScheduler.swift b/CodexBar/Services/Workflow/WorkflowSyncScheduler.swiftindex c5abb50..94bd066 100644--- a/CodexBar/Services/Workflow/WorkflowSyncScheduler.swift+++ b/CodexBar/Services/Workflow/WorkflowSyncScheduler.swift@@ -214,7 +214,7 @@ final class WorkflowSyncScheduler {}}- /// 空转的一轮什么都没改, 跟着 60 秒额度刷新记一条会把空闲机器的日志刷没+ /// 空转轮次不记录日志, 避免周期刷新产生重复信息/// 同步自身的起止由 WorkflowSyncService 记, 这里只承载维护结果, 不给 sync 开后门private func logMaintenanceOutcome(synchronize: Bool,diff --git a/CodexBar/Services/Workflow/WorkflowSyncService.swift b/CodexBar/Services/Workflow/WorkflowSyncService.swiftindex 9f672d5..8185d3f 100644--- a/CodexBar/Services/Workflow/WorkflowSyncService.swift+++ b/CodexBar/Services/Workflow/WorkflowSyncService.swift@@ -23,14 +23,14 @@ private nonisolated enum WorkflowSyncStage: String {case prune}-/// 将本机 daily.jsonl 的脱敏聚合行同步到 CloudKit private database+/// 将本机 daily.jsonl 中不含 sessionIds 和 turnIds 的聚合行同步到 CloudKit private databaseactor WorkflowSyncService {private let database: CKDatabaseprivate let fileManager: FileManagerprivate let directoryURL: URLprivate let tokenHistorySync: CodexTokenHistorySync- // zone 存在性和 account salt 首次确认后跨轮缓存, 省掉每轮同步的两次固定往返+ // zone 存在性和 account salt 首次确认后跨轮缓存, 避免每轮同步都重复请求// 任一轮同步失败时作废: iCloud 账号切换必然伴随请求报错, 下一轮会重新确认private var isSyncZoneConfirmed = falseprivate var cachedAccountSalt: Data?@@ -1374,7 +1374,8 @@ private extension WorkflowSyncService {}}-/// records 包含所有设备的脱敏聚合; currentDeviceId 用于展示时替换而不是叠加本机云端副本+/// records 包含所有设备的日聚合, 不含 sessionIds 和 turnIds+/// currentDeviceId 用于展示时替换本机云端副本, 避免重复计数nonisolated struct WorkflowSyncSnapshot: Equatable {let records: [WorkflowSyncedDailyRecord]let currentDeviceId: String?diff --git a/CodexBar/Views/Menu/CodexActivityCard.swift b/CodexBar/Views/Menu/CodexActivityCard.swiftindex 235a184..b62503c 100644--- a/CodexBar/Views/Menu/CodexActivityCard.swift+++ b/CodexBar/Views/Menu/CodexActivityCard.swift@@ -1,8 +1,7 @@import SwiftUI-/// Hook 开启时常驻的活动摘要, 使用菜单面板共享的逐秒时间-/// 在卡片内部观察 activityMonitor 与逐秒时间, 让 1Hz 失效范围只覆盖本卡片而不是整个菜单树-/// keepAliveController 同理, 它的 helperStatus 等字段与菜单树无关却会无条件发信号+/// Hook 开启时显示的活动摘要, 使用主面板共享的时间+/// 活动和防睡眠状态由卡片自行观察, 避免刷新整个菜单树struct CodexActivityCard: View {@ObservedObject var activityMonitor: CodexActivityMonitor@ObservedObject var presentationState: CodexActivityCenterPresentationState@@ -25,8 +24,7 @@ struct CodexActivityCard: View {presentationState.isPresented}- /// 额度数据不可用时卡片整体退到"暂无数据", 徽标属于活动信息, 必须跟着一起收- /// 否则会出现"暂无数据"配上防睡眠徽标的自相矛盾画面+ /// 卡片显示"暂无数据"时一并隐藏防睡眠徽标, 保持状态一致private var showsKeepAliveBadge: Bool {keepAliveController.isActivelyPreventingSleep && !showsUnavailableState}@@ -40,6 +38,8 @@ struct CodexActivityCard: View {}}+ // MARK: - 卡片布局+var body: some View {// 保留同一张卡片的视图身份, 空闲时只禁用交互, 避免打断内容和高度过渡Button {@@ -58,8 +58,9 @@ struct CodexActivityCard: View {private func card(now: Date) -> some View {let content = content(at: now)- return VStack(alignment: .leading, spacing: 8) {+ return VStack(alignment: .leading, spacing: 0) {statusRow(content)+ .frame(height: Metrics.height).id(snapshot.hasTaskCenterContent).transition(.opacity)if let usage = content.tokenUsage {@@ -67,17 +68,16 @@ struct CodexActivityCard: View {LiquidGlassDivider()tokenUsageMetrics(usage)}- .transition(.opacity.combined(with: .offset(y: 6)))+ .frame(height: Metrics.usageHeight - Metrics.height, alignment: .top)+ .transition(.modifier(+ active: ActivityTokenReveal(progress: 0),+ identity: ActivityTokenReveal(progress: 1)+ ))}}- .animation(.codexStatus, value: showsKeepAliveBadge)- .animation(.codexStatus, value: content.isAnonymous)- // 任务数变化会让 +N 增删, 防睡眠徽标跟着横移; 两者一起纳入动画上下文才不会跳- .animation(.codexStatus, value: content.otherTaskCount).padding(.horizontal, MenuMetrics.panelPadding).frame(maxWidth: .infinity)- .frame(height: content.tokenUsage == nil ? Metrics.height : Metrics.usageHeight)- .clipped()+ .modifier(ActivityCardHeight(height: content.tokenUsage == nil ? Metrics.height : Metrics.usageHeight)).activityStatusParticles(cornerRadius: MenuMetrics.panelCornerRadius).liquidGlassSurface(cornerRadius: MenuMetrics.panelCornerRadius).overlay {@@ -91,8 +91,8 @@ struct CodexActivityCard: View {.animation(.codexStatus, value: isHovered).animation(.codexStatus, value: isTaskCenterPresented)}- .animation(.codexStatus, value: snapshot.hasTaskCenterContent)- .animation(.codexStatus, value: content.tokenUsage != nil)+ .animation(Metrics.expansionAnimation, value: snapshot.hasTaskCenterContent)+ .animation(Metrics.expansionAnimation, value: content.tokenUsage != nil)}private func statusRow(_ content: ActivityCardContent) -> some View {@@ -154,6 +154,10 @@ struct CodexActivityCard: View {.help(String(localized: "activity.summary.other-task-count", defaultValue: "\(content.otherTaskCount, specifier: "%lld")"))}}+ .animation(.codexStatus, value: showsKeepAliveBadge)+ .animation(.codexStatus, value: content.isAnonymous)+ // 任务数变化会让 +N 增删, 防睡眠徽标跟着横移; 动画只作用于状态行+ .animation(.codexStatus, value: content.otherTaskCount)}private func tokenUsageMetrics(_ usage: CodexTokenUsage) -> some View {@@ -190,6 +194,8 @@ struct CodexActivityCard: View {.frame(minWidth: 0, maxWidth: .infinity)}+ // MARK: - 展示内容+private func content(at now: Date) -> ActivityCardContent {switch snapshot.primaryActivity {case let .waiting(task):@@ -335,6 +341,41 @@ struct CodexActivityCard: View {private enum Metrics {static let height: CGFloat = 58static let usageHeight: CGFloat = 108+ static let expansionAnimation = Animation.timingCurve(0.22, 1, 0.36, 1, duration: 0.32)+ }+}++// MARK: - 动画++/// 逐帧更新布局高度, 让相邻区块和窗口同步调整+private struct ActivityCardHeight: AnimatableModifier {+ var height: CGFloat++ var animatableData: CGFloat {+ get { height }+ set { height = newValue }+ }++ func body(content: Content) -> some View {+ content+ .frame(height: height, alignment: .top)+ .clipped()+ }+}++/// 用展开进度控制显隐, 让动画中途反向时保持连贯+private struct ActivityTokenReveal: AnimatableModifier {+ var progress: CGFloat++ var animatableData: CGFloat {+ get { progress }+ set { progress = newValue }+ }++ func body(content: Content) -> some View {+ content+ .opacity(Double(min(1, max(0, (progress - 0.6) / 0.4))))+ .offset(y: (1 - progress) * 4)}}@@ -349,7 +390,9 @@ private struct RotatingKeepAliveSun: View {}}-/// 卡片自行处理 hover/选中描边, 按钮样式不再修改 label 的前景色或透明度+// MARK: - 辅助视图与展示模型++/// 悬停和选中效果由卡片绘制, 按钮样式保留原有颜色和透明度private struct ActivityCardButtonStyle: ButtonStyle {func makeBody(configuration: Configuration) -> some View {configuration.label@@ -369,7 +412,7 @@ private struct ActivityCardContent {struct CodexActivityAnonymousIcon: View {var body: some View {Image(systemName: "person.crop.circle.dashed")- // 虚线圆形 symbol 留白较多, 13 pt 与 11 pt 咖啡图标的视觉面积更接近+ // 虚线圆形 symbol 留白较多, 适当放大以接近相邻状态图标的视觉面积.font(.system(size: 13, weight: .semibold)).foregroundStyle(Color.orange).help("activity.anonymous.keep-awake-exclusion")diff --git a/CodexBar/Views/Menu/CodexStatusMenuView.swift b/CodexBar/Views/Menu/CodexStatusMenuView.swiftindex bb63f0e..0226c01 100644--- a/CodexBar/Views/Menu/CodexStatusMenuView.swift+++ b/CodexBar/Views/Menu/CodexStatusMenuView.swift@@ -37,7 +37,7 @@ struct CodexStatusMenuView: View {@ObservedObject var workflowViewModel: WorkflowViewModel@ObservedObject var codexHookSettings: CodexHookSettings@ObservedObject var mainPanelSettings: MainPanelSettings- // 活动状态与逐秒时间只被活动卡片消费, 由卡片自行观察, 避免 1Hz tick 让整个菜单树每秒重算+ // 活动状态与时间变化由卡片自行观察, 避免刷新整个菜单树let activityMonitor: CodexActivityMonitor@ObservedObject var syncSettings: WorkflowSyncSettings// 同 activityMonitor, 交给活动卡片自行观察, 不让 helper 状态变化重算整个菜单树diff --git a/CodexBar/Views/Menu/UsageHeatmap.swift b/CodexBar/Views/Menu/UsageHeatmap.swiftindex b8d84d3..cc6ba53 100644--- a/CodexBar/Views/Menu/UsageHeatmap.swift+++ b/CodexBar/Views/Menu/UsageHeatmap.swift@@ -24,7 +24,7 @@ nonisolated struct UsageHeatmapSelection: Equatable {// MARK: - 摘要区-/// token 摘要和近 30 周热力图的组合区+/// Token 摘要和近期用量热力图的组合区struct UsageSummaryView: View {let usage: CodexUsageSnapshot?let isStale: Bool@@ -237,7 +237,7 @@ struct UsageSummaryView: View {// MARK: - 热力图与 hover 吸附-/// 近 30 周 token 热力图, hover 时把指针吸附到最近的有效日期格+/// 近期 Token 用量热力图, hover 时把指针吸附到最近的有效日期格struct UsageHeatmap: View {let days: [UsageHeatmapDay?]let onScreenFrameChange: (CGRect?) -> Voiddiff --git a/CodexBar/Views/Settings/AppSettingsView.swift b/CodexBar/Views/Settings/AppSettingsView.swiftindex 18fd581..bb0f663 100644--- a/CodexBar/Views/Settings/AppSettingsView.swift+++ b/CodexBar/Views/Settings/AppSettingsView.swift@@ -616,7 +616,7 @@ private extension AppSettingsView {// 低电量拦下时开关开着却不防睡眠, 不留一句无从解释// 判定用 isLowBatteryBlocking 而不是 isLowBatteryActive: 后者在没有任务时也成立, 那时无话可说// 它成立即意味着 helper 已就绪, 所以排在下面那个 switch 之前不影响 helper 类问题的呈现- // 不写具体阈值: 滞回让保护一直持续到阈值加 5, 说死数字会与用户看到的电量对不上+ // 提示不写具体电量, 因为滞回会让保护持续到电量超过恢复阈值if keepAliveController.isLowBatteryBlocking {return SettingsStatusCaption(message: String(localized: "keep-alive.status.low-battery"))}diff --git a/Docs/DeveloperGuide/README.md b/Docs/DeveloperGuide/README.mdindex e2e5aa3..2ecc4d7 100644--- a/Docs/DeveloperGuide/README.md+++ b/Docs/DeveloperGuide/README.md@@ -6,13 +6,13 @@| 文档 | 内容 || --- | --- |-| [整体架构](architecture.md) | 进程、模块、生命周期、actor 边界和 3 条数据链路 |+| [整体架构](architecture.md) | 进程、模块、生命周期、actor 边界和数据链路 || [设计原则与关键决策](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 租约、自动重置唤醒计划和恢复策略 |-| [CloudKit 同步](sync.md) | 私有数据库、设备匿名化、上传、合并和重建 |+| [CloudKit 同步](sync.md) | 私有数据库、设备标识哈希、上传、合并和重建 || [通知系统](notifications.md) | 通知触发、去重、声音、触觉和点击行为 || [UI 与应用生命周期](ui-and-lifecycle.md) | 菜单栏、面板、焦点、全局快捷键和服务装配 || [数据与隐私边界](data-and-privacy.md) | 本地文件、网络访问、云端字段和日志边界 |diff --git a/Docs/DeveloperGuide/activity-monitor.md b/Docs/DeveloperGuide/activity-monitor.mdindex bb3c07b..e462aa6 100644--- a/Docs/DeveloperGuide/activity-monitor.md+++ b/Docs/DeveloperGuide/activity-monitor.md@@ -222,7 +222,7 @@ rollout 坏行将当时尚未结束的 turn 标记为有覆盖缺口,后续重| 缓存命中率 | `cached_input_tokens / input_tokens`,输入为零时不可计算 || 推理输出 | `reasoning_output_tokens` |-六项计数均需存在且非负,总量必须等于输入加输出,缓存命中加写入不能超过输入,推理不能超过输出。解析同时校验 `thread_id`、`session_id`、`turn_id`、`root_turn_id` 和 `response_id` 的归属与有效性;字段缺失或校验失败时不生成用量。有效记录中的缓存写入或推理输出为零时直接展示零值。+所需的 Token 计数均需存在且非负,总量必须等于输入加输出,缓存命中加写入不能超过输入,推理不能超过输出。解析同时校验 `thread_id`、`session_id`、`turn_id`、`root_turn_id` 和 `response_id` 的归属与有效性;字段缺失或校验失败时不生成用量。有效记录中的缓存写入或推理输出为零时直接展示零值。`CodexActivityTokenUsage.swift` 按根任务收集主线程及已关联子线程的轮次引用,并按线程、轮次去重。运行中汇总本次读取完整且归属匹配的线程,尚未有用量的线程等待后续刷新;显示值因此可以是已知线程的小计。实时卡片使用内存任务快照,不读取历史日汇总或 iCloud 缓存。@@ -488,7 +488,7 @@ bootstrap 等待 rollout 期间如果恢复代次改变,会丢弃旧生命周- progress generation- 当时的阈值-通知返回或 3 秒 grace 到期时,四项都必须仍匹配才允许 suppress。任意新进展或阈值变化都会让旧尝试失效。+通知返回或 3 秒 grace 到期时,上述条件都必须仍匹配才允许 suppress。任意新进展或阈值变化都会让旧尝试失效。使用残缺末行兜底的候选还要复核末行观察的新鲜度和静默期限。末行继续增长或读取失败时取消尚未完成的隐藏尝试。diff --git a/Docs/DeveloperGuide/app-server.md b/Docs/DeveloperGuide/app-server.mdindex a90644e..dc13c30 100644--- a/Docs/DeveloperGuide/app-server.md+++ b/Docs/DeveloperGuide/app-server.md@@ -61,7 +61,7 @@ CodexCLIResolver从 Finder 或登录项启动的 `LSUIElement` App 通常没有用户交互式 shell 注入的完整 `PATH`。如果只调用 `/usr/bin/env codex`,Homebrew, Volta 或 npm 全局安装会在 Terminal 中可用,在 CodexBar 中却不可见。-resolver 会做 3 层归一化:+resolver 按以下步骤归一化进程环境:1. 使用 `getpwuid(getuid())` 解析真实登录用户主目录,避免继承 Xcode 或容器环境的错误 `HOME`2. 保留现有 `PATH`,再按顺序补充常见目录并去重@@ -431,7 +431,7 @@ Hook 设置也复用 app-server 链路,但采用独立的可用性状态:日志用于观察进程启动、JSON-RPC 方法、重试和错误分类。不应写入 access token 或 Hook prompt 内容。-`CodexProxyError` 的配置错误只写入系统日志 `settings` 分类,不创建 app-server 请求日志。RPC 响应及错误写入交互日志前,先解析 JSON 转义并遍历字符串值,对 HTTP/HTTPS URL 的认证信息脱敏;非 JSON 文本使用文本脱敏。+`CodexProxyError` 的配置错误只写入系统日志 `settings` 分类,不创建 app-server 请求日志。RPC 响应及错误写入交互日志前,先解析 JSON 转义并遍历字符串值,将 HTTP/HTTPS URL 中的用户名和密码替换为 `<redacted>`;非 JSON 文本直接执行同样的替换。### 请求日志与系统日志@@ -473,7 +473,7 @@ Reset Credits 明细包含 opaque credit ID。系统日志不能记录 ID 或原- 消费成功后的完整额度刷新不会被并发普通刷新丢弃- 手动刷新后 60 秒倒计时重新对齐-代理相关验证还包括:停用无效配置、清除损坏记录、测试取消后旧结果隔离、快速连续切换只提交一次、提交失败回滚,以及普通 URL 和 JSON 转义 URL 的日志脱敏。+代理相关验证还包括:停用无效配置、清除损坏记录、测试取消后旧结果隔离、快速连续切换只提交一次、提交失败回滚,以及日志中普通 URL 和 JSON 转义 URL 的用户名、密码替换。## 关键源码diff --git a/Docs/DeveloperGuide/architecture.md b/Docs/DeveloperGuide/architecture.mdindex 852cd0c..58bbedc 100644--- a/Docs/DeveloperGuide/architecture.md+++ b/Docs/DeveloperGuide/architecture.md@@ -8,7 +8,7 @@CodexBar 是 macOS 15+ 菜单栏应用,使用 Swift 6, SwiftUI, AppKit 和 MVVM。-工程只有 `CodexBar` scheme,包含三个 target:+工程只有 `CodexBar` scheme,包含以下 target:| Target | 职责 || --- | --- |@@ -39,7 +39,7 @@ CodexBar executable`-- fixed IOPM wake event```-边界设计有两个关键点:+边界设计遵循以下原则:- 同一个可执行文件承载 Hook 模式可以让 handler 始终指向当前 App 版本,不需要额外部署采集工具- root helper 不知道 Codex 任务、账户或重置凭证,只接收经过签名校验的睡眠租约和自动重置唤醒时间@@ -119,7 +119,7 @@ Hook handler 在 Codex 的关键路径上,它需要的是接近命令行工具## 3 条独立数据链路-三条数据链路分别管理不同的输入、时效和失败状态:+各数据链路分别管理不同的输入、时效和失败状态:| 链路 | 输入 | 输出 | 主要消费者 || --- | --- | --- | --- |diff --git a/Docs/DeveloperGuide/data-and-privacy.md b/Docs/DeveloperGuide/data-and-privacy.mdindex 75a818e..a98c92b 100644--- a/Docs/DeveloperGuide/data-and-privacy.md+++ b/Docs/DeveloperGuide/data-and-privacy.md@@ -9,7 +9,7 @@| 分类 | 示例 | 默认处理 || --- | --- | --- || 内容 | prompt, response, tool 参数和输出 | 不采集 |-| 身份和上下文 | session ID、完整路径、project 名 | 仅在必要链路最小化使用,上传前脱敏或删除 |+| 身份和上下文 | session ID、完整路径、project 名 | 原始 session ID 和完整路径不上传;Token 轮次使用哈希标识,项目显示名随统计上传 || 聚合指标 | 每日事件数、model 计数 | 可本地持久化,用户 opt-in 后上传规定字段 |## 信任边界@@ -51,9 +51,9 @@ CodexBar 的最小化顺序是:| app-server 账户、额度和 Reset Credits | 主面板、通知判断和用户启用的自动重置 | 仅短期状态 | 否 || Hook 结构化事件 | 历史聚合和实时任务 | 是,最长 210 天 | 只上传日聚合 || rollout 生命周期 | terminal 和进展对账 | 不单独持久化 | 否 |-| rollout token 累计值 | 轮次去重和日汇总 | 哈希身份、时间和计数,210 天 | 用户启用同步后上传脱敏轮次累计值 |+| rollout token 累计值 | 轮次去重和日汇总 | 轮次哈希标识、时间和计数,210 天 | 用户启用同步后上传轮次哈希标识及累计值 || App 设置 | 功能开关和阈值 | UserDefaults | 否 |-| Activity Protection | 异常会话恢复 | 哈希身份,最长 24 小时 | 否 |+| Activity Protection | 异常会话恢复 | 任务哈希标识,最长 24 小时 | 否 || CodexBarHelper ownership | 系统睡眠恢复 | root 状态文件 | 否 || 自动重置唤醒计划 | 固定 owner、`wake` 类型和下一次时间 | 系统电源管理 | 否 |@@ -65,7 +65,7 @@ App 通过本机 `codex app-server --listen stdio://` 获取账户、额度、toCodexBar 不自行实现账户登录。app-server 是否访问 OpenAI 服务由 Codex CLI 的正常认证和协议行为决定。-CodexBar 只通过 stdio 与本机进程通信,不从 app-server 响应中复制认证材料。request log 保存规范化后的完整请求与响应 JSON,只存在当前 App 进程内存,不持久化。内容可能包含账户响应、opaque credit ID 和幂等键,不能把它当作脱敏摘要。+CodexBar 只通过 stdio 与本机进程通信,不从 app-server 响应中复制认证材料。request log 保存规范化后的完整请求与响应 JSON,只存在当前 App 进程内存,不持久化。日志保留账户响应、opaque credit ID 和幂等键等协议字段。### Hook 事件@@ -87,7 +87,7 @@ Hook 子进程从 rollout 首条 `session_meta` 的完整记录或已完成字Hook recorder 通过 `transcript_path` 读取当前 rollout,`SubagentStop` 的来源使用子线程自身的 `agent_transcript_path`。实时活动 reader 访问 `$CODEX_HOME/sessions` 和 `$CODEX_HOME/archived_sessions` 中相关主线程及子线程的文件。-这些读取只解析来源分类、线程及轮次归属、生命周期、时间、turn context、progress、effort、reviewer 和 token 计数等结构字段。实时线程关联只在内存中使用;历史 token 账本仅保存哈希身份、必要时间和六项累计计数。对话正文不进入 CodexBar 存储或 UI。+这些读取只解析来源分类、线程及轮次归属、生命周期、时间、turn context、progress、effort、reviewer 和 token 计数等结构字段。实时线程关联只在内存中使用;历史 token 账本仅保存轮次哈希标识、必要时间和 Token 累计计数。对话正文不进入 CodexBar 存储或 UI。Token 历史扫描从文件起点建立轮次账本,再按游标增量读取。云端身份使用账户 salt 做 HMAC-SHA256,不上传原始线程或轮次 ID。字段和保留规则见 [Rollout Token 历史](sync.md#rollout-token-历史)@@ -210,13 +210,13 @@ App 内 [`RequestLog.swift`](../../CodexBar/Services/CodexStatus/RequestLog.swif- 完整项目路径或敏感项目名- 账户额度和 token 用量明细-`CodexProxyError` 的固定错误文案写入系统日志的 `settings` 分类,不包含配置值。app-server 响应写入 App 交互日志前会解析 JSON 转义,对字符串值中的 HTTP/HTTPS URL 认证信息脱敏;其他账户和协议字段仍按请求日志规则保留。+`CodexProxyError` 的固定错误文案写入系统日志的 `settings` 分类,不包含配置值。app-server 响应写入 App 交互日志前会解析 JSON 转义,将字符串值中 HTTP/HTTPS URL 的用户名和密码替换为 `<redacted>`;其他账户和协议字段仍按请求日志规则保留。## 网络访问| 目标 | 用途 | 触发条件 || --- | --- | --- |-| CloudKit private database | 同步日级 Hook 聚合和脱敏轮次 token 累计值 | 用户主动开启同步 |+| CloudKit private database | 同步日级 Hook 聚合、轮次哈希标识及 Token 累计值 | 用户主动开启同步 || Codex 服务(app-server 子进程) | 认证、额度、用量和 Reset Credit 消费 | 正式刷新、代理测试或自动重置 || Sparkle appcast 和更新资源 | 检查或安装更新 | 自动检查或用户手动检查 |@@ -230,7 +230,7 @@ CodexBarHelper 不进行任何网络访问。CloudKit 上传以下 Hook 日聚合字段:-- 设备 pseudonym+- 设备哈希标识 `deviceId`- 日期和 source generation- Hook 事件计数- session 和 turn 计数@@ -238,7 +238,7 @@ CloudKit 上传以下 Hook 日聚合字段:- model 计数- 更新时间-此外,token 历史上传账户内稳定的哈希轮次标识、根轮次关联、必要时间和六项累计计数,用于跨设备去重和按日汇总。+此外,token 历史上传账户内稳定的哈希轮次标识、根轮次关联、必要时间和 Token 累计计数,用于跨设备去重和按日汇总。CloudKit 不上传:@@ -257,7 +257,7 @@ project 显示名可能由目录名派生,仍可能包含用户敏感信息。## root helper 的数据隔离-CodexBarHelper 只需要知道 4 类状态:+CodexBarHelper 只接收以下状态:- 哪个已验证客户端持有哪一代 lease- `SleepDisabled` 当前实测值diff --git a/Docs/DeveloperGuide/design-decisions.md b/Docs/DeveloperGuide/design-decisions.mdindex bd299ce..cdf8f2e 100644--- a/Docs/DeveloperGuide/design-decisions.md+++ b/Docs/DeveloperGuide/design-decisions.md@@ -58,4 +58,4 @@ Token 账本以线程和轮次组成稳定身份,累计快照去重后按根任务识别、自动重置策略和网络访问在主 App 中执行。root helper 只接受固定的睡眠租约与唤醒操作,通过签名校验客户端,并回读系统结果。-CloudKit 同步日级活动聚合与脱敏的线程轮次 Token 记录。原始事件、原始会话标识、账户和代理密码留在本机;项目显示名属于上传内容,必须由用户开启同步。字段和存储范围见 [数据与隐私边界](data-and-privacy.md)+CloudKit 同步日级活动聚合与线程轮次 Token 记录,轮次标识由 thread ID 和 turn ID 组合后计算哈希生成。原始事件、原始会话标识、账户和代理密码留在本机;项目显示名属于上传内容,必须由用户开启同步。字段和存储范围见 [数据与隐私边界](data-and-privacy.md)diff --git a/Docs/DeveloperGuide/development.md b/Docs/DeveloperGuide/development.mdindex b71aa46..f94d94d 100644--- a/Docs/DeveloperGuide/development.md+++ b/Docs/DeveloperGuide/development.md@@ -4,7 +4,7 @@## 环境与构建-需要 macOS 15+、Xcode、Swift 6、`swiftformat` 和 `swiftlint`。唯一 scheme 为 `CodexBar`,包含 App、`CodexBarHelper` 和 `CodexBarTests` 三个 target。+需要 macOS 15+、Xcode、Swift 6、`swiftformat` 和 `swiftlint`。唯一 scheme 为 `CodexBar`,包含 App、`CodexBarHelper` 和 `CodexBarTests` target。```bashxcodebuild -project CodexBar.xcodeproj -scheme CodexBar -destination 'generic/platform=macOS' builddiff --git a/Docs/DeveloperGuide/hook-and-aggregation.md b/Docs/DeveloperGuide/hook-and-aggregation.mdindex 2c34182..d0eecf0 100644--- a/Docs/DeveloperGuide/hook-and-aggregation.md+++ b/Docs/DeveloperGuide/hook-and-aggregation.md@@ -285,7 +285,7 @@ source generation 让同一天的不同原始来源可被区分。同源结果### `pending` 和 `dirty` 的区别-`maintenance.json` 对每个日期维护两类待办:+`maintenance.json` 对每个日期维护以下待办:| 状态 | 何时使用 | 下一步 || --- | --- | --- |@@ -298,7 +298,7 @@ source generation 让同一天的不同原始来源可被区分。同源结果### 如何判断文件还是同一来源-维护层综合 4 类证据:+维护层综合以下证据:- inode 标识是否变化- 当前 size 是否小于已处理 offset@@ -436,7 +436,7 @@ schema 变化通常把保留期内所有事件日期标脏。source generation### scheduler 如何合并请求-`WorkflowSyncScheduler` 串行处理 3 类请求:+`WorkflowSyncScheduler` 串行处理以下请求:1. 用户重建,优先级最高2. 带同步的维护diff --git a/Docs/DeveloperGuide/notifications.md b/Docs/DeveloperGuide/notifications.mdindex 8dbba6e..c03e222 100644--- a/Docs/DeveloperGuide/notifications.md+++ b/Docs/DeveloperGuide/notifications.md@@ -6,7 +6,7 @@[`CodexNotificationService.swift`](../../CodexBar/Services/Notifications/CodexNotificationService.swift) 是通知副作用的统一入口。-它接收四类状态:+它接收以下状态:- app-server 账户与额度快照- `CodexActivityMonitor` 任务转场与异常会话保护候选@@ -35,7 +35,7 @@ App 激活、设置窗口重新获得焦点或显式打开时会重新读取系## 通知开关-通知总开关默认关闭。8 个可配置分类的子开关默认开启,触觉反馈默认关闭。+通知总开关默认关闭。各可配置分类的子开关默认开启,触觉反馈默认关闭。总开关关闭时不会申请系统通知权限,也不会发送任何分类通知。子开关用于在总开关开启后选择具体类型:@@ -210,7 +210,7 @@ App idle assertion 保留到通知提交结束,随后释放,由 macOS 按系## 触觉反馈-触觉反馈默认关闭。开启后使用 10 次脉冲,每次间隔约 100 ms。+触觉反馈默认关闭。开启后通过连续短脉冲提供提醒。触觉是系统通知之外的独立本地反馈。它响应非匿名任务的完成或等待 transition,服从通知总开关和触觉开关,但不依赖系统通知授权、分类通知开关或完成时长阈值。diff --git a/Docs/DeveloperGuide/sleep-prevention.md b/Docs/DeveloperGuide/sleep-prevention.mdindex 61e928e..130da9d 100644--- a/Docs/DeveloperGuide/sleep-prevention.md+++ b/Docs/DeveloperGuide/sleep-prevention.md@@ -23,7 +23,7 @@ AutoResetController## 状态分层-系统把状态拆成 4 层:+系统按职责区分状态:| 层级 | 代表字段 | 回答的问题 || --- | --- | --- |@@ -142,7 +142,7 @@ App 侧 assertion 只覆盖当前进程生命周期。系统级 `SleepDisabled`CodexBarHelper 通过 `SMAppService` 注册为 LaunchDaemon。App 和 CodexBarHelper 使用 [`CodexBarHelperXPC.swift`](../../Shared/CodexBarHelperXPC.swift) 定义的 XPC 接口。-接口只提供 4 类能力:+接口只提供以下能力:- 设置或撤销 App 租约- 查询 CodexBarHelper 运行和拥有状态@@ -424,7 +424,7 @@ App 更新可能改变内嵌 CodexBarHelper 的签名或内容。App 会记录 C- App 正常退出时恢复 owned 状态- App 强制退出或 XPC 断开后,watchdog 恢复 owned 状态- 自动重置和防睡眠每次开启都显示确认,取消后保持关闭-- 未注册、等待批准和已批准三种 helper 状态的确认文案与功能说明正确+- 未注册、等待批准和已批准等 helper 状态的确认文案与功能说明正确- 包完整且没有注册错误时,`.notRegistered` 和 `.notFound` 均显示“未安装”- 在测试包中分别移除 Helper、移除或篡改 plist、破坏签名,启动或再次激活后显示“不可用”,已授权状态也不能掩盖包异常- 安装前发现缺失后,旧校验结果不覆盖新异常;关闭两个功能并修复完整 App 包后,再次激活能清除异常,关于页面仍显示状态diff --git a/Docs/DeveloperGuide/sync.md b/Docs/DeveloperGuide/sync.mdindex 254553a..dc08f86 100644--- a/Docs/DeveloperGuide/sync.md+++ b/Docs/DeveloperGuide/sync.md@@ -20,7 +20,7 @@ app-server 账户、额度、账户 token 总量、Reset Credits、自动重置## 数据来源-Hook 日聚合展示同时使用 3 类值。Token 轮次账本及其云端缓存见 [Rollout Token 历史](#rollout-token-历史)+Hook 日聚合展示使用以下数据。Token 轮次账本及其云端缓存见 [Rollout Token 历史](#rollout-token-历史)| 数据 | 权威来源 | 断网时行为 || --- | --- | --- |@@ -61,7 +61,7 @@ zone 确认和账户 salt 在 actor 内跨轮次缓存;同步失败时使两每轮同步都会检查本地保留期内的全部日期,通过 hash 筛选需要上传的数据,首次启用和后续补传使用同一流程。同步调度有最短 8 秒冷却,合并短时间内的多次本地变化。-## 设备匿名化+## 设备标识哈希同步需要区分设备贡献,但不能直接上传硬件标识:@@ -70,7 +70,7 @@ zone 确认和账户 salt 在 actor 内跨轮次缓存;同步失败时使两3. 使用账户 salt 对 UUID 执行 HMAC-SHA2564. 把结果作为云端 `deviceId`-原始 `IOPlatformUUID` 不会上传。同一设备在同一 iCloud 账户中得到稳定 pseudonym,不同账户得到不同结果。+原始 `IOPlatformUUID` 不会上传。同一设备在同一 iCloud 账户中得到稳定的设备哈希标识,不同账户得到不同结果。salt 存在同一个 private custom zone 中。多台设备先后创建时通过 CloudKit 冲突后回读现有记录收敛到同一份 salt,而不是让每台设备各自产生不兼容身份。@@ -81,7 +81,7 @@ salt 存在同一个 private custom zone 中。多台设备先后创建时通过每条日记录包含:- schema-- device ID pseudonym+- 设备哈希标识 `deviceId`- 日期- source generation- Hook 事件计数@@ -118,7 +118,7 @@ Token 历史使用同一 private zone 中独立的 `CodexBarTokenTurn` 记录,| `startedAt` | Date | 轮次开始时间,可缺失 || `observedAt` | Date | 最近累计记录的时间 || `rebuiltAt` | Date | 可选的显式重建时间,用于拒绝旧统计回流 |-| `usage` | Bytes | 六项 token 整数的 JSON,可缺失 |+| `usage` | Bytes | Token 整数计数的 JSON,可缺失 |记录名直接使用轮次哈希,保持稳定;数据格式版本由 `schemaVersion` 字段管理。缺少 `usage` 的记录不贡献用量:根记录可用于确定子轮次日期,带 `rebuiltAt` 的记录可用于清除该轮旧计数。上传前读取服务端记录,保留更完整的累计快照,使用 `ifServerRecordUnchanged` 条件写入;并发冲突留待下一轮重新获取、合并和重试。不会把多个累计快照相加,也不会对输入、缓存和输出字段分别拼接最大值。@@ -128,7 +128,7 @@ Token 历史使用同一 private zone 中独立的 `CodexBarTokenTurn` 记录,日汇总累加去重后的线程轮次,缓存命中率使用日缓存命中总量除以日输入总量。热力图颜色和账户用量来自 app-server,与 rollout 用量独立。热力图日期详情将缺失用量显示为 `0`,缓存命中率显示为 `0%`;存储与同步仍保留缺失状态。-本地账本位于 `HookEvents/Tokens/ledger.json`,保存哈希身份、累计值、开始时间和文件读取游标。独立文件锁协调 Debug 和 Release。同步缓存与游标位于 `HookEvents/Sync/Tokens/cache.json`,记录按账户校验,Debug 和 Release 共用。整轮同步由非阻塞 `sync.lock` 协调,独立文件锁保护缓存读写,界面读取不等待网络。Hook 日聚合使用独立的存储与同步记录。+本地账本位于 `HookEvents/Tokens/ledger.json`,保存轮次哈希标识、累计值、开始时间和文件读取游标。独立文件锁协调 Debug 和 Release。同步缓存与游标位于 `HookEvents/Sync/Tokens/cache.json`,记录按账户校验,Debug 和 Release 共用。整轮同步由非阻塞 `sync.lock` 协调,独立文件锁保护缓存读写,界面读取不等待网络。Hook 日聚合使用独立的存储与同步记录。历史扫描覆盖 `$CODEX_HOME/sessions` 和 `$CODEX_HOME/archived_sessions` 中最近 210 天内修改的 `rollout-*.jsonl` 文件,单轮读取预算为 64 MiB,最多额外读完一条 1 MiB 内的记录。超出预算的历史在后续维护中继续补读。同批尚未读取的文件优先处理最近修改的会话,再逐步补齐更早历史。正文大行有界跳过,半行等待下一轮补齐;文件替换、截断或读取边界改变时重新扫描,已知累计用量不会再次叠加。轮次按 `updatedAt` 保留 210 天,仍被保留子轮次引用的根记录一同保留;日汇总只展示根轮次开始日位于保留期内的数据。原始 rollout 缺失或没有 `token_usage_record` 时无法补出用量。@@ -139,7 +139,7 @@ Token 历史使用同一 private zone 中独立的 `CodexBarTokenTurn` 记录,```text读取本地同步状态-> 创建或确认 custom zone- -> 读取账户 salt 并解析设备 pseudonym+ -> 读取账户 salt 并计算设备哈希标识-> 按设备身份和 schema 更新本地状态-> 拉取远端变更到缓存,处理待替换日期-> 上传当前设备变化日期@@ -256,7 +256,7 @@ replacement 删除前全量拉取当前设备同日记录,覆盖本地增量Hook 日聚合的 CloudKit record schema 为 `6`。本地同步状态 schema 为 `4`,能读取上一版 schema `3`-3 个文件有不同的可恢复等级:+各文件的可恢复等级如下:| 文件 | 丢失后代价 | 恢复方式 || --- | --- | --- |diff --git a/Docs/DeveloperGuide/ui-and-lifecycle.md b/Docs/DeveloperGuide/ui-and-lifecycle.mdindex 7d939af..50174bd 100644--- a/Docs/DeveloperGuide/ui-and-lifecycle.md+++ b/Docs/DeveloperGuide/ui-and-lifecycle.md@@ -10,7 +10,7 @@ CodexBar 在 [`Info.plist`](../../CodexBar/Resources/Info.plist) 中配置为 `LUI 使用 SwiftUI 声明内容,由 AppKit Controller 管理窗口。-## `LSUIElement` 下的 3 类焦点+## `LSUIElement` 下的焦点状态开发时需要区分:@@ -18,7 +18,7 @@ UI 使用 SwiftUI 声明内容,由 AppKit Controller 管理窗口。- 某个 window 是否 key- 菜单表面是否逻辑上 presented-这 3 个状态不会自动同步。例如 Command-Space 会让 App resign active,但用户可能只是临时打开 Spotlight,不希望菜单立即消失。设置窗口可能已经可见,但菜单关闭动画期间不应抢回 key 造成闪烁。+这些状态不会自动同步。例如 Command-Space 会让 App resign active,但用户可能只是临时打开 Spotlight,不希望菜单立即消失。设置窗口可能已经可见,但菜单关闭动画期间不应抢回 key 造成闪烁。因此代码不使用 `NSApp.isActive` 作为菜单唯一真相,而是维护显式的 menu surface 状态和当前容器,再由事件监听器协调 activation。@@ -52,14 +52,14 @@ UI 使用 SwiftUI 声明内容,由 AppKit Controller 管理窗口。| 场景 | 展示规则 || --- | --- || 存在活跃任务 | 等待批准优先于运行 |-| 其他任务仍活跃时确认结束事件 | 最新事件覆盖活动状态 3 秒,最后 0.5 秒淡出;新事件替换提示并重新计时 |-| 无活跃任务 | 快照中的最新终态按设置的结束时长显示,默认结束后 10 秒到期,最后 1 秒淡出 |+| 其他任务仍活跃时确认结束事件 | 最新事件短暂覆盖活动状态后淡出;新事件替换提示并重新计时 |+| 无活跃任务 | 快照中的最新终态按设置的结束时长显示,到期前淡出 |颜色、速度、亮度和结束时长由 `TaskGlowSettings.appearance` 提供。默认运行使用青色,等待批准使用橙色,完成使用绿色,终止使用红色;结束时间相同优先终止。所有计时包含进场动画,到期后按最新快照恢复展示。-设置从关闭切换为开启且 Hook 可用时,`TaskGlowSettings.previewRequests` 请求一次使用当前外观设置的运行预览,完成一个往返周期后恢复实际状态,标准速度下周期为 2.7 秒。启动和设置刷新只恢复开关值,不触发预览。+设置从关闭切换为开启且 Hook 可用时,`TaskGlowSettings.previewRequests` 请求一次使用当前外观设置的运行预览,完成一个往返周期后恢复实际状态。启动和设置刷新只恢复开关值,不触发预览。-双击设置面板中的颜色块请求对应状态的预览:运行播放一个往返周期,等待批准展开后播放两次呼吸,完成和终止显示 3 秒,最后 0.5 秒淡出。颜色预览可以替换正在播放的预览;收起设置子面板只结束颜色预览。开启预览在已有预览或窗口收尾期间忽略重复请求。+双击设置面板中的颜色块请求对应状态的预览:运行展示往返流光,等待批准展示呼吸效果,完成和终止短暂显示后淡出。颜色预览可以替换正在播放的预览;收起设置子面板只结束颜色预览。开启预览在已有预览或窗口收尾期间忽略重复请求。预览覆盖期间继续接收真实任务更新,不产生任务事件。真实结束提示暂停计时,恢复时按最新快照展示:已有提示继续剩余时长,暂停期间产生的提示保留完整时长。预览切换时各屏幕共用开始时刻,旧光带收回时间不占用目标效果的展示时长。@@ -86,15 +86,15 @@ UI 使用 SwiftUI 声明内容,由 AppKit Controller 管理窗口。- 活跃任务持续时间每分钟变化,只更新 tooltip- 额度过期但仍展示缓存时,图标和进度使用降低后的 alpha- `StatusItemIconView` 按符号名称和屏幕倍率缓存预渲染图片,缩放时复用图片,避免带徽章符号实时渲染时的卡顿-- 符号名称变化时,新旧图片在 0.2 秒内交叉淡入淡出,并在 75% 与完整大小之间缩放;只切换额度显隐时不触发图片替换-- 额度显隐在 0.3 秒内将彩色圆弧从零绘制到当前额度,或从当前额度收回到零,底轨独立淡入淡出-- 人物按符号基线对齐,隐藏额度时恢复正常大小;大小和位置在 0.2 秒内过渡+- 符号名称变化时,新旧图片交叉淡入淡出并配合缩放过渡;只切换额度显隐时不触发图片替换+- 额度显隐时将彩色圆弧从零绘制到当前额度,或从当前额度收回到零,底轨独立淡入淡出+- 人物按符号基线对齐,隐藏额度时恢复正常大小;大小和位置平滑过渡- 关闭额度时保留最后的额度和配色供收回动画使用,零额度与缺失额度保持不同语义- 初次渲染和唤醒重算时不播放过渡动画SwiftUI 视图持续挂载在原生 `NSStatusBarButton` 中,透明图片用于系统自适应占位。图标使用系统前景色,宿主视图不接受焦点或鼠标命中,左右键仍交给原按钮处理。-tooltip 在存在活跃任务时每 60 秒更新,空闲时停止计时。`NSInitialToolTipDelay` 为 500 ms。+tooltip 在存在活跃任务时每 60 秒更新,空闲时停止计时。左键打开主面板。右键或按住 Control 点击打开上下文菜单。@@ -106,7 +106,7 @@ tooltip 在存在活跃任务时每 60 秒更新,空闲时停止计时。`NSIn### 开合状态机-`menuSurfaceState` 有 4 个状态:+`menuSurfaceState` 的状态流转如下:```texthidden -> opening -> shown -> closing -> hidden@@ -143,9 +143,9 @@ hidden -> opening -> shown -> closing -> hidden### 淡入淡出与完成任务-`MenuSurfaceFadeCoordinator` 同时调整活动容器的内容视图和窗口透明度,淡入为 0.24 秒,淡出为 0.18 秒。控制器只保存一个完成任务;新动画开始前取消旧任务,任务等待结束后检查取消状态,再标记已显示或完成关闭。+`MenuSurfaceFadeCoordinator` 同时调整活动容器的内容视图和窗口透明度,实现面板的淡入淡出。控制器只保存一个完成任务;新动画开始前取消旧任务,任务等待结束后检查取消状态,再标记已显示或完成关闭。-关闭期间设置和日志窗口暂时拒绝 `makeKey()`,关闭完成后约 120 ms 恢复。完成任务弱引用当次窗口,关闭后恢复内容视图和窗口透明度。+关闭期间设置和日志窗口暂时拒绝 `makeKey()`,关闭完成后短暂延迟再恢复。完成任务弱引用当次窗口,关闭后恢复内容视图和窗口透明度。### 内容动画与展示状态@@ -155,11 +155,17 @@ popover 和备用面板分别持有 `MenuSurfaceAnimationState`。展示前将 ``MenuSurfaceVisibilityState` 在面板展示后开启,在关闭开始时结束。每次展示递增 `presentationGeneration`,额度和用量区域以该值作为视图身份,重新执行入场动画。+主面板根视图使用固定宽度和内容所需的高度。Popover 通过 `preferredContentSize` 跟随内容尺寸;备用面板通过 `onGeometryChange` 获取内容高度,在可见时直接更新窗口高度,保持宽度和顶边位置。+### 活动卡片-`CodexActivityCard` 使用 `primaryActivity`,优先显示等待批准,其次是运行中;无活跃任务时按结束时间选择最新的完成或终止,时间相同优先终止。`isActivelyPreventingSleep` 为 `true` 且卡片数据可用时显示青绿色 `sun.max.fill`,tooltip 按 `sleepPreventionSource` 显示来源。所属宿主的 `mainPanelAnimationsEnabled` 开启时,太阳徽标每 2 秒匀速顺时针旋转一圈;关闭时移除旋转视图并显示静态图标。+`CodexActivityCard` 使用 `primaryActivity`,优先显示等待批准,其次是运行中;无活跃任务时按结束时间选择最新的完成或终止,时间相同优先终止。`isActivelyPreventingSleep` 为 `true` 且卡片数据可用时显示青绿色 `sun.max.fill`,tooltip 按 `sleepPreventionSource` 显示来源。所属宿主的 `mainPanelAnimationsEnabled` 开启时,太阳徽标匀速顺时针旋转;关闭时移除旋转视图并显示静态图标。++活动卡片和任务中心共用 `CodexActivityStatusText`,文字颜色跟随任务状态。运行时显示扫光,等待批准时显示橙色粒子,完成和终止时静态显示。卡片状态文字动画由 `mainPanelAnimationsEnabled` 控制,任务中心状态文字动画要求 `presentationState.isPresented` 和 `MainPanelSettings.areEntranceAnimationsEnabled` 同时开启。每个面板共用一条粒子时间线,只从可见的等待文字发射粒子,按面板边界裁剪;没有发射源时移除时间线。-活动卡片和任务中心共用 `CodexActivityStatusText`,文字颜色跟随任务状态。运行时显示扫光,等待批准时显示橙色粒子,完成和终止时静态显示。卡片动画由 `mainPanelAnimationsEnabled` 控制,任务中心动画要求 `presentationState.isPresented` 和 `MainPanelSettings.areEntranceAnimationsEnabled` 同时开启。每个面板共用一条粒子时间线,只从可见的等待文字发射粒子,按面板边界裁剪;没有发射源时移除时间线。+活动卡片在 `primaryActivity.tokenUsage` 可用时展示 Token 指标和分割线。状态行固定在卡片顶部,卡片高度随 Token 区域显隐调整。++展开和收起采用平滑减速的过渡,独立于“动画效果”设置。Token 区域随展开进度淡入并轻微上移,收起时提前淡出。`ActivityCardHeight` 逐帧提交插值后的布局高度,使相邻区块和主面板尺寸同步变化。防睡眠徽标、匿名图标和并发任务数的动画限定在状态行内。## Fallback panel@@ -171,12 +177,12 @@ popover 和备用面板分别持有 `MenuSurfaceAnimationState`。展示前将 `- window 和 screen 存在- button 没有隐藏且 bounds 非空-- 转换后的屏幕 rect 有效且至少为 1 point-- rect 与目标屏幕 frame 在 1 point 容差内相交+- 转换后的屏幕 rect 有效且满足最小尺寸要求+- rect 与目标屏幕 frame 在允许的容差内相交只有全部成立才使用 popover 箭头。否则 fallback panel 放到鼠标所在屏幕。这避免 popover 被 AppKit 放到错误显示器或完全不可见的位置。-fallback panel 在展示前根据 SwiftUI fitting size 和目标屏幕可见区域约束尺寸。坐标计算集中在 `ScreenGeometry`,因为 AppKit 使用左下角原点,SwiftUI 局部布局和多显示器 frame 很容易混用。+fallback panel 展示前使用主面板固定宽度和 SwiftUI fitting height,在目标屏幕可见区域水平居中,顶部留有间距。无法取得有效 fitting size 时,使用默认高度。## 侧边详情面板@@ -194,17 +200,15 @@ fallback panel 在展示前根据 SwiftUI fitting size 和目标屏幕可见区主面板关闭时立即清理侧边面板。热力图详情和共享抽屉在立即关闭或窗口已不可见时,重置抽屉动画、执行 `orderOut` 并移除父子窗口关系。任务中心已结束逻辑展示时,立即关闭请求仍传递给共享抽屉。-热力图按格子的列、行位置错开入场。启用入场动画时,每个格子在自身入场延迟加 0.25 秒后接受悬停;关闭入场动画时立即接受悬停。+热力图按格子的列、行位置错开入场。启用入场动画时,每个格子在入场过渡后接受悬停;关闭入场动画时立即接受悬停。热力图详情面板以包含标题、日期范围和方格矩阵的完整热力图区域作为垂直锚点,因此主面板区域重排后仍优先保持两者顶边对齐。如果详情面板从该位置向下会超过主面板底边,则定位逻辑将它整体上移到与主面板底边对齐。主面板可见时,数字随数据变化滚动,Token 数字与待查询或不可用占位之间淡入淡出。“动画效果”控制入场动画、太阳徽标旋转和任务状态文字动画,数字更新不受此开关控制。-活动卡片的 Token 区域仅在 `primaryActivity.tokenUsage` 可用时出现,七项等宽居中,分割线随区域一起显示。可用性变化触发卡片高度和主面板尺寸动画,独立于“动画效果”设置。Popover 在内容尺寸更新前临时启用 `animates`;fallback 等待 `@Published` 完成赋值后测量,并保持顶边位置。--Hook 开启时,热力图详情采用两栏:顶部 10 格强度条通栏,左侧活动统计,右侧会话 Token。每栏用 `Grid` 按最长标签确定统一名称宽度,数值使用剩余空间。日期切换时,Token 与活动数值使用相同的 `numericText` 过渡,最常用模型使用同一文本视图过渡并按可用宽度缩小字号。+Hook 开启时,热力图详情按活动统计和会话 Token 分组,并展示用量强度条。各组用 `Grid` 对齐名称和数值。日期切换时,Token 与活动数值使用相同的 `numericText` 过渡,最常用模型使用同一文本视图过渡并按可用宽度缩小字号。-共享 `LiquidGlassDivider` 使用银灰和冷白渐变,按 8 秒周期缓慢移动。它通过所在 `NSView` 的窗口可见状态暂停或恢复时间线,不受“动画效果”设置控制。+共享 `LiquidGlassDivider` 使用银灰和冷白渐变,缓慢循环移动。它通过所在 `NSView` 的窗口可见状态暂停或恢复时间线,不受“动画效果”设置控制。相关控制器包括:@@ -252,7 +256,7 @@ SwiftUI 可能在窗口创建完成前上报高度。`SettingsWindowController``MainPanelSettings` 使用稳定区域标识保存账户、任务中心、额度、Token 用量和底部状态的顺序与显隐。布局归一化会去重、忽略无效值、补齐缺失区域,并保证至少保留一个可见区域。`StatusItemController` 在读取到 Hook 关闭状态后调用 `updateHookEnabled(_:)`,持久化关闭任务中心;如果任务中心原本是唯一可见区域,则同时开启账户区域。从关闭切换到开启时自动显示任务中心,首次恢复开启状态和重复开启通知均保留用户布局。设置面板只禁用任务中心开关,拖拽手柄仍保持可用。其他数据链路的临时可用性只影响当次渲染。-布局排序使用手柄上的自定义 `DragGesture`。拖动项通过悬浮副本跟随指针,其他行在跨过半行距离时按视图内预览顺序实时让位,松手后才调用 `setSectionOrder(_:)` 一次性持久化最终顺序。+布局排序使用手柄上的自定义 `DragGesture`。拖动项通过悬浮副本跟随指针,其他行随拖动位置按视图内预览顺序实时让位,松手后才调用 `setSectionOrder(_:)` 一次性持久化最终顺序。`SettingsWindowController` 持有这一窗口组唯一的 `UndoManager`。设置主窗口通过 `AuxiliaryHostingWindow` 暴露它,各设置子面板展示时从父窗口取得同一实例,因此焦点位于设置主窗口或任一子面板时,`⌘Z` 和 `⌘⇧Z` 都作用于同一份布局历史。Hook 状态变化引起的任务中心自动显隐不进入用户撤销历史。@@ -290,7 +294,7 @@ Carbon API 适合无 Dock 菜单栏 App,不需要安装全局键盘事件 tap## 自动刷新与面板打开-app-server 状态默认每 60 秒检查刷新。主面板的 0.24 秒淡入完成且面板仍可见时,调用 `refreshIfNeeded`;倒计时起点为空或距上次刷新结果提交超过 60 秒时才发起请求。成功和失败的结果提交都会重置倒计时。+app-server 状态默认每 60 秒检查刷新。主面板淡入完成且面板仍可见时,调用 `refreshIfNeeded`;倒计时起点为空或距上次刷新结果提交超过 60 秒时才发起请求。成功和失败的结果提交都会重置倒计时。主面板显示刷新倒计时,双击账户图标可立即手动刷新。@@ -318,13 +322,13 @@ app-server 状态默认每 60 秒检查刷新。主面板的 0.24 秒淡入完## 手动验证- 左键打开主面板,右键和 Control 点击打开上下文菜单-- 多任务运行或等待批准期间,完成和终止触发 3 秒流光提示;颜色跟随配置,全部任务结束后按所选结束时长到期+- 多任务运行或等待批准期间,完成和终止触发短暂流光提示;颜色跟随配置,全部任务结束后按所选结束时长到期- 开启流光按当前颜色、速度和亮度播放一次预览,关闭时收回并淡出,收尾期间不重播开启预览,收尾后可再次开启预览;双击颜色块可连续替换预览,收起子面板结束颜色预览;恢复时已有结束提示继续剩余时长,预览期间产生的提示按最新状态显示并保留完整时长- 历史重读及唤醒对账不补播旧终态短提示,恢复后的真实结束仍有提示;多显示器和屏幕配置变化后运动与到期时间一致- 菜单栏符号随任务状态切换,最新终态在结束 10 秒后恢复空闲,跨睡眠唤醒后按当前时间显示-- 普通人物与四种任务徽章之间切换时过渡完整,快速连续切换后显示最新状态;带徽章时反复切换额度显隐仍保持流畅,首次显示和唤醒重算不播放过渡+- 普通人物与各任务徽章之间切换时过渡完整,快速连续切换后显示最新状态;带徽章时反复切换额度显隐仍保持流畅,首次显示和唤醒重算不播放过渡- 切换额度圆弧显隐时动画完整,零额度保留底轨,缓存额度变淡-- 防睡眠生效时太阳徽标仅在“动画效果”开启且所属面板展示期间旋转;关闭动画效果后保留静态太阳,再次开启后仅可见宿主恢复旋转;冷启动后不打开面板、关闭后继续运行任务时均无持续旋转开销;重开、快速开关和 popover 与 fallback 切换后均保持每 2 秒一圈的匀速旋转,任务结束后徽标消失+- 防睡眠生效时太阳徽标仅在“动画效果”开启且所属面板展示期间旋转;关闭动画效果后保留静态太阳,再次开启后仅可见宿主恢复旋转;冷启动后不打开面板、关闭后继续运行任务时均无持续旋转开销;重开、快速开关和 popover 与 fallback 切换后均保持匀速旋转,任务结束后徽标消失- 代理密码显隐切换时淡化正常,输入内容、选区和焦点保留- 点击主面板外部正确关闭,点击侧边面板不误关闭- 热力图、Reset Credits 和活动中心保持互斥@@ -334,11 +338,11 @@ app-server 状态默认每 60 秒检查刷新。主面板的 0.24 秒淡入完- 从通知点击激活 App 并打开面板- 设置窗口首次打开、关闭和再次打开时焦点正确- 关于页刷新或重连期间,关闭、最小化、完全遮挡设置窗口或切离关于页后,重连图标不再持续绘制或摆动;恢复展示后仅在仍忙碌时恢复动画,窗口失焦但仍可见时行为正常-- 冷启动后首次打开设置时通用页直接使用完整内容高度;切换三个 tab 时窗口高度自适应,屏幕空间充足时均不显示滚动条+- 冷启动后首次打开设置时通用页直接使用完整内容高度;切换各设置页时窗口高度自适应,屏幕空间充足时均不显示滚动条- 主面板布局、流光、通知、自动重置和防睡眠子面板互斥,顶边对齐对应设置行,内容变化后高度正确- 流光子面板展开时颜色输入框不自动聚焦;六位输入限制、粘贴过滤和大写转换正确;无效颜色在回车、失焦及收起时恢复默认,显示与实际颜色一致- 设置子面板展开时从菜单栏打开主面板,主面板保持打开,设置子面板收起且不把焦点抢回设置窗口-- 主面板区域拖动时悬浮行跟随指针,跨过半行后其他行实时让位,松手后平滑落位并只保存最终顺序;拖拽和显隐操作可以通过 `⌘Z` 逐步撤销并通过 `⌘⇧Z` 重做,焦点在设置主窗口或任一设置子面板时均有效;重启后保持配置,最后一个可见区域无法关闭;Hook 关闭时任务中心自动关闭、开关置灰但仍可拖动,任务中心为唯一可见区域时账户自动开启;重新开启 Hook 后任务中心自动显示,手动隐藏后重启仍保持隐藏,自动联动不进入用户撤销历史+- 主面板区域拖动时悬浮行跟随指针,其他行随拖动位置实时让位,松手后平滑落位并只保存最终顺序;拖拽和显隐操作可以通过 `⌘Z` 逐步撤销并通过 `⌘⇧Z` 重做,焦点在设置主窗口或任一设置子面板时均有效;重启后保持配置,最后一个可见区域无法关闭;Hook 关闭时任务中心自动关闭、开关置灰但仍可拖动,任务中心为唯一可见区域时账户自动开启;重新开启 Hook 后任务中心自动显示,手动隐藏后重启仍保持隐藏,自动联动不进入用户撤销历史- 上下文菜单打开设置或日志时没有焦点丢失- 多显示器和不同菜单栏位置下 fallback panel 位于鼠标屏幕- 快捷键冲突后原快捷键仍可用@@ -346,7 +350,7 @@ app-server 状态默认每 60 秒检查刷新。主面板的 0.24 秒淡入完- 数字首次递减、连续增减、Token 单位切换和日期跨月时方向正确,主面板关闭后停止数字动画- 中英文下快速切换热力图日期,名称列宽稳定,Token 数字和模型名原位过渡-- Token 区域从无到有、由有到无时,popover 和 fallback 尺寸平滑变化;关闭动画设置后仍保留此效果+- Token 区域从无到有、由有到无或动画中途反向切换时,卡片、相邻区块和 popover、fallback 尺寸同步变化,区块间距不变且无重叠;关闭动画设置后仍保留此效果- 所有共享分割线缓慢流动,关闭或隐藏所属窗口后停止持续绘制## 关键源码diff --git a/Docs/UserGuide/activity-and-hook.md b/Docs/UserGuide/activity-and-hook.mdindex 973de65..2a22350 100644--- a/Docs/UserGuide/activity-and-hook.md+++ b/Docs/UserGuide/activity-and-hook.md@@ -43,7 +43,7 @@ CodexBar 自动检查和修复已开启的 Hook 配置,保留用户和其他 A## 关闭 Hook-关闭后,实时任务、任务通知、触觉反馈、防睡眠和 Hook 统计停止更新,活动与 Token 历史的跨设备同步停止。热力图隐藏两栏历史详情,账户、额度和 app-server Token 热力图仍可使用。+关闭后,实时任务、任务通知、触觉反馈、防睡眠和 Hook 统计停止更新,活动与 Token 历史的跨设备同步停止。热力图隐藏历史详情,账户、额度和 app-server Token 热力图仍可使用。Hook 记录任务的时间、模型、工具名和项目等信息,不保存提问、回复或工具输入输出正文。保存期限与同步内容见 [数据、同步与隐私](sync-data-privacy.md)diff --git a/Docs/UserGuide/main-panel.md b/Docs/UserGuide/main-panel.mdindex fce9884..9492dd9 100644--- a/Docs/UserGuide/main-panel.md+++ b/Docs/UserGuide/main-panel.md@@ -73,7 +73,7 @@ CodexBar 会展示 Codex 返回的全部额度分组和窗口。- 最长连续使用天数- 最长任务时长-热力图使用 30 列乘 7 行方块展示近 30 周每日 Token 用量,颜色强度相对于当前热力图中的峰值计算。+热力图按日期展示近期每日 Token 用量,颜色强度相对于当前热力图中的峰值计算。开启 `动画效果` 时,日期方块会在每次打开主面板时从左上到右下依次展示。@@ -89,7 +89,7 @@ CodexBar Hook 开启时,日期详情还会显示以下统计:- 权限请求次数- 上下文压缩次数-日期详情采用两栏布局:用量强度以 10 格强度条横跨顶部,左栏显示上述活动统计,右栏显示 rollout 的日 Token 汇总,依次为总量、输入、输出、缓存命中、缓存写入、缓存命中率和推理输出。两栏各项指标前显示彩色圆点。每栏名称区域按该栏最长名称统一宽度,其余空间用于右对齐的模型名和数值。Token 数量使用 K/M/B 缩写,缺失计数和零值均显示 `0`,缺失或为零的缓存命中率显示 `0%`。切换日期时,活动统计、Token 数字和最常用模型使用滚动切换动画。+日期详情按活动统计和 rollout 日 Token 用量分组展示,并通过强度条表示当日用量强度。Token 指标包括总量、输入输出、缓存使用和推理输出等。Token 数量使用 K/M/B 缩写,缺失计数和零值均显示 `0`,缺失或为零的缓存命中率显示 `0%`。切换日期时,活动统计、Token 数字和最常用模型使用滚动切换动画。每个线程轮次只计一次,主 Agent 和子 Agent 的用量归到根任务开始日期,跨午夜也不拆分。缓存命中率用当日缓存命中总量除以输入总量计算。启用 iCloud 同步后,各 Mac 的同一轮记录先去重再汇总。@@ -119,7 +119,7 @@ CodexBar Hook 开启时,日期详情还会显示以下统计:### 本轮 Token 用量-活动卡片取得本轮 rollout 用量后,在状态下方显示一排七项指标:总量、输入、输出、缓存命中、缓存写入、缓存命中率、推理输出。各项等宽居中,数量使用 K/M/B 缩写。用量区域和上方分割线一起展开或收起,动画不受 `动画效果` 开关控制。没有用量时隐藏整个区域。+活动卡片取得本轮 rollout 用量后,在状态下方展示 Token 总量、输入输出、缓存使用和推理输出等指标,数量使用 K/M/B 缩写。用量区域和上方分割线一起展开或收起,动画不受 `动画效果` 开关控制。没有用量时隐藏整个区域。运行中和等待批准时,已能确认归属的主线程与子 Agent 用量会持续更新;后续线程记录到达后继续补齐。完成或终止后会短暂补读本轮用量,取得完整汇总后显示。之后读取暂时失败时,保留已经取得的结束用量。这里统计的是当前对话轮次及其子 Agent,而非整个会话。diff --git a/Docs/UserGuide/settings.md b/Docs/UserGuide/settings.mdindex 267fdb5..6bac21d 100644--- a/Docs/UserGuide/settings.md+++ b/Docs/UserGuide/settings.md@@ -28,7 +28,7 @@ Hook 关闭时任务区域自动关闭,从关闭切换到开启时自动显示开启时按当前运行颜色、速度和亮度播放一次往返预览,随后显示实际任务状态。关闭时光带快速收回到屏幕中心并淡出,收尾完成前再次开启不会重播开启预览。-双击选项面板中的颜色块可预览对应状态:运行播放一个往返周期,等待批准播放两次呼吸,完成和终止显示 3 秒。再次双击会替换当前预览,收起选项面板会结束颜色预览并恢复实际任务状态。+双击选项面板中的颜色块可预览对应状态:运行展示往返流光,等待批准展示呼吸效果,完成和终止短暂显示后淡出。再次双击会替换当前预览,收起选项面板会结束颜色预览并恢复实际任务状态。| 默认颜色 | 含义 || --- | --- |@@ -39,7 +39,7 @@ Hook 关闭时任务区域自动关闭,从关闭切换到开启时自动显示颜色使用 Display P3 六位十六进制值,字母自动转为大写,空输入框显示默认颜色值。无效颜色以红框提示,按回车、移开焦点或收起面板时恢复默认颜色。动画速度可选较慢、标准和较快,默认标准;亮度可调范围为 20%–100%,默认 100%。-并发任务中有任务结束时,显示 3 秒的完成或终止提示,再恢复当前任务状态。全部任务结束后,从最新记录的结束时间起,按所选“结束时长”显示提示;可选 3、5、10、15、30 或 60 秒,默认 10 秒。预览期间继续接收任务更新,结束提示暂停计时。恢复时按最新任务状态展示,已有结束提示继续剩余时长,预览期间产生的结束提示按完整时长显示。+并发任务中有任务结束时,短暂显示完成或终止提示,再恢复当前任务状态。全部任务结束后,从最新记录的结束时间起,按所选“结束时长”显示提示;可选 3、5、10、15、30 或 60 秒,默认 10 秒。预览期间继续接收任务更新,结束提示暂停计时。恢复时按最新任务状态展示,已有结束提示继续剩余时长,预览期间产生的结束提示按完整时长显示。Hook 不可用时隐藏光带并保留开关选择。系统睡眠、屏幕休眠或用户会话不活跃时也会隐藏;恢复后显示当前状态,已过期的结束提示不会重播。diff --git a/Docs/UserGuide/sync-data-privacy.md b/Docs/UserGuide/sync-data-privacy.mdindex 3bc5ca4..c64b773 100644--- a/Docs/UserGuide/sync-data-privacy.md+++ b/Docs/UserGuide/sync-data-privacy.md@@ -19,7 +19,7 @@## 哪些数据会上传-同步数据保存在你的 iCloud 私有数据库中,包括日期、每日事件和会话统计、项目显示名、模型名,以及用于区分设备和避免重复计数的标识。Token 历史另行同步脱敏轮次标识、必要时间和六项累计计数,用于跨设备去重后计算日汇总。+同步数据保存在 iCloud 私有数据库中,包括日期、每日事件和会话统计、项目显示名、模型名,以及用于区分设备和避免重复计数的标识。Token 历史另行同步由 thread ID 和 turn ID 生成的哈希标识、必要时间和 Token 累计计数,用于跨设备去重后计算日汇总。以下内容不参与同步:diff --git a/Docs/en/DeveloperGuide/README.md b/Docs/en/DeveloperGuide/README.mdindex 2dc4d30..9525060 100644--- a/Docs/en/DeveloperGuide/README.md+++ b/Docs/en/DeveloperGuide/README.md@@ -6,13 +6,13 @@| Document | Contents || --- | --- |-| [Architecture](architecture.md) | Processes, modules, lifecycle, actor boundaries, and the three data flows |+| [Architecture](architecture.md) | Processes, modules, lifecycle, actor boundaries, and data flows || [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 |-| [CloudKit Sync](sync.md) | Private database, device pseudonymization, upload, merge, and rebuild |+| [CloudKit Sync](sync.md) | Private database, device identifier hashing, upload, merge, and rebuild || [Notification System](notifications.md) | Notification triggers, deduplication, sounds, haptics, and click behavior || [UI and App Lifecycle](ui-and-lifecycle.md) | Menu bar, panels, focus, global shortcuts, and service assembly || [Data and Privacy Boundaries](data-and-privacy.md) | Local files, network access, cloud fields, and logging boundaries |diff --git a/Docs/en/DeveloperGuide/activity-monitor.md b/Docs/en/DeveloperGuide/activity-monitor.mdindex 4fd4f88..b94a697 100644--- a/Docs/en/DeveloperGuide/activity-monitor.md+++ b/Docs/en/DeveloperGuide/activity-monitor.md@@ -222,7 +222,7 @@ Terminal resolution requires a nonempty `payload.turn_id` and a `complete` curre| Cache hit rate | `cached_input_tokens / input_tokens`; undefined when input is zero || Reasoning | `reasoning_output_tokens` |-All six counters must be present and nonnegative. Total must equal input plus output, cache hits plus writes must not exceed input, and reasoning must not exceed output. Parsing also validates the identities and ownership in `thread_id`, `session_id`, `turn_id`, `root_turn_id`, and `response_id`. Missing fields or failed validation produce no usage. Zero cache-write or reasoning counts in valid records are displayed as zero.+All required token counters must be present and nonnegative. Total must equal input plus output, cache hits plus writes must not exceed input, and reasoning must not exceed output. Parsing also validates the identities and ownership in `thread_id`, `session_id`, `turn_id`, `root_turn_id`, and `response_id`. Missing fields or failed validation produce no usage. Zero cache-write or reasoning counts in valid records are displayed as zero.`CodexActivityTokenUsage.swift` collects main and associated child-thread references for the root task, deduplicating by thread and turn. While running, it sums matching threads with complete current reads; threads without usage wait for later refreshes. The displayed value may therefore be a subtotal of known threads. The live card reads the in-memory task snapshot, not historical daily totals or iCloud caches.@@ -488,7 +488,7 @@ Every valid progress event increments `progressGeneration`. A protection candida- Progress generation- Threshold at the time-All four must still match when notification returns or grace expires. Any new progress or threshold change invalidates the old attempt.+All of these must still match when notification returns or grace expires. Any new progress or threshold change invalidates the old attempt.Candidates using the partial-tail fallback also revalidate observation freshness and the inactivity deadline. Further tail growth or a read failure cancels a pending suppression attempt.diff --git a/Docs/en/DeveloperGuide/app-server.md b/Docs/en/DeveloperGuide/app-server.mdindex d9004b8..286af60 100644--- a/Docs/en/DeveloperGuide/app-server.md+++ b/Docs/en/DeveloperGuide/app-server.md@@ -61,7 +61,7 @@ The data directory uses `CODEX_HOME` when set and otherwise uses `~/.codex` undeAn `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.-The resolver normalizes in three layers:+The resolver normalizes the process environment as follows:1. Resolve the real login user's home with `getpwuid(getuid())`, avoiding an incorrect `HOME` inherited from Xcode or a container2. Preserve the existing `PATH`, then append common directories in order and deduplicate@@ -77,7 +77,7 @@ A connection may be reused for up to 1 hour. If the user upgrades the on-disk bi## In-App Proxy-The proxy is implemented by four types:+The proxy is implemented by the following types:| Type | Responsibility || --- | --- |@@ -431,7 +431,7 @@ Enabling or validating Hook calls `readyConnectionInfo()`:It helps inspect process startup, JSON-RPC methods, retries, and error classifications. It must not contain access tokens or Hook prompt content.-`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.+`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 replace usernames and passwords in HTTP/HTTPS URLs with `<redacted>`. Non-JSON messages receive the same replacement directly.### Request and System Logs@@ -473,7 +473,7 @@ 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.+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 replacing usernames and passwords in plain and JSON-escaped URLs with `<redacted>`.## Key Source Filesdiff --git a/Docs/en/DeveloperGuide/architecture.md b/Docs/en/DeveloperGuide/architecture.mdindex 6f38c9c..388b13b 100644--- a/Docs/en/DeveloperGuide/architecture.md+++ b/Docs/en/DeveloperGuide/architecture.md@@ -8,7 +8,7 @@ Explore the processes, data flows, and recovery paths in the [Runtime ArchitectuCodexBar is a menu bar app for macOS 15 and later, built with Swift 6, SwiftUI, AppKit, and MVVM.-The project has one `CodexBar` scheme with three targets:+The project has one `CodexBar` scheme with the following targets:| Target | Responsibility || --- | --- |@@ -39,7 +39,7 @@ CodexBar executable`-- fixed IOPM wake event```-Two points define these boundaries:+These boundaries follow the principles below:- Using the same executable for Hook mode keeps the handler pointed at the current app version without deploying a separate capture tool- The root helper knows nothing about Codex tasks, accounts, or reset credits; it receives only signature-validated sleep leases and Automatic Reset wake times@@ -119,7 +119,7 @@ Releasing asynchronously in `applicationWillTerminate` is too late because that## Three Independent Data Flows-Three data flows manage distinct inputs, freshness requirements, and failure states:+The data flows manage distinct inputs, freshness requirements, and failure states:| Flow | Input | Output | Main consumers || --- | --- | --- | --- |diff --git a/Docs/en/DeveloperGuide/data-and-privacy.md b/Docs/en/DeveloperGuide/data-and-privacy.mdindex f10ed33..5b3d84f 100644--- a/Docs/en/DeveloperGuide/data-and-privacy.md+++ b/Docs/en/DeveloperGuide/data-and-privacy.md@@ -9,7 +9,7 @@ Classifying data during development helps determine its storage and propagation| Class | Examples | Default handling || --- | --- | --- || Content | Prompts, responses, tool arguments, and output | Do not collect |-| Identity and context | Session IDs, full paths, project names | Minimize use to necessary flows; redact or remove before upload |+| Identity and context | Session IDs, full paths, project names | Do not upload raw session IDs or full paths; token turns use hashed identifiers, and project display names accompany statistics || Aggregated metrics | Daily event counts, model counts | May persist locally; upload only specified fields after explicit opt-in |## Trust Boundaries@@ -51,9 +51,9 @@ CodexBar narrows data in this order:| app-server account, rate limits, and Reset Credits | Main panel, notification decisions, and user-enabled Automatic Reset | Short-lived state only | No || Structured Hook events | Historical aggregation and live tasks | Yes, up to 210 days | Daily aggregations only || Rollout lifecycle | Terminal and progress reconciliation | Not persisted separately | No |-| Rollout token counters | Deduplicated turns and daily totals | Hashed identities, timestamps, and counts for 210 days | Pseudonymous cumulative turns when sync is enabled |+| Rollout token counters | Deduplicated turns and daily totals | Hashed turn identifiers, timestamps, and counts for 210 days | Hashed turn identifiers and cumulative counts when sync is enabled || App settings | Feature switches and thresholds | UserDefaults | No |-| Activity Protection | Stalled-task recovery | Hashed identity, up to 24 hours | No |+| Activity Protection | Stalled-task recovery | Hashed task identifier, up to 24 hours | No || 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 |@@ -65,7 +65,7 @@ The app launches local `codex app-server --listen stdio://` to obtain account daCodexBar does not implement account sign-in. Whether app-server accesses OpenAI services follows normal Codex CLI authentication and protocol behavior.-CodexBar communicates with the local process only over stdio and does not copy authentication material from app-server responses. The request log stores normalized complete request and response JSON only in current-process memory. It may contain account responses, opaque credit IDs, and idempotency keys and must not be treated as a redacted summary.+CodexBar communicates with the local process only over stdio and does not copy authentication material from app-server responses. The request log stores normalized complete request and response JSON only in current-process memory. The log retains protocol fields such as account responses, opaque credit IDs, and idempotency keys.### Hook Events@@ -87,7 +87,7 @@ The working directory is used only to derive a project display name and live-tasThe Hook recorder reads the current rollout through `transcript_path`; origin for `SubagentStop` uses the child thread's own `agent_transcript_path`. The live-activity reader accesses relevant main-thread and child-thread files under `$CODEX_HOME/sessions` and `$CODEX_HOME/archived_sessions`.-These reads parse structural fields including origin classification, thread and turn relationships, lifecycle, time, turn context, progress, effort, reviewer, and token counters. Live thread associations remain in memory; historical token records store hashed identities, necessary timestamps, and six cumulative counters. Conversation text does not enter CodexBar storage or UI.+These reads parse structural fields including origin classification, thread and turn relationships, lifecycle, time, turn context, progress, effort, reviewer, and token counters. Live thread associations remain in memory; historical token records store hashed turn identifiers, necessary timestamps, and cumulative token counters. Conversation text does not enter CodexBar storage or UI.Historical token scanning starts at the beginning of each source and then follows persisted cursors. Cloud identities use account-salted HMAC-SHA256; raw thread and turn IDs are not uploaded. See [Rollout Token History](sync.md#rollout-token-history) for fields and retention.@@ -210,13 +210,13 @@ 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.+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 usernames and passwords in HTTP/HTTPS URLs within string values are replaced with `<redacted>`. Other account and protocol fields retain the existing request-log behavior.## Network Access| Destination | Purpose | Trigger || --- | --- | --- |-| CloudKit private database | Sync daily Hook aggregations and pseudonymous rollout token turns | User explicitly enables sync |+| CloudKit private database | Sync daily Hook aggregations, hashed turn identifiers, and cumulative token counts | 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 |@@ -230,7 +230,7 @@ When a proxy is enabled, its address and optional credentials are passed throughCloudKit uploads these daily Hook aggregate fields:-- Device pseudonym+- Hashed device identifier `deviceId`- Date and source generation- Hook event counts- Session and turn counts@@ -238,7 +238,7 @@ CloudKit uploads these daily Hook aggregate fields:- Model counts- Update time-Token history also uploads account-scoped hashed turn identities, root-turn links, necessary timestamps, and six cumulative counters for cross-device deduplication and daily totals.+Token history also uploads account-scoped hashed turn identities, root-turn links, necessary timestamps, and cumulative token counters for cross-device deduplication and daily totals.CloudKit does not upload:@@ -257,7 +257,7 @@ A project display name may derive from a directory name and still contain sensit## Root Helper Data Isolation-CodexBarHelper needs only four kinds of state:+CodexBarHelper receives only the following state:- Which verified client holds which lease generation- The currently measured `SleepDisabled` valuediff --git a/Docs/en/DeveloperGuide/design-decisions.md b/Docs/en/DeveloperGuide/design-decisions.mdindex f905360..6fa911d 100644--- a/Docs/en/DeveloperGuide/design-decisions.md+++ b/Docs/en/DeveloperGuide/design-decisions.md@@ -58,4 +58,4 @@ Activity Protection and helper ownership records recover state changes that haveTask 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.-CloudKit syncs daily activity aggregates and pseudonymous thread-turn token records. Raw events, raw 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.+CloudKit syncs daily activity aggregates and thread-turn token records, using identifiers derived by hashing the combined thread and turn IDs. Raw events, raw 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/hook-and-aggregation.md b/Docs/en/DeveloperGuide/hook-and-aggregation.mdindex a09c5df..d52b7cf 100644--- a/Docs/en/DeveloperGuide/hook-and-aggregation.md+++ b/Docs/en/DeveloperGuide/hook-and-aggregation.md@@ -285,7 +285,7 @@ Source generation distinguishes raw sources for the same day. Same-source result### `pending` Versus `dirty`-`maintenance.json` tracks two work states for a date:+`maintenance.json` tracks the following work states for a date:| State | Used when | Next step || --- | --- | --- |@@ -298,7 +298,7 @@ Explicit states are safer than guessing from `offset == 0`. A new empty file, tr### Determining Whether a File Is the Same Source-Maintenance combines four kinds of evidence:+Maintenance combines the following evidence:- Whether inode identity changed- Whether current size is below consumed offset@@ -436,7 +436,7 @@ Maintenance normally follows the 60-second refresh. An idle machine would otherw### How the Scheduler Coalesces Requests-`WorkflowSyncScheduler` serializes three request classes:+`WorkflowSyncScheduler` serializes the following requests:1. User rebuild, highest priority2. Maintenance with syncdiff --git a/Docs/en/DeveloperGuide/notifications.md b/Docs/en/DeveloperGuide/notifications.mdindex a76e0ec..0cdb871 100644--- a/Docs/en/DeveloperGuide/notifications.md+++ b/Docs/en/DeveloperGuide/notifications.md@@ -6,7 +6,7 @@[`CodexNotificationService.swift`](../../../CodexBar/Services/Notifications/CodexNotificationService.swift) is the single entry point for notification side effects.-It consumes four kinds of state:+It consumes the following state:- App-server account and quota snapshots- `CodexActivityMonitor` task transitions and Activity Protection candidates@@ -35,7 +35,7 @@ Haptic feedback does not depend on `UNUserNotificationCenter` authorization but## Notification Switches-The master switch is off by default. The eight configurable category switches default to on, and haptic feedback defaults to off.+The master switch is off by default. The configurable category switches default to on, and haptic feedback defaults to off.While the master switch is off, CodexBar neither requests system notification permission nor sends category notifications. Once it is on, category settings select specific types:@@ -210,7 +210,7 @@ System default and silent choices cannot be previewed. Preview is available for## Haptic Feedback-Haptic feedback is off by default. When enabled, it uses 10 pulses roughly 100 ms apart.+Haptic feedback is off by default. When enabled, it provides a sequence of short pulses.Haptics are a separate local feedback channel from system notifications. They respond to completion or waiting transitions for non-anonymous tasks and follow the notification master switch and haptics switch, but do not depend on system authorization, a category switch, or the completion-duration threshold.diff --git a/Docs/en/DeveloperGuide/sleep-prevention.md b/Docs/en/DeveloperGuide/sleep-prevention.mdindex 52632af..69e1faa 100644--- a/Docs/en/DeveloperGuide/sleep-prevention.md+++ b/Docs/en/DeveloperGuide/sleep-prevention.md@@ -23,7 +23,7 @@ AutoResetController## State Layers-State is split into four layers:+State is separated by responsibility:| Layer | Representative field | Question answered || --- | --- | --- |@@ -142,7 +142,7 @@ App assertions cover only the current process. CodexBarHelper manages system-levCodexBarHelper registers as a LaunchDaemon through `SMAppService`. The app and helper use the XPC interface in [`CodexBarHelperXPC.swift`](../../../Shared/CodexBarHelperXPC.swift).-The interface exposes only four capability classes:+The interface exposes the following capabilities:- Set or revoke an app lease- Query helper runtime and ownership statediff --git a/Docs/en/DeveloperGuide/sync.md b/Docs/en/DeveloperGuide/sync.mdindex 3f6e7b6..6c845db 100644--- a/Docs/en/DeveloperGuide/sync.md+++ b/Docs/en/DeveloperGuide/sync.md@@ -20,7 +20,7 @@ App-server account data, rate limits, account token totals, Reset Credits, Autom## Data Sources-Hook daily aggregates combine three kinds of data. See [Rollout Token History](#rollout-token-history) for the turn ledger and its cloud cache.+Hook daily aggregates combine the following data. See [Rollout Token History](#rollout-token-history) for the turn ledger and its cloud cache.| Data | Authoritative source | Offline behavior || --- | --- | --- |@@ -61,7 +61,7 @@ Sync runs only when all conditions hold: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+## Device Identifier HashingSync must distinguish device contributions without uploading a raw hardware identifier:@@ -70,7 +70,7 @@ Sync must distinguish device contributions without uploading a raw hardware iden3. Compute HMAC-SHA256 of the UUID with the account salt4. Use the result as the cloud `deviceId`-The raw `IOPlatformUUID` is never uploaded. One device receives a stable pseudonym within one iCloud account and a different value in another account.+The raw `IOPlatformUUID` is never uploaded. One device receives a stable hashed device identifier within one iCloud account and a different value in another 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.@@ -81,7 +81,7 @@ Local state records the most recently resolved `deviceId`. If it changes, sync cEach daily record contains:- Schema-- Device ID pseudonym+- Hashed device identifier `deviceId`- Date- Source generation- Hook event counts@@ -118,7 +118,7 @@ Deploy the following record type and fields to the CloudKit production schema be| `startedAt` | Date | Optional turn start time || `observedAt` | Date | Latest cumulative observation time || `rebuiltAt` | Date | Optional explicit rebuild time that supersedes stale statistics |-| `usage` | Bytes | Optional JSON with six token counters |+| `usage` | Bytes | Optional JSON with token counters |Record names use the stable turn hash without a prefix; `schemaVersion` describes the data format. A record without `usage` contributes no tokens: root records can anchor child dates, and records carrying `rebuiltAt` can clear a turn’s previous counts. Uploads fetch the existing record, retain the more complete cumulative snapshot, and use `ifServerRecordUnchanged`. Conflicts are fetched and merged again on the next sync. Counters from separate snapshots are not combined field by field.@@ -139,7 +139,7 @@ Automatic replay reports progress in the `workflow` system log after each commit```textRead local sync state-> Create or confirm custom zone- -> Read account salt and resolve device pseudonym+ -> Read account salt and compute the hashed device identifier-> Update local state for the device identity and schema-> Fetch remote changes into the cache and process replacement dates-> Upload changed dates for this device@@ -256,7 +256,7 @@ Sync state lives at:The current CloudKit record schema is `6`. The local sync-state schema is `4` and can read the previous schema `3`.-The three files have different recovery costs:+Recovery costs differ by file:| File | Cost if lost | Recovery || --- | --- | --- |diff --git a/Docs/en/DeveloperGuide/ui-and-lifecycle.md b/Docs/en/DeveloperGuide/ui-and-lifecycle.mdindex 49b00b2..5a33378 100644--- a/Docs/en/DeveloperGuide/ui-and-lifecycle.md+++ b/Docs/en/DeveloperGuide/ui-and-lifecycle.md@@ -10,7 +10,7 @@ It has no Dock icon or conventional main-window lifecycle. The menu bar, popoverThe UI declares content in SwiftUI and manages windows through AppKit controllers.-## Three Kinds of Focus Under `LSUIElement`+## Focus States Under `LSUIElement`Development must distinguish among:@@ -52,14 +52,14 @@ Shutdown reverses the order, except for helper-owned system state. AppDelegate f| Scenario | Presentation rule || --- | --- || Active tasks exist | Approval waiting takes priority over running |-| A task ending is confirmed while others remain active | The latest event overrides activity for 3 seconds, fading during the final 0.5 seconds; a new event replaces it and restarts the timer |-| No active tasks | The snapshot's latest terminal state uses the configured end duration, defaulting to 10 seconds after its end time, fading during the final second |+| A task ending is confirmed while others remain active | The latest event briefly overrides activity before fading; a new event replaces it and restarts the timer |+| No active tasks | The snapshot's latest terminal state uses the configured end duration, fading before it expires |`TaskGlowSettings.appearance` supplies colors, speed, brightness, and end duration. The default colors are cyan for running, orange for approval waiting, green for completion, and red for termination. Termination takes priority on equal end times. Durations include entrance animations. The latest snapshot determines the state after expiration.-Switching the setting from off to on while Hook is available sends a `TaskGlowSettings.previewRequests` event for one running preview using the current appearance settings. After one round trip, presentation returns to the actual state; the cycle lasts 2.7 seconds at Standard speed. Startup and settings refresh restore the switch value without requesting a preview.+Switching the setting from off to on while Hook is available sends a `TaskGlowSettings.previewRequests` event for one running preview using the current appearance settings. After one round trip, presentation returns to the actual state. Startup and settings refresh restore the switch value without requesting a preview.-Double-clicking a color swatch in the settings panel requests a preview of that state: running makes one round trip, approval waiting expands and pulses twice, and completion and termination appear for 3 seconds with a fade during the final 0.5 seconds. Color previews can replace a playing preview; closing the settings child panel ends only color previews. Requests for the preview triggered by enabling the feature are ignored while a preview or window dismissal is in progress.+Double-clicking a color swatch in the settings panel requests a preview of that state: running shows a moving glow, approval waiting pulses, and completion and termination appear briefly before fading. Color previews can replace a playing preview; closing the settings child panel ends only color previews. Requests for the preview triggered by enabling the feature are ignored while a preview or window dismissal is in progress.Real task updates continue during previews, which produce no task events. Real terminal indicator timers pause, and presentation resumes from the latest snapshot: existing indicators retain their remaining time, while indicators for tasks that ended during the pause receive their full duration. Preview transitions share a start time across displays; retraction of the previous glow does not consume the target effect's display duration.@@ -86,15 +86,15 @@ When no tasks are active, `CodexActivitySnapshot.statusItemActivity(at:)` select- Minute-by-minute duration updates affect only the tooltip- Cached quota dims the symbol and arc- `StatusItemIconView` caches rasterized images by symbol name and display scale, reusing them during scaling to avoid stuttering from live rendering of badged symbols-- Symbol-name changes crossfade the old and new images over 0.2 seconds while scaling between 75% and full size; quota visibility changes alone do not replace the image-- Showing or hiding quota animates the colored arc between zero and the current percentage over 0.3 seconds; the track fades independently-- Symbols share a baseline; hiding quota restores normal size with a 0.2-second size and position transition+- Symbol-name changes crossfade the old and new images with a scaling transition; quota visibility changes alone do not replace the image+- Showing or hiding quota animates the colored arc between zero and the current percentage; the track fades independently+- Symbols share a baseline; hiding quota restores normal size with a smooth size and position transition- Hiding quota retains its last percentage and color for retraction; zero and unavailable quota remain distinct- Initial rendering and wake reconciliation disable transitionsA persistent SwiftUI view lives inside the native `NSStatusBarButton`, with a transparent image preserving automatic spacing. Symbols use the system foreground color. The hosting view rejects focus and hit testing, leaving mouse actions with the original button.-The tooltip updates every 60 seconds while tasks are active and stops its timer when idle. `NSInitialToolTipDelay` is 500 ms.+The tooltip updates every 60 seconds while tasks are active and stops its timer when idle.Left-click opens the main panel. Right-click or Control-click opens the context menu.@@ -106,7 +106,7 @@ The main panel prefers an `NSPopover` with `behavior` set to `applicationDefined### Open and Close State Machine-`menuSurfaceState` has four states:+`menuSurfaceState` transitions as follows:```texthidden -> opening -> shown -> closing -> hidden@@ -143,9 +143,9 @@ Special rules include:### Fades and Completion Tasks-`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.+`MenuSurfaceFadeCoordinator` animates both the active container’s content view and window opacity to fade the panel in and 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.-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.+Settings and log windows temporarily reject `makeKey()` during closing and regain that ability after a short delay following completion. The completion task holds a weak reference to that window and restores content and window opacity after closing.### Content Animations and Presentation State@@ -155,11 +155,17 @@ When host animation permission is disabled, `CodexStatusMenuView` sets the root`MenuSurfaceVisibilityState` begins after the panel is shown and ends when closing starts. Each presentation increments `presentationGeneration`; the rate-limit and usage sections use that value as their view identity and run their entrance animations again.+The main panel root view uses a fixed width and its ideal content height. The popover follows content size through `preferredContentSize`. The fallback panel reads content height through `onGeometryChange` and directly updates its window height while visible, preserving its width and top edge.+### Activity Card-`CodexActivityCard` uses `primaryActivity`, prioritizing waiting for approval, then running, then the latest completion or termination by end time, with termination taking precedence on ties. When `isActivelyPreventingSleep` is `true` and card data is available, it shows a teal `sun.max.fill`; the tooltip identifies `sleepPreventionSource`. While the host's `mainPanelAnimationsEnabled` is true, the sun badge rotates clockwise at a constant speed of one revolution every 2 seconds. Disabling permission removes the rotating view and shows a static icon.+`CodexActivityCard` uses `primaryActivity`, prioritizing waiting for approval, then running, then the latest completion or termination by end time, with termination taking precedence on ties. When `isActivelyPreventingSleep` is `true` and card data is available, it shows a teal `sun.max.fill`; the tooltip identifies `sleepPreventionSource`. While the host's `mainPanelAnimationsEnabled` is true, the sun badge rotates clockwise at a constant speed. Disabling permission removes the rotating view and shows a static icon.++The activity card and Task Center share `CodexActivityStatusText`, whose color follows task state. Running text shimmers, approval-waiting text emits orange particles, and completed or terminated text stays static. Status-text animations in the card use `mainPanelAnimationsEnabled`; those in Task Center require both `presentationState.isPresented` and `MainPanelSettings.areEntranceAnimationsEnabled`. Each panel shares one particle timeline, emits only from visible waiting text, clips particles to the panel bounds, and removes the timeline when no emitters remain.-The activity card and Task Center share `CodexActivityStatusText`, whose color follows task state. Running text shimmers, approval-waiting text emits orange particles, and completed or terminated text stays static. The card uses `mainPanelAnimationsEnabled`; Task Center requires both `presentationState.isPresented` and `MainPanelSettings.areEntranceAnimationsEnabled`. Each panel shares one particle timeline, emits only from visible waiting text, clips particles to the panel bounds, and removes the timeline when no emitters remain.+The activity card shows token metrics and a divider when `primaryActivity.tokenUsage` is available. The status row stays anchored at the top, and the card height adjusts as the token area appears or disappears.++Expansion and collapse use a smooth, decelerating transition, independently of Animation Effects. The token area fades in and moves slightly upward with expansion progress, and fades out early during collapse. `ActivityCardHeight` commits the interpolated layout height on every animation frame so adjacent sections and the main panel resize together. Animations for the sleep-prevention badge, anonymous-task icon, and concurrent-task count are scoped to the status row.## Fallback Panel@@ -171,12 +177,12 @@ A global shortcut may fire before status-item layout completes, while the menu b- The window and screen exist- The button is visible and has nonempty bounds-- The converted screen rect is valid and at least 1 point-- The rect intersects the target screen frame within a 1-point tolerance+- The converted screen rect is valid and meets the minimum size requirement+- The rect intersects the target screen frame within the allowed toleranceOnly then does it use a popover arrow. Otherwise, the fallback panel appears on the screen under the pointer. This prevents AppKit from placing the popover on the wrong display or completely offscreen.-Before showing, the fallback panel constrains its size from the SwiftUI fitting size and the target screen's visible area. Coordinate calculations live in `ScreenGeometry` because AppKit's bottom-left origin, SwiftUI local layout, and multi-display frames are easy to mix up.+Before showing, the fallback panel uses the main panel's fixed width and the SwiftUI fitting height. It is centered horizontally in the target screen's visible area, with space above its top edge. If no valid fitting size is available, it uses a default height.## Side Detail Panels@@ -194,17 +200,15 @@ Heatmap hover requests animate the dismissal of other side panels. Click requestClosing the main panel immediately cleans up its side panels. For an immediate close or an already invisible window, heatmap details and the shared drawer reset drawer animations, call `orderOut`, and remove the parent-child window relationship. Task Center forwards immediate-close requests to the shared drawer even when its logical presentation has ended.-Heatmap squares enter with staggered delays based on their column and row. With entrance animations enabled, each square accepts hover after its own entrance delay plus 0.25 seconds. With entrance animations disabled, squares accept hover immediately.+Heatmap squares enter with staggered delays based on their column and row. With entrance animations enabled, each square accepts hover after its entrance transition. With entrance animations disabled, squares accept hover immediately.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.While the main panel is visible, digits roll as values change and Token values fade when switching to or from pending or unavailable placeholders. Animation Effects controls entrance animations, sun-badge rotation, and task status-text animations; it does not control numeric updates.-The activity card shows its token area only when `primaryActivity.tokenUsage` is available, with seven equally sized, centered metrics and a divider. Availability changes animate the card height and main-panel size independently of Animation Effects. The popover temporarily enables `animates` before the content-size update; the fallback waits for the `@Published` assignment before measuring and keeps its top edge fixed.--With Hook enabled, heatmap details use two columns beneath a full-width ten-segment intensity row: activity statistics on the left and session tokens on the right. Each column uses a `Grid` to size labels to its longest label, leaving the remaining width for values. Date changes use the same `numericText` transition for token and activity values. The most-used model transitions within one text view and scales its font to fit.+With Hook enabled, heatmap details group activity statistics and session tokens alongside a usage intensity bar. Each group uses a `Grid` to align labels and values. Date changes use the same `numericText` transition for token and activity values. The most-used model transitions within one text view and scales its font to fit.-The shared `LiquidGlassDivider` slowly moves a silver-gray and cool-white gradient over an 8-second cycle. It pauses or resumes its timeline using its `NSView` window visibility, independently of Animation Effects.+The shared `LiquidGlassDivider` slowly moves a silver-gray and cool-white gradient in a repeating cycle. It pauses or resumes its timeline using its `NSView` window visibility, independently of Animation Effects.Related controllers include:@@ -252,7 +256,7 @@ 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. Switching Hook from off to on automatically shows Task Center; initial restoration of an enabled Hook and repeated enabled notifications preserve the saved layout. 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 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.+Layout sorting uses a custom `DragGesture` on the handle. A floating copy follows the pointer, other rows move as the drag position changes, 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 settings child panel 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.@@ -290,7 +294,7 @@ Registration uses try-before-swap:## Automatic Refresh and Panel Opening-App-server state is checked for refresh every 60 seconds by default. Once the main panel's 0.24-second fade-in finishes and the panel is still visible, `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.+App-server state is checked for refresh every 60 seconds by default. Once the main panel's fade-in finishes and the panel is still visible, `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.The main panel shows a refresh countdown. Double-clicking the account icon requests an immediate manual refresh.@@ -319,12 +323,12 @@ Release scripts require Developer ID, signing, and notarization credentials and- Left-click opens the main panel; right-click and Control-click open the context menu- Enabling Task Glow plays one preview using the current color, speed, and brightness; disabling retracts and fades it out. Dismissal blocks the enabling preview, and enabling again after dismissal can preview again. Repeated color-swatch double-clicks replace previews, and closing the child panel ends color previews. On return, existing terminal indicators retain their remaining time, and indicators for tasks that ended during the preview follow the latest state and receive their full duration-- During concurrent running or approval waiting, completion and termination trigger a 3-second glow indicator; colors follow the settings, and the selected end duration applies once all tasks end+- During concurrent running or approval waiting, completion and termination trigger a brief glow indicator; colors follow the settings, and the selected end duration applies once all tasks end- History reloads and wake reconciliation do not replay old terminal hints; subsequent real task endings still produce hints, and motion and expiry stay aligned across displays and screen configuration changes- Menu bar symbols follow task state; terminal feedback expires 10 seconds after the task ends and is recalculated on wake-- Transitions between the plain person and all four task badges complete correctly, rapid changes settle on the latest state, and toggling quota visibility stays smooth with badges; initial presentation and wake reconciliation do not animate+- Transitions between the plain person and the task badges complete correctly, rapid changes settle on the latest state, and toggling quota visibility stays smooth with badges; initial presentation and wake reconciliation do not animate- Quota-arc visibility animates, zero quota retains the track, and cached quota dims-- The sun badge rotates only while sleep prevention is active, Animation Effects is enabled, and its host panel is presented; disabling Animation Effects preserves a static sun, and enabling it again resumes rotation only in the visible host; no continuous rotation work occurs before the first opening or while tasks continue after closing; reopening, rapid toggling, and switching between popover and fallback hosts preserve a constant speed of one revolution every 2 seconds, and the badge disappears when tasks end+- The sun badge rotates only while sleep prevention is active, Animation Effects is enabled, and its host panel is presented; disabling Animation Effects preserves a static sun, and enabling it again resumes rotation only in the visible host; no continuous rotation work occurs before the first opening or while tasks continue after closing; reopening, rapid toggling, and switching between popover and fallback hosts preserve a constant rotation speed, and the badge disappears when tasks end- Password reveal transitions preserve text, selection, and focus- Clicking outside the main panel dismisses it; clicking a side panel does not- Heatmap, Reset Credits, and Task Center panels remain mutually exclusive@@ -334,11 +338,11 @@ Release scripts require Developer ID, signing, and notarization credentials and- Clicking a notification activates the app and opens the panel- Focus is correct when opening Settings for the first time, closing it, and reopening it- During refresh or reconnection in About, closing, minimizing, fully occluding Settings, or switching away from About stops the reconnect icon's continuous drawing or wiggle; showing it again resumes animation only if still busy, and losing focus while visible preserves normal behavior-- On the first Settings open after a cold launch, General immediately uses its full content height; switching among all three tabs adapts the window height, with no scrollbar when screen space is sufficient+- On the first Settings open after a cold launch, General immediately uses its full content height; switching among Settings pages adapts the window height, with no scrollbar when screen space is sufficient- Main Panel Layout, Task Glow, Notification, Automatic Reset, and sleep-prevention child panels remain mutually exclusive, align their top edges with their setting rows, and resize correctly when content changes- Opening the task-glow panel does not focus a color field automatically; the six-character limit, paste filtering, and uppercase conversion work; invalid colors revert to the default on Return, focus loss, and panel dismissal, with displayed and applied colors matching- With a settings child panel open, opening the main panel from the menu bar keeps the main panel open, closes the settings child panel, and does not steal focus back to Settings-- While reordering the main panel, the floating row follows the pointer, other rows make room after the drag crosses half a row, and release settles smoothly while persisting only the final order; reordering and visibility changes can be undone step by step with `Command-Z` and redone with `Command-Shift-Z` while either the Settings window or any settings child panel has focus; the result persists across relaunches; the last visible section cannot be hidden; disabling Hook turns Task Center off and disables its switch without blocking drag, enables Account if Task Center was the only visible section; re-enabling Hook shows Task Center automatically, while a manual hide survives relaunch; automatic Hook changes do not enter user undo history+- While reordering the main panel, the floating row follows the pointer, other rows make room as the drag position changes, and release settles smoothly while persisting only the final order; reordering and visibility changes can be undone step by step with `Command-Z` and redone with `Command-Shift-Z` while either the Settings window or any settings child panel has focus; the result persists across relaunches; the last visible section cannot be hidden; disabling Hook turns Task Center off and disables its switch without blocking drag, enables Account if Task Center was the only visible section; re-enabling Hook shows Task Center automatically, while a manual hide survives relaunch; automatic Hook changes do not enter user undo history- Opening Settings or Logs from the context menu does not lose focus- On multiple displays and with different menu bar locations, the fallback panel appears on the pointer's screen- The old shortcut still works after a new shortcut conflicts@@ -346,7 +350,7 @@ Release scripts require Developer ID, signing, and notarization credentials and- Initial numeric decreases, consecutive changes, Token unit changes, and month boundaries roll in the correct direction; numeric animations stop when the main panel closes- Switch heatmap dates rapidly in Chinese and English; label widths remain stable while token values and model names transition in place-- Toggle token availability; popover and fallback sizes animate smoothly even with Animation Effects disabled+- Toggle token availability and reverse direction during transitions; the card, adjacent sections, popover, and fallback resize together without overlap or spacing changes, even with Animation Effects disabled- Shared dividers flow slowly and stop continuous rendering when their window closes or becomes hidden## Key Source Filesdiff --git a/Docs/en/UserGuide/activity-and-hook.md b/Docs/en/UserGuide/activity-and-hook.mdindex 62f1ea8..3ce63a1 100644--- a/Docs/en/UserGuide/activity-and-hook.md+++ b/Docs/en/UserGuide/activity-and-hook.md@@ -43,7 +43,7 @@ Sessions and turns are deduplicated within each day; activity continuing into an## Disable Hook-Disabling Hook stops updates to live tasks, task notifications, haptics, sleep prevention, and Hook statistics, and stops cross-device sync for activity and token history. The heatmap hides its two-column history details. Account, quota, and the app-server token heatmap remain available.+Disabling Hook stops updates to live tasks, task notifications, haptics, sleep prevention, and Hook statistics, and stops cross-device sync for activity and token history. The heatmap hides its history details. Account, quota, and the app-server token heatmap remain available.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.diff --git a/Docs/en/UserGuide/main-panel.md b/Docs/en/UserGuide/main-panel.mdindex 885c14a..33a3767 100644--- a/Docs/en/UserGuide/main-panel.md+++ b/Docs/en/UserGuide/main-panel.md@@ -73,7 +73,7 @@ Account usage comes from app-server. The summary area shows:- Longest usage streak- Longest task duration-The heatmap uses a 30-column by 7-row grid to show daily token usage over the last 30 weeks. Color intensity is relative to the highest value currently visible in the heatmap.+The heatmap shows recent daily token usage by date. Color intensity is relative to the highest value currently visible in the heatmap.When `Animation Effects` is enabled, the day squares appear from the top left to the bottom right whenever the main panel opens.@@ -89,7 +89,7 @@ When CodexBar Hook is enabled, the details also include:- Permission requests- Context compactions-The date detail panel uses two columns beneath a full-width, ten-segment intensity row. Activity metrics appear on the left; the right column shows daily rollout totals in this order: total, input, output, cached input, cache write, cache hit rate, and reasoning output. Each metric in either column has a colored dot. Labels share the width of the longest label within their own column, leaving the remaining space for right-aligned model names and values. Token counts use K/M/B units. Missing and zero counts display `0`; missing or zero cache hit rate displays `0%`. Activity counts, token values, and the most-used model roll between values when the selected date changes.+Date details group activity statistics and daily rollout token usage, with an intensity bar showing relative usage. Token metrics include totals, input and output, cache usage, and reasoning output. Token counts use K/M/B units. Missing and zero counts display `0`; missing or zero cache hit rate displays `0%`. Activity counts, token values, and the most-used model roll between values when the selected date changes.Each thread turn contributes once. Main and child-agent usage belongs to the root task's start date, including tasks that cross midnight. Daily cache hit rate divides total cached input by total input. With iCloud sync enabled, duplicate turns across Macs are merged before daily aggregation.@@ -119,7 +119,7 @@ Click a populated activity card to open Task Center. In both views, status-text### Token Usage for the Current Turn-Once rollout usage is available, the activity card shows seven equally sized, centered metrics beneath its status: Total, Input, Output, Cached, Cache-W, Cache-H, and Reasoning. Counts use K/M/B units. The usage row and its divider expand or collapse together, independently of `Animation Effects`. Both remain hidden when usage is unavailable.+Once rollout usage is available, the activity card shows token metrics beneath its status, including totals, input and output, cache usage, and reasoning output. Counts use K/M/B units. The usage row and its divider expand or collapse together, independently of `Animation Effects`. Both remain hidden when usage is unavailable.While a task is running or waiting for approval, usage updates for main and child threads whose ownership is confirmed. Later thread records fill in the subtotal. Completed and terminated tasks briefly reread turn usage and display it once a complete total is available. Later temporary read failures preserve the usage already obtained for the ended task. These values cover the current turn and its subagents, rather than the entire conversation.diff --git a/Docs/en/UserGuide/settings.md b/Docs/en/UserGuide/settings.mdindex 5d23719..c2fd7fd 100644--- a/Docs/en/UserGuide/settings.md+++ b/Docs/en/UserGuide/settings.md@@ -28,7 +28,7 @@ Shows task status along the top of each display. CodexBar Hook must be enabled aTurning it on plays one round-trip preview using the current running color, speed, and brightness, then shows actual task status. Turning it off quickly retracts the glow to the screen center and fades it out. Turning it back on before dismissal finishes does not trigger another preview.-Double-click a color swatch in the options panel to preview that state: running makes one round trip, approval waiting pulses twice, and completion and termination appear for 3 seconds. Double-clicking again replaces the current preview. Closing the options panel ends the color preview and restores actual task status.+Double-click a color swatch in the options panel to preview that state: running shows a moving glow, approval waiting pulses, and completion or termination appears briefly before fading. Double-clicking again replaces the current preview. Closing the options panel ends the color preview and restores actual task status.| Default color | Meaning || --- | --- |@@ -39,7 +39,7 @@ Double-click a color swatch in the options panel to preview that state: runningColors use six-digit Display P3 hexadecimal values. Letters are converted to uppercase, and empty fields show the default color as a placeholder. Invalid colors have a red border and revert to the default on Return, focus loss, or panel dismissal. Animation Speed offers Slower, Standard, and Faster, with Standard as the default. Brightness ranges from 20% to 100%, defaulting to 100%.-When a task ends while others remain active, its completion or termination appears for 3 seconds before returning to the current task state. Once all tasks end, the latest ending is shown for the selected End Duration, measured from its end time. Choices are 3, 5, 10, 15, 30, or 60 seconds; the default is 10 seconds. Task updates continue during previews while terminal indicator timers pause. Presentation resumes according to the latest task state: existing terminal indicators retain their remaining time, and indicators for tasks that ended during the preview receive their full duration.+When a task ends while others remain active, its completion or termination appears briefly before returning to the current task state. Once all tasks end, the latest ending is shown for the selected End Duration, measured from its end time. Choices are 3, 5, 10, 15, 30, or 60 seconds; the default is 10 seconds. Task updates continue during previews while terminal indicator timers pause. Presentation resumes according to the latest task state: existing terminal indicators retain their remaining time, and indicators for tasks that ended during the preview receive their full duration.The glow is hidden while Hook is unavailable, preserving your switch preference. System sleep, display sleep, or an inactive user session also hides it. On return, it shows the current state without replaying expired terminal indicators.diff --git a/Docs/en/UserGuide/sync-data-privacy.md b/Docs/en/UserGuide/sync-data-privacy.mdindex 1134976..64f05e8 100644--- a/Docs/en/UserGuide/sync-data-privacy.md+++ b/Docs/en/UserGuide/sync-data-privacy.md@@ -19,7 +19,7 @@ The main panel footer and Settings show sync status. Settings also shows the las## Uploaded Data-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. Token history separately syncs pseudonymous turn identities, necessary timestamps, and six cumulative counters for cross-device deduplication and daily totals.+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. Token history separately syncs hashed identifiers derived from thread and turn IDs, necessary timestamps, and cumulative token counters for cross-device deduplication and daily totals.The following are not synced:diff --git a/README.en.md b/README.en.mdindex ef2c2b5..9bb44d3 100644--- a/README.en.md+++ b/README.en.md@@ -40,7 +40,7 @@ It can notify you when a task finishes, needs approval, or when your rate limits- Track total tokens, your highest daily usage, and usage streaks- See your longest task duration-- Review 30 weeks of daily token usage in a heatmap+- Review recent daily token usage in a heatmap- Enable CodexBar Hook for daily session, turn, tool call, subagent, and other activity metrics### Keep track of active tasksdiff --git a/README.md b/README.mdindex c047adf..450fa69 100644--- a/README.md+++ b/README.md@@ -40,7 +40,7 @@ CodexBar 是面向 macOS 15 及更高版本的菜单栏 App,用于集中展示- 展示累计 Token、单日峰值和连续使用天数- 展示最长任务时长-- 通过 30 周热力图回顾每日 Token 用量+- 通过热力图回顾近期每日 Token 用量- 开启 CodexBar Hook 后可查看会话、对话轮次、工具调用和子 Agent 等每日统计### 不错过正在发生的任务